<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: demola12</title>
    <description>The latest articles on Forem by demola12 (@demola12).</description>
    <link>https://forem.com/demola12</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F498748%2Fa516df72-5f68-44e5-8688-422953299d96.jpeg</url>
      <title>Forem: demola12</title>
      <link>https://forem.com/demola12</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/demola12"/>
    <language>en</language>
    <item>
      <title>Building a Robust Windows Service in Python with win32serviceutil Part 1/3</title>
      <dc:creator>demola12</dc:creator>
      <pubDate>Mon, 29 Jan 2024 23:27:51 +0000</pubDate>
      <link>https://forem.com/demola12/building-a-robust-windows-service-in-python-with-win32serviceutil-part-13-1k6k</link>
      <guid>https://forem.com/demola12/building-a-robust-windows-service-in-python-with-win32serviceutil-part-13-1k6k</guid>
      <description>&lt;h2&gt;
  
  
  Problem Statement
&lt;/h2&gt;

&lt;p&gt;Creating a Windows service in Python is a common task, often facilitated by numerous code examples available online and tools like Chart GPT. However, a significant challenge arises when attempting to access or start Windows processes within the context of a Windows service. The primary complication stems from the fact that services run under the Local System authority, introducing permission constraints that can hinder the seamless execution of certain tasks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Windows services provide a powerful mechanism for running background tasks that do not require user interaction. In Python, the &lt;code&gt;win32serviceutil&lt;/code&gt; module, part of the &lt;code&gt;pywin32&lt;/code&gt; library, allows developers to create and manage Windows services seamlessly. In this article, we'll explore a Python script that utilizes &lt;code&gt;win32serviceutil&lt;/code&gt; to create a simple Windows service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import os
import time

class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = 'MyService'
    _svc_display_name_ = 'My Service'

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(120)
        self.is_alive = True

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.is_alive = False

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.main()

    def main(self):
        # Main service logic goes here
        while self.is_alive:
            # Perform your service tasks here
            time.sleep(5)  # Example: Sleep for 5 seconds


