<?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"><channel><title><![CDATA[ByteUp - Programming and Technology]]></title><description><![CDATA[A site for programming and technologies talks. Note.js and Python backend best practice, design and architecture SDLC]]></description><link>https://blog.byteup.co</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1736210752354/d92dd976-311b-476c-937a-6a4c466619f4.png</url><title>ByteUp - Programming and Technology</title><link>https://blog.byteup.co</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 23:48:30 GMT</lastBuildDate><atom:link href="https://blog.byteup.co/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[GraphQL Transforming API Development]]></title><description><![CDATA[Introduction
Modern web applications demand efficient, flexible, and robust data fetching capabilities. Enter GraphQL, a revolutionary query language that's reshaping how developers think about APIs. Since its public release by Facebook in 2015, Grap...]]></description><link>https://blog.byteup.co/graphql-transforming-api-development</link><guid isPermaLink="true">https://blog.byteup.co/graphql-transforming-api-development</guid><category><![CDATA[GraphQL]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Wed, 15 Jan 2025 17:58:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736963772052/90032be9-bd16-4d88-a6fa-067499f90be3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Modern web applications demand efficient, flexible, and robust data fetching capabilities. Enter GraphQL, a revolutionary query language that's reshaping how developers think about APIs. Since its public release by Facebook in 2015, GraphGL has gained massive adoption across industries, proving itself as more than just another tech trend.</p>
<h2 id="heading-understanding-graphqls-core-concepts">Understanding GraphQL's Core Concepts</h2>
<p>At its heart, GraphQL is a query language for APIs and a runtime for executing those queries against your data. Unlike traditional REST APIs, where the server determines the structure of the response, GraphQL empowers clients to request specific data in a single request. This fundamental shift in approach solves many of the challenges that developers face when building modern applications.</p>
<p>Think of GraphQL as a sophisticated librarian who knows exactly where every book is located and can fetch precisely what you need. Instead of visiting different shelves of the library (multiple API endpoints), you simply hand the librarian a detailed list of what you're looking for, and they return accurate that, no more, no less.</p>
<p>The schema-driven nature of GraphQL provides a clear contract between client and server. Every GraphQL service defines a set of types that completely describe the data that can be queried. When a client makes a request, GraphQL validates it against this schema before execution, ensuring that the response will be predictable and consistent.</p>
<h2 id="heading-the-technical-foundation">The Technical Foundation</h2>
<p>GraphQL operates on three main types of operations: queries for retrieving data, mutations for modifying data, and subscriptions for real-time updates. Each operation is built around a robust type system that describes the capacities of the API.</p>
<pre><code class="lang-javascript">type User {
  <span class="hljs-attr">id</span>: ID!
  name: <span class="hljs-built_in">String</span>!
  email: <span class="hljs-built_in">String</span>!
  posts: [Post!]!
  friends: [User!]!
}

type Post {
  <span class="hljs-attr">id</span>: ID!
  title: <span class="hljs-built_in">String</span>!
  content: <span class="hljs-built_in">String</span>!
  author: User!
  comments: [Comment!]!
  createdAt: <span class="hljs-built_in">String</span>!
}

type Comment {
  <span class="hljs-attr">id</span>: ID!
  text: <span class="hljs-built_in">String</span>!
  author: User!
  post: Post!
}
</code></pre>
<p>The schema defines relationships, allowing clients to retrieve nested data like a user's posts or friends in a single query.</p>
<h2 id="heading-resolvers-the-hearth-of-graphql">Resolvers: The Hearth of GraphQL</h2>
<p>One of graphQL's most powerful features lies in its resolver functions. These functions determine how the data for each field in your schema is retrieved. Resolvers can fetch data from databases, call other APIs, or perform complex computations, all while being completely invisible to the client.</p>
<h2 id="heading-example-resolvers">Example Resolvers</h2>
<p>Here's how you can implement resolvers for fetching a user's posts and friends using Prisma:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> resolvers = {
  <span class="hljs-attr">User</span>: {
    <span class="hljs-keyword">async</span> posts(parent, args, context) {
      <span class="hljs-comment">// Fetch posts for this user</span>
      <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> context.prisma.post.findMany({
        <span class="hljs-attr">where</span>: { <span class="hljs-attr">authorId</span>: parent.id },
        <span class="hljs-attr">orderBy</span>: { <span class="hljs-attr">createdAt</span>: <span class="hljs-string">'desc'</span> },
      });
      <span class="hljs-keyword">return</span> posts;
    },
    <span class="hljs-keyword">async</span> friends(parent, args, context) {
      <span class="hljs-comment">// Fetch user's friends</span>
      <span class="hljs-keyword">const</span> friends = <span class="hljs-keyword">await</span> context.prisma.user.findMany({
        <span class="hljs-attr">where</span>: {
          <span class="hljs-attr">id</span>: { <span class="hljs-attr">in</span>: parent.friendIds },
        },
      });
      <span class="hljs-keyword">return</span> friends;
    },
  },
};
</code></pre>
<p>These resolvers ensure data is fetched efficiently, only when requested by the client.</p>
<h2 id="heading-the-evolution-of-api-development">The Evolution of API Development</h2>
<p>Remember the days when REST APIs were the only game in town? Developers would create multiple endpoints, each returning fixed data structures. While this worked well for simple applications, it quickly became cumbersome as applications grew in complexity. Mobile apps needed different data than web clients, and developers found themselves making multiple API calls to gather the required information.</p>
<h2 id="heading-solving-the-n1-query-problem">Solving the N+1 Query Problem</h2>
<p>One of the most significant challenges in API development is the N+1 query problem, where fetching related data results in multiple database queries. GraphQL's ability to batch and optimize there queries through DataLoader and similar tools make it a game-changer for performance optimization.</p>
<p><strong>Consider this implementation:</strong></p>
<p>Fetching related data often results in multiple database queries, known as the N+1 query problem. GraphQL this through tools like DataLoader, which batches and caches database calls.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> DataLoader = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dataloader'</span>);

<span class="hljs-keyword">const</span> userLoader = <span class="hljs-keyword">new</span> DataLoader(<span class="hljs-keyword">async</span> (userIds) =&gt; {
  <span class="hljs-keyword">const</span> users = <span class="hljs-keyword">await</span> prisma.user.findMany({
    <span class="hljs-attr">where</span>: {
      <span class="hljs-attr">id</span>: { <span class="hljs-attr">in</span>: userIds },
    },
  });
  <span class="hljs-keyword">return</span> userIds.map(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> users.find(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id === id));
});

<span class="hljs-keyword">const</span> resolvers = {
  <span class="hljs-attr">Post</span>: {
    <span class="hljs-keyword">async</span> author(parent) {
      <span class="hljs-keyword">return</span> userLoader.load(parent.authorId);
    },
  },
};
</code></pre>
<p>This approach minimizes database queries by batching requests, significantly improving performance.</p>
<h2 id="heading-real-world-success-user-interface">Real-World Success User Interface</h2>
<h2 id="heading-netflixs-dynamic-user-interface">Netflix's Dynamic User Interface</h2>
<p>Netflix leverages GraphQL to power its dynamic user interface across different devices. Their implementation allows them to fetch absolutely the right amount of show information based on the viewing context, whether it's a thumbnail view, detailed view, or search result.</p>
<h2 id="heading-githubs-api-revolution">GitHub's API Revolution</h2>
<p>Our beloved repository GitHub's switch to GraphQL for their API v4 marked a significant milestone in the technology's adoption. They found that GraphQL reduced their API response payload sizes dramatically and gave developers more flexibility in accessing GitHub's vast data.</p>
<h2 id="heading-implementing-graphql-with-nodejs-and-apollo-server">Implementing GraphQL with Node.js and Apollo Server</h2>
<p>Let's look at a practical implementation using Node.js and Apollo Server:</p>
<ol>
<li>Install dependencies</li>
</ol>
<pre><code class="lang-bash">npm install @apollo/server graphql
</code></pre>
<ol start="2">
<li>Define your schema:</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> typeDefs = <span class="hljs-string">`#graphql
type Query {
  hello: String
}`</span>;
</code></pre>
<ol start="3">
<li>Add resolvers:</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> resolvers = {
  <span class="hljs-attr">Query</span>: {
    <span class="hljs-attr">hello</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">"Hello, GraphQL!"</span>,
  },
};
</code></pre>
<ol start="4">
<li>Start the server:</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { ApolloServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@apollo/server'</span>);

<span class="hljs-keyword">const</span> server = <span class="hljs-keyword">new</span> ApolloServer({ typeDefs, resolvers });
server.listen().then(<span class="hljs-function">(<span class="hljs-params">{ url }</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`🚀 Server ready at <span class="hljs-subst">${url}</span>`</span>);
});
</code></pre>
<h2 id="heading-performance-optimization-through-filed-selection">Performance Optimization Through Filed Selection</h2>
<p>One of GraphQL's most strong features is its ability to optimize database queries based on requested fields. Consider this example using Prisma:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { PrismaClient } <span class="hljs-keyword">from</span> <span class="hljs-string">'@prisma/client'</span>

<span class="hljs-keyword">const</span> prisma = <span class="hljs-keyword">new</span> PrismaClient()

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserData</span>(<span class="hljs-params">id: string, select: any</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> prisma.user.findUnique({
    <span class="hljs-attr">where</span>: { id },
    <span class="hljs-attr">select</span>: {
      <span class="hljs-attr">name</span>: select.name || <span class="hljs-literal">false</span>,
      <span class="hljs-attr">email</span>: select.email || <span class="hljs-literal">false</span>,
      <span class="hljs-attr">posts</span>: select.posts ? {
        <span class="hljs-attr">select</span>: {
          <span class="hljs-attr">title</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">content</span>: <span class="hljs-literal">true</span>,
        },
      } : <span class="hljs-literal">false</span>,
    },
  })
}
</code></pre>
<p>This ensures that only the required data is retrieved, reducing unnecessary overhead.</p>
<h2 id="heading-the-future-of-graphql">The Future of GraphQL</h2>
<p>Apollo Federation enables teams to split their GraphQL squema across multiple services while presenting a unified API to clients. This approach has been adopted by companies like Walmart and Paypal to scale their GraphQL implementations.</p>
<h2 id="heading-real-time-features-with-subscriptions">Real-Time Features with Subscriptions</h2>
<p>GraphQL subscriptions enable real-time updates, perfect for live notifications and collaborative applications.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { PubSub } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'graphql-subscriptions'</span>);
<span class="hljs-keyword">const</span> pubsub = <span class="hljs-keyword">new</span> PubSub();

<span class="hljs-keyword">const</span> typeDefs = <span class="hljs-string">`#graphql
type Subscription {
  messageAdded: String
}`</span>;

<span class="hljs-keyword">const</span> resolvers = {
  <span class="hljs-attr">Subscription</span>: {
    <span class="hljs-attr">messageAdded</span>: {
      <span class="hljs-attr">subscribe</span>: <span class="hljs-function">() =&gt;</span> pubsub.asyncIterator([<span class="hljs-string">'MESSAGE_ADDED'</span>]),
    },
  },
};
</code></pre>
<h2 id="heading-getting-started-with-graphql">Getting Started with GraphQL</h2>
<p>The beauty of GraphQL lies in its gradual adoption path. You don't need to rewrite your entire application to start using it. Begin implementing GraphQL alongside your existing REST APIs, possibly as a proxy layer. This way allows teams to experience the benefits while minimizing risk.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>GraphQL represents more than just a new way to query APIs; it's a paradigm shift in how we think about data fetching and client-server communication. GraphQL's flexible and efficient approach becomes increasingly valuable as applications continue to grow in complexity and scale. Whether you're building new applications or maintaining existing ones, considering GraphQL could be the key to unlocking better performance, developer experience, and user satisfaction.</p>
<p>Remember, the best way to understand GraphQL is to start using it; there are a lot of resources on its official site. Begin with small experiments, measure the impact, and gradually expand its use as you become more comfortable with the technology. The growing community and robust ecosystem make now the perfect time to embrace GraphQL in your development stack.</p>
<h2 id="heading-references">References</h2>
<ol>
<li><p><a target="_blank" href="https://graphql.org/learn/">GraphQL Official Documentation</a></p>
<blockquote>
<p>The authoritative source for GraphQL specifications, best practices, and core concepts.</p>
</blockquote>
</li>
<li><p><a target="_blank" href="https://www.apollographql.com/docs/">Apollo GraphQL Platform</a></p>
<blockquote>
<p>Comprehensive guides for implementing GraphQL with Apollo, including server setup and client integration.</p>
</blockquote>
</li>
<li><p><a target="_blank" href="https://netflixtechblog.com/how-netflix-scales-its-api-with-graphql-federation-part-1-ae3557c187e2">Netflix Engineering - GraphQL Federation</a></p>
<blockquote>
<p>Deep dive into Netflix's GraphQL federation implementation and scaling strategies.</p>
</blockquote>
</li>
<li><p><a target="_blank" href="https://github.blog/2016-09-14-the-github-graphql-api/">GitHub GraphQL API Case Study</a></p>
<blockquote>
<p>Detailed exploration of GitHub's migration to GraphQL and their implementation approach.</p>
</blockquote>
</li>
<li><p><a target="_blank" href="https://graphql.org/learn/best-practices/">GraphQL Best Practices</a></p>
<blockquote>
<p>Essential guidelines and patterns for building production-grade GraphQL APIs.</p>
</blockquote>
</li>
</ol>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on <a target="_blank" href="https://x.com/ldway27">X</a>, <a target="_blank" href="https://github.com/ivansing">Github</a>, and <a target="_blank" href="https://www.linkedin.com/in/lance-dev/">LinkedIn</a> for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[Python's Unstoppable Rise, Dominating The Modern Backend Environment]]></title><description><![CDATA[Introduction
This field of backend development has shown a remarkable transformation over the past decade, with Python emerging as the undisputed leader in this dynamic field. What started as a simple scripting language has advanced into the backbone...]]></description><link>https://blog.byteup.co/pythons-unstoppable-rise-dominating-the-modern-backend-environment</link><guid isPermaLink="true">https://blog.byteup.co/pythons-unstoppable-rise-dominating-the-modern-backend-environment</guid><category><![CDATA[Python]]></category><category><![CDATA[FastAPI]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[backend developments]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Fri, 10 Jan 2025 03:41:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736480397187/25714dbb-bed3-4fd5-af60-9b4aa37206b2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>This field of backend development has shown a remarkable transformation over the past decade, with Python emerging as the undisputed leader in this dynamic field. What started as a simple scripting language has advanced into the backbone of modern web applications, AI systems, and data-driven platforms.</p>
<p>This shift isn't merely a passing trend but represents a fundamental change in how developers and organizations approach their technological infrastructure. I will show some statistics about how, like always, Python is one of my favorite languages, maybe because this was the one that I learned first, and how this fantastic programming language is in the future of AI as data science.</p>
<p>First of all, let's look at the following graph from the Tiobe index for one of the best statistics we currently have to analyze how Python is still a trending programming language:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/21n2qi9amllt8lngtvis.png" alt="Tiobe Index" /></p>
<h2 id="heading-the-perfect-storm-why-python-dominates">The Perfect Storm: Why Python Dominates</h2>
<p>Python's ascendancy to the throne of backend development didn't happen by chance. Rather, it's the result of a perfect convergence of factors that have created an unprecedented momentum in the software development world. At its core, Python embodies a philosophy that prioritizes readability and simplicity, making it not just a programming language but a gateway to solving complex problems with elegant solutions.</p>
<p>The language's intuitive syntax, often described as "executable pseudocode," has revolutionized how developers approach problem-solving. Instead of getting overwhelmed by complex language builts, developers can focus on what truly matters: creating solutions that work. This accessibility has fostered the growth of an extensive talent pool, making it significantly easier for companies to build and maintain robust engineering teams.</p>
<h2 id="heading-modern-python-backend-frameworks">Modern Python Backend Frameworks</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a906b2y31l724yrjt87f.png" alt="Performance comparison" /></p>
<p>The maturation of Python's ecosystem has given rise to a sophisticated collection of frameworks, each serving distinct needs while maintaining the language's core principles of simplicity and efficiency. FastAPI, the newest star in this constellation, has redefined what developers expect from a modern web framework. Built on the foundations of Starlette and Pydantic (a high-perfomance web framework for building HTTP based service APIs in Python 3.8+), it delivers a perfect blend of performance and developer experience. The framework's automatic API documentation, built-in type checking, and asynchronous capabilities have set new standards in the industry, challenging the performance metrics of traditional, faster alternatives like Node.js and Go.</p>
<h2 id="heading-fastapi-the-new-standard-for-high-performance-apis">FastAPI: The New Standard for High-Performance APIs</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qu8v92dl1xmy87tetdzq.png" alt="Bar chart comparison FastAPI" /></p>
<p>While FastAPI represents the cutting edge, Django continues to evolve as a comprehensive solution for large-scale applications. Its "batteries-included" approach provides a robust foundation for enterprise-level projects, offering everything from an innovatory admin interface to a powerful ORM system. The recent addition of async views and middleware demonstrates Django's commitment to staying relevant in an increasingly asynchronous world.</p>
<h2 id="heading-python-in-the-ai-and-data-science-uprising">Python in the AI and Data Science Uprising</h2>
<p>Perhaps Python's most significant advantage lies in its unparalleled position at the intersection of backend development and artificial intelligence. This unique positioning has created a seamless bridge between traditional backend services and cutting-edge machine learning capabilities. Modern applications can now integrate advanced AI models directly into their backend infrastructure, creating more intelligent and approachable systems.</p>
<p>Leading technology companies have genuinely embraced this integration. Instagram's use of Django to manage billions of user interactions, Netflix's reliance on Python for content delivery, and Spotify's implementation of Python for data analysis all demonstrate the language's versatility and scalability. These real-world application examples serve as persuasive testimonials to Python's potentials at the enterprise scale.</p>
<h2 id="heading-the-evolution-of-backend-development-practices">The Evolution of Backend Development Practices</h2>
<p>The modern Python backend development field has advanced to embrace contemporary software engineering practices. Asynchronous programming once considered a specialty, has become mainstream thanks to Python's elegant async/await syntax. This prototype transition has enabled developers to build highly concurrent applications that can handle multiple operations efficiently, which is particularly crucial for applications dealing with real-time data processing and multiple external services.</p>
<p>The introduction of type hints and static type checking has transformed how developers approach code quality and maintenance. Tools like "mypy" have brought the benefits of static typing to Python's dynamic innovation, enabling early error detection and improved code maintainability. This has been especially transformative for large-scale applications where type safety is paramount.</p>
<h2 id="heading-future-horizons">Future Horizons</h2>
<p>As we look toward the future, Python's role in backend development appears poised for even greater expansion. Projects like Mojo and Pypy are actively addressing performance considerations while the async environment continues to mature and progress.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Python's dominance in backend development represents more than just a technological preference; it's a testament to the power of simplicity, adaptability, and community-driven innovation. As the digital landscape continues to advance, Python's individual ability to bridge traditional backend development with emerging technologies positions it not just as the language of today but as the foundation for tomorrow's technological innovations.</p>
<p>The future of backend development is being written in Python, one line of elegant code at a time. As we witness the continued convergence of traditional backend services with AI and data science, Python's role appears not just secure but expanding, promising even more exciting developments in the years to come.</p>
<p>Share your comments and thoughts below in the comments box, and let me know if you like my article and if you want me to write the next article so I can hear your ideas for this great community.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="http://Python.org">Python.org</a><a target="_blank" href="https://docs.python.org/3/">. (2024). "Python 3.12 Documentation."</a></p>
</li>
<li><p><a target="_blank" href="https://fastapi.tiangolo.com/">FastAPI. (2024). "FastAPI Documentation."</a></p>
</li>
<li><p><a target="_blank" href="https://docs.djangoproject.com/">Django Project. (2024). "Django Documentation."</a></p>
</li>
<li><p><a target="_blank" href="https://www.jetbrains.com/lp/python-developers-survey-2023/">JetBrains. (2023). "Python Developers Survey Results."</a></p>
</li>
<li><p><a target="_blank" href="https://survey.stackoverflow.co/2023">Stack Overflow. (2023). "Developer Survey 2023."</a></p>
</li>
<li><p><a target="_blank" href="https://octoverse.github.com/">GitHub. (2023). "The State of the Octoverse."</a></p>
</li>
<li><p><a target="_blank" href="https://fastapi.tiangolo.com/benchmarks/">Tiangolo. (2024). "FastAPI Benchmarks."</a></p>
</li>
<li><p><a target="_blank" href="https://netflixtechblog.com/">Netflix Technology Blog. (2023). "Python at Netflix."</a></p>
</li>
<li><p><a target="_blank" href="https://instagram-engineering.com/">Instagram Engineering. (2023). "Python at Scale."</a></p>
</li>
</ul>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on <a target="_blank" href="https://x.com/ldway27">X</a>, <a target="_blank" href="https://github.com/ivansing">Github</a>, and <a target="_blank" href="https://www.linkedin.com/in/lance-dev/">LinkedIn</a> for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[React Server Components: The Evolution]]></title><description><![CDATA[Introduction
Once I began my path as a software developer around a decade ago, I just coded HTML, CSS, JavaScript, and some Python 2 scripts; during those times, we depended solely on PHP and SQL for server-side client-server communication. After tha...]]></description><link>https://blog.byteup.co/react-server-components-the-evolution</link><guid isPermaLink="true">https://blog.byteup.co/react-server-components-the-evolution</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[rsc]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Tue, 07 Jan 2025 22:50:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736290074173/c22d9ef2-eedd-45d0-bb27-4d1d5a0ba292.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>Once I began my path as a software developer around a decade ago, I just coded HTML, CSS, JavaScript, and some Python 2 scripts; during those times, we depended solely on PHP and SQL for server-side client-server communication. After that, the next level was the magic word "React," like reacting to changes by state or effects. That's my understanding, without deepening into the matter, by the rumor that a Facebook engineer made it; this was a bombshell in the way we used to code frontend parts.</p>
<p>As software development evolved and the backend systems became complex, the React Server Components (RSC) felt that the evolution of our ecosystem was desperately needed. That reminds me of the days when massive JavaScript bundles and "loading" spinners were everywhere. Let's explore how RSC is changing the game.</p>
<p><strong>The Performance Revolution</strong></p>
<p>The main shift RSC brings isn't just technical but also philosophical. Instead of shipping entire component trees to the client, RSC lets us render components on the server while keeping the interactivity we love about React. I used to migrate dashboard applications to RSC, and it's pretty simple, nothing out of this world, and the clear impact impacts in dashboard applications the size dropped by 60%.</p>
<p>Here's a real-world example I encountered just recently:</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// Before: Client Component</span>
 <span class="hljs-keyword">import</span> { ComplexDataGrid } <span class="hljs-keyword">from</span> <span class="hljs-string">'heavy-grid-library'</span>;
<span class="hljs-keyword">import</span> { format } <span class="hljs-keyword">from</span> <span class="hljs-string">'date-fns'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dashboard</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [data, setData] = useState([]);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    fetchDashboardData().then(setData);
  }, []);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ComplexDataGrid</span> <span class="hljs-attr">data</span>=<span class="hljs-string">{data}</span> /&gt;</span></span>;
}
</code></pre>
<p>In this traditional client-side approach, several things are happening:</p>
<ul>
<li><p>We're importing a heavy data grid library that gets bundled with our client JavaScript.</p>
</li>
<li><p>We're using <code>useState</code> to manage our data locally in the browser.</p>
</li>
<li><p>We're fetching data after the component mounts using <code>useEffect</code>.</p>
</li>
<li><p>The user sees a loading state while data is being fetched.</p>
</li>
<li><p>All data processing happens in the browser, potentially slowing down the user's device. Now, let's look at the RSC version:</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { sql } <span class="hljs-keyword">from</span> <span class="hljs-string">'@vercel/postgres'</span>;
<span class="hljs-keyword">import</span> { DataGrid } <span class="hljs-keyword">from</span> <span class="hljs-string">'./DataGrid'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dashboard</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> sql<span class="hljs-string">`SELECT * FROM dashboard_metrics`</span>;

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DataGrid</span> <span class="hljs-attr">data</span>=<span class="hljs-string">{data}</span> /&gt;</span></span>;
}
</code></pre>
<ul>
<li><p>The component is async by default - no need for useEffect or useState.</p>
</li>
<li><p>Direct database access through server-side queries.</p>
</li>
<li><p>No client-side data fetching code is needed.</p>
</li>
<li><p>Zero loading states are required for initial data.</p>
</li>
<li><p>Data processing happens on powerful servers instead of user devices.</p>
</li>
<li><p>The imported DataGrid component can be much lighter as it only needs to handle display, not data fetching.</p>
</li>
</ul>
<p>The transformation is striking. No more <code>useEffect</code>, no more client-side data fetching, and most importantly, no more unnecessary shipping of JavaScript to the client.</p>
<p><strong>Real-World Benefits</strong></p>
<p>The impact goes beyond just performance metrics. When working with RSC, I've noticed that the database queries now happen closer to the data source (in the example above is not the best coding practice), the components are simpler and more focused, authentication and authorization patterns become more straightforward and SEO improvements come almost for free, something that in the React world wasn't happening before.</p>
<p>However, the most significant advantage is the developer experience. Writing components that can directly access your database (safety!) feels like a superpower. It's like having the best of both worlds: the component-based architecture from React, with the performance benefits of server-side rendering the most advanced with Next.js</p>
<p><strong>The Trade-offs</strong></p>
<p>Let's be honest: RSC isn't perfect. The mental model takes time to grasp, especially understanding the client/server boundary; for me, a kind of complex operation in the black box. I will follow my previous migration example, we hit some roadblocks with third-party libraries that weren't RSC-compatible. The solution? A hybrid approach:</p>
<pre><code class="lang-javascript"><span class="hljs-string">'use client'</span>;
<span class="hljs-comment">// Client Component for interactivity</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SearchFilter</span>(<span class="hljs-params">{ onSearch }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> onSearch(e.target.value)} /&gt;</span>;
}

