<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by kartik puri on Medium]]></title>
        <description><![CDATA[Stories by kartik puri on Medium]]></description>
        <link>https://medium.com/@kartik.puri95?source=rss-6cf6ec422886------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KmB9K5ITxu8Fa151X3yipQ.jpeg</url>
            <title>Stories by kartik puri on Medium</title>
            <link>https://medium.com/@kartik.puri95?source=rss-6cf6ec422886------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:26:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kartik.puri95/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Art of Python: Best Practices for Writing Elegant and Efficient Code]]></title>
            <link>https://medium.com/@kartik.puri95/the-art-of-python-best-practices-for-writing-elegant-and-efficient-code-d54e2858c9fb?source=rss-6cf6ec422886------2</link>
            <guid isPermaLink="false">https://medium.com/p/d54e2858c9fb</guid>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[kartik puri]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 04:43:46 GMT</pubDate>
            <atom:updated>2023-04-18T04:43:46.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d29rMW6XJynrtN-NQs6BbA.png" /></figure><h3>Introduction</h3><p>Python has rapidly become one of the most popular programming languages in the world, thanks to its versatility, readability, and extensive range of applications. From web development and data analysis to artificial intelligence and automation, Python has proven itself to be a powerful and adaptable language. However, as with any programming language, writing clean and efficient code is crucial for creating maintainable, high-performing applications.</p><p>In this article, we’ll dive into various tips and tricks that will help you master Python programming, enabling you to write cleaner, more efficient code. We’ll cover topics such as readability and style, effective use of data structures, list comprehensions, context managers, functions and decorators, error handling, and performance optimization techniques. By applying these strategies to your Python projects, you’ll not only improve your coding skills but also create more robust and optimized applications.</p><p>Stay tuned as we delve into the world of Python mastery, and embark on a journey to elevate your programming skills to new heights.</p><h3>2. Readability and Style</h3><p>One of the cornerstones of Python programming is its emphasis on readability and clean syntax. By adhering to established style guidelines and best practices, you can ensure that your code is not only easier to read and understand but also more maintainable and efficient. In this section, we’ll explore some key tips for enhancing the readability and style of your Python code.</p><h4><strong>2.1 PEP 8 Style Guide</strong></h4><p>The PEP 8 style guide is the de facto standard for Python code formatting and organization. Following PEP 8 recommendations ensures consistency across projects and makes it easier for others to read and understand your code. Some key aspects of PEP 8 include:</p><ul><li>Using 4 spaces per indentation level</li><li>Limiting line length to 79 characters</li><li>Employing lowercase names with underscores for variables and functions</li><li>Leaving a single space around operators</li><li>Utilizing blank lines to separate functions and classes</li></ul><p>There are several tools, such as autopep8 and flake8, that can help you automatically format your code according to PEP 8 guidelines.</p><h4>2.2 Meaningful Variable and Function Names</h4><p>Choosing descriptive and meaningful names for your variables and functions is crucial for code readability. Instead of using short, cryptic names, opt for names that clearly convey the purpose or value of the variable or function. For example, instead of using a and b as variable names, choose something more informative like price and discount.</p><h4><strong>2.3 Code Comments and Docstrings</strong></h4><p>Providing clear and concise comments throughout your code can significantly improve its readability. Inline comments should be used sparingly and only when necessary to explain complex or non-obvious code. Additionally, it’s important to use docstrings to document your functions and classes, describing their purpose, inputs, and outputs. By adhering to a consistent docstring format, such as Google or NumPy style, you can ensure that your documentation is both informative and professional.</p><p>By focusing on readability and style, you’ll be taking important steps toward mastering Python programming. In the next section, we’ll explore the effective use of data structures to further enhance your coding skills.</p><p>Here’s an example of a well-written docstring using the Google style format for a function called calculate_discount:</p><pre>def calculate_discount(price, discount_rate):<br>    &quot;&quot;&quot;<br>    Calculate the discounted price of an item given its original price and discount rate.<br><br>    Args:<br>        price (float): The original price of the item.<br>        discount_rate (float): The discount rate as a decimal value (e.g., 0.2 for 20% discount).<br><br>    Returns:<br>        float: The discounted price of the item.<br><br>    Raises:<br>        ValueError: If the price is negative or the discount rate is outside the range [0, 1].<br><br>    Example:<br>        &gt;&gt;&gt; calculate_discount(100, 0.2)<br>        80.0<br>    &quot;&quot;&quot;<br>    if price &lt; 0 or not (0 &lt;= discount_rate &lt;= 1):<br>        raise ValueError(&quot;Invalid price or discount rate&quot;)<br><br>    discounted_price = price * (1 - discount_rate)<br>    return discounted_price</pre><h3>3. Effective Use of Data Structures</h3><p>Python offers a variety of built-in data structures that are both powerful and versatile. Choosing the right data structure for a specific use case can have a significant impact on your code’s readability, maintainability, and performance. In this section, we’ll discuss Python’s core data structures and provide guidance on selecting the most suitable one for your needs.</p><h4>3.1 Lists</h4><p>Lists are ordered, mutable collections of elements, which can be of any type, including other lists. They are ideal for use cases that require easy access to elements by index, fast iteration, or frequent modification. Examples of list operations include:</p><pre># Create a list<br>fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;cherry&#39;]<br><br># Access elements by index<br>print(fruits[0])  # Output: &#39;apple&#39;<br><br># Modify an element<br>fruits[1] = &#39;blueberry&#39;<br><br># Add an element<br>fruits.append(&#39;orange&#39;)</pre><h4>3.2 Tuples</h4><p>Tuples are similar to lists but are immutable, meaning their elements cannot be changed once defined. Tuples are suitable for use cases where you need to store a fixed number of elements, such as coordinates or RGB color values. Example:</p><pre># Create a tuple<br>point = (3, 4)<br><br># Access elements by index<br>print(point[0])  # Output: 3</pre><h4>3.3 Sets</h4><p>Sets are unordered collections of unique elements. They are useful when you need to keep track of distinct items or perform set operations like union, intersection, and difference. Examples of set operations include:</p><pre># Create a set<br>colors = {&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;}<br><br># Add an element<br>colors.add(&#39;yellow&#39;)<br><br># Check if an element is in the set<br>print(&#39;red&#39; in colors)  # Output: True<br><br># Set operations<br>colors_1 = {&#39;red&#39;, &#39;green&#39;}<br>colors_2 = {&#39;green&#39;, &#39;blue&#39;}<br>print(colors_1.union(colors_2))  # Output: {&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;}</pre><h4>3.4 Dictionaries</h4><p>Dictionaries are key-value pairs, where each key is associated with a value. They are ideal for use cases that require fast lookup, insertion, or deletion based on keys. Examples of dictionary operations include:</p><pre># Create a dictionary<br>student_grades = {&#39;Alice&#39;: 90, &#39;Bob&#39;: 85, &#39;Charlie&#39;: 92}<br><br># Access a value by key<br>print(student_grades[&#39;Alice&#39;])  # Output: 90<br><br># Modify a value<br>student_grades[&#39;Bob&#39;] = 88<br><br># Add a new key-value pair<br>student_grades[&#39;Diana&#39;] = 95</pre><p>When selecting the most suitable data structure, consider factors like the order of elements, the need for mutability, the uniqueness of items, and the required operations. By making informed choices, you can optimize your code’s performance and readability, moving one step closer to Python mastery. In the next section, we’ll delve into list comprehensions and generator expressions to further enhance your Python programming skills.</p><h3>4. List Comprehensions and Generator Expressions</h3><p>List comprehensions and generator expressions are powerful Python features that allow you to create new lists or generators by applying an expression to each element in an iterable, often resulting in cleaner and more readable code. In this section, we’ll discuss their usage and benefits, along with examples to help you understand and apply these concepts in your Python projects.</p><h4>4.1 List Comprehensions</h4><p>A list comprehension is a concise way to create a list using a single line of code. The basic syntax is as follows:</p><pre>[expression for item in iterable if condition]</pre><p>Here, expression is the operation applied to each item in the iterable, and the optional if condition filters the items based on the specified condition.</p><pre>squares = [x**2 for x in range(1, 11)]<br>print(squares)  # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</pre><p>Example — create a list of even numbers from an existing list:</p><pre>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]<br>even_numbers = [x for x in numbers if x % 2 == 0]<br>print(even_numbers)  # Output: [2, 4, 6, 8]</pre><h4>4.2 Generator Expressions</h4><p>Generator expressions are similar to list comprehensions but create generator objects instead of lists. Generators are lazy, meaning they only compute the values as they are needed, making them more memory-efficient for large datasets. The syntax for generator expressions is similar to that of list comprehensions, except that they use parentheses instead of square brackets.</p><p>Example — create a generator of squares for numbers 1 to 10:</p><pre>squares_gen = (x**2 for x in range(1, 11))<br><br># Access the next value using the next() function<br>print(next(squares_gen))  # Output: 1<br><br># Iterate through the generator using a for loop<br>for square in squares_gen:<br>    print(square)</pre><p>By leveraging list comprehensions and generator expressions, you can create more concise and readable code, which is an essential aspect of mastering Python programming. In the next section, we’ll explore the power of context managers and the ‘with’ statement for effective resource management</p><h3>5. Context Managers and the ‘with’ Statement</h3><p>Context managers are an essential Python feature for managing resources such as file handles, sockets, and database connections. They ensure that resources are acquired and released properly, simplifying your code and reducing the risk of bugs or resource leaks. In this section, we’ll discuss the benefits of context managers and how to use the ‘with’ statement for effective resource management.</p><h4>5.1 Benefits of Context Managers</h4><p>Using context managers can improve your code by:</p><ul><li>Simplifying resource acquisition and release</li><li>Reducing the likelihood of bugs caused by improper resource management</li><li>Enhancing code readability and maintainability</li></ul><h4>5.2 The ‘with’ Statement</h4><p>The ‘with’ statement is used in conjunction with context managers to ensure that resources are correctly acquired and released. The basic syntax is as follows:</p><pre>with context_manager as resource:<br>    # Code using the resource</pre><p>Upon entering the ‘with’ block, the context manager’s __enter__() method is called to acquire the resource. When the block is exited, the __exit__() method is called to release the resource, even in cases where exceptions are raised within the block.</p><p>Example — using the ‘with’ statement for file handling:</p><pre># Read the contents of a file<br>with open(&#39;example.txt&#39;, &#39;r&#39;) as file:<br>    contents = file.read()<br>    print(contents)<br><br># Write contents to a file<br>with open(&#39;output.txt&#39;, &#39;w&#39;) as file:<br>    file.write(&#39;Hello, world!&#39;)</pre><h4>5.3 Creating Custom Context Managers</h4><p>You can create your own context managers by defining a class with __enter__() and __exit__() methods or by using the contextlib module&#39;s @contextmanager decorator with a function.</p><p>Example — custom context manager using a class:</p><pre>class Timer:<br>    def __enter__(self):<br>        import time<br>        self.start = time.time()<br>        return self<br><br>    def __exit__(self, exc_type, exc_val, exc_tb):<br>        import time<br>        self.end = time.time()<br>        print(f&#39;Elapsed time: {self.end - self.start:.2f} seconds&#39;)<br><br># Usage<br>with Timer():<br>    # Code to time</pre><p>Example — custom context manager using a function and @contextmanager decorator:</p><pre>from contextlib import contextmanager<br><br>@contextmanager<br>def timer():<br>    import time<br>    start = time.time()<br>    try:<br>        yield<br>    finally:<br>        end = time.time()<br>        print(f&#39;Elapsed time: {end - start:.2f} seconds&#39;)<br><br># Usage<br>with timer():<br>    # Code to time</pre><p>By using context managers and the ‘with’ statement, you can effectively manage resources in your Python code, improving readability and reducing potential errors. In the next section, we’ll explore the world of functions and decorators to further enhance your Python programming skills.</p><h3>6. Functions and Decorators</h3><p>Functions and decorators are fundamental building blocks of Python programming. They enable you to create reusable, modular code and extend the functionality of existing functions without modifying their code. In this section, we’ll discuss the key aspects of functions and decorators, along with examples to demonstrate their usage and benefits.</p><h4>6.1 Functions</h4><p>Functions in Python are defined using the def keyword, followed by the function name and a set of parentheses containing any input arguments. Functions can return values using the return statement, and if no return value is specified, the function returns None by default.</p><p>Example — a simple function to add two numbers:</p><pre>def add(a, b):<br>    return a + b<br><br>result = add(3, 4)<br>print(result)  # Output: 7</pre><h4>6.2 Function Arguments</h4><p>Python functions support various types of arguments, including positional, keyword, default, and variable-length arguments.</p><ul><li>Positional arguments: Passed in the order they are defined in the function.</li><li>Keyword arguments: Passed by specifying the name of the argument and its value.</li><li>Default arguments: Given default values in the function definition, which can be overridden when calling the function.</li><li>Variable-length arguments: Passed using the *args (for positional arguments) and **kwargs (for keyword arguments) syntax.</li></ul><p>Example — a function with different argument types:</p><pre>def greet(name, greeting=&#39;Hello&#39;, times=1):<br>    for _ in range(times):<br>        print(f&#39;{greeting}, {name}!&#39;)<br><br>greet(&#39;Alice&#39;)  # Output: Hello, Alice!<br>greet(&#39;Bob&#39;, greeting=&#39;Hi&#39;, times=2)  # Output: Hi, Bob! (twice)</pre><h4>6.3 Decorators</h4><p>Decorators are a powerful feature in Python that allows you to modify or extend the behavior of a function without changing its code. Decorators are essentially higher-order functions that take a function as input and return a new function as output.</p><p>To create a decorator, you need to define a function that takes another function as an argument, and then define a nested function within it. The nested function should contain the modified behavior you want to apply to the input function. Finally, return the nested function from the decorator.</p><p>To apply a decorator to a function, use the @decorator_name syntax above the function definition.</p><p>Example — a simple decorator to measure the execution time of a function:</p><pre>import time<br><br>def timer_decorator(func):<br>    def wrapper(*args, **kwargs):<br>        start = time.time()<br>        result = func(*args, **kwargs)<br>        end = time.time()<br>        print(f&#39;{func.__name__} took {end - start:.2f} seconds to execute.&#39;)<br>        return result<br><br>    return wrapper<br><br>@timer_decorator<br>def slow_function():<br>    time.sleep(2)<br><br>slow_function()  # Output: slow_function took 2.00 seconds to execute.</pre><p>By using functions and decorators effectively, you can write modular, reusable, and extensible code that is easier to maintain and understand. These concepts are crucial for mastering Python programming. In the next section, we’ll discuss error-handling techniques to help you build robust and reliable applications.</p><h3>7. Error Handling and Exceptions</h3><p>Error handling and exceptions are essential components of robust and reliable Python applications. By managing errors effectively, you can create programs that gracefully handle unexpected situations, provide useful feedback to users, and minimize the risk of crashes. In this section, we’ll discuss the key aspects of error handling and exceptions, along with examples to demonstrate their usage and benefits.</p><h4>7.1 Exceptions</h4><p>In Python, errors are represented as exceptions, which are events that occur during program execution when an error or exceptional situation is encountered. Exceptions are typically raised when a function encounters an unexpected situation that it cannot handle or when a runtime error occurs.</p><p>Some common built-in exceptions in Python include:</p><ul><li>TypeError: Raised when an operation or function is applied to an object of an inappropriate type.</li><li>ValueError: Raised when a function receives an argument of the correct type but an invalid value.</li><li>IndexError: Raised when a sequence is indexed with a number outside its valid range.</li><li>FileNotFoundError: Raised when trying to open a non-existent file.</li></ul><h4>7.2 Handling Exceptions</h4><p>To handle exceptions in Python, use the try and except statements. The try block contains the code that may raise an exception, while the except block contains the code to handle the exception if it occurs. You can also specify multiple except blocks to handle different types of exceptions.</p><p>Example — handling a division by zero error:</p><pre>def divide(a, b):<br>    try:<br>        result = a / b<br>    except ZeroDivisionError:<br>        print(&quot;Error: Division by zero.&quot;)<br>        result = None<br><br>    return result<br><br>print(divide(10, 2))  # Output: 5.0<br>print(divide(10, 0))  # Output: Error: Division by zero.</pre><h4>7.3 The finally Block</h4><p>The finally block is an optional part of the try statement, which is executed no matter whether an exception occurs or not. It is typically used for cleaning up resources, such as closing files or network connections.</p><p>Example — using the finally block to close a file:</p><pre>try:<br>    file = open(&#39;example.txt&#39;, &#39;r&#39;)<br>    content = file.read()<br>except FileNotFoundError:<br>    print(&quot;Error: File not found.&quot;)<br>else:<br>    print(content)<br>finally:<br>    if &#39;file&#39; in locals() and not file.closed:<br>        file.close()</pre><h4>7.4 Raising Exceptions</h4><p>You can raise exceptions in your own code using the raise a statement, which allows you to trigger an exception when a specific condition is met. This can be useful for validating inputs, enforcing constraints, or signaling that a function cannot continue execution due to an error.</p><p>Example — raising a custom exception:</p><pre>class InvalidAgeError(Exception):<br>    pass<br><br>def check_age(age):<br>    if age &lt; 0:<br>        raise InvalidAgeError(&quot;Age cannot be negative.&quot;)<br><br>try:<br>    check_age(-1)<br>except InvalidAgeError as e:<br>    print(f&quot;Error: {e}&quot;)</pre><p>By using error-handling techniques and exceptions effectively, you can create robust and reliable Python applications that are more resilient to unexpected situations and easier to debug and maintain. Mastering these concepts is crucial for becoming a proficient Python programmer.</p><h3>8. Performance Optimization Techniques</h3><p>Optimizing the performance of your Python applications can lead to significant improvements in execution speed and resource utilization. By using the right techniques, you can ensure that your programs run faster, use less memory, and provide a better user experience. In this section, we’ll discuss some key performance optimization techniques and best practices that you can apply to your Python projects.</p><h4>8.1 Profiling</h4><p>Before attempting to optimize your code, it’s essential to identify the performance bottlenecks. Profiling tools can help you analyze your code’s execution and identify the areas where improvements can be made. Some popular Python profiling tools include:</p><ul><li>cProfile: A built-in Python module that provides deterministic profiling of your code.</li><li>memory_profiler: A third-party module that profiles your code&#39;s memory usage.</li><li>py-spy: A sampling profiler that can profile your code without modifying it.</li></ul><p>By profiling your code, you can focus your optimization efforts on the parts that have the most significant impact on performance.</p><h4>8.2 Algorithmic Optimizations</h4><p>One of the most effective ways to optimize your code’s performance is to improve the algorithms used. Replacing an inefficient algorithm with a more efficient one can lead to substantial performance gains. Some common algorithmic optimizations include:</p><ul><li>Using more efficient data structures (e.g., sets instead of lists for membership testing)</li><li>Reducing time complexity (e.g., using binary search instead of linear search)</li><li>Reducing space complexity (e.g., using generators instead of lists)</li></ul><h4>8.3 Caching and Memoization</h4><p>Caching and memoization are techniques that involve storing the results of expensive function calls and reusing those results when the same inputs are encountered again. This can significantly speed up your code if you have functions with expensive computations that are called multiple times with the same arguments.</p><p>Python provides a built-in functools.lru_cache decorator that can be used to memoize your functions. The decorator caches the results of function calls in a least-recently-used (LRU) cache with a user-defined maximum size.</p><p>Example — memoizing a recursive Fibonacci function:</p><pre>import functools<br><br>@functools.lru_cache(maxsize=None)<br>def fib(n):<br>    if n &lt;= 1:<br>        return n<br>    return fib(n - 1) + fib(n - 2)<br><br>print(fib(100))  # Output: 354224848179261915075</pre><h4>8.4 Just-In-Time Compilation</h4><p>Just-in-time (JIT) compilation is a technique that involves compiling parts of your Python code to native machine code during runtime. This can lead to significant performance improvements, especially for CPU-bound tasks. Some popular JIT compilers for Python include:</p><ul><li>PyPy: An alternative Python interpreter with a built-in JIT compiler.</li><li>Numba: A JIT compiler for Python that specializes in optimizing numerical code.</li></ul><p>Using a JIT compiler can result in substantial performance gains, but it may also require changes to your code to take full advantage of the optimizations.</p><h4>8.5 Parallelism and Concurrency</h4><p>If your code has tasks that can be executed concurrently or in parallel, you can use parallelism and concurrency techniques to speed up your code. Python provides several built-in modules for parallel and concurrent programming, such as:</p><ul><li>threading: A module for working with threads in Python.</li><li>multiprocessing: A module for using multiple processes to parallelize your code.</li><li>asyncio: A module for asynchronous I/O and concurrency using coroutines.</li></ul><p>By leveraging parallelism and concurrency, you can make better use of your system’s resources and significantly improve your code’s performance.</p><p>By applying these performance optimization techniques, you can ensure that your Python applications run faster and more efficiently. Mastering these techniques is an essential skill</p><h3>Conclusion</h3><p>Mastering Python programming involves understanding and applying various concepts, techniques, and best practices to create efficient, maintainable, and robust applications. In this article, we covered several essential topics that every Python developer should be familiar with:</p><ol><li>Introduction to Python and its features</li><li>Readability and style best practices</li><li>Effective use of data structures</li><li>List comprehensions and generator expressions</li><li>Context managers and the ‘with’ statement</li><li>Functions and decorators</li><li>Error handling and exceptions</li><li>Performance optimization techniques</li></ol><p>By incorporating these concepts into your Python development process, you’ll be well on your way to becoming a proficient and effective Python programmer. Remember, mastering a programming language is an ongoing process, and the more you practice and explore, the more your skills and understanding will grow. Keep learning, experimenting, and challenging yourself to become the best Python developer you can be.</p><h3>Kartik Puri on Twitter: &quot;👋 Hi, I&#39;m Kartik, a full stack developer and the creator of @blogtonft, 🔥 which was featured on 🚀 @ProductHunt. I share insights on full-stack web development, including Python, JavaScript, React, Vue, and more!Follow me on Twitter @chopcoding 🐦 to stay updated on my... / Twitter&quot;</h3><p>👋 Hi, I&#39;m Kartik, a full stack developer and the creator of @blogtonft, 🔥 which was featured on 🚀 @ProductHunt. I share insights on full-stack web development, including Python, JavaScript, React, Vue, and more!Follow me on Twitter @chopcoding 🐦 to stay updated on my...</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d54e2858c9fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Dream of Becoming an Author and How Midjourney Helped Me Achieve It]]></title>
            <link>https://medium.com/@kartik.puri95/my-dream-of-becoming-an-author-and-how-midjourney-helped-me-achieve-it-b42f160b3cc8?source=rss-6cf6ec422886------2</link>
            <guid isPermaLink="false">https://medium.com/p/b42f160b3cc8</guid>
            <category><![CDATA[authors]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt3]]></category>
            <category><![CDATA[midjourney]]></category>
            <dc:creator><![CDATA[kartik puri]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 07:24:26 GMT</pubDate>
            <atom:updated>2023-04-08T07:24:26.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*tsVYU4-dcilRFeCn0Dj15A.jpeg" /></figure><p>I’m excited to share that my children’s book, “The Adventures of Zarp: A Little Alien’s Journey to Earth”, is finally available on Amazon Kindle! This book has been a long time in the making, and I’m thrilled to have it out in the world.</p><p>As a child, I always dreamed of writing a book. However, as I grew older, I struggled with finding the right illustrations to bring my stories to life. That is until I discovered the power of AI, specifically Midjourney. With their help, I was able to create beautiful illustrations that capture the essence of Zarp’s adventure.</p><p>As a child, I always dreamed of writing a book. However, as I grew older, I struggled with finding the right illustrations to bring my stories to life. That is until I discovered the power of AI, specifically Midjourney. With their help, I was able to create beautiful illustrations that capture the essence of Zarp’s adventure.</p><p><strong>“The Adventures of Zarp: A Little Alien’s Journey to Earth”</strong> tells the story of a curious little alien who sets out on a journey to explore Earth. Along the way, he meets new friends and faces unexpected challenges. Despite the differences between his species and the humans he encounters, Zarp learns to understand and appreciate the unique qualities of each individual.</p><p>Through Zarp’s journey, readers of all ages will be transported to new worlds and inspired to embrace the differences that make us unique. The book is full of beautiful illustrations that capture the wonder and magic of Zarp’s adventure.</p><p>Zarp didn’t embark on his journey alone, but with the help of Midjourney, I was able to bring his story to life. I am incredibly grateful for their support and expertise.</p><p>I hope you’ll join me on this adventure with Zarp and discover the beauty of exploring new worlds and the importance of understanding and embracing our differences.</p><p><a href="https://www.amazon.in/dp/B0BVKYSSMV/ref=cm_cr_srp_d_product_top?ie=UTF8">https://www.amazon.in/dp/B0BVKYSSMV/ref=cm_cr_srp_d_product_top?ie=UTF8</a></p><p>I am moving all my articles from <a href="https://www.linkedin.com/pulse/my-dream-becoming-author-how-midjourney-helped-me-achieve-kartik-puri/?trackingId=v28uMl4nS3yEfKcdCkYABw%3D%3D">LinkedIn</a> to medium</p><p><a href="https://twitter.com/chopcoding/status/1639535078144454659">https://twitter.com/chopcoding/status/1639535078144454659</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b42f160b3cc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create NFT of your own blog using BlogToNFT]]></title>
            <link>https://medium.com/coinmonks/create-nft-of-your-own-blog-using-blogtonft-9f879f7c8515?source=rss-6cf6ec422886------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f879f7c8515</guid>
            <category><![CDATA[nft-collectibles]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[nft-marketplace]]></category>
            <dc:creator><![CDATA[kartik puri]]></dc:creator>
            <pubDate>Sun, 10 Oct 2021 06:09:51 GMT</pubDate>
            <atom:updated>2021-10-20T13:00:20.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNTkhZnGzrA8zkcZTAFqRw.png" /></figure><p>NFT is a new craze in town and why not. People have made millions out of this amazing concept, I really like the idea of how you can own a digital piece of information that only belongs to you and no one else. This digital piece can be your artwork, your code, your scribbled thoughts, or maybe your blogs or write-up. NFT has given way to monetize your content in a much better way and own what you have created.</p><p>I am an occasional tech blogger and I never thought of making any money from my blogs because most of the places where I post my writeups don’t have such a concept of monetization. That’s when the lightning struck and I stumbled upon an idea of creating an NFT of my blog and I thought how about creating an app where other writers can come and create their own NFT of their blogs like a signature on a Tshirt or on a baseball bat or on a cricket bat just any other collectible but a digital version of it and most amazing part of this is the ability to sell this NFT or put them as an auction to earn some money because you never know one day your blog gets famous and your blog NFT is sold for some millions.</p><h3>BlogToNFT was Born</h3><p><em>With great powers come great responsibility</em></p><p>The idea was amazing but when it comes to implementation and make something for the crowd I know the journey would be bumpy. Being an experienced developer I was aware of how to layout things and make it is useful for the community. After researching and developing for almost 3 months I finished my project <a href="http://blogtonft.com/">blogtonft.com</a>.</p><p>BlogToNFT is kind of a decentralized application that helps writers or bloggers who have writeups hosted on the internet to create an NFT of their blog. This NFT can be kept as collectible or can be sold or can be auctioned at <a href="http://opensea.io/">OpenSea.io</a>. All the NFT’s minted at <a href="http://blogtonft.com/">blogtonft.com</a> are available inside one parent contract known as BLGNFT which can be seen <a href="https://opensea.io/collection/blog-to-nft">here</a>.</p><p><strong>So you might wonder what if anyone else makes NFT of someone else blog?</strong></p><p>There is an ownership verification process, where I ask the owner/writer of the blog to add a specific tag inside the blog(Which I will also explain in the latter half of this blog) with which I verify the actual ownership. Once the ownership is verified user is presented with NFT Artwork which can be modified and then later can be minted on the blockchain. Even at the contract level, I have made sure that no 2 blogs with the same URL ever get minted, So there can ever be one unique URL inside the smart contract.</p><h3>How do I create my Blog NFT?</h3><p>I have tried to make things as simpler as possible and the minimum requirement to create your NFT is the wallet address. If you don’t have your own wallet address I would recommend having one before trying to create your NFT. You can visit this <a href="https://myterablock.medium.com/how-to-create-or-import-a-metamask-wallet-a551fc2f5a6b">link</a> if you want to know how to create your wallet. But do make sure to keep your wallet safe as this is the only way you will have access to your NFT and also make sure that you are able to sign in at opensea using the wallet address before minting the blog</p><h3>Step 1 — Login using the magic link</h3><p>I believe login should be the simplest process, I don’t like remembering the password and then hitting forget the password. So to log in or signup, you just have to put your email inside the box and hit create NFT. The same thing can also be done using the login button at the top right corner. Once you hit login we will send you a magic link into your mailbox, also check your spam section as well, once you click on this link you will be straightaway logged into the <a href="http://blogtonft.com/">blogtonft.com</a> account section. Click on Mint my blog at the top right corner</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_HPtrw8ImAihmzac2c8MUg.gif" /><figcaption>How to log in and goto account</figcaption></figure><h3>Step 2 — Mint your blog, Please verify your blog ownership!</h3><p>This is the most important step, the user has to make sure that he/she is the owner of the blog. Here you have to select the blog source if it is medium or any other source. The verification process of medium is a little different hence I have to take this input separately. Once your blog source is selected go ahead and paste your blog URL, after pasting take the verification tag and put that inside the blog without any text modification. For a medium blog, the tag is just a set of numbers as medium won’t allow adding external HTML tags, for other blogs you can paste the HTML tag which is basically a badge like below which screams that your blog is minted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Nal8m1qF09V_g_NjDeCFiQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*_nxaCzA5XrK_betNo6vMwg.png" /></figure><blockquote>For medium users, once the blog is minted you can delete the verification tag and download the above image by right-clicking&gt; save as and add it inside your blog. Well everyone need’s to show off a little</blockquote><h3>Step 3 — Add metadata</h3><p>Once your blog is verified, you need an artwork to mint so that you can sell it or maybe auction it. Before minting it is really important to add the meta properties of your blog like author, title, description, etc. This metadata is really important to generate your artwork and is also very important when you put this NFT on <a href="http://opensea.io/">opensea.io</a>. There is an autofill button that tries to get most of the metadata but in case users want to do it manually they are free to do so. Once the metadata is added hit generate artwork, this artwork is the final piece of NFT which will be minted into the blockchain so just make sure all the spelling and meta tags are fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U2LU0eOhkd-2rS1XfFuOhg.png" /><figcaption>Add meta data and click generate artwork button</figcaption></figure><h3>Step 4 — Mint your blog</h3><p>This is the last and the final step which converts your artwork generated in step 3 to NFT and mint it inside the blockchain also note once the NFT’s are minted on the blockchain they cannot be removed or edited again. This step only requires your wallet address so just make sure to paste your right wallet address and also make sure to sign in to the <a href="http://opensea.io/">opensea.io</a> using the same wallet address. once the wallet address is pasted hit the mint button and <strong><em>there you have it your very own NFT minted inside the blockchain</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8AIK2BpiRLUWQzi4owD2hg.png" /><figcaption>Artwork minted inside blockchain</figcaption></figure><h3>Access your artwork using <a href="http://opensea.io/">opensea.io</a></h3><p>OpenSea is a peer-to-peer marketplace for crypto collectibles and non-fungible tokens. To access the artwork that you just minted you have to sign into the opensea using your wallet address and inside the profile section, you will see your artwork waiting for you. You can use this platform to sell or auction your NFT in return for some ETH. Also, note opensea takes time to load all the details and artwork so in case you don’t see the image is loaded you can hit the refresh meta button inside the NFT page</p><p>BlogToNFT UI is still in beta but the app is capable enough to mint your NFT. I hope you would create your own NFT using this app because you never know a blog written 5 years back is sold for $1 million. I hope you like my app, if you have any queries feel free to reach out to me on my Twitter or in the comment section below</p><p>PS: This blog is minted on <a href="http://blogtonft.com/">BlogToNFT.com</a> and below is my verification tag along with the image added manually.</p><blockquote><strong>Can be <em>seen</em> at </strong><a href="https://opensea.io/assets/matic/0x9ac2837a68307d573e5000a26af7e32e978a3aaa/23611091838938412358035193397177457697865868189846902744888488445419248149482"><strong>opensea</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*_nxaCzA5XrK_betNo6vMwg.png" /><figcaption>Minted Badge</figcaption></figure><blockquote>dfC1Ji59YlekytqXDMqPrnMCRjh1</blockquote><h4>Also Read</h4><ul><li><a href="https://blog.coincodecap.com/crypto-exchange">Best Crypto Exchange | Top 10 cryptocurrency exchanges 2022 | CoinCodeCap</a></li><li><a href="https://blog.coincodecap.com/crypto-lending">10 Best Crypto Lending Platforms 2022 | CoinCodeCap</a></li><li><a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">10 Best FREE Crypto Trading Bots in 2023</a></li><li><a href="https://medium.com/coinmonks/best-crypto-signals-telegram-5785cdbc4b2b">5 Best Crypto Telegram Channels 2024 (Trading Signals)</a></li><li><a href="https://blog.coincodecap.com/blockfi-review">BlockFi Review 2021: Pros, Cons and Interest Rates | CoinCodeCap</a></li><li><a href="https://medium.com/coinmonks/buy-bitcoin-in-india-feb50ddfef94">Top 6 Crypto Trading Apps in India — Best Exchanges</a></li><li><a href="https://medium.com/coinmonks/best-crypto-tax-tool-for-my-money-72d4b430816b">10 Best FREE Crypto Tax Software in 2024</a></li><li><a href="https://blog.coincodecap.com/best-hardware-wallet-bitcoin">Best Crypto Hardware Wallets to Store Bitcoin [2021] | CoinCodeCap</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f879f7c8515" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/create-nft-of-your-own-blog-using-blogtonft-9f879f7c8515">Create NFT of your own blog using BlogToNFT</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Ninja way to use Elasticsearch with python]]></title>
            <link>https://medium.com/@kartik.puri95/a-ninja-way-to-use-elasticsearch-with-python-40a1e841e859?source=rss-6cf6ec422886------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a1e841e859</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[kartik puri]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 07:29:46 GMT</pubDate>
            <atom:updated>2021-10-09T14:11:43.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LedzDk4gfV0a_3C8" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Émile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Who does not love object-oriented programming paradigms, we often use ORM(SQLAlchemy) with our python projects to make our world a better place. I have used Elasticsearch and I wish if it was a database but we can still use it as a database <strong><em>(depends on our use-case that is a whole new topic to discuss)</em></strong>. But what if we can just add the OOPS concept to our elastic search project instead of writing that big JSON and matching those brackets till the last end. In this article, we will be creating a small project to demonstrate the above concept and will be executing a few Elasticsearch queries without the need of writing big curly queries.</p><blockquote>Here I am assuming that you are already running an Elasticsearch instance</blockquote><h3>1. Install Elasticsearch and make a connection</h3><p>Let&#39;s start by installing <a href="https://elasticsearch-dsl.readthedocs.io/en/latest/">Elasticsearch DSL</a> (Elasticsearch DSL is a high-level library whose aim is to help with writing and running queries against Elasticsearch. It is built on top of the official low-level client (elasticsearch-py))</p><pre>pip install elasticsearch <br>pip install elasticsearch_dsl</pre><p>Let&#39;s create a python file and start making a connection to our Elasticsearch</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c99860ed1a5abf1e2f687d8559836d87/href">https://medium.com/media/c99860ed1a5abf1e2f687d8559836d87/href</a></iframe><h3>2. Add a class and save one document to our Elasticsearch</h3><p>For demo purposes, I will be creating a class <em>Blogpost </em>and save a sample blog to our index. Mapping will be created automatically based on the attributes of the <em>Blogpost</em> class. I have added comments wherever necessary</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0161e01e83e872d901d149c732193829/href">https://medium.com/media/0161e01e83e872d901d149c732193829/href</a></iframe><p>From the above example, we can easily create indexes without using those complicated requests since mapping is created based on the attribute type there are fewer things to worry about now</p><h3>3. Writing shorthand Elasticsearch queries</h3><p>First, let&#39;s write a normal Elasticsearch query</p><pre><strong>from</strong> <strong>elasticsearch</strong> <strong>import</strong> Elasticsearch<br>client = Elasticsearch()<br><br>response = client.search(<br>    index=&quot;blog_index&quot;,<br>    body={<br>      &quot;query&quot;: {<br>        &quot;filtered&quot;: {<br>          &quot;query&quot;: {<br>            &quot;bool&quot;: {<br>              &quot;must&quot;: [{&quot;match&quot;: {&quot;title&quot;: &quot;A better way&quot;}}],<br>              &quot;must_not&quot;: [{&quot;match&quot;: {&quot;body&quot;: &quot;Hello world&quot;}}]<br>            }<br>          },<br>          &quot;filter&quot;: {&quot;term&quot;: {&quot;tags&quot;: &quot;tech&quot;}}<br>        }<br>      }<br>      }<br>    }<br>)</pre><p>As the number of cases increases our query becomes complex, a shorthand pythonic approach can decrease the above query to 1–2 lines lets see how</p><pre>s = Search(using=es, index=&quot;blog_index&quot;).filter(&quot;term&quot;, tags=&quot;tech&quot;) .query(&quot;match&quot;, title=&quot;python&quot;).exclude(&quot;match&quot;, body=&quot;Hello world&quot;)</pre><p>We have significantly reduced the length of our query, for more information about the Elasticsearch DSL please visit this <a href="https://elasticsearch-dsl.readthedocs.io/en/latest/">link</a>.</p><p>To view the complete code, you can visit this <a href="https://github.com/kartikpuri95/ElasticsearchPython">repository</a>.</p><p>If you have any confusion or query please leave a comment below.</p><p>dfC1Ji59YlekytqXDMqPrnMCRjh1</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a1e841e859" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to embed ECharts to salesforce lightning web components]]></title>
            <link>https://medium.com/@kartik.puri95/how-to-embed-echarts-to-salesforce-lightning-web-components-16b9bda40941?source=rss-6cf6ec422886------2</link>
            <guid isPermaLink="false">https://medium.com/p/16b9bda40941</guid>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[salesforce-lightning]]></category>
            <category><![CDATA[lightning-web-component]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[kartik puri]]></dc:creator>
            <pubDate>Sat, 14 Dec 2019 16:30:25 GMT</pubDate>
            <atom:updated>2019-12-15T14:31:21.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kGIB_0OrlIpEXmr0" /><figcaption>Photo by <a href="https://unsplash.com/@jcoudriet?utm_source=medium&amp;utm_medium=referral">Jason Coudriet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Beautiful dashboards are incomplete without charts and creating an application with charts sometimes becomes challenging, recently I was building an application on top of the Salesforce app using Lightning web components(<strong>Lightning Web Components</strong> is the Salesforce implementation of that new breed of lightweight frameworks built on <strong>web</strong> standards). <br>Since I have used the Echarts in my previous projects I was adamant to use Echarts in my new salesforce LWC app. After doing a bit of research and some trial and error I was successful in embedding the Echarts to my salesforce app.</p><p>Note: In the below application I am assuming that Salesforce CLI has already been installed, if not please follow this <a href="https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_install_cli.htm">link</a></p><h3>1. Create a Salesforce Project</h3><pre>cd path/to/your/sfdx/projects<br>sfdx force:project:create --projectname lwc-hello-world<br>cd lwc-hello-world</pre><p>After creating the project we need to add the lightning web component, let&#39;s name our component as hello world, this component will be added in the lwc folder which is the default structure for the salesforce app</p><pre>cd force-app/main/default/lwc</pre><pre>sfdx force:lightning:component:create --type lwc -n helloWorld</pre><pre>cd force-app/main/default/lwc/helloWorld</pre><pre>ls</pre><pre><strong>helloWorld.html  helloWorld.js  helloWorld.js-meta.xml</strong></pre><p>3 files are created inside force-app/main/default/lwc/helloWorld</p><ul><li>helloWorld.html</li><li>helloWorld.js</li><li>helloWorld.js-meta.xml</li></ul><h3>2. Add Static Resource for Echarts</h3><p>let&#39;s navigate to the project directory where we can see the folder name <strong>staticresources</strong></p><pre>cd force-app/main/default</pre><pre>ls</pre><pre><strong>applications  aura  classes  contentassets  flexipages  layouts  lwc  objects  permissionsets  staticresources  tabs  triggers</strong></pre><pre>cd staticresources</pre><p>Inside the <strong>staticresource</strong> folder, we need to add <strong>echarts.js </strong>which can be downloaded from there GitHub <a href="https://github.com/apache/incubator-echarts/tree/master/dist">link</a></p><p>Upon adding the echarts we also need to add the Meta XML file for the <strong>echarts.js</strong> which is actually the configuration for our<strong> echarts.js </strong>so that we can tell the salesforce app about the MIME type of our added script.</p><blockquote>The naming convention for adding Meta XML is the <strong>filename.resource-meta.xml</strong></blockquote><p>So let us add <strong>echarts.resource-meta.xml </strong>with the following content</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dd7bc5d6f84479c8401fba42e31f894/href">https://medium.com/media/6dd7bc5d6f84479c8401fba42e31f894/href</a></iframe><p>Let&#39;s list our directory and check its content before proceeding further</p><pre>cd force-app/main/default/staticresources</pre><pre>ls</pre><pre><strong>echarts.js  echarts.resource-meta.xml</strong></pre><p>Moving back to our component folder lwc</p><pre>cd force-app/main/default/lwc/helloWorld</pre><pre>ls</pre><pre><strong>helloWorld.html  helloWorld.js  helloWorld.js-meta.xml</strong></pre><h3>3. Embedding Echarts</h3><p>Let&#39;s add the following code to <strong>helloWorld.js,</strong> I have added comments wherever necessary for better understanding</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6285a6385c6b73a212659e43d6afb3f/href">https://medium.com/media/c6285a6385c6b73a212659e43d6afb3f/href</a></iframe><p>Now add our frontend code to <strong>helloWorld.html</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fce4bffcbedd2de8b92990ee099f590/href">https://medium.com/media/8fce4bffcbedd2de8b92990ee099f590/href</a></iframe><blockquote>Note that we have targeted <strong>div.main</strong> in our javascript file</blockquote><p>Once everything is completed you can now easily push the code to the org and see the changes.</p><blockquote>This article is not limited to echarts we can easily add other charting libraries using the above method</blockquote><p>If you have any confusion or query please leave a comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16b9bda40941" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The untold story about Unicode to UTF -8]]></title>
            <link>https://medium.com/@kartik.puri95/the-untold-story-about-unicode-to-utf-8-1aaf64e7120f?source=rss-6cf6ec422886------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aaf64e7120f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[unicode]]></category>
            <category><![CDATA[utf-8]]></category>
            <dc:creator><![CDATA[kartik puri]]></dc:creator>
            <pubDate>Sat, 28 Sep 2019 19:17:06 GMT</pubDate>
            <atom:updated>2021-09-18T18:47:58.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jA_IVmPyVEw0dpb4kd178g.jpeg" /></figure><p>Days back while looking at one of the python documentation I stumble upon<em> “Python source files are treated as encoded in UTF-8”. </em>I have been looking at UTF-8 since my college days in python script, pandas encoding format or while opening an excel sheet and plenty of other places but I never thought of going down the rabbit hole. Every day there is some new open-source repository or new library which is making our work painless and we hardly realized the importance of ASCII to UNICODE to UTF-8 transition and being a developer these little things are important to know.</p><p>Coming back to our topic, to understand the UTF-8 we need to time travel back in the past when C programming was being invented and all that was really matter was English characters. Developers in that time introduced the ASCII standard, with ASCII every character in the alphabet can be represented with a number between 32 to 127 since 7 bits were sufficient to represent ASCII character. The range between 0–31 was used to store nonprintable system codes like “beep” etc, range between 32 to 127 was used to store character where the value A starts from 65 and small ‘a’ start from 97 below is the binary format to store ‘A’ and ‘a’. Adding up all the numbers at 1 will give you the actual decimal number 65 and 97 respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/0*e1s2Mdi0z1Mlj1fq" /></figure><p>Most of the computers in those days were using 8 bit so not only we could store ASCII character but we have a whole lot of space to store other characters as well, everything went well and people started using ASCII standard.</p><p>Wait, What? ASCII is only for people who understand English what about other languages?</p><p>Because Bytes have room for 8 bits people started thinking of using those extra bits for other devious purposes there was a range from 128 to 255 that was available for all those extra talented people who have their own ideas to play with the remaining range.</p><p>The problem arrive when people from one country started to send emails and letters to other countries. Hello sir was being received as ☐☐☐☐ which results in a more chaotic environment, ANSII standard came into the picture and everyone agreed to one common resolution of what to do below 128 but above 128 was still not clear and everyone was using there own way to deal with that extra range. Coming to the ASIA region where there were more characters that can’t be fit inside the ASCII range there was a need to come with one unified solution so that all the continents can sing in unison.</p><h3>…</h3><h3>UNICODE</h3><p>Unlike ASCII table Unicode is just another kind of lookup table until now we have seen that characters are mapped to some bit which can be stored in the memory.</p><p>In English Letter <em>A </em>is different than the letter a, In the german meaning of the letter, Ä/ä is completely different which could raise another conflict. Unicode consortium came for the rescue and started using the code point. Every character was assigned with some code point.</p><p>A <em>code point</em> is the atomic unit of information. <em>Text</em> is a sequence of code points. Each code point is a number which is given meaning by the Unicode standard.</p><p>Every letter was assigned with a number which was written as below where U+ means Unicode</p><p>A- &gt; U+0041</p><p>You can find all the Unicode in this link <a href="https://www.rapidtables.com/code/text/unicode-characters.html">https://www.rapidtables.com/code/text/unicode-characters.html</a></p><p>Note, Unicode was just the number assigned to the character it has nothing to do with the storage of these numbers. People started thinking of using bizarre ways to store these Unicode in memory which led to the invention of UTF-8.</p><h3>…</h3><h3>UTF-8</h3><p>UTF-8 was another system to store a string of Unicode code point. In UTF-8 format the codepoint is first converted to its actual bytes and 1 to 4 bytes can be used to store the code point. UTF-8 was designed with backward compatibility for ASCII standard the first 128 characters in Unicode are mapped one to one as in ASCII using single-byte(1 Byte) with the same value in ASCII encoding.</p><p>Since UTF-8 support till 4bytes, you can easily store 1112064 characters lets understand how we arrived at that value</p><ul><li>1 byte can store characters from 0 to 127 which is equivalent to ASCII</li><li>2 byte can store characters from 128 to 2047</li><li>3 byte can store characters from 2048 to 65535</li><li>4 byte can store characters from 65536 to 1112064</li></ul><p>To understand how UTF-8 store this number, we also need to have a little understanding of hexadecimal. 1 hexadecimal notation always corresponds to 4 bits(1 nibble). Below is the table which represents Hexadecimal value for all the corresponding binary numbers.</p><p>For example, if I write 2A in hexadecimal</p><p>2A = (2 *16¹) + (10*16⁰)=(32+10)=42(in decimal)</p><p>42 in binary = 101010</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/0*h4DBMWoHSv8Fl6VR" /></figure><h3>1 Byte UTF — 8 Encoding</h3><p>1-byte Encoding will always store 0 as its first value or higher-order value which will look like below table, remaining bits are used to encode character</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*CuP3-CQNgztENTZK" /></figure><h3>2 Byte UTF — 8 Encoding</h3><p>2-byte will always store 110 and 10 which gives 11 bits to encode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*C1PZ_WellkmlRWU4" /></figure><h3>3 Byte UTF — 8 Encoding</h3><p>3-byte encoding will always store 1110 10 10 which gives 16 bits to encode actual character</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*hbsxBTjrg7Dt9k6b" /></figure><p>To encode to UTF 8 we need to check the numerical range of the value based on the numerical range we can decide 1,2,3 or 4 bytes encoding which can be used to encode.</p><p>For example, let’s take a codepoint as U + 927 to store 927 we need to get its binary value which is equivalent to 1110011111 to store this codepoint in Unicode we need to use 2-byte encoding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*aE5ZhGmBdWqvWUQB" /></figure><p>We can add 0 to an unfilled Bit and the final value will look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*gVcY2mkoatS0qdKv" /></figure><p>To store Code point hexadecimal 1F we can easily do that by storing its binary(0001 1111) to its respective range.</p><p>Please note that UTF-8 is just a way to encode the Unicode, Unicode is made up of codepoints and UTF-8 is used to store those code points.</p><p>I hope this article has helped you to give a very basic idea about the Unicode and UTF-8 to understand in more detail please have a look at the base number system which will give you the clear idea about the number system used from ASCII to UTF-8</p><p>&lt;a id=”p210o1m7twVXXQE6HPwuP8FWHF62&quot; href=”https://google.com&quot;&gt;&lt;img src=”https://img.shields.io/static/v1?label=BlogNFT&amp;message=Minted&amp;color=9cf&quot;/&gt;&lt;/a&gt;</p><p><a href="https://code.tutsplus.com/articles/number-systems-an-introduction-to-binary-hexadecimal-and-more--active-10848">Number Systems: An Introduction to Binary, Hexadecimal, and More</a></p><p>p210o1m7twVXXQE6HPwuP8FWHF62</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aaf64e7120f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>