if __name__ == '__main__':
    if len(os.sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(MyService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(MyService)

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Understanding the Python Script:
&lt;/h2&gt;

&lt;p&gt;Let's break down the provided Python script, which serves as the foundation for our Windows service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import os
import time

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

&lt;/div&gt;



&lt;p&gt;These import statements include essential modules such as &lt;code&gt;win32serviceutil&lt;/code&gt;, &lt;code&gt;win32service&lt;/code&gt;, &lt;code&gt;win32event&lt;/code&gt;, &lt;code&gt;servicemanager&lt;/code&gt;, &lt;code&gt;socket&lt;/code&gt;, &lt;code&gt;os&lt;/code&gt;, and &lt;code&gt;time&lt;/code&gt;. These modules collectively provide the necessary tools for creating and managing Windows services.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = 'MyService'
    _svc_display_name_ = 'My Service'

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

&lt;/div&gt;



&lt;p&gt;Here, a class named &lt;code&gt;MyService&lt;/code&gt; is defined, inheriting from &lt;code&gt;win32serviceutil.ServiceFramework&lt;/code&gt;. This class represents our custom Windows service. The &lt;code&gt;_svc_name_&lt;/code&gt; attribute defines the service name, and &lt;code&gt;_svc_display_name_&lt;/code&gt; sets the display name visible in the Windows Services manager.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__(self, args)
    self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
    socket.setdefaulttimeout(120)
    self.is_alive = True

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

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;__init__&lt;/code&gt; method initializes the service. It creates an event (&lt;code&gt;hWaitStop&lt;/code&gt;) that signals the service to stop when set. The &lt;code&gt;socket.setdefaulttimeout(120)&lt;/code&gt; line sets the default timeout for socket operations, and &lt;code&gt;self.is_alive&lt;/code&gt; tracks whether the service is running.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    win32event.SetEvent(self.hWaitStop)
    self.is_alive = False

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

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;SvcStop&lt;/code&gt; method is called when the service is stopped. It reports the stop status and signals the &lt;code&gt;hWaitStop&lt;/code&gt; event.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def SvcDoRun(self):
    servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                          servicemanager.PYS_SERVICE_STARTED,
                          (self._svc_name_, ''))
    self.main()

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

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;SvcDoRun&lt;/code&gt; method is the main entry point for the service. It logs a service start message and calls the &lt;code&gt;main&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def main(self):
    # Main service logic goes here
    while self.is_alive:
        # Perform your service tasks here
        time.sleep(5)  # Example: Sleep for 5 seconds

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

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;main&lt;/code&gt; method contains the core logic of your service. In this example, it includes a loop simulating a service that performs tasks every 5 seconds.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if __name__ == '__main__':
    if len(os.sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(MyService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(MyService)

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

&lt;/div&gt;



&lt;p&gt;Finally, the script checks whether it's being run as a standalone application or imported as a module. If run standalone, it initializes and starts the service using &lt;code&gt;servicemanager&lt;/code&gt;.&lt;/p&gt;

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

&lt;p&gt;This script provides a template for building Windows services in Python using win32serviceutil. Customize the main method to implement your service's specific functionality. In subsequent articles, we'll explore service installation, execution, and management.&lt;/p&gt;

&lt;p&gt;Stay tuned for more on mastering Windows services with Python Part II&lt;/p&gt;

</description>
      <category>python</category>
      <category>software</category>
    </item>
    <item>
      <title>Optimizing Event Handlers in React using useCallback</title>
      <dc:creator>demola12</dc:creator>
      <pubDate>Sat, 27 Jan 2024 22:41:14 +0000</pubDate>
      <link>https://forem.com/demola12/optimizing-event-handlers-in-react-using-usecallback-5hc3</link>
      <guid>https://forem.com/demola12/optimizing-event-handlers-in-react-using-usecallback-5hc3</guid>
      <description>&lt;p&gt;React's &lt;code&gt;useCallback&lt;/code&gt;hook is a powerful tool for optimizing performance in your applications by memoizing functions. This is particularly useful when dealing with event handlers, as it helps prevent unnecessary re-creation of functions during renders. In this article, we'll explore how to effectively use &lt;code&gt;useCallback&lt;/code&gt;to optimize event handlers in your React components.&lt;/p&gt;

&lt;p&gt;Why Optimize Event Handlers?&lt;br&gt;
In React, when a component re-renders, its functions are recreated. If you pass a new function reference as a prop to a child component, even if the function logic is the same, React treats it as a different prop. This can lead to unnecessary renders in child components, impacting the overall performance of your application.&lt;/p&gt;

&lt;p&gt;useCallback addresses this issue by memoizing the function, ensuring that it remains the same between renders unless its dependencies change. This is particularly beneficial for event handlers, which are often passed down as props.&lt;/p&gt;

&lt;p&gt;Basic Usage of &lt;code&gt;useCallback&lt;/code&gt;&lt;br&gt;
Let's start with a simple example. Consider a parent component that renders a child component with a button and an &lt;code&gt;onClick&lt;/code&gt;handler:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ParentComponent.js
import React, { useCallback, useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () =&amp;gt; {
  const [count, setCount] = useState(0);

  // Define the event handler using useCallback
  const handleClick = useCallback(() =&amp;gt; {
    setCount(count + 1);
  }, [count]);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Clicked {count} times&amp;lt;/p&amp;gt;
      &amp;lt;ChildComponent onClick={handleClick} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default ParentComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, the &lt;code&gt;handleClick&lt;/code&gt;event handler is created using &lt;code&gt;useCallback&lt;/code&gt;. The dependency array [count] indicates that the memoized function should only be recreated if the count state changes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Child Component Handling the Click Event
&lt;/h2&gt;

&lt;p&gt;Now, let's look at the child component that receives the &lt;code&gt;onClick&lt;/code&gt;prop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ChildComponent.js
import React from 'react';

const ChildComponent = ({ onClick }) =&amp;gt; {
  return (
    &amp;lt;button onClick={onClick}&amp;gt;
      Click me
    &amp;lt;/button&amp;gt;
  );
};

export default ChildComponent;

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

&lt;/div&gt;



&lt;p&gt;The child component simply renders a button with the provided &lt;code&gt;onClick&lt;/code&gt;handler. By using &lt;code&gt;useCallback&lt;/code&gt;in the parent component, we ensure that the &lt;code&gt;onClick&lt;/code&gt;prop remains stable between renders, preventing unnecessary re-renders of the child component.&lt;/p&gt;

&lt;h2&gt;
  
  
  Comparing with Regular Function Definition
&lt;/h2&gt;

&lt;p&gt;To highlight the optimization achieved with &lt;code&gt;useCallback&lt;/code&gt;, let's compare it with a scenario where we use a regular function definition in the parent component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ParentComponentWithoutCallback.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponentWithoutCallback = () =&amp;gt; {
  const [count, setCount] = useState(0);

  // Regular function definition
  const handleClick = () =&amp;gt; {
    setCount(count + 1);
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Clicked {count} times&amp;lt;/p&amp;gt;
      &amp;lt;ChildComponent onClick={handleClick} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default ParentComponentWithoutCallback;

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

&lt;/div&gt;



&lt;p&gt;In this case, without using &lt;code&gt;useCallback&lt;/code&gt;, the &lt;code&gt;handleClick&lt;/code&gt; function is recreated on every render. This could potentially lead to unnecessary renders in the child component.&lt;/p&gt;

&lt;h2&gt;
  
  
  When to Use &lt;code&gt;useCallback&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;While &lt;code&gt;useCallback&lt;/code&gt;is a powerful tool, it's important to use it judiciously. Consider using &lt;code&gt;useCallback&lt;/code&gt;in the following scenarios:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Event Handlers Passed as Props:&lt;br&gt;
 When passing event handlers down to child components as props.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Memoization of Expensive Functions:&lt;br&gt;
 When dealing with functions that involve heavy computations &lt;br&gt;
 and you want to memoize them.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Functions with Dependencies:&lt;br&gt;
 When the function logic depends on certain values (add those &lt;br&gt;
 values to the dependency array).&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

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

&lt;p&gt;Optimizing event handlers using &lt;code&gt;useCallback&lt;/code&gt;is an effective way to improve the performance of your React applications. By memoizing functions, you can ensure that unnecessary re-renders are avoided, leading to a smoother user experience.&lt;/p&gt;

&lt;p&gt;Remember to use &lt;code&gt;useCallback&lt;/code&gt;selectively, focusing on scenarios where function stability across renders is crucial. As with any optimization technique, always profile and test your application to ensure that the chosen optimizations align with your specific use cases.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>typescript</category>
      <category>react</category>
      <category>hook</category>
    </item>
  </channel>
</rss>