<span class="hljs-comment">// Server Component for data fetching</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductList</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> products = <span class="hljs-keyword">await</span> getProducts();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">SearchFilter</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ProductGrid</span> <span class="hljs-attr">items</span>=<span class="hljs-string">{products}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<p>Let' s break down what's happening in this hybrid approach:</p>
<ul>
<li><p>The <code>use client</code> directive explicitly marks SearchFilter as a client component.</p>
</li>
<li><p>SearchFilter handles user interactions (onChange events) which can only happen on the client.</p>
</li>
<li><p>ProductList remains a server component, fetching data server-side.</p>
</li>
<li><p>The component composition allows us to mix server and client rendering where appropriate.</p>
</li>
<li><p>Only the interactive parts (SearchFilter) carry JavaScript to the client.</p>
</li>
<li><p>The data-heavy parts (ProductGrid with products) are rendered on the server.</p>
</li>
</ul>
<p><strong>Conclusion (The Future is Server-First)</strong></p>
<p>RSC represents more than just a new feature - it's a paradigm conveyed in how we build React applications. The ability to move expensive computations and data fetching to the server while maintaining React's component model is revolutionary.</p>
<p>For teams building data-heavy applications, RSC offers a path to better performance without sacrificing developer experience. As the environment matures and more libraries become RSC compatible, I expect this pattern to become the default way we build React applications.</p>
<p><strong>Share Your Experience</strong></p>
<p>Have you started using React Server Components in your projects? I'd love to hear from you, challenges and wins in the comments below. Drop a ❤️ if this article helped you understand RSC better, and don't forget to follow me for more deep dives into modern systems.</p>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on <a target="_blank" href="https://x.com/ldway27">X</a>, <a target="_blank" href="https://github.com/ivansing">Github</a>, and <a target="_blank" href="https://www.linkedin.com/in/lance-dev/">LinkedIn</a> for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[The Rise of Serverless Architecture and Edge Computing]]></title><description><![CDATA[🎉 Some words before we further read the following article:🥳 I wish everyone a Happy New Year 2025. 🎆 Have a great time with your loved ones!!! ❤️
Introduction
I've seen that over the past few years, the world of software development has been turni...]]></description><link>https://blog.byteup.co/the-rise-of-serverless-architecture-and-edge-computing</link><guid isPermaLink="true">https://blog.byteup.co/the-rise-of-serverless-architecture-and-edge-computing</guid><category><![CDATA[serverless]]></category><category><![CDATA[edgecomputing]]></category><category><![CDATA[software development]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Tue, 31 Dec 2024 20:41:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735677585326/405c24f5-26da-4c10-bab5-0afecff8f1ad.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>🎉 Some words before we further read the following article:🥳 I wish everyone a Happy New Year 2025. 🎆 Have a great time with your loved ones!!! ❤️</p>
<h2 id="heading-introduction">Introduction</h2>
<p>I've seen that over the past few years, the world of software development has been turning into a pace that's hard to keep up with. New technologies have emerged frameworks, and paradigms seem to pop up every other week, but few trends have grabbed my attention as much as Serverless Architectures and Edge Computing. These two concepts are perspectives on why these trends are not just buzzwords but the foundation of a more efficient and scalable future for modern software development.</p>
<h2 id="heading-what-exactly-is-serverless">What Exactly is Serverless?</h2>
<p>When I first heard this fancy cryptic term, I thought it was out of this world. Somebody was doing all the jobs without servers, but it was more like a magic spell or something; I'm just kidding. How can anything be server-less when, ultimately, there are still servers running somewhere? The term might be misleading, but the philosophy is straightforward: developers shouldn't have to worry about provisioning, scaling, or maintaining servers, as simple as that! Instead, we focus on writing code, and the infrastructure takes care of itself; what a beauty, right?</p>
<p>Platforms like AWS Lambda, Google Cloud Functions, and Vercel have taken center stage in enabling this shift. They allow developers to write small, focused pieces of code (functions) that execute in response to specific events--whether it's a user clicking a button, an API call, or a database update.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovt2ih5k4ma0y1017gne.png" alt="Serverless vs Edge" /></p>
<p>The charm of serverless lies in its scalability. If 10,000 users suddenly hit your app, you don't need to frantically spin up more servers identical to a monolithic infrastructure going vertical all the time. The platform scales your functions automatically. And when no one's using them? You're not paying for idle servers sitting around doing nothing, for this was a game changer.</p>
<p>But serverless isn't perfect. Cold starts, vendor lock-in, and resource limitations can still pose challenges. Yet, the benefits-reduced operational overhead, pay-as-you-go pricing, and simplified deployment far outweigh the downsides for most use cases.</p>
<h2 id="heading-enter-edge-computing-bringing-servers-closer-to-users">Enter Edge Computing: Bringing Servers Closer to Users</h2>
<p>While serverless systems have transformed how we deploy backend functions, Edge Computing focuses on where those functions run. In traditional cloud computing, your application might live in a data center halfway across the world from your users and customers. Every request has to travel that distance, adding latency.</p>
<p>With the advent of edge computing, those computations happen closer to your users. Think of it like having tiny data centers spread across the globe. Platforms like Cloudflare Workers, AWS Lambda@Edge, and Fastly Compute@Edge are pushing this trend forward.</p>
<p>For developers, this means snappier performance, lower latency, and better user experiences. Imagine you're building an e-commerce app, and your users in Europe can access the backend services from a nearby edge server instead of making a round trip to a data center in South America or the US.</p>
<p>But edge computing isn't just about speed. It's also about resilience. By distributing workloads across multiple edge nodes, we can reduce the risk of regional outages and single points of failure.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6rohm4ut0ux8x6dj4nrt.png" alt="Packets in action" /></p>
<h2 id="heading-real-world-use-cases">Real-World Use Cases</h2>
<p>One of the first projects where I experimented with serverless and edge computing was a real-time analytics dashboard for a customer. They wanted to track user behavior across their platform and display analytics with minimal delay. Traditional server setups would have required complex infrastructure planning, but we deployed a solution in record time with AWS Lambda and Cloudflare Workers.</p>
<p>Every user event triggered a Lambda function, which processed the data and pushed it to our analytics store. The edge workers ensured the data was delivered to the front end instantly, no matter where the user was located; this is really common these days.</p>
<p>Another project involved building an image optimization pipeline. Every time a user uploaded an image, a serverless function would compress, resize, and optimize it. With edge computing, the optimized was then served to users based on their geographic location, ensuring minimal load times.</p>
<h2 id="heading-challenges-and-trade-offs">Challenges and Trade-offs</h2>
<p>As a rule, it's not all rainbows and sunshine. Serverless comes with cold starts--the slight delay when a function is invoked after being idle. For latency-sensitive applications, this can be a dealbreaker. Additionally, debugging and monitoring serverless apps require specialized tools since you can't simply SSH into a server.</p>
<p>Vendor lock-in is another real concern. Once you build an app tightly coupled to AWS Lambda, for example, migrating to antoher platform can be a nightmare.</p>
<p>Edge computing also introduces its own set of complexities. Not all workloads are suitable for the edge, and deciding which logic runs at the edge versus the central cloud requires careful planning.</p>
<h2 id="heading-the-future-a-harmonious-relationship">The Future: A Harmonious Relationship</h2>
<p>Despite these challenges, I believe serverless and edge computing are not competing technologies--they're complementary. Serverless focuses on abstracting infrastructure, while edge computing focuses on improving proximity to the end user. Together, they form a powerful duo that allows developers to build scalable, resilient, and highly performant applications.</p>
<p>In the coming years, I predict we'll see more frameworks and tools that seamlessly integrate these two archetypes. The rise of multi-cloud serverless platforms and global edge networks will further blur the lines between backend and edge workloads.</p>
<p>For developers, the future looks bright. With serverless and edge computing, we can focus less on infrastructure headaches and more on delivering value to our users.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you've made it this far, thank you! I'm genuinely excited about where serverless architectures and edge computing are headed, and I'd love to hear your thoughts. Are you already using these technologies in your projects? Have you faced any challenges on your work team?</p>
<p>Drop a comment below and share your experiences! In addition, if you're interested in staying updated with the latest trends and tutorials in software development, consider subscribing to my newsletter below. I share almost daily articles, insights, tips, and case studies that you won't want to miss.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p>AWS Lambda Documentation: <a target="_blank" href="https://aws.amazon.com/lambda/">https://aws.amazon.com/lambda/</a></p>
</li>
<li><p>Google Cloud Functions Documentation: <a target="_blank" href="https://cloud.google.com/functions">https://cloud.google.com/functions</a></p>
</li>
<li><p>Vercel Documentation: <a target="_blank" href="https://vercel.com/docs">https://vercel.com/docs</a></p>
</li>
<li><p>Cloudflare Workers Documentation: <a target="_blank" href="https://developers.cloudflare.com/workers/">https://developers.cloudflare.com/workers/</a></p>
</li>
<li><p>AWS Lambda@Edge Documentation: <a target="_blank" href="https://aws.amazon.com/lambda/edge/">https://aws.amazon.com/lambda/edge/</a></p>
</li>
<li><p>Fastly Compute@Edge Documentation: <a target="_blank" href="https://www.fastly.com/products/compute-at-edge">https://www.fastly.com/products/compute-at-edge</a></p>
</li>
</ul>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on <a target="_blank" href="https://x.com/ldway27">X</a>, <a target="_blank" href="https://github.com/ivansing">Github</a>, and <a target="_blank" href="https://www.linkedin.com/in/lance-dev/">LinkedIn</a> for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript: The Superhero JavaScript Needed]]></title><description><![CDATA[Introduction
This article dives into TypeScript, not just as a transformative tool that's reshaping how we build modern web applications. I've been working with TypeScript in recent years, and I'm continually amazed by how it has revolutionized web d...]]></description><link>https://blog.byteup.co/typescript-the-superhero-javascript-needed</link><guid isPermaLink="true">https://blog.byteup.co/typescript-the-superhero-javascript-needed</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Tue, 31 Dec 2024 04:29:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735618947213/642488fa-af90-425b-a071-cb20fd941e52.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>This article dives into TypeScript, not just as a transformative tool that's reshaping how we build modern web applications. I've been working with TypeScript in recent years, and I'm continually amazed by how it has revolutionized web development. Rather than delving into its history, let's explore what makes TypeScript unique and why it's become indispensable in today's development landscape. I won't compare it with other "type" languages like Java, C++ (more popular), and many others; I will just immerse myself in the world of TypeScript and Javascript for a bit.</p>
<h2 id="heading-type-safety-and-performance">Type Safety and Performance</h2>
<p>The heart of TypeScript's power lies in its static typing system, but it's so much more than just adding <code>: string</code> or <code>: number</code> to your variables. If you have worked like me for years with JavaScript, this is where TypeScript helps out. What truly sets it apart is how it catches potential issues before reaching production. Is that amazing? I remember the days of debugging (still I do) Javascript applications where a simple type in a property name would slip through testing and cause production crashes. TypeScript eliminates these scenarios entirely.</p>
<p>Let me show you a practical example that I encounter frequently in my work:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processUser</span>(<span class="hljs-params">user: User</span>) </span>{
    <span class="hljs-built_in">console</span>.log(user.name.toUpperCase()); <span class="hljs-comment">// Safe!</span>
}
</code></pre>
<p>This might look simple, but there's profound safety here. In JavaScript, this function would be a ticking time bomb - what if <code>user</code> is undefined? What if <code>name</code> is missing? In TypeScript, these concerns vanish because the type system ensures all these properties exist before your code even runs.</p>
<h2 id="heading-reliability">Reliability</h2>
<p>What truly amazes me about TypeScript is how it transforms JavaScript development from a minefield of potential runtime errors into a confident, guided experience. The compiler becomes your pair programmer, but not in an intrusive way. Instead of finding out about errors when your users do, TypeScript catches them as you type. It's like having a senior developer looking over your shoulder, pointing out potential issues before they become problems.</p>
<p>The type system is incredibly sophisticated, yet it feels natural to JavaScript developers. Take this example I worked with recently: I needed to ensure different parts of my application could "speak" to each other. In JavaScript, I'd hope everything matches up. In the other hand, with TypeScript, I get guarantees:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> CanSpeak {
     speak(): <span class="hljs-built_in">string</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makeSpeak</span>(<span class="hljs-params">speaker: CanSpeak</span>) </span>{
    <span class="hljs-built_in">console</span>.log(speaker.speak());
}
</code></pre>
<p>This code tells a story about how TypeScript brings clarity to our applications. Any object with a speak method works seamlessly, maintaining JavaScript's flexibility while adding compile time safety. No one couldn't imagine that in the golden years of JavaScript.</p>
<h2 id="heading-productivity">Productivity</h2>
<p>Let me share something fascinating about TypeScript's impact on productivity. Last year, I worked on a large-scale applications refactor in those old projects you have ready to make it work. What would have been weeks of careful JavaScript modifications became days of confident changes in TypeScript. The secret? TypeScript intelligent IDE support transforms how we write code. As you type, your editor understands your entire codebase, offering suggestions that feel almost magical.</p>
<p>The tooling ecosystem is extraordinary, but not in an overwhelming way. Whether you're using webpack, Vite, or esbuild, TypeScript just works. The compiler messages are like having a conversation with a helpful colleague rather than fighting with cryptic errors that happens many often with JavaScript alone. When you make a mistake, TypeScript not only tells you what went wrong but regularly suggests how to fix it.</p>
<h2 id="heading-use-cases">Use Cases</h2>
<p>Want to hear something incredible? Microsoft's Office 365, the suite applications millions use daily, is built with TypeScript; I'm stunned. This isn't just a language for small projects - it scales to millions of lines of code while keeping development smooth and maintainable.</p>
<p>The frontend framework field has been transformed by TypeScript. Angular embraced it fully, making it a requirement. React developers, including myself, once skeptical, now consider TypeScript essential for any serious project. Vue 3's rewrite in TypeScript speaks volumes about the value of the language in building reliable user interfaces.</p>
<p>But here's what really excites me: TypeScript isn't just for browsers anymore. Companies like Nest.js brought TypeScript's benefits to server-side development. Imagine having the same "type safety" and developer experience across your entire stack. It's a game-changer for full-stack development.</p>
<p>The financial technology sector has particularly embraced TypeScript. When I learned that companies like Bloomberg and Revolut use TypeScript for their web platforms, it made perfect sense. When handling financial data, you can't afford runtime type errors. TypeScript provides the confidence these applications need.</p>
<p>Visual Studio Code, the editor I have used for years, is written in TypeScript. It's a testament to the language's capabilities that one of the most popular development tools is built with it. The language's powerful type system makes it perfect for tools that are needed to parse, analyze, and manipulate code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Through my journey with TypeScript, I've watched it evolve from "JavaScript with types" into an essential tool for modern web development. Its combination of static typing, excellent developer experience, and seamless JavaScript integration makes it invaluable for projects of any size. The learning curve might seem steep at first, especially around the type system, but the benefits become clear quickly: fewer monstrosity bugs, better tooling, and more maintainable code.</p>
<p>As web applications grow more complex and teams get larger, TypeScript isn't just nice to have - it's becoming a necessity. Whether you're building a small personal project or a large enterprise application, TypeScript provides the elements and safety nets needed for confident, productive development. The future of web development is typed, and TypeScript is leading the way in the scripting language.</p>
<p>These were just a few lines of code, the tip of the iceberg. In the coming days, we will create a step-by-step tutorial on building an app to help you better understand.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="https://www.typescriptlang.org/docs/"><strong>TypeScript Official Documentation</strong></a> – Microsoft</p>
</li>
<li><p><a target="_blank" href="https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals"><strong>Anders Hejlsberg. (2023). TypeScript Design Goals</strong></a></p>
</li>
<li><p><a target="_blank" href="https://code.visualstudio.com/blogs/2018/03/23/text-buffer-reimplementation"><strong>Microsoft Engineering Blog: Visual Studio Code's Architecture</strong></a></p>
</li>
<li><p><a target="_blank" href="https://angular.io/guide/typescript-configuration"><strong>Angular Documentation: Why TypeScript?</strong></a></p>
</li>
<li><p><a target="_blank" href="https://stateofjs.com"><strong>State of JS 2023 Survey: TypeScript Usage Statistics</strong></a></p>
</li>
</ul>
<p>For further reading, you can explore the TypeScript Handbook and release notes on the official TypeScript website.</p>
<p>If you like my articles, please consider following me. If you feel more comfortable, please share your thoughts in the comments below so we can exchange more ideas.</p>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on <a target="_blank" href="https://x.com/ldway27">X</a>, <a target="_blank" href="https://github.com/ivansing">Github</a>, and <a target="_blank" href="https://www.linkedin.com/in/lance-dev/">LinkedIn</a> for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[2024 Tech Year in Review: From AI Revolution to Quantum Leaps]]></title><description><![CDATA[Hey there, fellow tech enthusiasts! As we are almost at the end of 2024, I wanted to take a moment to share my thoughts on what's been an absolutely incredible year in technology. As a software developer and tech blogger (I was a blogger not too long...]]></description><link>https://blog.byteup.co/2024-tech-year-in-review-from-ai-revolution-to-quantum-leaps</link><guid isPermaLink="true">https://blog.byteup.co/2024-tech-year-in-review-from-ai-revolution-to-quantum-leaps</guid><category><![CDATA[AI]]></category><category><![CDATA[quantum computing]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[technology]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[Python]]></category><category><![CDATA[Rust]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Fri, 27 Dec 2024 01:53:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735264280662/54885adf-9c2f-47ec-a733-4a368d31f6f2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, fellow tech enthusiasts! As we are almost at the end of 2024, I wanted to take a moment to share my thoughts on what's been an absolutely incredible year in technology. As a software developer and tech blogger (I was a blogger not too long ago), I found this to be an excellent opportunity to share my thoughts and some knowledge in this area.</p>
<p>I've had a front-row seat for some mind-blowing developments. Let's dive into what shaped our tech landscape this year.</p>
<h2 id="heading-the-ai-revolution-continues">The AI Revolution Continues</h2>
<p>This year has been nothing short of revolutionary in the AI space. I don't have time something to see what's new because every minute, there is another AI toll already built; I have no time, and every time I read a book or article from great bloggers, people around this world, technology, the list goes and on all the time. The release of more powerful large language models has transformed how we approach software development. I've personally integrated AI tools into my development workflow, and it's been a game changer for code review, documentation, and even architectural decisions.</p>
<p>What's really caught my attention is the rise of smaller, more efficient AI models that can run locally. This shift towards edge AI has opened up new possibilities for privacy-focused applications. As a Node.js developer in Python and Java, I've seen how libraries like TensorFlow.js have matured, making it easier than ever to implement AI features in web applications.</p>
<h2 id="heading-programming-languages-the-shifting-landscape">Programming Languages: The Shifting Landscape</h2>
<p>Speaking of development, the programming language landscape has seen some interesting shifts. Rust continues its unstoppable rise, particularly in systems programming and WebAssembly applications. I've noticed more companies moving performance-critical parts of their Node.js applications to Rust, and the results have been impressive.</p>
<p>Python, my go-to language for many projects, has maintained its dominance in data science and AI. The improvements in Python 3.12's performance and the growing ecosystem around tools like PyPy have made it even more attractive for large-scale applications.</p>
<h2 id="heading-cloud-native-and-infrastructure-evolution">Cloud Native and Infrastructure Evolution</h2>
<p>The cloud-native field has become increasingly more mature. Kubernetes has evolved from being just a container orchestrator to a true cloud-native application platform. Sometimes, I've seen how tools like service meshes and eBPF have transformed observability and security.</p>
<p>What's particularly exciting is the rise of platform engineering. More organizations are building internal developer platforms to streamline their workflows.</p>
<h2 id="heading-database-technologies-the-new-wave">Database Technologies: The New Wave</h2>
<p>This year has been fascinating for database technologies. Vector databases are a new trend like Milvus and Pinecone, driven by the AI boom, which has introduced new ways to handle similarity search and recommendation systems.</p>
<p>Traditional databases haven't stood still either. PostgreSQL's latest features around JSON handling and performance improvements have made it an even more compelling choice for modern applications. The emergence of edge databases and improved distributed database systems has also caught my attention.</p>
<h2 id="heading-quantum-computing-from-theory-to-practice">Quantum Computing: From Theory to Practice</h2>
<p>While still in the early stages, quantum computing has made remarkable progress this year. The major cloud providers have expanded their quantum offerings, making it easier for developers to experiment with quantum algorithms. I've been following developments in quantum-resistant cryptography, especially given the increasing urgency of preparing our systems for the post quantum era.</p>
<h2 id="heading-web-development-trends">Web Development Trends</h2>
<p>The web development space continues to evolve rapidly. Web Components have gained more traction with more Progressive Web Applications, like desktop apps, but with web technologies, this is not something new but has more advanced features also with no more code and low code platforms.</p>
<h2 id="heading-security-and-privacy">Security and Privacy</h2>
<p>We can't discuss 2024 without mentioning the increasing focus on security and privacy. Zero-trust architecture has moved from a buzzword to a necessity, and passwordless authentication has begun to reshape how we think about identity management.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>This year has been transformative for our industry. As someone deeply embedded in the tech world, I'm constantly amazed by the pace of innovation. What excites me most is how these technologies are becoming more accessible to developers at all levels.</p>
<p>Before I wrap up, I want to wish all my readers a very Merry Christmas! May your code be bug-free and your deployments be smooth in the coming year. 🎄✨</p>
<p>What are your thoughts on these trends? Have you experimented with any of these technologies? I'd love to hear about your experiences in the comments below. If you decide to subscribe, that would also be awesome!</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="https://python.langchain.com/docs/get_started/introduction">LangChain Docs</a></p>
</li>
<li><p><a target="_blank" href="https://www.tensorflow.org/js">TensorFlow.js Docs</a></p>
</li>
<li><p><a target="_blank" href="https://platform.openai.com/docs">OpenAI Docs</a></p>
</li>
<li><p><a target="_blank" href="https://docs.python.org/3.12/whatsnew/3.12.html">Python 3.12 Notes</a></p>
</li>
<li><p><a target="_blank" href="https://doc.rust-lang.org/book/">Rust Book</a></p>
</li>
<li><p><a target="_blank" href="https://nodejs.org/docs/latest/api/">Node.js Docs</a></p>
</li>
<li><p><a target="_blank" href="https://kubernetes.io/docs/home/">Kubernetes Docs</a></p>
</li>
<li><p><a target="_blank" href="https://backstage.io/docs">Backstage Docs</a></p>
</li>
<li><p><a target="_blank" href="https://www.postgresql.org/docs/">PostgreSQL Docs</a></p>
</li>
<li><p><a target="_blank" href="https://docs.pinecone.io/">Pinecone Docs</a></p>
</li>
<li><p><a target="_blank" href="https://milvus.io/docs">Milvus Docs</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Build Lightning-Fast Data Processing in Rust: From Single Thread to Parallel Performance]]></title><description><![CDATA[Introduction
Following our deep dive into Rust's capabilities, I'll take you on a hands-on small project. In this project, we'll harness Rust's power, to build to generate a large dataset and compare performance between single-threaded and parallel p...]]></description><link>https://blog.byteup.co/build-lightning-fast-data-processing-in-rust-from-single-thread-to-parallel-performance</link><guid isPermaLink="true">https://blog.byteup.co/build-lightning-fast-data-processing-in-rust-from-single-thread-to-parallel-performance</guid><category><![CDATA[Rust]]></category><category><![CDATA[Rust programming]]></category><category><![CDATA[Threading]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Fri, 20 Dec 2024 03:18:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734664529354/8fc44720-ac6d-4cba-be69-7347f24487be.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Following our deep dive into Rust's capabilities, I'll take you on a hands-on small project. In this project, we'll harness Rust's power, to build to generate a large dataset and compare performance between single-threaded and parallel processing. This example uses two powerful libraries, <code>rand</code> and <code>rayon</code>  to get the job done. </p>
<p>This is your practical guide to seeing Rust's performance metrics in action. If you have been following my previous Rust article: <a target="_blank" href="https://dev.to/ivansing/what-is-rust-and-what-is-for-it-35b4">"What is Rust, and What is it For?</a>" This tutorial will show you exactly how these pieces fit together.</p>
<h2 id="heading-setting-up-the-environment">Setting Up the Environment</h2>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li>Basic understanding of type programming languages</li>
<li>Code Editor</li>
</ul>
<h2 id="heading-step-1-setting-up-the-project">Step 1: Setting Up the Project</h2>
<p>For the most popular OS you can go to: <a target="_blank" href="https://www.rust-lang.org/learn/get-started">Rust Language Page</a>, and will quite easy installation, for windows subsystem for Linux, and also make the first easy tutorial of your first Rust program.</p>
<p>Now that you have already installed the Rust and did the checks that is actually in your OS we can proceed with the next part.</p>
<p><strong>Initialize a new Rust project:</strong></p>
<p>I'm using VS Code it works for me, if you have another code editor no problem just open your terminal and add the following code to start building the project:</p>
<pre><code class="lang-bash">cargo new rust_performance_demo
</code></pre>
<p>Next move to that folder:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> rust_performance_demo
</code></pre>
<p><strong>File structure</strong></p>
<pre><code class="lang-bash">├── Cargo.lock
├── Cargo.toml
└── src
    └── main.rs
</code></pre>
<p>This creates some folders and files like: <code>Cargo.toml</code> file and a <code>src/lib.rs</code> file.
Add dependencies to <code>Cargo.toml</code>: Open the <code>Cargo.toml</code> file and add the following dependencies:</p>
<pre><code class="lang-bash">[package]
name = <span class="hljs-string">"rust_performance_demo"</span>
version = <span class="hljs-string">"0.1.0"</span>
edition = <span class="hljs-string">"2021"</span>

[dependencies]
rand = <span class="hljs-string">"0.8"</span>
rayon = <span class="hljs-string">"1.7"</span>
</code></pre>
<p>After you added the dependencies build the program this like in Python <code>pip</code> or in Node <code>npm</code> for Rust is:</p>
<pre><code class="lang-bash">cargo build
</code></pre>
<p>Now, we need to modify the file <code>main.rs</code>inside src folder with the following code step by step code explanation:</p>
<h2 id="heading-explanation">Explanation</h2>
<p><strong>Generating a Dataset</strong></p>
<p>Inside the main function <code>fn main()</code>  add the following code steps: The first thing I do in this program is generate a large dataset. I create a vector (a dynamic array) of 50 million random integers, each between 0 and 99. To achieve this, I use the <code>rand</code> library to generate random numbers and fill up the vector. Here's how I do it:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">let</span> size = 50_000_000;
<span class="hljs-built_in">let</span> mut rng = rand::thread_rng();
<span class="hljs-built_in">let</span> data: Vec&lt;u32&gt; = (0..size).map(|_| rng.gen_range(0..100)).collect();

println!(<span class="hljs-string">"Generated a vector of {} elements."</span>, size);
</code></pre>
<p>What's happening here? I use the <code>thread_rng()</code> method to get a random number generator, and I generate 50 million random numbers using <code>rng.gen_range(0..100)</code>. The <code>map</code> function is perfect for transforming a range into random numbers, and I collect them all into a vector.</p>
<p><strong>Measuring Single-Threaded Performance</strong></p>
<p>Next, I calculate the sum of all the numbers in the vector using a single-threaded approach. I use Rust's built-in <code>iter()</code> method to loop through each element, cast it to a <code>u64</code>(since the sum can get quite large), and sum everything up:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">let</span> start = Instant::now();
<span class="hljs-built_in">let</span> sum_single: u64 = data.iter().map(|&amp;x| x as u64).sum();
<span class="hljs-built_in">let</span> duration_single = start.elapsed();
println!(<span class="hljs-string">"Single-threaded sum: {}, took: {:?}"</span>, sum_single, duration_single);
</code></pre>
<p>I also measure how long this operation takes using <code>std::time::Instant</code>. The <code>elapsed()</code> method gives me the duration and print it out both the sum and the time taken.</p>
<p><strong>Measuring Parallel Performance</strong></p>
<p>Now comes the exciting part: parallel processing. Rust's <code>rayon</code> library makes parallelism incredibly simple. Instead of using <code>iter()</code> to loop through the data, I use <code>par_iter()</code>(from <code>rayon</code>), which splits the work across multiple threads automatically:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">let</span> start = Instant::now();
<span class="hljs-built_in">let</span> sum_parallel: u64 = data.par_iter().map(|&amp;x| x as u64).sum();
<span class="hljs-built_in">let</span> duration_parallel = start.elapsed();
println!(<span class="hljs-string">"Parallel sum: {}, took: {:?}"</span>, sum_parallel, duration_parallel);
</code></pre>
<p>This approach processes the vector much faster by utilizing all the available CPU cores. Again, I measure and print the time taken.</p>
<p><strong>Ensuring Correctness</strong></p>
<p>It's not enough for the parallel version to be faster, it must also produce the same result as the single-threaded version. To confirm this, I use Rust's <code>assert_eq!</code> macro:</p>
<pre><code class="lang-bash">assert_eq!(sum_single, sum_parallel);
</code></pre>
<p>If the two sums don't match, the program will panic. This ensures that parallelism doesn't compromise accuracy.</p>
<p><strong>Printing Results</strong></p>
<p>Finally, I print a comparison of the single-threaded and parallel times:</p>
<pre><code class="lang-bash">println!(<span class="hljs-string">"\nPerformance Comparison:"</span>);
println!(<span class="hljs-string">" - Single-threaded: {:?}\n - Parallel:       {:?}"</span>, duration_single, duration_parallel);
</code></pre>
<p><strong>Full code</strong></p>
<pre><code class="lang-bash">use rand::Rng;
use rayon::prelude::*;
use std::time::Instant;

fn <span class="hljs-function"><span class="hljs-title">main</span></span>() {
    // Generate a large dataset
    <span class="hljs-built_in">let</span> size = 50_000_000;
    <span class="hljs-built_in">let</span> mut rng = rand::thread_rng();
    <span class="hljs-built_in">let</span> data: Vec&lt;u32&gt; = (0..size).map(|_| rng.gen_range(0..100)).collect();

    println!(<span class="hljs-string">"Generated a vector of {} elements."</span>, size);

    // Measure single-threaded sum
    <span class="hljs-built_in">let</span> start = Instant::now();
    <span class="hljs-built_in">let</span> sum_single: u64 = data.iter().map(|&amp;x| x as u64).sum();
    <span class="hljs-built_in">let</span> duration_single = start.elapsed();
    println!(<span class="hljs-string">"Single-threaded sum: {}, took: {:?}"</span>, sum_single, duration_single);

    // Measure parallel sum
    <span class="hljs-built_in">let</span> start = Instant::now();
    <span class="hljs-built_in">let</span> sum_parallel: u64 = data.par_iter().map(|&amp;x| x as u64).sum();
    <span class="hljs-built_in">let</span> duration_parallel = start.elapsed();
    println!(<span class="hljs-string">"Parallel sum: {}, took: {:?}"</span>, sum_parallel, duration_parallel);

    // Check correctness
    assert_eq!(sum_single, sum_parallel);

    println!(<span class="hljs-string">"\nPerformance Comparison:"</span>);
    println!(<span class="hljs-string">" - Single-threaded: {:?}\n - Parallel:       {:?}"</span>, duration_single, duration_parallel);
}
</code></pre>
<p>This gives us a clear view of the performance improvement provided by parallelism.</p>
<p>Now it's time to make it run type the following:</p>
<pre><code class="lang-bash">cargo run
</code></pre>
<p>And you will see the following result:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/61hv4r3eh7bte7ok0zlf.png" alt="Cargo run result" /></p>
<p>You can see crystal clear the comparison of single threaded operation vs parallel threaded cores full CPU, in milliseconds or seconds single threaded took the operation: ~5 seconds and for multiple cores just ~ 1.7 seconds amazing.</p>
<p>We can figure out and maybe try to do another small program in different programming languages and make comparisons. What will be out of the scope of this tutorial is in your hands to give a try, maybe C or C++.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This hands-on project demonstrates the remarkable power of Rust in handling intensive data processing tasks. By comparing single-threaded and parallel approaches with a substantial dataset of 50 million numbers, we've seen how Rust's safety guarantees don't come at the cost of performance. The rayon library makes parallel programming surprisingly accessible, with just a simple change from iter() to par_iter(), we can harness the full potential of modern multi-core processors while maintaining computational accuracy.
What makes this example particularly valuable is that it showcases Rust's practical benefits: the ability to write safe, concurrent code without the typical headaches of thread management and race conditions. Whether you're building high-performance systems, working with big data, or developing complex applications, Rust's combination of safety, control, and efficiency makes it an excellent choice for modern software development.
Have you tried implementing parallel processing in Rust? Or any other language? I'd love to hear about your experiences! Drop a comment below sharing your results or thoughts about it. If you found this tutorial helpful, just gaining insights into this language, consider subscribing to stay updated on more practical Rust tutorials in the future.</p>
<p>If you have any questions or errors, please let me know, soon I will add the GitHub repository.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><a target="_blank" href="https://www.rust-lang.org/">Rust</a></li>
<li><a target="_blank" href="https://doc.rust-lang.org/book/">The Rust Book</a></li>
<li><a target="_blank" href="https://doc.rust-lang.org/std/">Standard Library</a></li>
<li><a target="_blank" href="https://crates.io/crates/rand">Rand Crate</a></li>
<li><a target="_blank" href="https://crates.io/crates/rayon">Rayon Crate</a></li>
<li><a target="_blank" href="https://crates.io/crates/reqwest">Reqwest Crate</a></li>
<li><a target="_blank" href="https://crates.io/crates/tokio">Tokio Crate</a></li>
<li><a target="_blank" href="https://crates.io/crates/serde">Serde Crate</a></li>
<li><a target="_blank" href="https://crates.io/crates/ferris-says">Ferris-Says Crate</a></li>
<li><a target="_blank" href="https://crates.io/crates/hyper">Hyper Crate</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[What is Rust, and What is it for?]]></title><description><![CDATA[Introduction
This article is about Rust as a language; as for our regular question, I won't explain the origin of the language, just the use of this almost new language. I will dig into performance, reliability, productivity, and use cases.
I'm excit...]]></description><link>https://blog.byteup.co/what-is-rust-and-what-is-it-for</link><guid isPermaLink="true">https://blog.byteup.co/what-is-rust-and-what-is-it-for</guid><category><![CDATA[Rust]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Thu, 19 Dec 2024 02:23:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734574882455/c3f37567-4007-4e5a-b671-78fb007a3970.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>This article is about Rust as a language; as for our regular question, I won't explain the origin of the language, just the use of this almost new language. I will dig into performance, reliability, productivity, and use cases.</p>
<p>I'm excited because I've been studying this language for some months, but you know the best way to learn is by doing. In this article, I won't do a small app like I did in previous articles, so you can check it out, too.</p>
<p>So, Why the use of Rust?</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/76zpi6lseu9clrs1f0vq.jpeg" alt="Rust ecosystem logo" /></p>
<h2 id="heading-performance">Performance</h2>
<p>I was reading the rust-lang.org, and I have found that one of the main use if for performance for low level language, it has memory-efficient capabilities so no runtime or various phases to run the program or app. I noted also that not using garbage collector in other words: like other languages that removes objects no longer in use.</p>
<p>This makes it extremely faster than most languages, to name a few, like Java, C#, Python, Ruby, Javascript, Go, etc. Besides that, can run on embedded devices like: Smart TVs, Digital cameras, Video game consoles, Smartwatches, E-book readers, the list is almost infinite.</p>
<h2 id="heading-reliability">Reliability</h2>
<p>As on the official page, it's explained: "Rust's rich type system and ownership model guarantee memory-safety and thread-safe, enabling you to eliminate many classes of bugs at compile-time". That means that when I'm writing code in Rust, I have a powerful ally in the compiler that prevents me from making common programming mistakes before my code even runs. That sounds really good to be true amazing, right? For instance, if I accidentally try to use a variable after I've freed its memory or if I attempt to modify data that's being accessed by multiple threads simultaneously, Rust will catch these issues during compilation.</p>
<p>Think of it like having a very meticulous code reviewer who checks every single detail of memory usage and data sharing in your program. The compiler ensures I can't shoot myself in the foot with problems like null pointer exceptions, memory leaks, or data races-- issues that are notoriously difficult to debug in Java, where the JVM's garbage collector can mask underlying memory management problems and concurrent modifications can lead to subtle runtime errors.</p>
<h2 id="heading-productivity">Productivity</h2>
<p>When I first started working with Rust, what immediately struck me was how the entire ecosystem is designed for developer productivity. Unlike many other systems programming languages, Rust doesn't leave you guessing. Its documentation is comprehensive and accessible, reading more like a helpful guide than a technical manual. For me, this is the most boring and tedious task, but we, as developers, must take it.</p>
<p>But what truly sets Rust apart is its compiler. Instead of cryptic error messages that send you down a Google rabbit hole or our great community of Stackoverflow (I love it), Rust's compiler acts like a patient mentor. It not only points out what went wrong but often suggests how to fix it. For example, if you make a common mistake with borrowing or ownership, the compiler provides clear, actionable feedback about how to correct your code.</p>
<p>The tooling ecosystem is equally impressive. Cargo, Rust's package manager, like in node we use npm modules, or in Java import packages too, Rust build tool, makes dependency management and project build feel effortless. The IDE support is top-notch -- whether you're using VS Code like me, IntelliJ, or another major editor, you'll get smart auto-completion and real-time type inspections that help you catch issues as you code. Plus, with tools like <code>rustfmt</code> automatically formatting your code as you go, you can focus on solving problems rather than arguing about code style.</p>
<h2 id="heading-use-cases">Use Cases</h2>
<p>Do you know what's fascinating about Rust? It's showing up everywhere these days. Let me paint you a picture of where Rust is making waves:</p>
<h2 id="heading-systems-and-infrastructure">Systems and Infrastructure?</h2>
<p>That's Rust's playground. Discord moved their gaming platform over to Rust and managed to cut their memory usage dramatically. Instead of their server catching fire during massive gaming sessions, Rust's memory efficiency keeps things running smoothly. Even Dropbox uses Rust for its file synchronization because when you're handling millions of people's files, you can't afford memory glitches.</p>
<p>Then there's Cloudfare, which is using Rust right at the edge of the Internet. They replaced some of their critical C code with Rust, and guess what? Better security and fewer crashes. When you're protecting websites from attacks, that's exactly what you need.</p>
<p>But here's what really gets me excited: Firefox. Mozilla (Rust's original creator) is gradually replacing Firefox's core engine parts with Rust code. Why? Because they want their browser to be fast AND secure. No more memory-related security bugs keeping their engineers up at night.</p>
<h2 id="heading-operating-systems">Operating Systems</h2>
<p>Oh yes. Microsoft is seriously looking at Rust for Windows components, I can't even believe but well let's see. They're tired of dealing with memory security bugs in C and C++ code. Even the Linux kernel (please don't kill me to say this I hope :) ) the hardcode C fortress -- is opening its doors to Rust.</p>
<p>And another cool one: Microsoft's Azure IoT Edge? Rust. Because when you're running code on tiny devices processing sensitive data, you need something that's both lightweight and bulletproof.</p>
<h2 id="heading-cryptocurrency">Cryptocurrency</h2>
<p>Even cryptocurrency folks jumped on the Rust train, but we all know it was a natural process. Projects like Solana picked Rust because they need their blockchain to be fast and absolutely secure. When you're handling people's money, there's no room for memory bugs.</p>
<p>There are countless of use cases I can't even imagine what will be the future without Rust, I love my other main languages like: Javascript, Python, Java, but his one it the one I've added to my repertoire.</p>
<p><strong>Oh one more please sir:</strong></p>
<p>Want to know what's wild? Companies like 1Password rewrote their password manager's core in Rust. Think about it, when you're protecting people's passwords this is an obvious pick, you want a language that takes security right down to the memory level.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I have shown the field of Rust, what Rust is, performance gains with this amazing popular language, and what we can do with memory issues and garbage collection so, just get rid of no more crashes. The use cases are amazing many companies are embracing this language. With its blazing performance, reliability, and developer-friendly tools, Rust is transforming everything from web browsers to blockchain platforms. While its learning curve might be steep, the payoff is clear: more reliable software, fewer critical bugs, and happier developers. As we move into an era where security and performance are non-negotiable, Rust isn't just an alternative; it's increasingly becoming the go-to choice for building the future of software.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><a target="_blank" href="https://www.rust-lang.org/">Rust Programming Language</a></li>
<li><a target="_blank" href="https://doc.rust-lang.org/">Rust Documentation</a></li>
<li><a target="_blank" href="https://crates.io/">Rust Package Registry (crates.io)</a></li>
<li><a target="_blank" href="https://blog.discord.com/how-discord-handles-two-and-half-million-concurrent-voice-users-using-rust-3f626385e9b9">Discord's Journey with Rust</a></li>
<li><a target="_blank" href="https://blog.cloudflare.com/tag/rust/">Cloudflare's Experience</a></li>
<li><a target="_blank" href="https://hacks.mozilla.org/category/rust/">Firefox and Rust</a></li>
<li><a target="_blank" href="https://this-week-in-rust.org/">This Week in Rust</a></li>
<li><a target="_blank" href="https://github.com/rust-unofficial/awesome-rust">Awesome Rust</a></li>
<li><a target="_blank" href="https://blog.rust-lang.org/">Rust Blog</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[AI Agents: Decoding the Future of Intelligent Automation]]></title><description><![CDATA[Introduction
In this faster AI field with everyday constant development, AI agents is seen it as one of the most intriguing and transformative developments; it wasn’t in the sterile laboratory or a tech conference. I have tried other tools so far thi...]]></description><link>https://blog.byteup.co/ai-agents-decoding-the-future-of-intelligent-automation</link><guid isPermaLink="true">https://blog.byteup.co/ai-agents-decoding-the-future-of-intelligent-automation</guid><category><![CDATA[ai agents]]></category><category><![CDATA[AI]]></category><category><![CDATA[#ai-tools]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Wed, 18 Dec 2024 04:08:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734565308519/b67b88c2-e32a-4c85-b14f-a57f786d1cb2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In this faster AI field with everyday constant development, AI agents is seen it as one of the most intriguing and transformative developments; it wasn’t in the sterile laboratory or a tech conference. I have tried other tools so far this year, but AI agents it’s like having your own development team, or can be many virtual assistant tools. This is like witchcraft for me, but well it’s just logical thinking this advent of the new AI era.</p>
<h2 id="heading-the-invisible-revolution">The Invisible Revolution</h2>
<p>AI agents are not the flashy robots of science fiction. They’re something far more subtle and profound intelligent systems that exist in the preliminary space between pure compútation and something that eerily resembles thought. Of course, they’re not replacements for human intelligence but amplifiers or resemble us digital companions that extend our cognitive capabilities in ways we’re only beginning to comprehend.</p>
<p>Think of them as cognitive prosthetics. Just as a physical prosthetic extends human mobility, AI agents extend our mental reach. Those artifacts don’t think for us; they thin with us as a tools, revealing pathways of logic and creativity never explored that remain hidden in our perspectives.</p>
<h2 id="heading-the-anatomy-of-intelligence">The Anatomy of Intelligence</h2>
<p>What makes an AI agent truly fascinating is not its raw computational power, but its capacity for contextual understanding. Traditional software follows instructions: AI agents interpret intentions. They don’t just process data they understand narratives, recognize emotional nuances and adapt in real-time.</p>
<p>Consider the difference between a translation app and an AI translator. The app mechanically converts words;the AI agent captures context, understand idiomatic expressions, and virtually bridges human communication gaps. It’s not just translation it’s understanding.</p>
<h2 id="heading-beyond-the-binary-adaptive-intelligence">Beyond the Binary: Adaptive Intelligence</h2>
<p>The most revolutionary aspect of AI agents is their ability to learn and evolve. They’re not static algorithms but dynamic entities that grow through interaction. Each conversation and each problem solved becomes part of their expanding intelligence. I tried to train this chat model as a friend, but I know thousands of servers are cumbersome and are linked to each other, spreading mini-tasks and algorithms everywhere.</p>
<p>In my own work developing complex software systems, I’ve watched AI agents transform from rudimentary tools to sophisticated collaborators; I get some kind of nostalgia for a short-term past this is too fast for me, for all I mean. They challenge my assumptions, suggest innovative approaches, and often see solutions that emerge from the complex interplay of data in ways no human could instantaneously perceive.</p>
<h2 id="heading-use-cases-examples-just-few">Use Cases Examples just Few</h2>
<h2 id="heading-1-customer-service-and-support-agents">1. Customer Service and Support Agents</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/edxsfqoehtvj55zin9km.jpeg" alt="Customer support AI virtual agent" /></p>
<p><strong>Description</strong>: AI-driven virtual assistants and chatbots that can handle common questions, process requests, and resolve customer issues interactively.</p>
<ul>
<li><p><strong>E-commerce helpdesk</strong>: Offering product recommendations, handling order inquiries, and processing returns.</p>
</li>
<li><p><strong>Banking &amp; Insurance</strong>: Automating routine tasks like balance checks, passwords, resets, or initiating clams.</p>
</li>
</ul>
<p>These agents reduce wait times and provide 24/7 support, these is just some basic functions of these it, so the humans can focus on more complex inquiries.</p>
<h2 id="heading-2-personal-assistants-and-productivity-tools">2. Personal Assistants and Productivity Tools</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aye0tkky40hafl0f4438.jpeg" alt="Personal assistant and productivity tools" /></p>
<p><strong>Description</strong>: AI agents that understand user queries, manage calendar appointments, set reminders, and help users organize daily tasks.</p>
<ul>
<li><p><strong>Virtual Personal Assistants (VPAs)</strong>: Siri, Google Assistant, Amazon Alexa for scheduling meetings, controlling smart homes, and retrieving information.</p>
</li>
<li><p><strong>Workplace Productivity Bots</strong>: Slack bots or Microsoft Teams assistants that can summarize meeting notes, track to-dos, and schedule follows-ups.</p>
</li>
</ul>
<p>They streamline daily routines, enhance productivity, and reduce the cognitive load of task management.</p>
<h2 id="heading-3-autonomous-vehicles-and-robotics">3. Autonomous Vehicles and Robotics</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m664a43xd8c66zwnxoo1.jpeg" alt="Autonomous vehicles and robotics" /></p>
<p><strong>Description:</strong> AI agents that navigate physical environments using computer vision, sensor data, and machine learning to act autonomously.</p>
<ul>
<li><p><strong>Self-Driving Cars:</strong> Perceive surrounding vehicles, pedestrians, traffic signals, and road conditions to make safe driving decisions.</p>
</li>
<li><p><strong>Warehouse Robotics:</strong> Picking and packing items efficiently in logistics centers, guided by AI-driven route planning and object recognition.</p>
</li>
</ul>
<p>They improve safety and increase operational efficiency across industries like transportation, logistics, and manufacturing.</p>
<h2 id="heading-4-healthcare-assistants-and-diagnostic-tools">4. Healthcare Assistants and Diagnostic Tools</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y49l6gnpgm8yux4tyi0a.jpeg" alt="Healthcare assistants and diagnostic" /></p>
<p><strong>Description:</strong> AI agents that assist doctors, nurses, or patients by analyzing medical data, recommending treatments, or monitoring patient health.</p>
<ul>
<li><p><strong>Diagnostic Assistants:</strong> AI agents analyze medical images (X-rays, MRIs) and electronic health records to flag anomalies or suggest diagnoses.</p>
</li>
<li><p><strong>Virtual Nursing Assistants:</strong> Agents that answer patient queries, remind patients to take medications, and monitor vital signs remotely.</p>
</li>
</ul>
<p>It helps to reduce clinician workload improve diagnostic, and continuous patient monitoring.</p>
<h2 id="heading-5-financial-trading-and-portfolio-management">5. Financial Trading and Portfolio Management</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8z7dzep9uxsu1v67q867.jpeg" alt="Financial trading and portfolio management" /></p>
<p><strong>Description:</strong> AI agents that analyze market data, predict trends, and execute trades based on strategic goals, total automatization of trades with no human errors by emotions.</p>
<ul>
<li><p><strong>Algorithmic Trading Bots:</strong> Continuously scan markets, evaluate risk, and place buy/sell orders to capitalize on market opportunities.</p>
</li>
<li><p><strong>Robo-Advisors:</strong> Offer personalized investment recommendations based on user-defined risk profiles and financial goals.</p>
</li>
</ul>
<p>As humans trading it’s the hardest taking decision to buy or sell simple because we are really emotional, so we can lost trade opportunities or lost trades because hungry for money.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I don't want to stress this is all of this matter; this is a huge topic for the coming years, not relevant to say in just one single article, but keep in mind this is just an illustration of the beginning but already of this technology. AI agents emerge not as distant, impersonal technologies but as collaborative panthers in our collective journey of innovation. This kind of technology challenges us to reimagine the boundaries of intelligence, creativity, and problem-solving–inviting us to become active participants in a narrative that extends far beyond code and algorithms. I ask you, dear reader, colleague, casual reader, whatever your field, to share your thoughts. What possibilities do you see in these intelligent systems? Or we as humans can able to deliver right now the know-how to do things, if we really are ready for this technology. Well, so please drop a comment below thank you.</p>
<h2 id="heading-references">References</h2>
<h2 id="heading-research">Research</h2>
<ul>
<li><p><a target="_blank" href="https://www.technologyreview.com/topic/artificial-intelligence/">MIT Technology Review</a></p>
</li>
<li><p><a target="_blank" href="https://ai.stanford.edu/">Stanford AI Lab</a></p>
</li>
<li><p><a target="_blank" href="https://arxiv.org/list/cs.AI/recent">arXiv AI Research</a></p>
</li>
</ul>
<h2 id="heading-industry-insights">Industry Insights</h2>
<ul>
<li><p><a target="_blank" href="https://ai.googleblog.com/">Google AI Blog</a></p>
</li>
<li><p><a target="_blank" href="https://openai.com/research">OpenAI Research</a></p>
</li>
<li><p><a target="_blank" href="https://deepmind.com/research">DeepMind</a></p>
</li>
</ul>
<h2 id="heading-tech-publications">Tech Publications</h2>
<ul>
<li><p><a target="_blank" href="https://www.wired.com/category/artificial-intelligence/">Wired AI</a></p>
</li>
<li><p><a target="_blank" href="https://arstechnica.com/gadgets/ai/">Ars Technica AI</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Quantum Computing Development 2024]]></title><description><![CDATA[An Introduction to Quantum Computing
In the following reading, I will explain Quantum as 2024, what is Quantum but I won’t deep dive into details.
Quantum computing will emerge in the coming years and well I can say from today, we can see it. I love ...]]></description><link>https://blog.byteup.co/quantum-computing-development-2024</link><guid isPermaLink="true">https://blog.byteup.co/quantum-computing-development-2024</guid><category><![CDATA[quantum computing]]></category><category><![CDATA[Qubits]]></category><category><![CDATA[supercomputers]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Tue, 17 Dec 2024 01:12:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734396406365/4316c785-220f-4c66-8be6-cc01d9f89177.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-an-introduction-to-quantum-computing">An Introduction to Quantum Computing</h2>
<p>In the following reading, I will explain Quantum as 2024, what is Quantum but I won’t deep dive into details.</p>
<p>Quantum computing will emerge in the coming years and well I can say from today, we can see it. I love technology as an engineer I have seen and coded many things, I hope will try to do my best to show you what is this Quantum computer thing.</p>
<p>This will be a revolution for everyone in this particular field that is software development, the way we code will be change forever not just binaries 0 and 1 but Qubits hypothetical not 0 or 1 but probabilities in the quantum bit or qubit. Qubits can exist in multiple states simultaneously through a phenomenon called superpostion either dead or alive not like Schrödinger's cat it can be both at the same time.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c63otl6zb87pwgahzdi5.jpg" alt="Schrodinger cat" /></p>
<p><strong>Qubit geometric representation</strong></p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ff4txwc9vj4dt9q3wj4.jpg" alt="Qubit geometrical representation" /></p>
<h2 id="heading-current-qubit-technologies">Current Qubit Technologies</h2>
<h2 id="heading-superconducting-qubits">Superconducting Qubits</h2>
<p>Dominant technology used by major tech companies:Anyon Systems, Atlantic Quantum, Bleximo, IQM, Rigetti Computing. Offers high control and relatively stable quantum states. Challenges include maintaining coherence (like a way to have a quantum system to keep a relationship between different states in a superposition) and reducing error rates</p>
<h2 id="heading-trapped-ion-qubits">Trapped Ion Qubits</h2>
<p>Provides exceptional quantum coherence. The qubits of a trapped ion quantum computer are ions that are trapped by electric fields and manipulated using lasers.</p>
<h2 id="heading-topological-qubits">Topological Qubits</h2>
<p>It’s a type quantum qubit that store and process information in a common way that is inherently protected from errors caused by local disturbances. In principle, perform any computation that a conventional quantum computer can do, and vice versa. This gives an error-free operation of it’s logic circuits, with an extreme accuracy.</p>
<h2 id="heading-key-development-trends">Key Development Trends</h2>
<h2 id="heading-quantum-algorithm-development">Quantum Algorithm Development</h2>
<p>This is a new matter in the field, so many researchers and developers (here we are we can join the party in the coming years I hope with the right knowledge) are in constant focus on how to improve or create algorithms that can solve complex problems more efficiently than classical algorithms. Primary areas of focus include:</p>
<ul>
<li><p>Optimization problems</p>
</li>
<li><p>Cryptography</p>
</li>
<li><p>Molecular and material simulation</p>
</li>
<li><p>Machine learning acceleration</p>
</li>
</ul>
<h2 id="heading-quantum-machine-learning">Quantum Machine Learning</h2>
<p>Here in this phase of AI and Machine learning trending now, it’s crucial to understand the basics first so then can be good at quantum developing areas, this can potentially improve the Quantum machine learning algorithms:</p>
<ul>
<li><p>Process massive datasets exponentially faster</p>
</li>
<li><p>Create more complex neural network architectures</p>
</li>
<li><p>Solve non-linear optimization problems with unprecedented efficiency</p>
</li>
</ul>
<h2 id="heading-quantum-cloud-services">Quantum Cloud Services</h2>
<p>Major actors cloud providers like AWS, Google Cloud, and Microsoft Azure have significantly expanded their quantum computing offerings:</p>
<ul>
<li><p>Providing access to quantum hardware</p>
</li>
<li><p>Developing quantum simulation environments</p>
</li>
<li><p>Bestows quantum algorithm development tools</p>
</li>
<li><p>Creating standardized quantum computing APIs</p>
</li>
</ul>
<h2 id="heading-quantum-cryptography-and-security">Quantum Cryptography and Security</h2>
<p>I know many people will say here myself included, this will break all passwords and blockchain technology, but it not as easy as it sounds because will be some areas of specialization like:</p>
<ul>
<li><p>Post-quantum cryptographic algorithms</p>
</li>
<li><p>Quantum key distribution techniques</p>
</li>
<li><p>Quantum-safe encryption standards</p>
</li>
<li><p>Creating resilient communication protocols</p>
</li>
</ul>
<h2 id="heading-industrial-applications">Industrial Applications</h2>
<h2 id="heading-pharmaceutical-and-chemical-research">Pharmaceutical and Chemical Research</h2>
<p>Quantum computers are evolving drug discovery and molecular simulation:</p>
<ul>
<li><p>Modeling complex molecular interactions</p>
</li>
<li><p>Predicting protein folding</p>
</li>
<li><p>Designing new materials with specific properties</p>
</li>
<li><p>Accelerating chemical reaction simulations</p>
</li>
</ul>
<h2 id="heading-financial-modeling">Financial Modeling</h2>
<p>I love to build MQL4 and MQL5 bots to trade the financial market automatically, especially in forex and cryptos, so I can't imagine this will be another revolution apart from the one already with AI, too much research ahead for this field. Besides that, financial institutions are exploring quantum computing for:</p>
<ul>
<li><p>Risk management assessment optimization</p>
</li>
<li><p>Portfolio optimization</p>
</li>
<li><p>High-frequency (HF) trading strategies</p>
</li>
<li><p>Fraud detection algorithms</p>
</li>
</ul>
<h2 id="heading-aerospace-and-defence">Aerospace and Defence</h2>
<h2 id="heading-applications-will-be-found-in">Applications will be found in:</h2>
<ul>
<li><p>Advanced simulation of air defense systems</p>
</li>
<li><p>Optimization of logistics and supply chains</p>
</li>
<li><p>Cryptographic security</p>
</li>
<li><p>Sophisticated computational modeling</p>
</li>
</ul>
<h2 id="heading-challenges-and-limitations">Challenges and Limitations</h2>
<h2 id="heading-technical-challenges">Technical Challenges</h2>
<ul>
<li><p>Quantum decoherence is the process by which a quantum system loses its quantum properties and coherence when it interacts with its environment.</p>
</li>
<li><p>Error correction</p>
</li>
<li><p>Scalability of quantum systems</p>
</li>
<li><p>Maintaining qubit stability</p>
</li>
</ul>
<h2 id="heading-some-considerations-to-keep-in-mind">Some Considerations to Keep in Mind</h2>
<p>At the current time there, this technology still has many challenges to overcome like: High development and maintenance costs due to the complex supercomputer not even implement for commercial use yet. Limited number of quantum computer experts in this particular field, and this is like just the beginning point.</p>
<h2 id="heading-future-outlook">Future Outlook</h2>
<ul>
<li><p>Continued improvements in qubit stability</p>
</li>
<li><p>More accessible quantum development tools</p>
</li>
<li><p>Increased industrial pilot projects</p>
</li>
<li><p>Standardization of quantum computing frameworks</p>
</li>
</ul>
<p>This just a small article in the quantum computer I hope can able to deliver more on this topic because it’s crucial for software development future after the AI trend this will be the next one if not now.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="https://www.ibm.com/quantum">IBM Quantum Computing Research</a></p>
</li>
<li><p><a target="_blank" href="https://www.nature.com/subjects/quantum-computing">Nature: Quantum Computing Special Issue</a></p>
</li>
<li><p><a target="_blank" href="https://quantumai.google">Google Quantum AI Laboratory</a></p>
</li>
<li><p><a target="_blank" href="https://www.technologyreview.com/topic/quantum-computing">MIT Technology Review - Quantum Computing</a></p>
</li>
<li><p><a target="_blank" href="https://www.nist.gov/programs-projects/quantum-information-science">National Institute of Standards and Technology (NIST) Quantum Information Program</a></p>
</li>
<li><p><a target="_blank" href="https://quantumcomputingreport.com">Quantum Computing Report</a></p>
</li>
<li><p><a target="_blank" href="https://queue.acm.org">ACM Queue - Quantum Computing Research</a></p>
</li>
<li><p><a target="_blank" href="https://spectrum.ieee.org/tag/quantum-computing">IEEE Spectrum - Quantum Computing Section</a></p>
</li>
<li><p><a target="_blank" href="https://arxiv.org/list/quant-ph/recent">arXiv Quantum Physics Section</a></p>
</li>
<li><p><a target="_blank" href="https://www.microsoft.com/en-us/quantum/development-kit">Microsoft Quantum Development Kit</a></p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Quantum computing in December 2024 represents a pivotal moment of technological transition. I don't really say that this is the mainstream technology yet; it stands on the cusp of practical, widespread implementation. The convergence of advanced algorithm design, improved hardware, and growing industrial interest suggest that quantum computing is moving from a primarily academic pursuit to a transformative technological paradigm. As for us developers, it will take us some time to adapt to these transition technologies time is not new for us we can make it all the time.</p>
]]></content:encoded></item><item><title><![CDATA[The AI Revolution: How Generative AI is Reshaping Our World]]></title><description><![CDATA[A Brief Introduction
In the rapidly evolving landscape of technology, artificial intelligence has emerged as the most transformative force of our time. Generative AI, in particular, has captured the imagination of industries, professionals, and every...]]></description><link>https://blog.byteup.co/the-ai-revolution-how-generative-ai-is-reshaping-our-world</link><guid isPermaLink="true">https://blog.byteup.co/the-ai-revolution-how-generative-ai-is-reshaping-our-world</guid><category><![CDATA[AI News and Updates]]></category><category><![CDATA[AI]]></category><category><![CDATA[generative ai]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[technology]]></category><category><![CDATA[Technical writing ]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Wed, 11 Dec 2024 03:04:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733883591374/f77fa3cc-716b-4bba-b815-cbc21be6b8bf.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-a-brief-introduction">A Brief Introduction</h2>
<p>In the rapidly evolving landscape of technology, artificial intelligence has emerged as the most transformative force of our time. Generative AI, in particular, has captured the imagination of industries, professionals, and everyday users alike, promising to revolutionize how we work, create, and solve complex problems.</p>
<hr />
<h2 id="heading-the-rise-of-generative-ai-more-than-just-a-buzzword">The Rise of Generative AI: More Than Just a Buzzword</h2>
<p>A few years ago, AI was primarily associated with data analysis and simple automation. Today, generative AI has shattered those limitations, demonstrating an unprecedented ability to create original content, solve complex problems, and provide insights across multiple domains.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5910uz1clf03x0dmsh9x.jpeg" alt="People collaboring" /></p>
<hr />
<h2 id="heading-transforming-creative-industries">Transforming Creative Industries</h2>
<p>Generative AI has particularly disrupted the creative sector. Writers, designers, musicians, and artists are discovering powerful new tools that augment their creativity. AI can now:</p>
<ul>
<li>Generate initial drafts of creative writing</li>
<li>Create complex visual designs</li>
<li>Compose original music</li>
<li>Develop unique artwork</li>
<li>Assist in storyboarding and concept development</li>
</ul>
<p>These tools don't replace human creativity but expand the boundaries of what's possible. They serve as collaborative partners, offering novel perspectives and breaking through creative blockages.</p>
<hr />
<h2 id="heading-revolutionizing-business-and-professional-workflows">Revolutionizing Business and Professional Workflows</h2>
<p>Beyond creativity, generative AI is fundamentally changing how businesses operate:</p>
<ul>
<li><strong>Customer Service</strong>: AI-powered chatbots and support systems provide more nuanced, context-aware interactions.</li>
<li><strong>Product Development</strong>: Rapid prototyping and idea generation have been accelerated through AI-assisted design.</li>
<li><strong>Market Analysis</strong>: Complex data sets can be quickly analyzed, with AI generating actionable insights.</li>
<li><strong>Training and Education</strong>: Personalized learning experiences are being crafted using adaptive AI technologies.</li>
</ul>
<hr />
<h2 id="heading-breaking-new-ground-in-scientific-research">Breaking New Ground in Scientific Research</h2>
<p>Scientific research is experiencing a renaissance with AI technologies. Machine learning algorithms can now:</p>
<ul>
<li>Predict complex molecular structures</li>
<li>Assist in medical diagnosis</li>
<li>Model climate change scenarios</li>
<li>Accelerate drug discovery processes</li>
<li>Analyze massive scientific datasets</li>
</ul>
<p>The computational power of AI is helping researchers solve problems that would take human experts decades to unravel.</p>
<hr />
<h2 id="heading-ethical-considerations-and-challenges">Ethical Considerations and Challenges</h2>
<p>With great technological power comes significant responsibility. The AI revolution isn't without its challenges:</p>
<ul>
<li><strong>Privacy Concerns</strong>: How do we protect individual data?</li>
<li><strong>Bias Mitigation</strong>: Ensuring AI systems are fair and unbiased</li>
<li><strong>Job Market Transformation</strong>: Understanding and managing workforce transitions</li>
<li><strong>Regulatory Frameworks</strong>: Developing responsible guidelines for AI development</li>
</ul>
<p>These challenges require collaborative efforts from technologists, ethicists, policymakers, and society.</p>
<hr />
<h2 id="heading-the-human-ai-collaboration-model">The Human-AI Collaboration Model</h2>
<p>The most exciting aspect of generative AI isn't about replacement but collaboration. The most effective approach sees AI as a powerful tool that enhances human capabilities rather than competing with them.</p>
<p>Imagine a world where:</p>
<ul>
<li>Writers use AI to overcome writer's block</li>
<li>Doctors leverage AI for more accurate diagnoses</li>
<li>Engineers design more efficient solutions with AI assistance</li>
<li>Educators create personalized learning experiences</li>
</ul>
<hr />
<h2 id="heading-looking-to-the-future">Looking to the Future</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5agla1cbuqggjlnrkflx.jpeg" alt="Future of AI" /></p>
<p>The next decade will likely see even more remarkable developments:</p>
<ul>
<li>More sophisticated natural language interactions</li>
<li>Enhanced personalization across services</li>
<li>Improved problem-solving capabilities</li>
<li>More seamless integration of AI in daily life</li>
</ul>
<p>Generative AI is not just a technological trend—it's a fundamental shift in how we approach creativity, problem-solving, and innovation.</p>
<hr />
<h2 id="heading-embracing-the-ai-revolution">Embracing the AI Revolution</h2>
<p>As we stand on the cusp of this technological transformation, one thing becomes clear: adaptability is key. Those who learn to work alongside AI and understand its capabilities and limitations will be best positioned to thrive in this new landscape.</p>
<p>The AI revolution isn't about technology replacing humans—it's about humans and technology creating something extraordinary together.</p>
<h2 id="heading-references">References</h2>
<ol>
<li><a target="_blank" href="https://www.mckinsey.com/capabilities/quantumblack/our-insights/the-state-of-ai-in-2023-and-2024-generative-ais-breakout-year">McKinsey - The State of AI in 2023 and 2024: Generative AI's Breakout Year</a></li>
<li><a target="_blank" href="https://www.nature.com/articles/d41586-023-03300-x">Nature - Generative AI Transforming Scientific Research</a></li>
<li><a target="_blank" href="https://www.wired.com/story/ai-is-transforming-creative-work/">Wired - AI Transforming Creative Work</a></li>
<li><a target="_blank" href="https://hbr.org/2023/11/collaborative-intelligence-humans-and-ai-are-joining-forces">Harvard Business Review - Collaborative Intelligence</a></li>
<li><a target="_blank" href="https://www.science.org/content/article/what-generative-ai-means-science">Science Magazine - What Generative AI Means for Science</a></li>
<li><a target="_blank" href="https://www.nature.com/articles/d41586-023-02623-2">Nature - Ethical AI Development</a></li>
<li><a target="_blank" href="https://www.forbes.com/sites/bernardmarr/2023/10/30/the-future-of-work-how-humans-and-ai-will-work-together/">Forbes - The Future of Work: Humans and AI</a></li>
<li><a target="_blank" href="https://www.technologyreview.com/2024/01/08/1086552/the-future-of-generative-ai/">MIT Technology Review - Future of Generative AI</a></li>
</ol>
<p>The future is not just artificial—it's intelligently collaborative.</p>
]]></content:encoded></item><item><title><![CDATA[Meet Claude: The Digital Companion in the World of Artificial Intelligence]]></title><description><![CDATA[Introduction
In the ever-advancing landscape of artificial intelligence, one name is reshaping the way we think about digital assistance: Claude. Envision an intelligent companion that effortlessly transitions from drafting detailed project proposals...]]></description><link>https://blog.byteup.co/meet-claude-the-digital-companion-in-the-world-of-artificial-intelligence</link><guid isPermaLink="true">https://blog.byteup.co/meet-claude-the-digital-companion-in-the-world-of-artificial-intelligence</guid><category><![CDATA[AI]]></category><category><![CDATA[claude.ai]]></category><category><![CDATA[technology]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Tue, 10 Dec 2024 00:05:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733788983391/a3988c93-c3c2-4952-8d9a-70790a695115.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In the ever-advancing landscape of artificial intelligence, one name is reshaping the way we think about digital assistance: Claude. Envision an intelligent companion that effortlessly transitions from drafting detailed project proposals to explaining complex scientific theories and even brainstorming imaginative story ideas—all with precision and speed. Claude isn't just another AI tool; it's a revolutionary partner in productivity and creativity.</p>
<hr />
<h2 id="heading-not-just-another-chatbot">Not Just Another Chatbot</h2>
<p>Claude redefines what a digital assistant can be. While most AI systems are designed for basic, predefined tasks, Claude breaks barriers with its ability to engage in sophisticated, multi-domain interactions. Think of it as a digital Swiss Army knife—a versatile tool that adapts to the diverse demands of professionals, students, and creatives alike.</p>
<hr />
<h2 id="heading-transforming-writing-into-a-seamless-collaboration">Transforming Writing Into a Seamless Collaboration</h2>
<p>For writers in any field, Claude is a game-changer. Its capabilities go beyond simple grammar checks or autocorrect features. Whether you're crafting a formal research paper, drafting a business proposal, or writing a blog post, Claude tailors its assistance to your specific needs. It offers everything from brainstorming ideas and structuring content to refining tone and style.</p>
<p>Claude’s strength lies in its adaptability. It can seamlessly switch between professional business language for job applications and casual conversational tones for blog posts. Its nuanced understanding of language allows it to cater to the distinct demands of academic, technical, and creative writing, ensuring every piece is polished and impactful.</p>
<hr />
<h2 id="heading-mastering-analysis-simplifying-complexity">Mastering Analysis: Simplifying Complexity</h2>
<p>Claude excels in tackling complex problems with clarity. It dissects intricate challenges and provides detailed, step-by-step solutions. From simplifying advanced mathematical concepts to mapping out strategic business decisions, Claude ensures that users gain a deeper understanding of the issues at hand.</p>
<p>More than just giving answers, Claude fosters critical thinking by walking users through reasoning processes. Whether you're analyzing data, making strategic decisions, or solving difficult puzzles, Claude offers insights and guidance that empower you to approach challenges methodically.</p>
<hr />
<h2 id="heading-technical-expertise-a-developers-best-friend">Technical Expertise: A Developer’s Best Friend</h2>
<p>For tech enthusiasts, Claude is a powerful ally. Its technical proficiency spans multiple programming languages, making it a valuable assistant for both beginners and experienced developers. It can generate code, debug errors, and explain algorithms in simple terms, bridging the gap between complexity and comprehension.</p>
<p>What sets Claude apart is its focus on teaching. It doesn’t just provide ready-made code—it explains the logic behind the solution, enabling users to understand not just how the code works, but why it works that way. This collaborative approach enhances technical knowledge and problem-solving skills.</p>
<hr />
<h2 id="heading-amplifying-creativity">Amplifying Creativity</h2>
<p>Creativity goes beyond art—it’s about thinking innovatively and solving problems in new ways. Claude acts as a creative partner, sparking ideas for marketing campaigns, helping to build story arcs, and suggesting fresh narrative perspectives.</p>
<p>Instead of replacing creativity, Claude amplifies it. By introducing unique ideas and perspectives, it helps users explore paths they might not have considered on their own. Whether you’re developing a novel, crafting a screenplay, or designing a campaign, Claude’s input can be the catalyst for groundbreaking ideas.</p>
<hr />
<h2 id="heading-ethical-ai-built-with-responsibility">Ethical AI: Built With Responsibility</h2>
<p>Despite its power, Claude is designed with a commitment to ethical principles. It avoids generating harmful or misleading content, ensuring every interaction is constructive and transparent. Its goal is not just to be helpful but to be a trustworthy tool that prioritizes user safety and positive outcomes.</p>
<hr />
<h2 id="heading-the-future-of-digital-assistance">The Future of Digital Assistance</h2>
<p>Claude is a glimpse into the future of AI-powered tools, where human potential and artificial intelligence work in harmony. It’s not about replacing human creativity or expertise but enhancing it—offering support, insights, and solutions across a wide range of tasks and industries.</p>
<p>As AI continues to evolve, tools like Claude will redefine the way we work, learn, and create. Whether you're a professional seeking efficiency, a student looking for clarity, or a creative pushing boundaries, Claude offers a new standard of digital assistance.</p>
<hr />
<h2 id="heading-references">References</h2>
<ul>
<li>https://www.anthropic.com/claude</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Develop a Dynamic Inflation Data Visualizer with Flask Python Matplot Pandas]]></title><description><![CDATA[Introduction
At this time, when many places in the world have inflation, and everybody is talking about it, I decided to do an inflation calculator. First, let me explain what inflation is.
I love economics, but as you know, I am a software developer...]]></description><link>https://blog.byteup.co/develop-a-dynamic-inflation-data-visualizer-with-flask-python-matplot-pandas</link><guid isPermaLink="true">https://blog.byteup.co/develop-a-dynamic-inflation-data-visualizer-with-flask-python-matplot-pandas</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Python]]></category><category><![CDATA[Flask Framework]]></category><category><![CDATA[Matplotlib]]></category><category><![CDATA[pandas]]></category><category><![CDATA[economics]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Tue, 08 Oct 2024 17:06:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728359257771/83590f63-b59b-4d06-a2ef-350caede2df2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>At this time, when many places in the world have inflation, and everybody is talking about it, I decided to do an inflation calculator. First, let me explain what inflation is.</p>
<p>I love economics, but as you know, I am a software developer. So, I will have the following reference from a well-known book in economics:</p>
<p>"In the XVI century, gold and silver deposits in the American Continent were discovered and exploited, and enormous quantities of the precious metals were transported to Europe. The result of this increase in the quantity of money was a general tendency for prices in Europe to move upward. In the same way, today, when a government increases the amount fo paper money, the result is that the purchasing power of the unit of currency begins to fall, and prices begin to rise. This is called inflation". As you can see, it is an excellent explanation from a great writer in economics.</p>
<p>Excerpted from "Economic Policy book by Ludwid Von Mises, (4th Conference, pg: 32)</p>
<p>Now it's time to work on the program that will show us the U.S. inflation relative calculator:</p>
<h2 id="heading-requirements"><strong>Requirements:</strong></h2>
<ul>
<li><p>In the program, a user inputs a determined starting year and end year, with boundaries from 1947 to 2024 or the current year.</p>
</li>
<li><p>I will take a <a target="_blank" href="https://fred.stlouisfed.org/docs/api/api_key.html">FRED (Federal Reserve Bank of St. Louis) API</a> from the USA that gathers all economics data from the USA. You can also utilize public data from your country, but I'm using the US public economics data for educational purposes.</p>
</li>
<li><p>Once I connect to the API, the program will generate a PNG to show the data.</p>
</li>
</ul>
<h2 id="heading-setting-up-the-environment"><strong>Setting Up the Environment</strong></h2>
<h2 id="heading-prerequisites"><strong>Prerequisites:</strong></h2>
<ul>
<li><p>Basic Python language</p>
</li>
<li><p>Code editor</p>
</li>
<li><p>Basic command line</p>
</li>
</ul>
<h2 id="heading-step-1-setting-up-the-project"><strong>Step 1: Setting Up the Project</strong></h2>
<ul>
<li>Install Python <a target="_blank" href="https://www.python.org/downloads/">here</a>. From the Python page, download the latest stable version of Python. Once you've downloaded the installation file, execute it, install it on your computer, and follow all recommended prompts. Clone the repository and move to it:</li>
</ul>
<p>Code: <a target="_blank" href="https://github.com/ivansing/inflation-tracker.git">inflation-tracker-app</a></p>
<p>Your project's path:</p>
<p><code>/home/your-username/Projects/my_project</code> (Linux)</p>
<p><code>/Users/your-username/Projects/my_project</code> (Mac)</p>
<ul>
<li><p>Open VS Code at the top of the bar and press <code>Terminal in the dropdown box. Select</code> New Terminal`.</p>
</li>
<li><p>For Windows using subsystem WSL:</p>
</li>
<li><p>Follow the previous steps from Linux/Mac.</p>
</li>
</ul>
<p>Type the following command in the terminal:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> inflation-tracker
</code></pre>
<p>In the <code>inflation-tracker</code> type the following in the terminal:</p>
<pre><code class="lang-bash">mkdir static templates
</code></pre>
<p>This will create two directories: <code>static</code> to store assets PNG image and <code>templates</code> where I code the HTML code to show UI.</p>
<p>I will create the following two files: <a target="_blank" href="http://app.py"><code>app.py</code></a> as the entry point for the application to work and the <code>.env</code> file to store sensitive information like the API secret key that I will use in this project:</p>
<pre><code class="lang-bash">touch app.py .env
</code></pre>
<h2 id="heading-step-2install-libraries"><strong>Step 2:Install libraries</strong></h2>
<pre><code class="lang-bash">pip install Flask requests pandas matplotlib dotenv
</code></pre>
<p>So, those were quite too many libraries, but they will ensure that the program works like charm magic. Here, it was installed <code>In Flask</code> to render the <code>index.html</code> file, <code>requests</code> to resolve or read the given URL path, a famous Data Science Python library <code>pandas</code> for data manipulation analysis, handling structured data such as tables, spreadsheets, and time series, <code>matplotlib.pyplot</code> to plot to have an output to visualize data in graphs, and finally <code>load_dotenv</code> to load <code>.env</code> sensitive secret key.</p>
<p>Before writing the code, you need to get the API key to retrieve the information from FRED:</p>
<p>Sign Up for an account with just your email and set a password in the right upper corner where it reads My Account:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96071acoyqmibr1qsn0p.png" alt="FRED landing page" /></p>
<p>Then register as shown in tabs select "Create New Account" with your email and password or you can use with Google but for the moment is not enable that feature:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llr31mol3m0lzo170b5c.png" alt="FRED register" /></p>
<p>After that just press "Okay" button to follow to the dashboard:</p>
<p>Now that you are in the dashboard see the button "Request or view your API keys"</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wpeeroynp2mf583q3mi0.png" alt="FRED request or see API key" /></p>
<p>Then you have to explain why the request of data so as student this will be education purposes:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b2ho54do6eedjjup5r6q.png" alt="FRED why data requests" /></p>
<p>After that, check the result API key:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20v6unleqg59g0u3mpr2.png" alt="FRED generated apikey" /></p>
<p>Finally, check the result I have mine it's secret so you have to use this one in the <code>.env</code> in the following steps:</p>
<p>Remember that I've created the <code>.env</code> file paste key like this:</p>
<pre><code class="lang-bash">API_KEY=paste-here-your-key-without-any-other-symbol
</code></pre>
<p>So, for now in this part I'm done with the <code>.env</code> secure secret key.</p>
<h2 id="heading-step-3-write-the-code"><strong>Step 3: Write the code</strong></h2>
<p><strong>Import the libraries:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, render_template, request
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
<span class="hljs-keyword">import</span> os 
<span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv
</code></pre>
<p><strong>app.py rest of the code:</strong></p>
<pre><code class="lang-python">load_dotenv()

app = Flask(__name__)

<span class="hljs-meta">@app.route('/', methods=['GET', 'POST'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span>():</span>
    plot_url = <span class="hljs-literal">None</span>

    <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">'POST'</span>:
        start_year = int(request.form[<span class="hljs-string">'start_year'</span>])
        end_year = int(request.form[<span class="hljs-string">'end_year'</span>])


        API_KEY = os.getenv(<span class="hljs-string">"API_KEY"</span>)
        url = <span class="hljs-string">f"https://api.stlouisfed.org/fred/series/observations?series_id=CPIAUCSL&amp;api_key=<span class="hljs-subst">{API_KEY}</span>&amp;file_type=json"</span>

        response = requests.get(url)

        <span class="hljs-keyword">if</span> response.status_code == <span class="hljs-number">200</span>:
            data = response.json()


            df = pd.DataFrame(data[<span class="hljs-string">'observations'</span>])
            df[<span class="hljs-string">'value'</span>] = df[<span class="hljs-string">'value'</span>].astype(float)
            df[<span class="hljs-string">'date'</span>] = pd.to_datetime(df[<span class="hljs-string">'date'</span>])


            inflation_start_year = df[df[<span class="hljs-string">'date'</span>].dt.year == start_year][<span class="hljs-string">'value'</span>].values[<span class="hljs-number">0</span>] <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> df[df[<span class="hljs-string">'date'</span>].dt.year == start_year].empty <span class="hljs-keyword">else</span> <span class="hljs-number">0</span>


            df[<span class="hljs-string">'normalized_inflation'</span>] = ((df[<span class="hljs-string">'value'</span>] - inflation_start_year) / inflation_start_year) * <span class="hljs-number">100</span>


            df_filtered = df[(df[<span class="hljs-string">'date'</span>].dt.year &gt;= start_year) &amp; (df[<span class="hljs-string">'date'</span>].dt.year &lt;= end_year)]


            average_normalized_inflation = df_filtered[<span class="hljs-string">'normalized_inflation'</span>].mean()
            print(<span class="hljs-string">f"Average Normalized Inflation Rate from <span class="hljs-subst">{start_year}</span> to <span class="hljs-subst">{end_year}</span>: <span class="hljs-subst">{average_normalized_inflation:<span class="hljs-number">.2</span>f}</span>%"</span>)

            plt.figure(figsize=(<span class="hljs-number">10</span>, <span class="hljs-number">6</span>))
            plt.plot(df_filtered[<span class="hljs-string">'date'</span>], df_filtered[<span class="hljs-string">'normalized_inflation'</span>], label=<span class="hljs-string">'Normalized Inflation Rate'</span>, color=<span class="hljs-string">'blue'</span>)
            plt.axhline(<span class="hljs-number">0</span>, color=<span class="hljs-string">'red'</span>, linestyle=<span class="hljs-string">'--'</span>, label=<span class="hljs-string">'0% Inflation'</span>)
            plt.xlabel(<span class="hljs-string">'Year'</span>)
            plt.ylabel(<span class="hljs-string">'Normalized Inflation (%)'</span>)
            plt.title(<span class="hljs-string">f'Normalized U.S. Inflation (<span class="hljs-subst">{start_year}</span> - <span class="hljs-subst">{end_year}</span>)'</span>)
            plt.legend()
            plt.grid()
            plt.xticks(rotation=<span class="hljs-number">45</span>)  
            plt.tight_layout()

            plot_path = <span class="hljs-string">'static/inflation_plot.png'</span>
            plt.savefig(plot_path)
            plt.close()

            plot_url = plot_path
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">f"Error fetching data: <span class="hljs-subst">{response.status_code}</span> - <span class="hljs-subst">{response.text}</span>"</span>)

    <span class="hljs-keyword">return</span> render_template(<span class="hljs-string">'index.html'</span>, plot_url=plot_url)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    app.run(debug=<span class="hljs-literal">True</span>)
</code></pre>
<ol>
<li><strong>Environment Variable Loading:</strong></li>
</ol>
<ul>
<li><code>load_dotenv()</code> loads environment variables from a <code>.env</code> file into the program, allowing the app to access sensitive data (like API keys) without hardcoding them.</li>
</ul>
<ol start="2">
<li><strong>Flask App Initialization:</strong></li>
</ol>
<ul>
<li><p><code>app = Flask(__name__)</code> initializes the Flask web app, preparing it to handle web requests.</p>
</li>
<li><p><code>render_template()</code> is used to render HTML templates, and <code>request</code> allows handing GET and POST request data from the form.</p>
</li>
</ul>
<ol start="3">
<li><strong>Route Definition and Method Handling:</strong></li>
</ol>
<ul>
<li><p><code>@app.route('/', methods=['GET', 'POST'])</code> defines a route at the route URL <code>/</code>. This route accepts both <code>GET</code> and <code>POST</code> requests.</p>
</li>
<li><p>The <code>index()</code> function processes these requests, displaying a form on <code>GET</code> and handling user input on <code>POST</code>.</p>
</li>
</ul>
<ol start="4">
<li><strong>Form Input(POST):</strong></li>
</ol>
<ul>
<li>When the form is submitted via <code>POST</code>, the <code>start_year</code> and <code>end_year</code> are fetched from the user's input and converted into integers for further processing. It defines the date range for the inflation data the user wants to see.</li>
</ul>
<ol start="5">
<li><p><strong>Requests:</strong></p>
<ul>
<li>This library handles making HTTP requests to external APIs. It fetches inflation data from the St. Lous Fed API <code>requests.get()</code>.</li>
</ul>
</li>
<li><p><strong>Handling API Response:</strong></p>
</li>
</ol>
<ul>
<li>If the request is successful <code>response.status_code == 200</code>, the inflation data is converted into a Pandas DataFrame <code>df</code>, allowing easier data manipulation.</li>
</ul>
<ol start="7">
<li><strong>Data Processing and Normalization:</strong> Using Pandas library as <code>pd</code> extracts the inflation value for the Start year with a Data Science script:</li>
</ol>
<pre><code class="lang-python">            inflation_start_year = df[df[<span class="hljs-string">'date'</span>].dt.year == start_year][<span class="hljs-string">'value'</span>].values[<span class="hljs-number">0</span>] <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> df[df[<span class="hljs-string">'date'</span>].dt.year == start_year].empty <span class="hljs-keyword">else</span> <span class="hljs-number">0</span>
</code></pre>
<ul>
<li><p>This line looks for the inflation value in the DataFrame for the <code>start_year</code> provided by the user.</p>
</li>
<li><p><code>df[df['date'].dt.year == start_year]</code>: It filters the DataFrame to select rows where the <code>date</code> column matches the <code>start_year</code>.</p>
</li>
<li><p><code>['value'].values[0]</code>: It extracts the inflation value for that year (first math).</p>
</li>
<li><p>If the filtered result is empty (no data for that year), it assigns <code>0</code> as a fallback <code>else 0</code>.</p>
</li>
<li><p>Normalization means expressing inflation values relative to the inflation in the <code>start_year</code>.</p>
</li>
<li><p>The inflation value for the <code>start_year</code> is retrieved, and the data is normalized relative to that year. The data normalization is: normalized_inflation=((value-inflation_start_year)/inflation_start_year) * 100</p>
</li>
<li><p>It makes comparing inflation changes over time easier by expressing them as percentages relative to the starting year.</p>
</li>
</ul>
<ol start="8">
<li><strong>Data Filtering for Specific Years:</strong></li>
</ol>
<ul>
<li>The DataFrame is filtered <code>df_filtered</code> only to include rows between the user's selected <code>start_year</code>and <code>end_year</code>.</li>
</ul>
<ol start="9">
<li><strong>Calculating Average Inflation:</strong></li>
</ol>
<ul>
<li>The average normalized inflation rate for the selected period is calculated and printed out.</li>
</ul>
<ol start="10">
<li><strong>Plotting the Data:</strong></li>
</ol>
<ul>
<li>A line chart is created using Matplotlib to visualize the normalized inflation rate over the selected time period <code>start_year</code> to <code>end_year</code>. The plot is saved as an image in the <code>static</code> folder <code>static/inflaction_plot.png</code>.</li>
</ul>
<ol start="11">
<li><strong>Rendering the Template:</strong></li>
</ol>
<ul>
<li>After processing the data and saving the plot, the template <code>index.html is rendered and displays the plot image if the</code> POST` request is successful.</li>
</ul>
<ol start="12">
<li><p><strong>Running the App:</strong></p>
<ul>
<li><a target="_blank" href="http://app.run"><code>app.run</code></a><code>(debug=True)</code> starts the Flask app in debug mode, which allows easy error tracking and automatic reloading when changes are made to the code.</li>
</ul>
</li>
</ol>
<h2 id="heading-code-flow">Code Flow:</h2>
<ul>
<li><p>The app collects start and end years from a user-submitted form.</p>
</li>
<li><p>It fetches inflation data using the API and processes it with Pandas.</p>
</li>
<li><p>A graph of the normalized inflation rate is plotted and displayed on the web page.</p>
</li>
</ul>
<p><strong>UI index.htm</strong></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>U.S. Inflation Over Time<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>U.S. Inflation Calculator<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Instructions:<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Input the begining year from 1947 and ahead. For example, 1947 to 2024, or 2000 to 2024,<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The output will be the calculation relative to the end year to substract start year.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>2008 to 2012, you can place whatever year from 1947 to 2024 boundaries:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"start_year"</span>&gt;</span>Start Year:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"start_year"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"start_year"</span> <span class="hljs-attr">required</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"start_year"</span>&gt;</span>End Year:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"end_year"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"end_year"</span> <span class="hljs-attr">required</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Show Inflation Data"</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

    { if plot_url }
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Inflation Plot<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"{{ plot_url }}"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Inflation Plot"</span>&gt;</span>
    { endif }
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><strong>HTML Structure</strong></p>
<ul>
<li><p>Basic webpage.</p>
</li>
<li><p>It uses the element <code>form</code> to provide a form where the users can input text or a URL.</p>
</li>
<li><p>It uses the POST method to send input to the Flask app, such as <code>start_year</code> and <code>end_year</code>.</p>
</li>
<li><p>The form submits data via POST to the root URL <code>action="/"</code></p>
</li>
<li><p>The dynamic content section within <code>{% if plot_url %}</code> checks if a plot image is available and displays it using <code>img</code> tag when the plot URL exits.</p>
</li>
</ul>
<p>In this way, the page dynamically shows a graph generated by the backend.</p>
<h2 id="heading-step-4-test-the-app"><strong>Step 4: Test the app</strong></h2>
<p>In the terminal, type:</p>
<pre><code class="lang-bash">python3 inflation-tracker
</code></pre>
<p>It will run the Flask server on <code>http//127.0.0.1:5000</code>:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/taik1k4jzrtbws66n5j4.png" alt="Run the app" /></p>
<p>Then, see the browser up and running:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8cgnzz77lwntskqrxthi.png" alt="Webpage Inflation calculator" /></p>
<p>Input the date ranges from the starting year to the end year and press the "Show Inflation Data" button to show the graph:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wbqm78u8vmhewozcefwe.png" alt="Input values and press button" /></p>
<p>Result image:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzb3mcawi73bmvaio8yt.png" alt="Result image" /></p>
<p>If you have any problems, you can check the code from my repo in the header of this page. If you like my code, please give it a star on Github or follow me here. I would really appreciate it.</p>
<h2 id="heading-summarize">Summarize</h2>
<p>I believe you learned how to handle data with the Python "Pandas" library in this lesson. We also use the Flask library to build our backend and connect it with the UI template <code>index.html</code>. Furthermore, I used API from FRED to get fresh data from US economics and explain what is indeed inflation so we understand how the concept works. Besides that, I use <code>matplotlib</code> to plot the results in our UI. Finally, I secure the API key in a <code>.env</code> file to avoid vulnerabilities once we work with repositories.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The flexibility of this app also opens up possibilities for future enhancements, such as adding more datasets or customizing the visualizations. This guide helps others see how easy it can be to use public economic data in meaningful and educational ways. You can also retrieve that public data from your country: check the Central Bank public API or the financial institution for research in your country, and just change the endpoint URL and replace it.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="https://www.python.org/downloads/">Python Official</a></p>
</li>
<li><p><a target="_blank" href="https://flask.palletsprojects.com/en/3.0.x/">Flask</a></p>
</li>
<li><p><a target="_blank" href="https://matplotlib.org/">Matplotlib</a></p>
</li>
<li><p><a target="_blank" href="https://pandas.pydata.org/">Pandas</a></p>
</li>
<li><p><a target="_blank" href="https://fred.stlouisfed.org/">FRED</a></p>
</li>
<li><p><a target="_blank" href="https://mises.org/library/book/economic-policy-thoughts-today-and-tomorrow">Economic Policy - Ludwig von Mises</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How to build a QR Generator using Flask and qrcode]]></title><description><![CDATA[Introduction
Have you ever wondered how to build a QR code generator? This is the right tutorial for you. If we want to build such a tool, we need to think about the right language, so guess which one? You got it: "Python," which is a general high-le...]]></description><link>https://blog.byteup.co/how-to-build-a-qr-generator-using-flask-and-qrcode</link><guid isPermaLink="true">https://blog.byteup.co/how-to-build-a-qr-generator-using-flask-and-qrcode</guid><category><![CDATA[qrcode python]]></category><category><![CDATA[Python]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Flask Framework]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Fri, 04 Oct 2024 16:54:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728059250429/a953130a-011a-45a4-abe8-16887c8277bb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>Have you ever wondered how to build a QR code generator? This is the right tutorial for you. If we want to build such a tool, we need to think about the right language, so guess which one? You got it: "Python," which is a general high-level language for building anything in this digital world and also physical robots (software).</p>
<h2 id="heading-setting-up-the-environment"><strong>Setting Up the Environment</strong></h2>
<h2 id="heading-prerequisites"><strong>Prerequisites:</strong></h2>
<ul>
<li><p>Basic Python language</p>
</li>
<li><p>Code Editor</p>
</li>
<li><p>Basic command line</p>
</li>
</ul>
<h2 id="heading-step-1-setting-up-the-project"><strong>Step 1: Setting Up the Project</strong></h2>
<ul>
<li><p>Install Python <a target="_blank" href="https://www.python.org/downloads/">here</a>. From the Python page, download the latest stable version of Python. Once you've downloaded the installation file, execute it, install it on your computer, and follow all the recommended prompts.</p>
</li>
<li><p>Clone the repository and move to it:</p>
</li>
</ul>
<p><a target="_blank" href="https://github.com/ivansing/qr-code-generator-app.git">qr-code-generator-app</a></p>
<p>Your projects would then be located in paths like:</p>
<p><code>/home/your-username/Projects/my_project</code> (Linux)</p>
<p><code>/Users/your-username/Projects/my_project</code> (Mac)</p>
<ul>
<li><p>Open VS Code at the top of the bar and press <code>Terminal</code> in the dropdown box. Select <code>New Terminal</code>.</p>
</li>
<li><p>For Windows using Linux subsystem WSL:</p>
</li>
<li><p>Open VS Code, press F1, and select connect to WSL.</p>
</li>
<li><p>Follow the previous steps from Linux/Mac.</p>
</li>
</ul>
<p>Type the following command in the terminal:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> qr-code-generator-app
</code></pre>
<p>In the <code>qr-code-generator-app</code> type the following in the terminal:</p>
<pre><code class="lang-bash">mkdir static templates
</code></pre>
<p>This action will create two directories at once <code>static</code> to store ouput qr code file image, and <code>templates</code> directory to show the UI <code>index.html</code>.</p>
<p>Let's create the files in the project's structure:</p>
<pre><code class="lang-bash">touch app.py
</code></pre>
<p>That was the application's entry point because I'm using Flask as the server to display the UI <code>index.html</code>.</p>
<p>Next, create an <code>index.html</code> file in the templates directory:</p>
<pre><code class="lang-bash">touch templates/index.html
</code></pre>
<h2 id="heading-step-2-install-libraries"><strong>Step 2: Install libraries</strong></h2>
<pre><code class="lang-bash">pip install qrcode Flask
</code></pre>
<p>In the previous command, I'm using <code>qrcode</code> to generate PNG files and Flask to render the endpoint <code>index.html</code></p>
<h2 id="heading-step-3-write-the-code"><strong>Step 3: Write the code</strong></h2>
<ul>
<li><h3 id="heading-import-the-libraries"><strong>Import the libraries</strong></h3>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> qrcode

<span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, request, render_template, send_file
</code></pre>
<p>The code import our <code>qrcode</code> so we can generate our precious QR codes, <code>Flask</code> a web framework to create a simple web server, <code>request</code> helps handle incoming form data (data input from a user), <code>render_template</code> to render HTML templates, and finally the <code>send_file</code> to send files (generated QR code image) to the user.</p>
<ul>
<li><h3 id="heading-create-flask-app"><strong>Create Flask App:</strong></h3>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> qrcode 
<span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, request, render_template, send_file 

app = Flask(__name__)

<span class="hljs-meta">@app.route("/", methods=["GET", "POST"])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_qr</span>():</span>
    <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">"POST"</span>:
        data = request.form[<span class="hljs-string">"data"</span>]
        qr_img = qrcode.make(data)

        qr_path = <span class="hljs-string">"static/qr_code.png"</span>
        qr_img.save(qr_path)

        <span class="hljs-keyword">return</span> send_file(qr_path, mimetype=<span class="hljs-string">'image/png'</span>)

    <span class="hljs-keyword">return</span> render_template(<span class="hljs-string">"index.html"</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    app.run(debug=<span class="hljs-literal">True</span>)
</code></pre>
<ul>
<li><p><strong>Flask App Setup</strong>: `app = Flask(__name__) initializes the web app.</p>
</li>
<li><p><strong>Route Definition:</strong> <code>@app.route("/", methods=["GET, POST"])</code> handles both GET and POST requests at the root URL.</p>
</li>
<li><p><strong>Form Handling (POST):</strong> When the form is submitted(POST), the user input is fetched and a QR code is generated and saved as <code>static/qr_code.png</code> image file.</p>
</li>
<li><p><strong>Send QR Code:</strong> The saved QR code is returned to the browser using <code>send_file</code> method.</p>
</li>
<li><p><strong>Render HTML(GET):</strong> On a GET requests, the <code>index.html</code> template is rendered.</p>
</li>
<li><p><strong>Run the App:</strong> <a target="_blank" href="http://app.run"><code>app.run</code></a><code>(debug=True)</code> starts the app in debug mode for easy error tracing.</p>
</li>
</ul>
<h3 id="heading-indexhtml"><strong>index.html</strong></h3>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>QR Code Generator<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>QR Code Generator<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"data"</span>&gt;</span>Enter Text or a URL:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"data"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"data"</span> <span class="hljs-attr">required</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Generate QR Code<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

    {% if qr_code %}
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Generated QR Code:<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"{{ qr_code }}"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"QR Code"</span>&gt;</span>
    {% endif %}  

<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<ul>
<li><p><strong>HTML Structure:</strong> Basic webpage with UTF-8 encoding.</p>
</li>
<li><p><strong>Form:</strong> This provides a form where users can input text or a URL. It uses the POST method to send the input to the Flask app, and then the "Generate QR Code" button is clicked.</p>
</li>
<li><p><strong>QR Code Display:</strong> After form submission, if a QR code is generated, it checks (`{% if qr_code %}`) and displays the QR code image the <code>&lt;img&gt;</code> tag. This uses Flask templating to dynamically insert the QR code image source (`{{ qr_code }}`).</p>
</li>
</ul>
<h2 id="heading-test-the-app"><strong>Test the App</strong></h2>
<p>Now that the app is done, I'm ready to show you how to test it, like copying and pasting a URL from any website that gives in return a QR image so you can scan it to send to other friends:</p>
<p>Again, if you did all the steps as I did before, type the following command in the same level directory <code>qr-code-generator-app</code>:</p>
<pre><code class="lang-bash">python3 app.py
</code></pre>
<p>You will have the following output in the terminal:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728060151858/48aa1883-54a1-46b5-ac10-e0c21f2e0b6f.png" alt class="image--center mx-auto" /></p>
<p>So, open it in the browser, and you can see this result:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728060174568/aec5fd44-f8ec-41a5-9045-99e4627f0260.png" alt class="image--center mx-auto" /></p>
<p>Now copy any page like: <a target="_blank" href="https://google.com%60"><code>https://google.com</code></a> and paste it in the input box and just press the button <code>Generate QR Code</code>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728060189869/69328596-badd-4af9-8f3e-edd60ce774e4.png" alt class="image--center mx-auto" /></p>
<p>And here you have the result QR code image:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728060267389/60b66e35-1bec-471e-9569-509eac021198.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>This was a small tutorial, we build a simple Flask application that allows users to generate their own QR codes. The app accepts user input (text or a URL), converts it into QR code, and displays the generated QR code on the browser. We used the Flask framework for creating the web app, the <code>qrcode</code> library for generating QR codes, and basic HTML for the front-end form and displaying the output as template.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>As we did this tutorial, we learned how to create a basic web app using Flask, it's an amazing framework for python dynamic pages and integrate a Python library <code>qrcode</code> to generate QR codes from user input. Moreover, we saw how to handle GET and POST requests, render HTML templates using Flask, and display images dynamically in a web application. This project demonstrated the simplicity and power of Flask for building lightweight web applications.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="https://www.python.org/downloads/">Python Official</a></p>
</li>
<li><p><a target="_blank" href="https://flask.palletsprojects.com/en/3.0.x/">Flask</a></p>
</li>
<li><p><a target="_blank" href="https://pypi.org/project/qrcode/">qrcode</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Audio to Text using Python and OpenAI]]></title><description><![CDATA[Introduction
In the following tutorial, I will build a basic app to recognize audio files and convert them to text. Moreover, with OpenAI API tools, a Python library "pydub" for audio manipulation, and the library python-dotenv to save environment va...]]></description><link>https://blog.byteup.co/audio-to-text-using-python-and-openai</link><guid isPermaLink="true">https://blog.byteup.co/audio-to-text-using-python-and-openai</guid><category><![CDATA[pydub]]></category><category><![CDATA[AI]]></category><category><![CDATA[Python]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[command line]]></category><category><![CDATA[openai]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Wed, 02 Oct 2024 01:08:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727830973631/5d9a00a3-c3c3-46a5-9e33-68a367567845.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In the following tutorial, I will build a basic app to recognize audio files and convert them to text. Moreover, with OpenAI API tools, a Python library "pydub" for audio manipulation, and the library python-dotenv to save environment variables, it's easy to do. Without cumbersome code, it is easy to follow with a detailed explanation to make it work in your daily tasks.</p>
<p>Let's get dirty:</p>
<p>Clone the repository:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/ivansing/audio-to-text-app.git
    <span class="hljs-built_in">cd</span> audio-to-text-app
</code></pre>
<p>You should get the sample files in <code>assets</code> and copy them to your <code>assets</code> folder.</p>
<h2 id="heading-setting-up-the-environment">Setting Up the Environment</h2>
<h3 id="heading-prerequisites">Prerequisites:</h3>
<ul>
<li>Basic Python language</li>
<li>Code Editor</li>
<li>Basic command line</li>
</ul>
<h2 id="heading-step-1-setting-up-the-project">Step 1: Setting Up the Project</h2>
<ul>
<li>Install Python <a target="_blank" href="https://www.python.org/downloads/">Here</a>. It is straightforward; just follow the (recommended) prompts to "yes."</li>
<li>I will use VS Code as managing any project and development is relatively easy.</li>
<li>Open VS Code at the top of the bar and press <code>Terminal</code> in the dropdown box. Select <code>New Terminal</code> and type the following bash command:<pre><code class="lang-bash">mkdir audio-text-app
</code></pre>
Then move to the directory that we did previously:<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> audio-text-app
</code></pre>
Your projects would then be located in paths like:
<code>/home/your-username/Projects/my_project</code> (Linux)
<code>/Users/your-username/Projects/my_project</code> (Mac)</li>
</ul>
<p>In your folder <code>audio-text-app</code> create the following files:</p>
<pre><code class="lang-bash">touch audio-to-text.py .env
</code></pre>
<p>The file <code>audio-text-app</code> is for this small script app's main functionality and entry point.
<code>.env</code> is where I will save the API keys from OpenAi. I will use it in the following steps.</p>
<p>For Windows using Linux subsystem WSL</p>
<ul>
<li>Open VS Code, press F1, and select connect to WSL.</li>
<li>Follow the previous steps from Linux/Mac.</li>
</ul>
<h2 id="heading-step-2-install-required-libraries-and-folders-files">Step 2: Install Required Libraries and folders files</h2>
<ul>
<li>In your  command line windows, type the following instructions:<pre><code class="lang-bash">pip install openai pydub python-dotenv
</code></pre>
</li>
<li><p>Install FFmpeg:</p>
<ul>
<li>On macOS (using Homebrew): brew install ffmpeg</li>
<li>On Ubuntu: sudo apt install ffmpeg</li>
<li>On Windows: Download and install from ffmpeg.org</li>
</ul>
</li>
<li><p>Make another directory named: <code>assets</code> inside the audio-text-app folder. I will use it to get the audio <code>.wav</code> files for testing:</p>
<pre><code class="lang-bash">mkdir assets
</code></pre>
</li>
</ul>
<h2 id="heading-step-3-setup-your-openai-api-key">Step 3: Setup your OpenAI API Key:</h2>
<ul>
<li>Go to <a target="_blank" href="https://platform.openai.com/docs/overview">OpenAI</a> and sign up to generate your openai-api-key.</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xb4n90ktxnwqcdn3c2st.png" alt="Follow to create API key" /></p>
<ul>
<li>Then, Create a new secret key, which is the openai-api-key.</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9x4r65ddb8sf1rx5uy27.png" alt="Create key button" /></p>
<ul>
<li>Follow the steps in the popup modal window, and press "Create secret key."</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mynf2nykw8p5hn0zanu.png" alt="Modal window form" /></p>
<ul>
<li>Finally, Save this generated key in a notepad or safe place, always hidden from the public, and press "Done."</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wsvitj35cwjw6wult8c8.png" alt="Copy openai secret key" /></p>
<p>Now that we have already generated our precious hidden key, let's keep the following:</p>
<h2 id="heading-step-4-write-the-code">Step 4: Write the code</h2>
<ul>
<li><strong>Import the libraries:</strong><pre><code class="lang-python"><span class="hljs-keyword">import</span> openai
<span class="hljs-keyword">from</span> pydub <span class="hljs-keyword">import</span> AudioSegment
<span class="hljs-keyword">import</span> os 
<span class="hljs-keyword">import</span> uuid 
<span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv
</code></pre>
</li>
<li><code>open</code>:  For interaction with the OpenAI Whisper API to transcribe audio.</li>
<li><code>pydub</code>: This will make the file smaller so as not to stress too much the CPU work when handling audio file manipulations like changing channels (mono) and resampling.</li>
<li><code>os</code>: To generate unique file names for processed audio, removing redundant output files.</li>
<li><code>uuid</code>: To generate unique file names for processed audio.</li>
<li><code>dotenv</code> To load environment variables from a <code>.env</code> file, which securely stores the API key.</li>
</ul>
<h2 id="heading-functions">Functions</h2>
<p><strong>convert_to_mono_16k</strong></p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">convert_to_mono_16k</span>(<span class="hljs-params">audio_file_path, output_dir=<span class="hljs-string">"assets"</span></span>):</span>
    <span class="hljs-string">"""Converts audio to mono and 16kHz, returns the path to the converted audio."""</span>
    sound = AudioSegment.from_file(audio_file_path)
    sound = sound.set_channels(<span class="hljs-number">1</span>)  <span class="hljs-comment"># Mono</span>
    sound = sound.set_frame_rate(<span class="hljs-number">16000</span>)  <span class="hljs-comment"># 16kHz</span>

    <span class="hljs-comment"># Generate a unique filename for the mono version</span>
    converted_file_name = <span class="hljs-string">f"<span class="hljs-subst">{uuid.uuid4()}</span>.wav"</span>
    converted_file_path = os.path.join(output_dir, converted_file_name)

    <span class="hljs-comment"># Export the converted audio file</span>
    sound.export(converted_file_path, format=<span class="hljs-string">"wav"</span>)
    <span class="hljs-keyword">return</span> converted_file_path
</code></pre>
<p>This function takes an audio file, converts it to mono (1 audio channel), and resamples it to 16kHz, which is required for optimal transcription with Whisper.</p>
<ul>
<li>The audio file is loaded using <code>AudioSegment</code>.</li>
<li>It is converted to mono with <code>set_channels(1)</code>.</li>
<li>The sample rate is set to 16kHz using <code>set_frame_rate(16000)</code>.</li>
<li>A unique file name is generated using <code>uuid</code> to avoid filename conflicts.</li>
<li>The processed audio file is exported to the specified output directory (<code>assets</code> by default).</li>
<li>This function returns the file path of the converted audio, which will be used later for transcription.</li>
</ul>
<p><strong>transcribe_audio</strong></p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">transcribe_audio</span>(<span class="hljs-params">audio_file_path, clean_up=True</span>):</span>
    <span class="hljs-string">"""Transcribes audio to text using OpenAI's Whisper."""</span>
    <span class="hljs-comment"># Convert audio to mono and 16kHz</span>
    mono_audio_path = convert_to_mono_16k(audio_file_path)

    <span class="hljs-comment"># Transcribe audio using OpenAI's Whisper</span>
    <span class="hljs-keyword">with</span> open(mono_audio_path, <span class="hljs-string">"rb"</span>) <span class="hljs-keyword">as</span> audio_file:
        transcript = openai.Audio.transcribe(<span class="hljs-string">"whisper-1"</span>, audio_file)

    <span class="hljs-comment"># Clean up the converted file if needed</span>
    <span class="hljs-keyword">if</span> clean_up:
        os.remove(mono_audio_path)

    <span class="hljs-keyword">return</span> transcript[<span class="hljs-string">'text'</span>]
</code></pre>
<p>This function transcribes an audio file into text using the OpenAI Whisper API.</p>
<ul>
<li>It calls the <code>convert_to_mono_16k</code> function to ensure the audio is in the correct format (mono, 16kHz).</li>
<li>The converted file is opened in binary mode <code>"rb"</code> and passed to the Whisper API transcription.</li>
<li>The function optionally cleans up (deletes) the temporary audio file after the transcription, controlled by the <code>clean_up</code> argument.</li>
<li>The function returns the transcription text extracted from the Whisper API's response.</li>
</ul>
<h2 id="heading-test-code">Test code</h2>
<pre><code class="lang-python"><span class="hljs-comment"># Example usage</span>
audio_file = <span class="hljs-string">"assets/jackhammer.wav"</span>
transcription = transcribe_audio(audio_file)
print(<span class="hljs-string">"Transcription:"</span>, transcription)
</code></pre>
<p>This section demonstrates how to use the <code>transcribe_audio</code> function.</p>
<p>Besides the samples that are stored in the <code>assets</code> folder, you can add more <code>.wav</code> files to test it</p>
<p>Test the code with the following command:</p>
<pre><code class="lang-bash">python3 audio-to-text.py
</code></pre>
<p>Now check the output text from the audio file in the terminal:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/664bjglgijutiwhvp0cb.png" alt="Test Output text" /></p>
<ul>
<li>The <code>audio_file</code> variable specifies the audio file to be transcribed.</li>
<li>The <code>transcribre_audio</code> function is called with the audio file path.</li>
<li>The transcription result is printed to the console.</li>
</ul>
<h2 id="heading-summary">Summary</h2>
<p>It was an ideal tutorial for learning the basis of using various Python libraries. After all, we learned the OpenAI API Whisper, which is a trained model based on a neural net on English speech recognition. And the use of <code>pydub</code> to manipulate the audio. I used native Python libraries <code>os</code> for path source and definition and <code>uuid</code> to rename the mono output file.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Python is a vast universe that is used in general software construction. You can use this tool as part of a small software package. It is an essential program that needs many more things, like more test cases than you can imagine. Ideally, you can have an output text file, but for this short tutorial, I didn't want to add more complexity; if you're going to add more features, look at Python docs, and you will be amazed at what you can manipulate in this world and with the help of API (outside programs to communicate), there will be fantastic software builds.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><a target="_blank" href="https://platform.openai.com/docs/overview">OpenAI Docs</a></li>
<li><a target="_blank" href="https://www.python.org/">Python Official</a></li>
<li><a target="_blank" href="https://pypi.org/project/pydub/">pydub</a></li>
</ul>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on <a target="_blank" href="https://x.com/ldway27">X</a>, <a target="_blank" href="https://github.com/ivansing">Github</a>, and <a target="_blank" href="https://www.linkedin.com/in/lance-dev/">LinkedIn </a>for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[Solana Wallet Integration for SOL Transactions]]></title><description><![CDATA[Introduction
In previous years, the Solana blockchain and crypto coin "SOL" have gained a strong reputation for building more modern blockchain technologies apart from Bitcoin and Etherium blockchains, adding more advanced features for this current t...]]></description><link>https://blog.byteup.co/solana-wallet-integration-for-sol-transactions</link><guid isPermaLink="true">https://blog.byteup.co/solana-wallet-integration-for-sol-transactions</guid><category><![CDATA[phantomwallet]]></category><category><![CDATA[Solana]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Wed, 11 Sep 2024 15:29:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726068449035/5fd0f3a6-3b5c-4495-ad5b-e2081b04a085.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In previous years, the Solana blockchain and crypto coin "SOL" have gained a strong reputation for building more modern blockchain technologies apart from Bitcoin and Etherium blockchains, adding more advanced features for this current time like high processing speeds, the Proof of History concept to make transactions before timestamps, and the priority for developers to work on top of a layer for fast development.</p>
<p>In this tutorial, we will learn some basic functionality with the Solana standard wallet. In this case, we will use a web-based Phanton Wallet on the devnet network. With this basic app, you can build an app to send SOL to another Solana wallet.</p>
<p>Then, all wallet interactions use npm @solana packages like Solana, @solana/web3.js, @solana/wallet-adapter-react-ui, and others.</p>
<p>We will use React with Next.js to create a basic layout for the UI rendering component. You can add more functionalities or leave them as a template. All these are referenced in the Solana docs. This tutorial enriched your stack developer with more knowledge of modern blockchain technologies.</p>
<h2 id="heading-use-cases">Use Cases</h2>
<ul>
<li><p>Users should be able to connect their Solana wallet to the application web extension.</p>
</li>
<li><p>Users can send SOL to another address or user using the Phanton Wallet web extension.</p>
</li>
<li><p>Users can view their current SOL balance.</p>
</li>
<li><p>Users can track SOL once the transaction was made.</p>
</li>
</ul>
<p><strong>Understanding Public and Secret keys in the Phantom Wallet</strong></p>
<p>When using the Phantom Wallet or interacting with it, it's essential to understand the roles of public and secret keys in making transactions. For our tutorial purposes, we only need the Public Key because sending transactions will be handled by the Phantom Wallet, so why the keys:</p>
<ul>
<li><p><strong>Public Key:</strong> The Solana wallet's address ID points to the Solana network. You can share it with others to receive SOL tokens or interact with dApps (decentralized apps).</p>
</li>
<li><p><strong>Secret Key:</strong> This is the most sensitive key you should keep to access and control your funds. It's used to sign transactions and prove ownership of the funds in your wallet. The Phantom wallet securely stores this key and never exposes it to any external applications, including the one you're building.</p>
</li>
</ul>
<h2 id="heading-setting-up-the-environment">Setting Up the Environment</h2>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li><p>Code Editor of your preference I use VS Code</p>
</li>
<li><p>Basic JavaScript</p>
</li>
<li><p>Node.js</p>
</li>
<li><p>Typescript</p>
</li>
<li><p>Code Editor</p>
</li>
<li><p>Basic HTML, and CSS</p>
</li>
</ul>
<h2 id="heading-instructions">Instructions</h2>
<ul>
<li><p>Setup environment and install dependencies</p>
</li>
<li><p>Initialize project and configure file structure</p>
</li>
</ul>
<p><strong>Frontend</strong></p>
<ul>
<li><p>Configure Solana connection</p>
</li>
<li><p>Implement wallet integration</p>
</li>
<li><p>Create UI components</p>
</li>
<li><p>Handle transactions</p>
</li>
</ul>
<p><strong>Backend</strong></p>
<ul>
<li><p>Handle transaction and security</p>
</li>
<li><p>Testing</p>
</li>
</ul>
<ol>
<li>Setup environment and install dependencies</li>
</ol>
<p>First, open VS Code:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1u5rxcwouegs9zfol4nv.png" alt="Open VS Code" /></p>
<p>Open VS Code press F1, and select connect to WSL.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kit0j1ty1rh18vu16g1r.png" alt="Connect WSL" /></p>
<ul>
<li>Open the terminal View &gt; terminal</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qpsng0oyc2qeruehjdop.png" alt="Open Terminal" /></p>
<ul>
<li>Follow the same previous instructions from Linux/Mac</li>
</ul>
<p><strong>Terminal VS Code</strong></p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sqa07kjqxrzhgbhzowq4.png" alt="Terminal VS Code" /></p>
<p>Next, make a folder on your PC, like in a Linux/Mac root folder or Windows. Linux/Mac</p>
<p>It's common to place your projects in a Projects directory within your home directory.</p>
<pre><code class="lang-bash">mkdir -p ~/Projects
</code></pre>
<p>and move to the project's folder by running:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> Projects
</code></pre>
<p>Your projects would then be located in path like: <code>/home/your-username/Projects/my_project</code> (Linux) <code>/Users/your-username/Projects/my_project</code> (Mac)</p>
<p><strong>Windows Using Linux subsystem WSL</strong></p>
<ul>
<li>Follows same steps as previous on Linux/Mac</li>
</ul>
<h2 id="heading-installing-nextjs">Installing Next.js</h2>
<p>Initialize the Next.js project, and ensure you're in the project directory:</p>
<pre><code class="lang-bash">npx create-next-app@latest wallet-app
</code></pre>
<p>It will ask some questions yes to all except in include:</p>
<ul>
<li><p>Tailwing CSS <strong>NO</strong>,</p>
</li>
<li><p>to App router <strong>NO</strong>,</p>
</li>
<li><p>and import alias (@/*) NO, so then Next.js built all the folder and files for you including <code>.env.local</code> that we will use on next steps.</p>
</li>
</ul>
<p>Move into the project directory:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> wallet-app
</code></pre>
<p>Install required dependencies:</p>
<pre><code class="lang-bash">npm install @solana/web3.js @solana/wallet-adapter-base @solana/wallet-adapter-react @solana/wallet-adapter-react-ui @solana/wallet-adapter-wallets
</code></pre>
<p>This will install the Solana web3.js library and wallet adapter packages necessary for interacting with the Solana blockchain and handling wallet connections.</p>
<ol start="2">
<li>Initialize project and configure file structure, run the following command to test the app:</li>
</ol>
<pre><code class="lang-bash">npm run dev
</code></pre>
<p>Run it in your browser most of the time <a target="_blank" href="http://localhost:3000"><code>localhost:3000</code></a></p>
<p><strong>Note</strong>: While you are coding the app try to see the results in your <a target="_blank" href="http://localhost:3000"><code>localhost:3000</code></a> to make sure everything it's working as expected.</p>
<p>We have to do the file structure like the following tree structure:</p>
<pre><code class="lang-bash">wallet-app/
├── README.md
├── next-env.d.ts
├── next.config.mjs
├── package-lock.json
├── package.json
├── public
│   └── solanaLogo.png       <span class="hljs-comment"># Any public assets go here</span>
├── src
│   ├── components           <span class="hljs-comment"># Reusable React components</span>
│   ├── pages                <span class="hljs-comment"># Next.js pages (e.g., index.tsx)</span>
│   └── styles               <span class="hljs-comment"># CSS/SCSS files</span>
├── tsconfig.json
└── utils                    <span class="hljs-comment"># Utility functions and scripts</span>
    └── generator-public-data.ts
</code></pre>
<p>Make a folder in the root of the project called <code>utils</code> and create two files inside <a target="_blank" href="http://generator-public.data"><code>generator-public.data</code></a><code>.ts</code> and <code>publicKeyGenerator.ts</code> that will be used later in the future.</p>
<pre><code class="lang-bash">mkdir utils
</code></pre>
<p>And create the files:</p>
<pre><code class="lang-bash">touch utils/generator-public-data.ts utils/publicKeyGeneratos.ts
</code></pre>
<p>Write the following script in Javascript and React to <code>generator-public-data.ts</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Keypair } <span class="hljs-keyword">from</span> <span class="hljs-string">"@solana/web3.js"</span>;
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">"fs"</span>;
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">"path"</span>;

<span class="hljs-comment">// Define the path to the .env.local file</span>
<span class="hljs-keyword">const</span> envFilePath = path.resolve(__dirname, <span class="hljs-string">"../.env.local"</span>);

<span class="hljs-comment">// Function to check if a key exists in the .env.local file</span>
<span class="hljs-keyword">const</span> keyExistsInEnv = (key: string, <span class="hljs-attr">filePath</span>: string): <span class="hljs-function"><span class="hljs-params">boolean</span> =&gt;</span> {
  <span class="hljs-keyword">if</span> (!fs.existsSync(filePath)) {

    <span class="hljs-comment">// File doesn't exist, so the key doesn't exist either</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; 
  }

  <span class="hljs-keyword">const</span> envFileContent = fs.readFileSync(filePath, <span class="hljs-string">"utf-8"</span>);
  <span class="hljs-keyword">return</span> envFileContent.includes(<span class="hljs-string">`<span class="hljs-subst">${key}</span>=`</span>);
};

<span class="hljs-comment">// Check if the keys already exist in the .env.local file</span>
<span class="hljs-keyword">const</span> programIdKey = <span class="hljs-string">"NEXT_PUBLIC_PROGRAM_ID"</span>;
<span class="hljs-keyword">const</span> dataAccountPubKeyKey = <span class="hljs-string">"NEXT_PUBLIC_DATA_ACCOUNT_PUBKEY"</span>;

<span class="hljs-keyword">const</span> programIdExists = keyExistsInEnv(programIdKey, envFilePath);
<span class="hljs-keyword">const</span> dataAccountPubKeyExists = keyExistsInEnv(dataAccountPubKeyKey, envFilePath);

<span class="hljs-keyword">if</span> (programIdExists &amp;&amp; dataAccountPubKeyExists) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Keys already exist in .env.local. No action taken."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Generate and append only the keys that don't already exist</span>
  <span class="hljs-keyword">let</span> envContent = <span class="hljs-string">""</span>;

  <span class="hljs-keyword">if</span> (!programIdExists) {
    <span class="hljs-keyword">const</span> programKeypair = Keypair.generate();
    <span class="hljs-keyword">const</span> programId = programKeypair.publicKey.toBase58();
    envContent += <span class="hljs-string">`<span class="hljs-subst">${programIdKey}</span>=<span class="hljs-subst">${programId}</span>\n`</span>;
  }

  <span class="hljs-keyword">if</span> (!dataAccountPubKeyExists) {
    <span class="hljs-keyword">const</span> dataAccountKeypair = Keypair.generate();
    <span class="hljs-keyword">const</span> dataAccountPubKey = dataAccountKeypair.publicKey.toBase58();
    envContent += <span class="hljs-string">`<span class="hljs-subst">${dataAccountPubKeyKey}</span>=<span class="hljs-subst">${dataAccountPubKey}</span>\n`</span>;
  }

  <span class="hljs-comment">// Append the new content to the .env.local file if necessary</span>
  <span class="hljs-keyword">if</span> (envContent) {
    fs.appendFileSync(envFilePath, envContent.trim());
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Missing keys generated and saved to .env.local"</span>);
  }
}
</code></pre>
<p><strong>Explanation:</strong></p>
<p>This script is an enhanced utility for generating and managing cryptographic keys in your Solana wallet application. It automates generating keys and adequately stores them in the <code>.env.local</code> file.</p>
<p>Here's a step-by-step explanation:</p>
<p><strong>PublicKey:</strong> This is the identification and when somebody transfers funds from. <strong>Data Account Public Key:</strong> This is where you save all related transactions and contract information.</p>
<ul>
<li><p>First, we import the Solana web3 package to get the Keypair function to generate the keys; then, we import the <code>fs</code> File System Module to file reading, writing, and manipulation.</p>
</li>
<li><p>Make the <code>path</code> module resolves file paths and cross-platform ways.</p>
</li>
<li><p>We define a function <code>keyExistsInEnv()</code> to check if any keys are already in the <code>.env.local</code> file.</p>
</li>
<li><p>Save constant values to use with the <code>keyExistsInEnv()</code> function.</p>
</li>
<li><p>Saves the result of the <code>keyExitsInEnv()</code> function to constant programIdExist.</p>
</li>
<li><p>Generate and save the keys if necessary: If the keys exist, no action is taken.</p>
</li>
<li><p>Key generation: if no keys inside the <code>.env.local</code> file, the script will generate the keypairs.</p>
</li>
<li><p>Program ID: if the <code>NEXT_PUBLIC_PROGRAM_ID</code> is missing, the script will generate the key.</p>
</li>
<li><p>Data Account Public Key: If the key is missing, the script will generate the key.</p>
</li>
<li><p>Appending to <code>.env.local</code>: If missing, the new keys are only appended to the <code>.env.local</code> file. This ensures that existing keys aren't overwritten and that only the missing ones are generated.</p>
</li>
</ul>
<p>Ensure that the <code>.env.local</code> is in the root directory so we can follow along.</p>
<p>Then, ensure the <code>.env.local</code> is in the directory's root. Next.js usually creates us automatically, and the <code>.gitignore</code> files to be ignored will be added there once the project is created from the beginning of the setup project.</p>
<p>It's the most extended script in the app, but it's straightforward, as you can see.</p>
<p>After this, we can generate the keys out of thin air like magic:</p>
<p>Now, run the following command to generate the public keys in the root's project folder:</p>
<pre><code class="lang-bash">npx esrun utils/generator-public-data.ts
</code></pre>
<p>If everything is working as expected, you will see the message in the terminal:</p>
<pre><code class="lang-bash">Missing keys generated and saved to .env.local
</code></pre>
<p>Check the <code>.env.local</code> in the root's project structure for the generate it public key strings values:</p>
<pre><code class="lang-bash">NEXT_PUBLIC_PROGRAM_ID=<span class="hljs-string">"YourGeneratedProgramID"</span>
NEXT_PUBLIC_DATA_ACCOUNT_PUBKEY=<span class="hljs-string">"YourGeneratedDataAccountPubKey"</span>
</code></pre>
<h2 id="heading-publickeygeneratorts">publicKeyGenerator.ts</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {Keypair} <span class="hljs-keyword">from</span> <span class="hljs-string">"@solana/web3.js"</span>

<span class="hljs-keyword">const</span> keypair2 = Keypair.generate()

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The public key 2 is: <span class="hljs-subst">${keypair2.publicKey.toBase58()}</span>`</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The secret key 2 is: <span class="hljs-subst">${keypair2.secretKey}</span>`</span>)
</code></pre>
<h2 id="heading-explanation">Explanation</h2>
<p>This silly, tiny script basically imports the <code>Keypair</code> object from the Solana web3 library. Next, it generates a keypair from the <code>generate()</code> method of the <code>Keypair</code> object and saves it in a keypair variable. The log the result pairs one: it's a <code>publicKey</code> of 58 chars and a <code>secretKey</code> with an array of numbers; in this tutorial, for testing purposes, don't worry about the <code>secretKey</code>. In real life, in the <code>mainnet</code> Solana blockchain, you have to save it in another safe place.</p>
<p>We will use this script at a later time in the project.</p>
<p>The next instruction from the program's design is the 'frontend' part. This also includes the backend. It's a small project, but you can modularize more. These are just the basic concepts to grasp.</p>
<h2 id="heading-building-the-components">Building the components</h2>
<p>In the root's folder structure, expand <code>src</code> and pages, and you will see two files: <code>_app.tsx</code> and <code>index.tsx</code> erase all content from it, and we will implement the following code into those files:</p>
<p>Next.js main entry point app <code>_app.tsx</code></p>
<h2 id="heading-apptsx">_app.tsx</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">'../styles/globals.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyApp</span>(<span class="hljs-params">{ Component, pagePros}</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Component</span> {<span class="hljs-attr">...pagePros</span>} /&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyApp
</code></pre>
<p>This file includes global CSS to render the appropriate component for the current route.</p>
<p>The main page of your application <code>index.tsx</code></p>
<h2 id="heading-indextsx">index.tsx</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { NextPage } <span class="hljs-keyword">from</span> <span class="hljs-string">"next"</span>
<span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">'../styles/Home.module.css'</span>
<span class="hljs-keyword">import</span> { AppBar } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/AppBar"</span>
<span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">"next/head"</span>
<span class="hljs-keyword">import</span> WalletContextProvider <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/WalletContextProvider"</span>
<span class="hljs-keyword">import</span> { BalanceDisplay } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/BalanceDisplay"</span>
<span class="hljs-keyword">import</span> { InputFormWallet } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/InputFormWallet"</span>


<span class="hljs-keyword">const</span> Home: NextPage = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.App}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Wallet-Adapter Example<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span>
          <span class="hljs-attr">name</span>=<span class="hljs-string">"description"</span>
          <span class="hljs-attr">content</span>=<span class="hljs-string">"Wallet-Adapter Example"</span>
        /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Head</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">WalletContextProvider</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AppBar</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.AppBody}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">BalanceDisplay</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">InputFormWallet</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">WalletContextProvider</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<p>This is your application's main page. It integrates all the components to display a functional UI for interacting with Solana wallets and features. The <code>Home</code> component renders the <code>AppBar</code>, <code>BalanceDisplay</code>, and 'InputFormWallet' components, all wrapped inside the <code>WalletContextProvider</code>.</p>
<h2 id="heading-connect-your-wallet">Connect Your Wallet</h2>
<p>Before diving into the technical steps, ensure you have the Phantom wallet installed and set up. Phantom is a popular Solana wallet that you'll use to interact with the Solana blockchain</p>
<h2 id="heading-how-to-open-and-set-up-phantom-wallet">How to open and Set Up Phantom Wallet:</h2>
<ol>
<li><p>Visit the <a target="_blank" href="https://phantom.app/">Phatom Wallet Website</a> and download the extension for you preferred browser.</p>
</li>
<li><p>Follow the on-screen instructions to create a new wallet or import an existing one.</p>
</li>
<li><p>Once set up, open the Phantm wallet extension and ensure it is connected to the Solana network; in the upper left side, click on config and follow preferences, and then move to <code>devnet</code>.</p>
</li>
</ol>
<p>In the Phantom wallet, you have your own public key where you receive tokens. In this case, test tokens are not real. Once you open again your Phantom Solana wallet in the upper right corner, once you connect and enter the password, then click on the button and copy that public key address. In order to have some test tokens, go to <a target="_blank" href="https://faucet.solana.com/">Solana Faucet</a> to get some tokens to test paste your public key there and get some tokens.</p>
<p>Remember, you can send these new test tokens to another public key address for testing purposes. That's the reason we did the previous script to generate a public key address, as well as a secret one, but we won't use it in this project because we are using Phantom wallet, which has its own secret key.</p>
<p>In Chrome, you will see the extension jigsaw symbol "not the movie" :smile: in the upper right corner. Open it and pin the "Phantom wallet" extension to the main bar so that the next time you enter, it's your sight right away.</p>
<h2 id="heading-ui-components-and-connection-to-wallet">UI Components and Connection to Wallet</h2>
<p>Before we further create a new folder in the src folder:</p>
<pre><code class="lang-bash">mkdir src/components
</code></pre>
<p>Inside it, let's add the following files using this command:</p>
<pre><code class="lang-bash">touch src/components/AppBar.tsx src/components/InputFormWallet.tsx src/components/WalletContextProvider.tsx
</code></pre>
<h2 id="heading-appbartsx">AppBar.tsx</h2>
<p>This component shows the application's top navigation bar, which includes a logo, title, and wallet connection button.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { FC } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">'../styles/Home.module.css'</span>
<span class="hljs-keyword">import</span> Image <span class="hljs-keyword">from</span> <span class="hljs-string">"next/image"</span>;
<span class="hljs-keyword">import</span> dynamic <span class="hljs-keyword">from</span> <span class="hljs-string">"next/dynamic"</span>;
<span class="hljs-keyword">const</span> WalletMultiButton = dynamic(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'@solana/wallet-adapter-react-ui'</span>).then(<span class="hljs-function"><span class="hljs-params">mod</span> =&gt;</span> mod.WalletMultiButton), { <span class="hljs-attr">ssr</span>: <span class="hljs-literal">false</span> });


<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AppBar: FC = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span>(
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.AppHeader}</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Image</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/solanaLogo.png"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">{30}</span> <span class="hljs-attr">width</span>=<span class="hljs-string">{200}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo-image"</span>/&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Wallet-Adapter Example<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">WalletMultiButton</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<p>As always, test the result in <a target="_blank" href="http://localhost:3000"><code>localhost:3000</code></a> to see the desired behavior.</p>
<p>The component imports the <code>WalletMultiButton</code> dynamically, which is used to connect to various Solana wallets. This button will allow users to connect their wallets to the application. The <code>styles</code> object is imported from the <code>Home.module.css</code> file, which provides CSS styling for the component. The logo is rendered using the Next.js <code>image</code> component for optimized image loading.</p>
<p>Copy this image from your browser or download it to place in <code>wallet-app/public/solanaLogo.png</code></p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/64y15luybaw2ohcaawep.png" alt="Solana Logo" /></p>
<h2 id="heading-balancedisplaytsx">BalanceDisplay.tsx</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useConnection, useWallet } <span class="hljs-keyword">from</span> <span class="hljs-string">"@solana/wallet-adapter-react"</span>
<span class="hljs-keyword">import</span> { LAMPORTS_PER_SOL } <span class="hljs-keyword">from</span> <span class="hljs-string">"@solana/web3.js"</span>
<span class="hljs-keyword">import</span> { FC, useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> BalanceDisplay: FC = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [balance, setBalance] = useState(<span class="hljs-number">0</span>);
    <span class="hljs-keyword">const</span> { connection } = useConnection();
    <span class="hljs-keyword">const</span> { publicKey } = useWallet();

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (!connection || !publicKey) {
            <span class="hljs-keyword">return</span>;
        }

        connection.onAccountChange(
            publicKey,
            <span class="hljs-function"><span class="hljs-params">updatedAccountInfo</span> =&gt;</span> {
                setBalance(updatedAccountInfo.lamports / LAMPORTS_PER_SOL)
            },
            <span class="hljs-string">"confirmed"</span>,
        );

        connection.getAccountInfo(publicKey).then(<span class="hljs-function"><span class="hljs-params">info</span> =&gt;</span> {
            setBalance(info.lamports);
        });
    }, [connection, publicKey]);

    <span class="hljs-keyword">return</span>(
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{publicKey ? `Balance ${balance / LAMPORTS_PER_SOL}` : ""} <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<ul>
<li><p>Displays the balance of SOL (Solana) tokens in the connected wallet in the UI.</p>
</li>
<li><p>Imports all hooks required to interact with Solana wallets, like <code>useConnection</code> and <code>useWallet</code>.</p>
</li>
<li><p><code>LAMPORTS_PER_SOL</code> is a constant from <code>@solana/web3.js</code> representing the number of lamports (the smallest unit of SOL) per SOL (1 SOL = 1,000,000,000 lamports).</p>
</li>
<li><p><code>FC</code> stands for Function component, a type in React. <code>useEffect</code> and <code>useState</code> are Reach hooks for managing side effects and component state.</p>
</li>
<li><p><code>useState(0)</code> initializes a state variable <code>balance</code> with a value of <code>0</code>. -<code>useConnection</code> provides access to the <code>connection</code> object, which is used to interact with the Solana blockchain.</p>
</li>
<li><p><code>useWallet</code> provides the <code>publicKey</code> of the connected wallet.</p>
</li>
<li><p>The 'useEffect' hook runs the code inside whenever 'connection' or 'publicKey' changes.</p>
</li>
<li><p>If either <code>connection</code> or <code>publicKey</code> is unavailable, the function exits early <code>return</code>.</p>
</li>
<li><p><code>connection.onAccountChange</code> is an event listener that listens for changes in the account associated with <code>publicKey</code>. When the account changes, it updates the <code>balance</code> state with the new balance (converted from imports to SOL).</p>
</li>
<li><p><code>connection.getAccountInfo</code> fetches the account information for <code>publicKey</code> and updates the <code>balance</code> state with the initial balance. Lastly, it's the return to render the content's component.</p>
</li>
</ul>
<h2 id="heading-inputformwallettsx">InputFormWallet.tsx</h2>
<p>This file is the body of the page where you see all the functionality to interact with the external Phantom wallet, in this case, with user inputs.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useConnection, useWallet } <span class="hljs-keyword">from</span> <span class="hljs-string">"@solana/wallet-adapter-react"</span>
<span class="hljs-keyword">import</span> React, { FC, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> web3 <span class="hljs-keyword">from</span> <span class="hljs-string">"@solana/web3.js"</span>
<span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">'../styles/Home.module.css'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> InputFormWallet: FC = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [amount, setAmount] = useState&lt;string&gt;(<span class="hljs-string">""</span>)
    <span class="hljs-keyword">const</span> [recipient, setRecipient] = useState&lt;string&gt;(<span class="hljs-string">""</span>)
    <span class="hljs-keyword">const</span> { connection } = useConnection()
    <span class="hljs-keyword">const</span> { publicKey, sendTransaction } = useWallet()
    <span class="hljs-keyword">const</span> [transactionLink, setTransactionLink] = useState&lt;string&gt;(<span class="hljs-string">""</span>)

    <span class="hljs-keyword">const</span> handleAmountChange = <span class="hljs-function">(<span class="hljs-params">event: React.ChangeEvent&lt;HTMLInputElement&gt;</span>) =&gt;</span> {
        setAmount(event.target.value)
    }

    <span class="hljs-keyword">const</span> handleRecipientChange = <span class="hljs-function">(<span class="hljs-params">event: React.ChangeEvent&lt;HTMLInputElement&gt;</span>) =&gt;</span> {
        setRecipient(event.target.value)
    }

    <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> (event: React.FormEvent) =&gt; {
        event.preventDefault()

        <span class="hljs-keyword">if</span> (!connection || !publicKey) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Connection or publickey is not available."</span>)
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> lamports = <span class="hljs-built_in">parseFloat</span>(amount) * web3.LAMPORTS_PER_SOL
            <span class="hljs-keyword">const</span> recipientPubKey = <span class="hljs-keyword">new</span> web3.PublicKey(recipient)
            <span class="hljs-keyword">const</span> transaction = <span class="hljs-keyword">new</span> web3.Transaction()

            <span class="hljs-keyword">const</span> sendSolInstruction = web3.SystemProgram.transfer({
                <span class="hljs-attr">fromPubkey</span>: publicKey,
                <span class="hljs-attr">toPubkey</span>: recipientPubKey,
                lamports,
            })

            transaction.add(sendSolInstruction)


            <span class="hljs-keyword">const</span> signature = <span class="hljs-keyword">await</span> sendTransaction(transaction, connection)
            <span class="hljs-keyword">const</span> explorerUrl = <span class="hljs-string">`https://explorer.solana.com/tx/<span class="hljs-subst">${signature}</span>?cluster=devnet`</span>
            setTransactionLink(explorerUrl)

        } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Transaction failed:"</span>, error)
        }
    }

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.AppBody}</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.form}</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Amount (in SOL) to send:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                    <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
                    <span class="hljs-attr">value</span>=<span class="hljs-string">{amount}</span>
                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleAmountChange}</span>
                    <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter amount"</span>
                    <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`${<span class="hljs-attr">styles.input</span>} ${<span class="hljs-attr">styles.formField</span>}`}
                /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Send SOL to:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                    <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
                    <span class="hljs-attr">value</span>=<span class="hljs-string">{recipient}</span>
                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleRecipientChange}</span>
                    <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter recipient address"</span>
                    <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`${<span class="hljs-attr">styles.input</span>} ${<span class="hljs-attr">styles.formField</span>}`}
                /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
                {transactionLink &amp;&amp; (
                    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> 
                    <span class="hljs-attr">href</span>=<span class="hljs-string">{transactionLink}</span> 
                    <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
                    <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.transactionLink}</span>
                    &gt;</span>
                        Check transaction at Solana Explorer
                    <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>

                )}
                <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`${<span class="hljs-attr">styles.input</span>} ${<span class="hljs-attr">styles.formField</span>}`}&gt;</span>Send SOL<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<p>This is a long explanation with all the steps included in each part's file to fully understand the process of handling transactions.</p>
<h2 id="heading-imports">Imports</h2>
<ul>
<li><p><code>useConnection</code> and <code>useWallet</code> are hooks from <code>@solana/wallet-adapter-react</code> that allow users to interact with Solana's blockchain and use their wallets.</p>
</li>
<li><p><code>React</code> and <code>useState</code>: React imports for building components and managing state.</p>
</li>
<li><p><code>web3</code>: Solana's library to handle blockchain interactions.</p>
</li>
</ul>
<h2 id="heading-component-definition">Component Definition</h2>
<ul>
<li><p><code>amount</code> and <code>recipient</code>: State variables to store the amount of SOL to send and the recipient's address.</p>
</li>
<li><p><code>connection</code>: Provides the connection to the Solana blockchain.</p>
</li>
<li><p><code>publicKey</code>: The user's public key from the wallet.</p>
</li>
<li><p><code>sendTransaction</code>: Function to send a transaction to the Solana blockchain.</p>
</li>
<li><p><code>transationLink</code>: State variable to store the URL transaction URL on Solana Explorer.</p>
</li>
</ul>
<h2 id="heading-handlers">Handlers</h2>
<p>Then, the <code>handleAmountChange</code> function calculates the <code>imports</code> (these ones are like satoshi in Bitcoin) or something similar from <code>amount</code> to convert SOL to imports (the smallest unit of SOL). So far, so good.</p>
<p>Next is the <code>handleRecipientChange</code> function, which updates the <code>recipient</code> state when the user types the recipient address input field.</p>
<h2 id="heading-form-submission">Form Submission</h2>
<p>In the beginning, we used the <code>handleSubmit</code> function to handle form submissions, which has the transaction functionality to check if the connection and public key exist.</p>
<p>After that, we used our beloved <code>try-catch</code> block for better debugging practices. We placed all the logic inside the try and initialized the constant variables.</p>
<p>Convert <code>lamports</code> from the <code>amount</code> state variable to <code>lamport</code> (the smallest unit of SOL). Next, we create the <code>recipientPubKey</code> to convert the recipient address to a <code>PublicKey</code> object and save it to a constant variable <code>transaction</code> to construct a new transaction object.</p>
<p>Here, we use a helper function from the 'w3' Solana library to transfer some SOL and chain with the transfer method with the address from the public key and to the recipient address public key. All of these are saved in the <code>sendSolIntruction</code> constant variable.</p>
<p>Then, execute the instructions with <code>sendsolInstructions</code>, chaining the method 'add' from <code>transaction</code> constant variable.</p>
<p>To check if the transaction was successful and if it didn't catch any errors in the process. In blockchain operations in most cryptos, we see that process checking the result of the transaction, the <code>tx</code>, the transaction validation or signature, which is a long string of alphanumeric values.</p>
<p>Give the arguments 'transaction' and 'connection' to the <code>sendTransaction</code> function from Solana web3. This asynchronous operation saves to a constant variable, <code>signature</code>. Now that we have our <code>signature</code>, we save it to show the result of building a URL, which we call a variable <code>explorerUrl</code>. Set the <code>explorerUrl</code> as argument in the <code>setTransactionLink</code> state hook.</p>
<h2 id="heading-rendering">Rendering</h2>
<ul>
<li><p>Form: a form that triggers 'handleSubmit' on submission.</p>
</li>
<li><p>Amount Input: Field for entering the amount of SOL to send.</p>
</li>
<li><p>Recipient Input: Field for entering the recipient's public address or address to send the SOL tokens.</p>
</li>
<li><p>Submit Button: Button to submit the form and send SOL.</p>
</li>
</ul>
<p>This file has all the app's main logic. That's why the explanation took centuries.</p>
<h2 id="heading-walletcontextprovider">WalletContextProvider</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { FC, ReactNode, useMemo } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> {
    ConnectionProvider,
    WalletProvider,
} <span class="hljs-keyword">from</span> <span class="hljs-string">"@solana/wallet-adapter-react"</span>
<span class="hljs-keyword">import</span> { WalletModalProvider} <span class="hljs-keyword">from</span> <span class="hljs-string">"@solana/wallet-adapter-react-ui"</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> web3 <span class="hljs-keyword">from</span> <span class="hljs-string">"@solana/web3.js"</span>;
<span class="hljs-built_in">require</span>(<span class="hljs-string">"@solana/wallet-adapter-react-ui/styles.css"</span>)

<span class="hljs-keyword">const</span> WalletContextProvider: FC&lt;{ <span class="hljs-attr">children</span>: ReactNode }&gt; = <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> endpoint = web3.clusterApiUrl(<span class="hljs-string">"devnet"</span>);
    <span class="hljs-keyword">const</span> wallets = useMemo(<span class="hljs-function">() =&gt;</span> [], [])

    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ConnectionProvider</span> <span class="hljs-attr">endpoint</span>=<span class="hljs-string">{endpoint}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">WalletProvider</span> <span class="hljs-attr">wallets</span>=<span class="hljs-string">{wallets}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">WalletModalProvider</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">WalletModalProvider</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">WalletProvider</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ConnectionProvider</span>&gt;</span></span>
    );
  };

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> WalletContextProvider;
</code></pre>
<p>This code file integrates the Solana wallet functionality into our React Next application. It ensures our app can connect to the Solana blockchain and interact with various Solana wallets.</p>
<h2 id="heading-imports-1">Imports</h2>
<ul>
<li><p><code>FC</code> and <code>ReactNode</code>: Typescript types for defining functional components and their children.</p>
</li>
<li><p><code>useMemo</code>: A React hook for memoizing(not repeating, speed up) values to optimize performance.</p>
</li>
<li><p><code>ConnectionProvider</code>, <code>WalletProvider</code>: Providers from <code>@solana/wallet-adapter-react</code> to handle Solana blockchain connections and wallet interactions.</p>
</li>
<li><p><code>WalletModalProvider</code>: Provides a modal UI for wallet selection from <code>@solana/wallet-adapter-react-ui</code>.</p>
</li>
<li><p><code>web3</code>: Solana library for interacting with the blockchain.</p>
</li>
<li><p><code>require("@solana/wallet-adapter-react-ui/styles.css")</code>: Imports the default styles for the wallet UI components.</p>
</li>
</ul>
<h2 id="heading-explanation-1">Explanation</h2>
<p>The <code>WalletContextProvider</code> is A functional component that takes <code>children</code> as a prop. Those children represent the nested components that this provider will wrap.</p>
<p>Next, to interact with the blockchain, call the <code>devnet</code> Solana blockchain from the <code>clusterApiUrl</code> function from the <code>web3</code> library. If it were a real transaction, it has to be the <code>mainnet</code> blockchain.</p>
<p>Another variable here is <code>wallets</code>, a memoized empty array—adapters to specify which wallets your application supports.</p>
<h2 id="heading-rendering-1">Rendering</h2>
<ul>
<li><p><code>ConnectionProvider</code>: Wraps the application and connects to the Solana blockchain. It takes the <code>endpoint</code> as a prop.</p>
</li>
<li><p><code>WalletProvider</code>: Provides wallet functionality and context to the components. It uses the <code>wallets</code> array, eventually containing the wallet adapters. The <code>children</code> Represent the components nested inside <code>WalletContextProvider</code>, which will have access to the Solana connection and wallet functionality.</p>
</li>
</ul>
<p>Finally, export the component.</p>
<h2 id="heading-style-the-pages-body">Style the page's body:</h2>
<p>In the file structure in your VS Code panel or your code of choice, localize the folder: <code>src/styles</code> and then open <code>global.css</code> and erase all the content and place this one standard CSS code:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">'Segoe UI'</span>, <span class="hljs-string">'Roboto'</span>, <span class="hljs-string">'Oxygen'</span>,
    <span class="hljs-string">'Ubuntu'</span>, <span class="hljs-string">'Cantarell'</span>, <span class="hljs-string">'Fira Sans'</span>, <span class="hljs-string">'Droid Sans'</span>, <span class="hljs-string">'Helvetica Neue'</span>,
    sans-serif;
  <span class="hljs-attribute">-webkit-font-smoothing</span>: antialiased;
  <span class="hljs-attribute">-moz-osx-font-smoothing</span>: grayscale;
}

<span class="hljs-selector-tag">code</span> {
  <span class="hljs-attribute">font-family</span>: source-code-pro, Menlo, Monaco, Consolas, <span class="hljs-string">'Courier New'</span>,
    monospace;
}
</code></pre>
<p>Do the same with the following file in <code>src/styles</code> and the open <code>Home.module.css</code> erase all and copy this code:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.App</span> {
  <span class="hljs-attribute">min-height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">text-align</span>: left;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#282c34</span>;
}

<span class="hljs-selector-class">.AppHeader</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">90px</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">background-color</span>: black;
  <span class="hljs-attribute">flex-direction</span>: row;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">padding-left</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">padding-right</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
}

<span class="hljs-selector-class">.AppBody</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">justify-content</span>: flex-start;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-built_in">calc</span>(<span class="hljs-number">10px</span> + <span class="hljs-number">2vmin</span>);
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">padding-top</span>: <span class="hljs-number">50px</span>;
}

<span class="hljs-selector-class">.form</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ccc</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">8px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
}

<span class="hljs-selector-class">.input</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#f2f2f2</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">300px</span>;
  <span class="hljs-attribute">border-radius</span>:  <span class="hljs-number">4px</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ccc</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
}

<span class="hljs-selector-class">.formField</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">transition</span>: border-color <span class="hljs-number">0.3s</span> ease, box-shadow <span class="hljs-number">0.3s</span> ease;
}
<span class="hljs-selector-class">.formField</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">border-color</span>: <span class="hljs-number">#0070f3</span>;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">5px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">122</span>, <span class="hljs-number">243</span>, <span class="hljs-number">0.5</span>);
}

<span class="hljs-selector-class">.formButton</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">4px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#0070f3</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">cursor</span>: pointer;

}


<span class="hljs-selector-class">.transactionLink</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#61dafb</span>;
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">transition</span>: color <span class="hljs-number">0.3s</span> ease;
}
<span class="hljs-selector-class">.transactionLink</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#21a1f1</span>;
}
</code></pre>
<p>All the previous CSS files were to style the body and buttons of the main app's index.tsx` file.</p>
<h2 id="heading-testing">Testing</h2>
<ul>
<li>Check results <a target="_blank" href="http://localhost:3000"><code>localhost:3000</code></a> in your favorite browser.</li>
</ul>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lmsorrw36ufu8eyzdbzy.png" alt="UI and Phantom Wallet" /></p>
<p>Now we have to connect to Phantom wallet:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ucyhvt3pgyusd9b2abwi.png" alt="Connect Phantom Wallet" /></p>
<p>In the upper right corner, you will see the Phantom Wallet public key:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i5nyca8zcrv13gzxdm6o.png" alt="Balance Publickey Phantom wallet" /></p>
<p>Now, let's do the main work of this project to send SOL(solana tokens) test tokens as we are using <code>devnet</code> blockchain not real.</p>
<p>-First, input some SOL token to send, in this case, just 0.1:</p>
<ul>
<li><p>Remember the file that we did earlier in the project: at <code>src/utils/publicKeyGenerator.ts</code>, open another terminal with this shortcut in Windows: <code>Ctrl+Shift+</code> or in Mac <code>Cmd +</code> press simultaneously, and you will see another terminal window to work while the server <a target="_blank" href="http://localhost:3000"><code>localhost:3000</code></a> it's working.</p>
</li>
<li><p>In that terminal type this command:</p>
</li>
</ul>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> Projects/wallet-app
</code></pre>
<p>And then, also type this command:</p>
<pre><code class="lang-bash">npx esrun utils/publicKeyGenerator.ts
</code></pre>
<p>You will see his result in the terminal console:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p2l9x52aiwi86hjwl697.png" alt="Generated PublicKey Address" /></p>
<p>Underneath the public key, you see the secret key and a warning message from <code>punny</code> module. For now, just focus on the public key. Those are warnings that once you have to deploy, you will clean it. There is nothing to worry about for now.</p>
<p>Copy Windows <code>Ctrl + c</code> Mac <code>Cmd + c</code> and paste in the the input "Send SOL to:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2yocjiuja5ue15icdf7w.png" alt="Paste Solana Address" /></p>
<p>After that, send the transaction using are UI to connect to Phantom wallet:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/auvlsfen6thorq0fb0d7.png" alt="Press send button" /></p>
<p>That precious action will open the 'Phantom Wallet', and you will see too some warning messages. Don't worry about those since this is testing in real life you have to clean it. Just click on the 'Confirm' button.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wiv6mfjkbu7kz0xsgd3h.png" alt="Phantom Wallet window transaction" /></p>
<p>The 'Phantom' window disappears after that, and you will see a blue message between the address we sent the tokens for and the <strong>Send SOL button</strong>:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iknjiklg5mcrp8q6myn5.png" alt="Solana transaction tx" /></p>
<p>That action will open a new window, the 'Solana Explorer'. It's a web page where you can see your transaction results in action with all the information like:</p>
<ul>
<li><p>Signature</p>
</li>
<li><p>Result</p>
</li>
<li><p>Timestamp</p>
</li>
<li><p>Confirmation Status</p>
</li>
<li><p>Number of confirmations</p>
</li>
</ul>
<p>With, all that information, you already know if the transaction was made or not. Remember that this the 'Devnet'; for testing in production app we have to work on 'Mainnet' blockchain.</p>
<p>Back to our UI window, you can see your remaining SOL's balance.</p>
<p>It was a long tutorial please take your time to do it ufffff.</p>
<h2 id="heading-summary">Summary</h2>
<p>This project tutorial explains how to create a simple Solana wallet app using React, TypeScript, and the Solana Web3.js library. The app allows user to connect their wallets, display their SOL balance, and send transitions to other Solana addresses. Key components like <code>BalanceDisplay</code>, <code>InputFormWallet</code>, and <code>WalletContextProvider</code> are covered, along with the necessary imports, state management, and form handling.</p>
<p>The app's styling is also provided to ensure a smooth user interface.</p>
<p>I used all the references from Solana's Official web page. I added some more functionality scripts so you can be comfortable working with this project tutorial.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>By following this project tutorial, you've taken the first step toward building decentralized applications on the Solana blockchain. This basic Solana wallet app demonstrates how to connect to a Solana wallet, display the user's balance, and send transactions using React and TypeScript. The integration with Solana Web3.js introduces essential blockchain interactions, offering a practical introduction to working with decentralized finance(DeFi) and Web3 technologies.</p>
<p>Download the project at: <a target="_blank" href="https://github.com/ivansing/solana/tree/main/wallet-app">Github Wallet-App</a></p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="https://solana.com/es/docs">Solana docs</a></p>
</li>
<li><p><a target="_blank" href="https://solana.com/es">Solana Official Page</a></p>
</li>
<li><p><a target="_blank" href="https://solana.com/es/developers/courses/intro-to-solana/interact-with-wallets">Solana Interact with Wallets</a></p>
</li>
</ul>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on <a target="_blank" href="https://x.com/ldway27">X</a>, <a target="_blank" href="https://github.com/ivansing">Github</a>, and <a target="_blank" href="https://www.linkedin.com/in/lance-dev/">LinkedIn</a> for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[Part II: Foundations of Logical Thinking in Programming, Logical Connectors]]></title><description><![CDATA[Logical Connectors
Introduction
If you haven't read the previous article If you haven't read the previous article, please read it first to understand the basic concepts quite well. With this second part, I can provide real-life examples of handling u...]]></description><link>https://blog.byteup.co/part-ii-foundations-of-logical-thinking-in-programming-logical-connectors</link><guid isPermaLink="true">https://blog.byteup.co/part-ii-foundations-of-logical-thinking-in-programming-logical-connectors</guid><category><![CDATA[Math]]></category><category><![CDATA[logic]]></category><category><![CDATA[propositions]]></category><category><![CDATA[programming]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Wed, 11 Sep 2024 15:26:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726068313776/e036de38-0615-465a-b0d2-a5e99150595b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-logical-connectors">Logical Connectors</h2>
<h2 id="heading-introduction">Introduction</h2>
<p>If you haven't read the previous article If you haven't read the <a target="_blank" href="https://dev.to/ivansing/foundations-of-logical-thinking-in-programming-2g6b">previous article</a>, please read it first to understand the basic concepts quite well. With this second part, I can provide real-life examples of handling use cases using truth tables for basic logic, implementing basic sentences to convert in the conjunction math logic, and programming tables "AND."</p>
<h2 id="heading-conjunction-and-in-programming-and">Conjunction and in programming "AND"</h2>
<p>For example, in writing sentences that have meaning, you have to emphasize what makes sense in real life so you can apply it in math logic:</p>
<p>p: I will give you cupcakes q: I will provide you with gift cards</p>
<ol>
<li><p>If I give you cupcakes "and" gift cards, the result is "True."</p>
</li>
<li><p>If I don't give you cupcakes, I give you gift cards. The whole phrase will be "False."</p>
</li>
<li><p>If I give you cupcakes and don't give you gift cards. The entire phrase again is "False."</p>
</li>
<li><p>If I don't give you cupcakes and gift cards. The reasonable result is "False," right?</p>
</li>
</ol>
<p><strong>In conclusion, conjunction:</strong> if one sentence is false, the final result will be false; otherwise, just one option will be true.</p>
<p>Now, I can apply all of the previous sentences in "true tables" like this: I need first to calculate how to make the cells and columns to build the table with the following formula:</p>
<p>Since I have two sentences, p and q, then: 2^n where "n" to the power of the number of propositions 2^2= 4. In this case, we need four rows</p>
<h2 id="heading-conjunction-table-and">Conjunction Table "AND"</h2>
<p>When we use "AND," try to understand that if we have two options and one is false, the results will always be false. If both are true, of course, the result is correct. First, we need a row for headings, for a total of five rows.</p>
<p>Then, we follow the math logic but with True "T" and False "F" symbols and represent the sentences as symbols, too, "p" and "q."</p>
<p>I built like "p" column values, the second column for "q" values, and a third column for the join result of the columns "p" and "q" with the added conjunction symbol."∧" or "AND":</p>
<p><strong>Conjunction Table "AND"</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>p</td><td>q</td><td>p ∧ q</td></tr>
</thead>
<tbody>
<tr>
<td>V</td><td>V</td><td>V</td></tr>
<tr>
<td>V</td><td>F</td><td>F</td></tr>
<tr>
<td>F</td><td>V</td><td>F</td></tr>
<tr>
<td>F</td><td>F</td><td>F</td></tr>
</tbody>
</table>
</div><p><strong>Disjuction "OR" Table</strong></p>
<p>As we did in the previous example with the Conjunction table, I will apply these principles to our "OR" table next. Remember that "OR" means that you can choose if you have two options, and the result will be more truthful than false.</p>
<p>First, let's build our sentences:</p>
<ol>
<li><p>If I give you cupcakes "or" gift cards. The result will be "True".</p>
</li>
<li><p>I will give you cupcakes or (not give you) gift cards. The join result will be "True". Why? (Logic explanation: If either sentence is true, the entire phrase is true because we have two options to pick from.)</p>
</li>
<li><p>If I don't give you cupcakes, "but" I give you gift cards. In this case, the "but" is like the "or" option, so if you pick between both and one, the result will indeed be true.</p>
</li>
<li><p>If I don't give you cupcakes or gift cards, the entire phrase is false.</p>
</li>
</ol>
<p><strong>In conclusion</strong>, if just one sentence proposition is true, the result will be true, and in just one case, it is false where two sentences are false.</p>
<p>Now, let's build the Disjuction "OR" table:</p>
<p>Once again, we have two sentences, so use the formula 2^n. Where "n" is the number of sentence propositions. 2^2 = 4. Apply four rows to our table plus one row for the headings:</p>
<p><strong>Disjunction "OR" Table</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>p</td><td>q</td><td>p V q</td></tr>
</thead>
<tbody>
<tr>
<td>V</td><td>V</td><td>V</td></tr>
<tr>
<td>V</td><td>F</td><td>V</td></tr>
<tr>
<td>F</td><td>V</td><td>V</td></tr>
<tr>
<td>F</td><td>F</td><td>F</td></tr>
</tbody>
</table>
</div><h2 id="heading-negation-table">Negation Table</h2>
<p>It's just to negate one sentence like this: I'm hungry. Negation will be: I'm not hungry. It's pretty straightforward to understand and do the opposite of the sentence. If it's positive, swapped to negative.</p>
<p>p: I'm hungry ¬ p: I'm not hungry</p>
<ol>
<li><p>If I'm hungry(it's true) but I'm not hungry. This will a false statement, so the result will be false.</p>
</li>
<li><p>If I'm not hungry(it's a lie), but the truth is I'm hungry. The result in this case it's true because I'm hungry.</p>
</li>
</ol>
<p><strong>Note:</strong> This is the only logical connector that we can negative twice next keep on doing the next example:</p>
<p>¬ ¬ p or (¬ p):(that means two negations):</p>
<pre><code class="lang-plaintext">It's false that    I'm not        hungry             
    ¬                ¬               p
</code></pre>
<p>Now, to get the result of the third column, we have to analyze the following: If we have two negations in a row, those negatives are eliminated. The previous compound propositions will be the initial proposition. Let's show the example in the negation table:</p>
<p>To build the table, the same formula: 2^n. "n" power number proposition. 2^1 = 2. So we only need two rows.</p>
<p><strong>¬, ~ No, or Negation</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>p</td><td>¬p</td><td>¬ ¬ p</td></tr>
</thead>
<tbody>
<tr>
<td>V</td><td>F</td><td>V</td></tr>
<tr>
<td>F</td><td>V</td><td>F</td></tr>
</tbody>
</table>
</div><p>As you can see, the initial value in the first row of column "p" is "V," so the result of that negation will be "V" and vice versa.</p>
<p>Check this example sentence:</p>
<p>It is not colorless, which means that it does indeed have some color. Why? because we eliminated two negations: "not" and "less." As a result, it has a "color."</p>
<p>The previous statement is hypothetical and might be true; this is just an example. Don't take it for granted; you have never heard that statement that often.</p>
<h2 id="heading-conditional-ifthen">Conditional If/Then →</h2>
<p>If we have two propositions to join and get a result, in other words, if you have a cause, then you have a consequence. Let's see these two sentences examples:</p>
<p>p: You study every day q: I will take you to travel</p>
<p>Now, let's convert the sentences into propositions: If you study daily, I will take you on a trip.</p>
<p>As you remember, we have to build a truth table. Let's do it now: Since we have to sentences apply the formula: 2^2 = 4. We get four rows plus one row for the headings and three columns: "p", "q" and "p → q"(conditionals)</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>p</td><td>q</td><td>p → q</td></tr>
</thead>
<tbody>
<tr>
<td>V</td><td>V</td><td>V</td></tr>
<tr>
<td>V</td><td>F</td><td>F</td></tr>
<tr>
<td>F</td><td>V</td><td>V</td></tr>
<tr>
<td>F</td><td>F</td><td>V</td></tr>
</tbody>
</table>
</div><p><strong>Note:</strong> If the result is false, it's because the first value is True, and the second value is False.</p>
<p>Analyze the four cases of the table based on the initial propositions statements:</p>
<p><strong>"If you study daily, I will take you on a trip."</strong></p>
<ol>
<li><p>If you study daily, then I will take you on a trip. The result is "True." The explanation is that if you study daily, I will give you the promised trip.</p>
</li>
<li><p>I studied daily but didn't give him the promised trip. Explanation: I didn't comply, "but" (it's like then) it works like his request to go on a trip. In this case, the entire proposition will be "False."</p>
</li>
<li><p>I didn't study, and then he took me on a trip. Here, we see that the first sentence is false, but it was recognized with the trip. In this case, the result is "True". It finally has the trip.</p>
</li>
<li><p>I didn't study, and you didn't take a trip. Finally, we have the two sentences that are false, so the result is "False."</p>
</li>
</ol>
<p><strong>Summary</strong></p>
<ol>
<li><p>Applying principles of propositions and building true tables.</p>
</li>
<li><p>Conjunction tables logic "AND."</p>
</li>
<li><p>Disjunction table logic "OR."</p>
</li>
<li><p>Negation table NOT.</p>
</li>
<li><p>Basic principles use conditional If/Then in building compound propositions to build a true compound conditional table.</p>
</li>
</ol>
<p><strong>Conclusion</strong></p>
<p>With this second part of the math logic series, you will have a more robust knowledge of the math logic involved that you might encounter in basic programming principles. Please take your time to do more exercises. Once you master the key components and how to build sentences and transform them into tables, the rest of the logic will be more straightforward.</p>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on <a target="_blank" href="https://x.com/ldway27">X</a>, <a target="_blank" href="https://github.com/ivansing">Github</a>, and <a target="_blank" href="https://www.linkedin.com/in/lance-dev/">LinkedIn</a> for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[Implementing System Design: A Use Case Example]]></title><description><![CDATA[Hypothetical Case Study: Innovative Prison Solutions - Implementing Digital Wallets with Blockchain Technology
Disclaimer: This hypothetical case study is designed for educational purposes and is not intended to represent a real-life project because ...]]></description><link>https://blog.byteup.co/implementing-system-design-a-use-case-example</link><guid isPermaLink="true">https://blog.byteup.co/implementing-system-design-a-use-case-example</guid><category><![CDATA[software development]]></category><category><![CDATA[SDLC]]></category><category><![CDATA[UML]]></category><category><![CDATA[System Architecture]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Wed, 11 Sep 2024 15:20:57 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ghykxhmg9195uf3avdjk.jpg" alt="Grid Fence" /></p>
<h3 id="heading-hypothetical-case-study-innovative-prison-solutions-implementing-digital-wallets-with-blockchain-technology">Hypothetical Case Study: Innovative Prison Solutions - Implementing Digital Wallets with Blockchain Technology</h3>
<p><strong>Disclaimer:</strong> This hypothetical case study is designed for educational purposes and is not intended to represent a real-life project because it needs many improvements.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>Innovative solutions can transform various industries, including the correctional system, in the ever-evolving landscape of technology. This article explores a visionary project to revolutionize prison finances by implementing a blockchain-based digital wallet system for inmates. This system will enhance the prison environment's security, transparency, and efficiency.</p>
<p>Digital money in prisons offers numerous benefits. It reduces the risks associated with handling physical cash, ensures accurate tracking of inmate funds, and facilitates seamless transactions within the prison. Integrating blockchain technology further enhances these benefits by providing a secure, immutable ledger for all transactions.</p>
<h2 id="heading-requirements-specification">Requirements Specification</h2>
<h2 id="heading-functional-requirements">Functional Requirements</h2>
<h2 id="heading-inmate-booking">Inmate Booking</h2>
<p>The system must allow administrators to enter and store detailed information about each inmate when booked into the prison, including personal details, booking date, and available funds. The system must automatically create a digital wallet for each inmate, initialized with the amount of money they have when booking.</p>
<h2 id="heading-digital-wallet">Digital Wallet</h2>
<p>Each inmate's digital wallet must securely store their available digital credit.</p>
<p>The wallet should support transactions such as adding credit, deducting credit for purchases, and viewing transaction history.</p>
<h2 id="heading-purchases-within-the-prison">Purchases within the Prison</h2>
<p>Inmates should be able to purchase using their digital credit at authorized prison facilities.</p>
<p>Each purchase transaction is securely uploaded to the database system, with details including the item purchased, the amount deducted, and the date and time of the transaction.</p>
<h2 id="heading-security">Security</h2>
<p>All transactions must be encrypted and securely transmitted to prevent unauthorized access.</p>
<p>The current user must use blockchain technology to ensure the immutability and transparency of all transaction records.</p>
<h2 id="heading-administrative-functions">Administrative Functions</h2>
<p>Administrators should have access to tools for monitoring and managing inmate accounts, including adding or removing credit, viewing transaction history, and generating reports on inmate spending.</p>
<h2 id="heading-non-functional-requirements">Non-Functional Requirements</h2>
<h2 id="heading-scalability">Scalability</h2>
<p>The system must be able to handle a large number of inmates and transactions without performance degradation.</p>
<h2 id="heading-performance">Performance</h2>
<p>It must process the system transaction in real time to ensure accurate and up-to-date account balances.</p>
<h2 id="heading-security-1">Security</h2>
<p>All inmate data and transaction records must be encrypted and securely stored to prevent unauthorized access. Blockchain technology must ensure the immutability and transparency of all transaction records.</p>
<h2 id="heading-usability">Usability</h2>
<p>The system must have an intuitive and user-friendly interface for inmates and administrators, with easy-to-navigate menus and clear task instructions.</p>
<h2 id="heading-use-case-diagram">Use Case Diagram</h2>
<p>The use case diagram visualizes user interactions (inmates, admins) and the system, highlighting key functionalities such as inmate booking, digital wallet management, purchases, and administrative tasks.</p>
<h2 id="heading-design">Design</h2>
<h2 id="heading-high-level-design">High-Level Design</h2>
<h2 id="heading-system-architecture">System Architecture</h2>
<p>The overall system architecture includes the following components:</p>
<ul>
<li><p><strong>Inmate Management System:</strong> Handles inmate details, booking information, and digital wallet creation.</p>
</li>
<li><p><strong>Digital Wallet:</strong> Manages inmate funds, supports transactions, and maintains balance records.</p>
</li>
<li><p><strong>Transaction Processing System:</strong> Processes purchases made by inmates and updates digital wallet balances.</p>
</li>
<li><p><strong>Blockchain Integration:</strong> Ensures secure, immutable records of all transactions.</p>
</li>
<li><p><strong>Administrative Interface:</strong> Provides tools for administrators to monitor and manage inmate accounts.</p>
</li>
</ul>
<h2 id="heading-component-diagram">Component Diagram</h2>
<p>The component diagram illustrates how different parts of the system interact, including the inmate management system, digital wallet, transaction processing, blockchain integration, and administrative interface.</p>
<h2 id="heading-detailed-design">Detailed Design</h2>
<h2 id="heading-uml-diagrams">UML Diagrams</h2>
<p>##Use Case Diagram</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d05rqrovmjz0897i2nna.png" alt="Use Case Diagram" /></p>
<p>The Use Case Diagram visualizes user interactions (Inmates and Admins) and the system, highlighting key functionalities such as inmate booking, wallet management, purchases, and administrative tasks.</p>
<p><strong>Explanation:</strong> The Use Case Diagram outlines the interactions between actors (Inmates and Admins) and the system, highlighting the main functionalities provided by the system.</p>
<ul>
<li><p><strong>Inmate:</strong> Can make purchases and view transaction history.</p>
</li>
<li><p><strong>Admin:</strong> Can book inmates, manage accounts, and generate reports.</p>
</li>
</ul>
<p>The diagram shows the system's major use cases or functionalities and the interactions between users and system components, providing a high-level overview of user interactions.</p>
<h2 id="heading-class-diagram">Class Diagram</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5w90zr923hdgqqfqz5nr.png" alt="Class diagram" /></p>
<p>The class diagram shows the classes involved in the system, such as Inmate, Wallet, Transaction, and Admin.</p>
<p><strong>Explanation:</strong> The Class Diagram represents the system's static structure. It shows the main classes involved, their attributes (data), methods (functions), and the relationships between them.</p>
<ul>
<li><p><strong>Inmate:</strong> Contains information about each inmate and is associated with a Wallet.</p>
</li>
<li><p><strong>Wallet:</strong> Manages digital credit, supports transactions, and maintains a transaction history.</p>
</li>
<li><p><strong>Transaction:</strong> Represents individual financial transactions, including the amount and type.</p>
</li>
<li><p><strong>Admin:</strong> Manages inmate accounts, including adding or removing credit, viewing transaction histories, and generating reports.</p>
</li>
<li><p><strong>Report:</strong> Represents the generated reports for administrative purposes.</p>
</li>
</ul>
<p>The diagram helps us understand how different system components interact and are organized.</p>
<h2 id="heading-sequence-diagram">Sequence Diagram</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ir61c0p1exlpr3874ggu.png" alt="Sequence Diagram" /></p>
<p>The sequence diagram illustrates the sequence of interactions for critical processes, such as booking an inmate and making a purchase.</p>
<p><strong>Explanation:</strong> The Sequence Diagram illustrates the sequence of interactions between various actors (Admin, Inmate) and system components (System, Wallet, Blockchain, Database) during critical processes.</p>
<ul>
<li><p><strong>Inmate Booking:</strong> This shows how an Admin books an inmate, creates a digital wallet, and stores details.</p>
</li>
<li><p><strong>Making a Purchase:</strong> This demonstration demonstrates the process of an inmate making a purchase, with credit deducted from their wallet and the transaction recorded.</p>
</li>
<li><p><strong>Managing Accounts:</strong> Details how Admins manage inmate accounts by adding or removing credit and updating details.</p>
</li>
<li><p><strong>Generating Reports:</strong> Describes how to create reports by retrieving data from the database.</p>
</li>
</ul>
<p>The diagram provides a dynamic view of how different system parts work together over time.</p>
<h2 id="heading-activity-diagram">Activity Diagram</h2>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irxg6z3nkh9xa3clbsy3.png" alt="Activity Diagram" /></p>
<p>The activity diagram shows the workflow of processes like inmate booking and transaction processing.</p>
<p>Explanation: The Activity Diagram depicts the workflow of various processes within the system. It illustrates the activities involved in critical processes like booking an inmate, purchasing, and managing accounts.</p>
<ul>
<li><p><strong>Inmate Booking:</strong> Includes steps for entering details, creating a wallet, and storing information.</p>
</li>
<li><p><strong>Making a Purchase:</strong> Shows the purchasing process, including authentication and wallet updates.</p>
</li>
<li><p><strong>Managing Accounts:</strong> Details how Admins add or remove credit and update account details.</p>
</li>
<li><p><strong>Generating Reports:</strong> Includes steps to retrieve data and create reports.</p>
</li>
</ul>
<p>The diagram helps visualize the flow of activities and decision points in the system's processes, clarifying how different tasks are carried out.</p>
<h2 id="heading-summary">Summary</h2>
<p>This article explored a hypothetical case study on implementing a blockchain-based digital wallet system for prison inmates. This system aims to modernize and secure the management of inmate finances, ensuring accurate and transparent transactions within the prison environment. We outlined the functional and non-functional requirements, including the need for real-time transaction processing, high security, and a user-friendly interface. Additionally, we provided various UML diagrams, such as use case, class, sequence, and activity diagrams, to illustrate the design and workflow of the system.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article presented a use-case example of implementing a blockchain-based digital wallet system within a prison environment, demonstrating how system design principles can address complex real-world challenges. We illustrated the key components and workflows necessary for secure and efficient inmate financial management by outlining the functional and non-functional requirements and providing detailed UML diagrams.</p>
<p>Integrating blockchain technology showcases the potential for enhancing transparency and security in traditional systems. This case study underscores the value of careful system design and planning in developing scalable solutions, offering insights into how modern technologies can be leveraged to improve operational efficiency and integrity.</p>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. You can follow on X for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[Building an AI-Powered Web Application with Next.js and TensorFlow.js]]></title><description><![CDATA[This tutorial is designed to guide you through building an AI-powered web application and showcase the potential of AI in everyday web development. Artificial Intelligence (AI) is revolutionizing modern web technology, making it more innovative and r...]]></description><link>https://blog.byteup.co/building-an-ai-powered-web-application-with-nextjs-and-tensorflowjs</link><guid isPermaLink="true">https://blog.byteup.co/building-an-ai-powered-web-application-with-nextjs-and-tensorflowjs</guid><category><![CDATA[Node.js]]></category><category><![CDATA[TensorFlow]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Wed, 11 Sep 2024 15:05:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726067004020/557c7e6d-316e-4fb2-af22-8013b992a0b8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This tutorial is designed to guide you through building an AI-powered web application and showcase the potential of AI in everyday web development. Artificial Intelligence (AI) is revolutionizing modern web technology, making it more innovative and responsive. By incorporating AI, developers can enhance user experiences through features like real-time data analysis, personalized content recommendations, and advanced image recognition.</p>
<p>Next.js is a robust Reach framework that enables developers to quickly build server-side rendered and static web applications. It offers excellent performance, scalability, and a seamless developer experience. TensorFlow.js, on the other hand, TensorFlow.js is a Javascript library that allows you to train and run machine learning models directly in the browser. By combining Next.js and TensorFlow.js, you can create sophisticated web applications that leverage the power of AI without needing extensive backend infrastructure.</p>
<p>By the end of this tutorial, you will have built a fully functional AI-powered web application capable of performing image recognition tasks. You'll gain hands-on experience with Next.js and TensorFlow.js, learning how to integrate machine learning models into a modern web framework. This tutorial will equip you with the skills to start incorporating AI features into your projects, opening up new possibilities for innovation and user engagement.</p>
<h2 id="heading-setting-up-the-environment">Setting Up the Environment</h2>
<h3 id="heading-prerequisites">Prerequisites:</h3>
<ul>
<li><p>Basic JavaScript</p>
</li>
<li><p>Node.js</p>
</li>
<li><p>Code Editor</p>
</li>
</ul>
<h2 id="heading-step-1-setting-up-the-project">Step 1: Setting Up the Project</h2>
<ul>
<li><p>First, ensure you have Node.js installed on your system. If you haven't already, you can download it from <a target="_blank" href="http://nodejs.org">nodejs.org</a>.</p>
</li>
<li><p>Next, make a folder on your PC, like in a Linux/Mac root folder or Windows.</p>
</li>
<li><p><strong>Linux/Mac</strong></p>
</li>
</ul>
<p>It's common to place your projects in a <code>Projects</code> directory within your home directory.</p>
<ul>
<li>Open the VS Code at the top bar, select <code>View</code> scroll down to the terminal, and create a folder called <code>Projects</code> this into the terminal:</li>
</ul>
<pre><code class="lang-bash">mkdir -p ~/Projects
</code></pre>
<p>and move to the project's folder by running:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> Projects
</code></pre>
<p>Your projects would then be located in path like: <code>/home/your-username/Projects/my_project</code> (Linux) <code>/Users/your-username/Projects/my_project</code> (Mac)</p>
<p><strong>Windows Using Linux subsystem WSL</strong></p>
<ul>
<li><p>Open VS Code press F1, and select connect to WSL.</p>
</li>
<li><p>Follow the same previous instructions from Linux/Mac</p>
</li>
</ul>
<h2 id="heading-step-2-installing-nextjs">Step 2: Installing Next.js</h2>
<p>If you haven't installed Next.js yet, you can create a new Next.js project using the following command:</p>
<h3 id="heading-installing-nextjs">Installing Next.js:</h3>
<pre><code class="lang-bash">npx create-next-app ai-web-app
</code></pre>
<p>Test that the app is working as for now:</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<p>You will see the Next.js app on the page <a target="_blank" href="http://localhost:3000"><code>http://localhost:3000</code></a>. If it works, we can proceed.</p>
<h3 id="heading-installing-tensorflowjs">Installing TensorFlow.js:</h3>
<pre><code class="lang-bash">npm install @tensorflow/tfjs @tensorflow-models/mobilenet
</code></pre>
<h3 id="heading-project-structure">Project Structure</h3>
<pre><code class="lang-bash">ai-web-app/
├── node_modules/
├── public/
├── src/
│   ├── pages/
│   │   ├── api/
│   │   │   └── hello.js
│   │   ├── _app.js
│   │   ├── _document.js
│   │   ├── index.js
│   ├── styles/
│   │   ├── globals.css
│   │   ├── Home.module.css
│   ├── utils/
│   │   └── imageProcessing.js
├── .gitignore
├── package.json
├── README.md
</code></pre>
<p>So, we have to add the following file:</p>
<ul>
<li><p>imageProcessing.js</p>
</li>
<li><p>Edit src/pages/index.js:</p>
</li>
</ul>
<p>Erase all the code and add the following ones:</p>
<h2 id="heading-part-1-imports-and-state-initialization">Part 1: Imports and State Initialization</h2>
<ol>
<li>Imports</li>
</ol>
<ul>
<li><p><code>Head</code> from <code>next/head</code>: Used to modify the <code>&lt;head&gt;</code> section of the HTML.</p>
</li>
<li><p><code>styles</code> from <code>../styles/Home.module.css</code>: Imports the CSS module for styling.</p>
</li>
<li><p><code>useState</code> from <code>react</code>: React hook for state management.</p>
</li>
<li><p><code>loadModel</code> and <code>loadImage</code> from <code>@/utils/imageProcessing</code>: Utility functions for loading the model and image.</p>
</li>
</ul>
<ol start="2">
<li>State Initialization</li>
</ol>
<ul>
<li><p><code>model</code>: State to store the loaded TensorFlow model.</p>
</li>
<li><p><code>predictions</code>: State to store the predictions made by the model.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">"next/head"</span>;
<span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">"../styles/Home.module.css"</span>;
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { loadModel, loadImage } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/utils/imageProcessing"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [model, setModel] = useState(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> [predictions, setPredictions] = useState([]);
</code></pre>
<h2 id="heading-part-2-handling-image-analysis">Part 2: Handling Image Analysis</h2>
<ol start="3">
<li>handleAnalyzeClick Function:</li>
</ol>
<ul>
<li><p>Retrieves the uploaded image file.</p>
</li>
<li><p>Loads the image and passes it to the model for classification.</p>
</li>
<li><p>Sets the predictions state with the results.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> handleAnalyzeClick = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> fileInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"image-upload"</span>);
    <span class="hljs-keyword">const</span> imageFile = fileInput.files[<span class="hljs-number">0</span>];

    <span class="hljs-keyword">if</span> (!imageFile) {
      alert(<span class="hljs-string">"Please upload an image file."</span>);
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> image = <span class="hljs-keyword">await</span> loadImage(imageFile);
      <span class="hljs-keyword">const</span> predictions = <span class="hljs-keyword">await</span> model.classify(image);
      setPredictions(predictions);
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error analyzing the image:'</span>, error);
    }
  };
</code></pre>
<ol>
<li>Retrieving the Uploaded Image File:</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fileInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"image-upload"</span>);
<span class="hljs-keyword">const</span> imageFile = fileInput.files[<span class="hljs-number">0</span>];
</code></pre>
<ul>
<li><p><code>document.getElementById("image-upload");</code>: This retrieves the file input element from the DOM. This element is where users upload their images.</p>
</li>
<li><p><code>const imageFile = fileInput.files[0];</code>: This gets the first file from the file input. The <code>files</code> property is an array-like object, so we select the first file uploaded.</p>
</li>
</ul>
<ol start="2">
<li>Checking if an Image File is Uploaded:</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!imageFile) {
  alert(<span class="hljs-string">"Please upload an image file."</span>);
  <span class="hljs-keyword">return</span>;
}
</code></pre>
<ul>
<li><p><code>if (!imageFile)</code>: This checks if an image file is selected. If no file is selected, <code>imageFile</code> will be <code>null</code> or <code>undefined</code>.</p>
</li>
<li><p><code>alert("Please upload an image file.");</code>: If no file is selected, an alert message is displayed to the user.</p>
</li>
<li><p><code>return;</code>: The Function exits early if no file is selected, preventing further execution.</p>
</li>
</ul>
<ol start="3">
<li>Loading the Image and Classifying It:</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> image = <span class="hljs-keyword">await</span> loadImage(imageFile);
  <span class="hljs-keyword">const</span> predictions = <span class="hljs-keyword">await</span> model.classify(image);
  setPredictions(predictions);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error analyzing the image:'</span>, error);
}
</code></pre>
<ul>
<li><p><code>try { ... } catch (error) { ... }</code>: The <code>try-catch</code> The block handles any errors during the image loading and classification process.</p>
</li>
<li><p>Loading the Image:</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> image = <span class="hljs-keyword">await</span> loadImage(imageFile);
</code></pre>
<ul>
<li><p><code>loadImage(imageFile)</code>: This function is a utility that converts the image file into a format suitable for processing TensorFlow.js. It likely involves reading the file and creating an HTML image element or a TensorFlow.js tensor.</p>
</li>
<li><p><code>await</code>: This keyword ensures that the Function waits for the image loading to complete before moving to the next step.</p>
</li>
<li><p><code>const image =</code>: The loaded image is stored in the image Variable.</p>
</li>
</ul>
<h3 id="heading-classifying-the-image">Classifying the Image:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> predictions = <span class="hljs-keyword">await</span> model.classify(image);
</code></pre>
<ul>
<li><p><code>model.classify(image)</code>: This method uses the TensorFlow.js model to classify the input image. It returns predictions about what the image contains.</p>
</li>
<li><p><code>await</code>: This ensures the Function waits for the classification process to complete.</p>
</li>
<li><p><code>const predictions =</code>: The classification results are stored in the predictions Variable.</p>
</li>
</ul>
<h3 id="heading-setting-predictions-state">Setting Predictions State:</h3>
<pre><code class="lang-javascript">setPredictions(predictions);
</code></pre>
<p><code>setPredictions(predictions)</code>: This updates the predictions State with the new classification results. This triggers a re-render of the component, displaying the predictions to the user.</p>
<ol start="4">
<li>Handling Errors:</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error analyzing the image:'</span>, error);
}
</code></pre>
<p>catch (error) { ... }: This block catches any errors that occur during the try block. console.error('Error analyzing the image:', error);: If an error occurs, it logs the error message to the console for debugging purposes.</p>
<h2 id="heading-part-3-loading-the-tensorflow-model">Part 3: Loading the TensorFlow Model</h2>
<ol start="4">
<li>Model Loading:</li>
</ol>
<ul>
<li><p>Uses a <code>useState</code> Hook to load the model when the component mounts.</p>
</li>
<li><p>Sets the loaded model into the state.</p>
</li>
</ul>
<pre><code class="lang-javascript">useState(<span class="hljs-function">() =&gt;</span> {
    (<span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> loadedModel = <span class="hljs-keyword">await</span> loadModel();
        setModel(loadedModel);
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error loading the model:'</span>, error);
      }
    })();
  }, []);
</code></pre>
<ul>
<li><p>Defines a React <code>useState</code> Hook that initializes and loads the TensorFlow.js model when the component mounts.</p>
</li>
<li><p>It uses an immediately invoked asynchronous function to call the <code>loadModel</code> Function, which loads the model and sets it in the component's state using the <code>setModel</code> Function.</p>
</li>
<li><p>If an error occurs during the model loading process, it catches the error and logs it to the console.</p>
</li>
<li><p>The empty dependency array <code>[]</code> ensures this effect runs only once when the component is first rendered.</p>
</li>
</ul>
<h3 id="heading-basic-layout">Basic Layout</h3>
<p>To begin building our AI-powered web application with Next.js and TensorFlow.js, we'll set up a basic layout using Next.js components. This initial structure will be the foundation for our application's user interface.</p>
<h2 id="heading-part-4-rendering-the-ui">Part 4: Rendering the UI</h2>
<p>###5. Rendering:</p>
<ul>
<li><p>Renders the main layout of the application.</p>
</li>
<li><p>Provides input for image upload and button for analysis.</p>
</li>
<li><p>Displays the predictions if available.</p>
</li>
</ul>
<h2 id="heading-jsx-return-statement">JSX Return Statement</h2>
<h3 id="heading-1-fragment-wrapper">1. Fragment Wrapper</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      ...
    <span class="hljs-tag">&lt;/&gt;</span></span>
</code></pre>
<p><code>&lt;&gt; ... &lt;/&gt;</code>: This React Fragment allows multiple elements to be grouped without adding extra nodes to the DOM.</p>
<h3 id="heading-2-container-div">2. Container Div</h3>
<pre><code class="lang-javascript">&lt;div className={styles.container}&gt;
  ...
&lt;/div&gt;
</code></pre>
<p><code>&lt;div className={styles.container}&gt; ... &lt;/div&gt;</code>: This div wraps the main content of the page and applies styling from the <code>styles.container</code> Class.</p>
<h3 id="heading-3-head-component">3. Head Component</h3>
<pre><code class="lang-javascript">&lt;Head&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>AI-Powered Web App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span></span>
&lt;/Head&gt;
</code></pre>
<h3 id="heading-4-main-content">4. Main Content</h3>
<pre><code class="lang-javascript">&lt;main className={styles.main}&gt;
  ...
&lt;/main&gt;
</code></pre>
<p><code>&lt;main className={styles.main}&gt; ... &lt;/main&gt;</code>: This main element contains the primary content of the page and applies styling from the <code>styles.main</code> class</p>
<h3 id="heading-5-title-and-description">5. Title and Description</h3>
<pre><code class="lang-javascript">&lt;h1 className={styles.title}&gt;AI-Powered Web Application&lt;/h1&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.description}</span>&gt;</span>
  Using Next.js and TensorFlow.js to show some AI model.
<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
</code></pre>
<ul>
<li><p><code>&lt;h1 className={styles.title}&gt; ... &lt;/h1&gt;</code>: This heading displays the main title of the page with styling from the <code>styles.title</code> Class.</p>
</li>
<li><p><code>&lt;p className={styles.description}&gt; ... &lt;/p&gt;</code>: This paragraph provides a brief description and is styled using the <code>styles.description</code> Class.</p>
</li>
</ul>
<h3 id="heading-6-input-area">6. Input Area</h3>
<pre><code class="lang-javascript">&lt;div id=<span class="hljs-string">"input-area"</span>&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.input}</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"image-upload"</span> /&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.button}</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleAnalyzeClick}</span>&gt;</span>
    Analyze Image
  <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<ul>
<li><p><code>&lt;div id="input-area"&gt; ... &lt;/div&gt;</code>: This div wraps the input elements for uploading and analyzing an image.</p>
</li>
<li><p><code>&lt;input type="file" className={styles.input} id="image-upload" /&gt;</code>: This input element allows users to upload an image file. It uses the <code>styles.input</code> class for styling and has an ID of <code>image-upload</code>.</p>
</li>
<li><p><code>&lt;button className={styles.button} onClick={handleAnalyzeClick}&gt;Analyze Image&lt;/button&gt;</code>: This button triggers the <code>handleAnalyzeClick function</code> when clicked. It is styled using the <code>styles.button</code> Class.</p>
</li>
</ul>
<h3 id="heading-7-ouput-area">7. Ouput Area</h3>
<pre><code class="lang-javascript">&lt;div id=<span class="hljs-string">"output-area"</span>&gt;
  {predictions.length &gt; <span class="hljs-number">0</span> &amp;&amp; (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {predictions.map((pred, index) =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>
          {pred.className}: {(pred.probability * 100).toFixed(2)}%
        <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      ))}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
  )}
&lt;/div&gt;
</code></pre>
<ul>
<li><p><code>&lt;div id="output-area"&gt; ... &lt;/div&gt;</code>: This div contains the output area where predictions are displayed.</p>
</li>
<li><p><code>{predictions.length &gt; 0 &amp;&amp; ( ... )}</code>: This conditional rendering checks for predictions and renders the list of predictions if there are any.</p>
</li>
<li><p><code>&lt;ul&gt; ... &lt;/ul&gt;</code>: An unordered list that will contain the prediction items.</p>
</li>
<li><p><a target="_blank" href="http://predictions.map"><code>predictions.map</code></a><code>((pred, index) =&gt; ( ... ))</code>: This maps over the predictions Array and render each prediction as a list item.</p>
</li>
<li><p><code>&lt;li key={index}&gt; ... &lt;/li&gt;</code>: Each list item displays the class name and probability of the prediction, formatted to two decimal places. The <code>key</code> attribute helps React identify which items have changed</p>
</li>
</ul>
<p>Edit the Styles for the index.js file in Home.module.css erase all the code, and add the following one:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">min-height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span> <span class="hljs-number">0.5rem</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
}
<span class="hljs-selector-class">.main</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">5rem</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">flex</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
}
<span class="hljs-selector-class">.title</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">line-height</span>: <span class="hljs-number">1.15</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">4rem</span>;
  <span class="hljs-attribute">text-align</span>: center;
}
<span class="hljs-selector-class">.description</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">4rem</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">line-height</span>: <span class="hljs-number">1.5</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.5rem</span>;
  <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-id">#ouput-area</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">2rem</span>;
}
<span class="hljs-selector-class">.li</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
}
<span class="hljs-selector-class">.button</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.5rem</span> <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">cursor</span>:pointer;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#0070f3</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-class">.button</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#005bb5</span>;
}
</code></pre>
<p>Once you have done the previous steps, check to see something like this:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v2t07fw8s29mw4g7uees.png" alt="UI Visual" /></p>
<p>Now, let's work with the brain of the app. imageProcessing.js File:</p>
<h2 id="heading-part-1-loading-the-model">Part 1: Loading the Model</h2>
<h3 id="heading-function-loadmodel">Function: loadModel</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> tf <span class="hljs-keyword">from</span> <span class="hljs-string">"@tensorflow/tfjs"</span>;
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> mobilenet <span class="hljs-keyword">from</span> <span class="hljs-string">"@tensorflow-models/mobilenet"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadModel</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> model = <span class="hljs-keyword">await</span> mobilenet.load();
    <span class="hljs-keyword">return</span> model;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error loading the model:"</span>, error);
    <span class="hljs-keyword">throw</span> error;
  }
}
</code></pre>
<p>This Function loads the MobileNet model using TensorFlow.js. Here's a step-by-step explanation:</p>
<ul>
<li><p>Imports: The Function imports TensorFlow.js (<code>tf</code>) and the MobileNet model (<code>mobilenet</code>).</p>
</li>
<li><p>Function Definition: The <code>loadModel</code> function is defined as an asynchronous function.</p>
</li>
<li><p>Try-Catch Block: Within a try-catch block, the Function loads the MobileNet model asynchronously with <code>await mobilenet.load()</code>.</p>
</li>
<li><p>Return Model: If successful, it returns the loaded model.</p>
</li>
<li><p>Error Handling: If an error occurs, it logs the error to the console and throws it, allowing the calling function to handle it.</p>
</li>
</ul>
<h2 id="heading-part-2-preprocessing-the-image">Part 2: Preprocessing the Image</h2>
<h3 id="heading-function-preprocesimage">Function: preprocesImage</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">preprocesImage</span>(<span class="hljs-params">image</span>) </span>{
  <span class="hljs-keyword">const</span> tensor = tf.browser
    .fromPixels(image)
    .resizeNearestNeighbor([<span class="hljs-number">224</span>, <span class="hljs-number">224</span>]) <span class="hljs-comment">// MobileNet input size</span>
    .toFloat()
    .expandDims();
  <span class="hljs-keyword">return</span> tensor.div(<span class="hljs-number">127.5</span>).sub(<span class="hljs-number">1</span>); <span class="hljs-comment">// Normalize to [-1, 1] range</span>
}
</code></pre>
<p>This function preprocesses an image in the format required by MobileNet. Here's a step-by-step explanation:</p>
<ul>
<li><p>Function Definition: The <code>preprocesImage function</code> is defined to take an image as an argument.</p>
</li>
<li><p>Tensor Conversion: The Function converts the image to a tensor using <code>tf.browser.fromPixels(image)</code>.</p>
</li>
<li><p>Resize: It resizes the image tensor to <code>[224, 224]</code>, which is the required input size for MobileNet.</p>
</li>
<li><p>Float Conversion: The tensor is then converted to a float using <code>.toFloat()</code>.</p>
</li>
<li><p>Add Dimension: The tensor is expanded to include a batch dimension using <code>.expandDims()</code>.</p>
</li>
<li><p>Normalization: Finally, the tensor is normalized to a range of <code>[-1, 1]</code> by dividing by <code>127.5</code> and subtracting <code>1</code>.</p>
</li>
</ul>
<h2 id="heading-part-3-loading-the-image">Part 3: Loading the Image</h2>
<h3 id="heading-function-loadimage">Function: loadImage</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadImage</span>(<span class="hljs-params">file</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> reader = <span class="hljs-keyword">new</span> FileReader();
    reader.onload = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
      <span class="hljs-keyword">const</span> img = <span class="hljs-keyword">new</span> Image();
      img.src = event.target.result;
      img.onload = <span class="hljs-function">() =&gt;</span> resolve(img);
    };
    reader.onerror = <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> reject(error);
    reader.readAsDataURL(file);
  });
}
</code></pre>
<p>This Function loads an image file and returns an HTML Image element. Here's a step-by-step explanation:</p>
<ul>
<li><p>Function Definition: The <code>loadImage function</code> is defined to take a file as an argument.</p>
</li>
<li><p>Promise Creation: The Function returns a new Promise, which resolves with the loaded image or rejects with an error.</p>
</li>
<li><p>FileReader: A <code>FileReader</code> Object is created to read the file.</p>
</li>
<li><p>Reader onLoad: The <code>onload</code> event handler of the reader is defined. It creates a new Image Object sets its source to the file reader's result and resolves the promise with the image once it is loaded.</p>
</li>
<li><p>Reader onError: The <code>onerror</code> event handler of the reader is defined to reject the promise with an error if one occurs. Read File: The file reader reads the file as a data URL using <code>reader.readAsDataURL(file)</code>.</p>
</li>
</ul>
<p>Now you can test this final project by uploading images to the project's page and seeing the final results; if you have any problems, please check the provided link to clone the project from Github:</p>
<p><a target="_blank" href="https://github.com/ivansing/ai-web-app">Github repository project</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This tutorial taught you how to build an AI-powered web application using Next.js and TensorFlow.js. We covered:</p>
<ol>
<li><p><strong>Setting Up the Environment</strong>: You installed Next.js and TensorFlow.js and set up your development environment.</p>
</li>
<li><p><strong>Creating the User Interface</strong>: You made a simple UI for uploading images and displaying predictions.</p>
</li>
<li><p><strong>Integrating TensorFlow.js</strong>: You integrated the MobileNet model to perform image classification directly in the browser.</p>
</li>
</ol>
<p>By combining Next.js and TensorFlow.js, you can create sophisticated web applications that leverage the power of AI, enhancing user experiences with features like image recognition.</p>
<h2 id="heading-next-steps">Next Steps</h2>
<p>To further improve your application, consider exploring these additional features:</p>
<ul>
<li><p><strong>Enhanced UI</strong>: Improve the user interface with more advanced styling or additional features.</p>
</li>
<li><p><strong>Additional Models</strong>: Integrate other pre-trained models from TensorFlow.js or train your custom models.</p>
</li>
<li><p><strong>Real-Time Data</strong>: Implement real-time data processing and display for dynamic user interactions.</p>
</li>
</ul>
<h2 id="heading-additional-resources">Additional Resources</h2>
<ul>
<li><p><a target="_blank" href="https://nextjs.org/docs">Next.js Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://www.tensorflow.org/api_docs">TensorFlow.js Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/tensorflow/tfjs-models/tree/master/mobilenet">MobileNet Model Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://vercel.com/docs">Vercel Documentation</a></p>
</li>
</ul>
<h2 id="heading-about-the-author">About the Author</h2>
<p>Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on <a target="_blank" href="https://x.com/ldway27">X</a>, <a target="_blank" href="https://github.com/ivansing">Github</a>, and <a target="_blank" href="https://www.linkedin.com/in/lance-dev/">LinkedIn</a> for more insights and updates.</p>
]]></content:encoded></item><item><title><![CDATA[Backend Developer Roadmap]]></title><description><![CDATA[There are many things in life that definitely require something to be accomplished. It takes time and effort to study to be a Backend Engineer, and if you are a self-learner, it's more complicated than ever. Sometimes, studying for four years straigh...]]></description><link>https://blog.byteup.co/backend-developer-roadmap</link><guid isPermaLink="true">https://blog.byteup.co/backend-developer-roadmap</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[backend]]></category><category><![CDATA[Roadmap]]></category><dc:creator><![CDATA[Ivan]]></dc:creator><pubDate>Fri, 30 Aug 2024 16:40:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728473216793/f601285a-2ace-4ea3-a78a-d6595bff6999.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There are many things in life that definitely require something to be accomplished. It takes time and effort to study to be a Backend Engineer, and if you are a self-learner, it's more complicated than ever. Sometimes, studying for four years straight to have a Bachelor's in Computer Science is better. The following is an informal way to show you the guidelines to remember. It's my recommendation opinion:</p>
<p>The following bullets don't include subcategories because it will be a long page that won't end just with the basics:</p>
<ul>
<li><p>What is the internet</p>
</li>
<li><p>Pick a programming language (Python, Javascript, Java, C++, etc.)</p>
</li>
<li><p>Version Control Sytems</p>
</li>
<li><p>Relational Database</p>
</li>
<li><p>Learn about APIs</p>
</li>
<li><p>Caching</p>
</li>
<li><p>Web Security</p>
</li>
<li><p>Testing</p>
</li>
<li><p>Scaling Databases</p>
</li>
<li><p>Software Design &amp; Architecture</p>
</li>
<li><p>Design and Development Principles</p>
</li>
<li><p>Containerization vs Virtualization</p>
</li>
<li><p>Real-Time Data</p>
</li>
<li><p>GraphQL</p>
</li>
<li><p>NoSQL Databases</p>
</li>
<li><p>Building For Scale</p>
</li>
<li><p>Basic Infrastructure Knowledge</p>
</li>
</ul>
<p>That will take a long time, but I don't have to follow that order. Many things are connected and more organized; I recommend a free tool to do that. You can generate your own roadmap in this for me Backend Developer:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728473214845/2e647ff6-cad4-48d9-8ffd-7fe1141fd275.png" alt="Backend developer roadmap" /></p>
<p>This website tool allows you to generate your own Roadmap. I love this page because you can record what you do in your daily life, so you don't have to worry about tracking it in a spreadsheet, Word document, or any other media that has this kind of project structure as a diagram.</p>
<p>There are many roadmaps to choose from:</p>
<ul>
<li><p>Full Stack</p>
</li>
<li><p>Frontend</p>
</li>
<li><p>Backend</p>
</li>
<li><p>Android</p>
</li>
<li><p>Blockchain</p>
</li>
<li><p>QA</p>
</li>
<li><p>UX Design</p>
</li>
<li><p>Game Developer</p>
</li>
<li><p>Product Manager</p>
</li>
<li><p>Data Analyst</p>
</li>
</ul>
<p>And much more, so if you feel lost next time, this is a great tool to have a direction.</p>
<p>I hope you enjoy this short article. If you want to stay informed about software engineering and more, please don't hesitate to follow me. Thank you.</p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://roadmap.sh/">Roadmap</a></p>
]]></content:encoded></item></channel></rss>