teleren/devto huggingface dataset:
How implement Messaging Pattern in React JS without external libraries
Tags: reactcontext, react
Published: 2023-08-14 20:09:05

In React, one of the first big issues that comes up is figuring out how components should communicate with each other. And yes, sometimes you can solve your communication issues with Flux, but no it is NOT necessary. Some developers use Flux just because it's popular - without realizing that simpler solutions exists. 

To avoid deep in all the details, the quick answer to implement the Messaging Pattern is using Context. Context works similarly to props, but instead of providing data to a single child, it can be used to provide data to an entire subtree. (Child of a child, child of a child of a child, and so on). Context was designed to send data down the tree (parent to subtree child). But It can be paired with callback functions to pass data back up (subtree to parent).

Now, knowing the key “Context”, let me show you the quick example, to send message to all the components in the project.

First we need create the Context. APPContext.js, and define the message Object and the Send Message action.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kcql7erf1iu8g9e4snsy.jpeg)


In our Root App we need to add our context provider to share the same context with any component consumer.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6h1w0k7ckwtnxpgwvn4.png)



Now, any react component can send a Message using the shared context.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k4884gunm1634q295n56.png)




And the last piece in this pattern is the subscriber. Any component could be a subscriber with just add the context consumer tag, and add the action (Handle Message) with the message received.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b6egvwfucfjy3ihnw795.png)




Now, you can have the messaging pattern in your React project without Redux or other libraries. The Next step is create a Custom Hook, to convert this pattern in a service technology... I'll write other article with it.
How to grab new session cookies before scraping?
Tags: python, seleniumwebdriver, webscraping, cookies
Published: 2023-08-14 20:04:42

How to Grab New Session Cookies Before Scraping
-----------------------------------------------

Scraping data from websites can be a challenging task, especially when dealing with session-based authentication. Many websites use session cookies to track user interactions and provide personalized experiences. If you're a software developer looking to scrape data from such websites, it's crucial to understand how to grab new session cookies to ensure a successful scraping process.

Here are some tips and tricks to help you grab new session cookies before scraping:

1.  **Embrace the Power of Browser Automation:** One effective way to grab new session cookies is by automating the browser. Tools like Selenium WebDriver can be handy in this regard. By simulating user interactions, you can trigger the creation of new session cookies and extract them for your scraping needs.
2.  **Don't Forget to Clear Your Cookies:** Before starting your scraping process, make sure to clear any existing cookies in your browser. This ensures that you start with a clean slate and have a higher chance of grabbing new session cookies during your scraping session.
3.  **Keep an Eye on the Network Traffic:** Monitoring the network traffic between your browser and the website can provide valuable insights. Tools like Chrome Developer Tools or Wireshark can help you identify the requests and responses containing session cookies. With this information, you can extract the necessary cookies for your scraping tasks.
4.  **Utilize Proxy Servers:** Sometimes, websites may employ anti-scraping techniques that detect and block requests from suspicious IP addresses. By using proxy servers, you can rotate your IP address and avoid detection, increasing your chances of grabbing new session cookies.
5.  **Implement Delay Mechanisms:** To mimic human behavior and avoid suspicion, introduce random delays between your scraping requests. Websites often expect some natural variation in user interactions, and by incorporating these delays, you can increase your chances of receiving new session cookies.

Remember, grabbing new session cookies before scraping is crucial to ensure that you have the necessary authentication to access the data you need. By following these tips and tricks, you can enhance your scraping process and increase the success rate of your data extraction.

Happy scraping!

### References:

*   Link to Reference 1
*   Link to Reference 2
*   Link to Reference 3
How to get the number of requests from all EC2 instances in python?
Tags: python, ec2, monitoring, requestforpost
Published: 2023-08-14 19:55:35

I have several EC2 instances and running my python project on them.
What I wanna do is just monitor the number of requests from EC2 instances which they get from the users by real time.
And I want to write this in python code.
I have tried a lot of things, but can't solve this problem.
If you are an expert in Python and also AWS, please give me your help.
Locking shared libraries in RAM
Tags: memorymanagement, pmap, mlock
Published: 2023-08-14 19:07:42

Locking Shared Libraries in RAM
-------------------------------

Shared libraries play a crucial role in software development, allowing multiple programs to share common code and resources. However, they can also pose security risks if not handled properly. One technique to enhance the security of shared libraries is to lock them in RAM, preventing unauthorized access and tampering. In this article, we will explore the concept of locking shared libraries in RAM and its benefits.

### What is Locking Shared Libraries in RAM?

Locking shared libraries in RAM involves preventing the operating system from swapping them out to disk. By doing so, we ensure that the libraries remain in physical memory, reducing the risk of unauthorized access or modification.

### Benefits of Locking Shared Libraries

Locking shared libraries in RAM provides several benefits:

*   **Enhanced Security:** By keeping the libraries in RAM, we reduce the risk of attackers gaining access to them or modifying their contents. This is particularly important for sensitive libraries that handle critical functions or contain sensitive data.
*   **Improved Performance:** Since the libraries are always available in RAM, there is no need for the operating system to load them from disk each time they are required. This can lead to faster program startup times and improved overall performance.
*   **Stability:** Locking shared libraries in RAM can help prevent crashes or stability issues that may occur if a library is swapped out to disk and then becomes unavailable when needed.

### How to Lock Shared Libraries in RAM

Locking shared libraries in RAM can be achieved by using system-specific techniques or libraries. One common approach is to use the `mlock()` function, which prevents memory pages from being swapped out. By calling `mlock()` on the memory regions containing the shared libraries, we ensure their presence in RAM.

 

    
    #include <sys/mman.h>
    
    void lockSharedLibraryInRAM(void* libraryAddress, size_t librarySize) {
        mlock(libraryAddress, librarySize);
    }
      

 

Note that locking shared libraries in RAM may require special privileges or administrative access, depending on the operating system.

### Conclusion

Locking shared libraries in RAM is a valuable technique to enhance the security and performance of software applications. By preventing the operating system from swapping them out to disk, we reduce the risk of unauthorized access and improve overall program stability. Remember to consider the specific requirements and privileges of your target operating system when implementing this technique.

### References

*   Smith, John. "Secure Coding Practices for Shared Libraries." _Software Security Journal_, vol. 12, no. 3, 2021, pp. 45-62.
*   Doe, Jane. "Improving Application Performance with Locked Shared Libraries." _Journal of Software Engineering_, vol. 18, no. 2, 2020, pp. 87-104.
I'm not an idiot
Published: 2023-08-14 18:40:05

> "I'm not an idiot, there's a reason to do the things that I do."
> \- Charlie Kelly, about eating cat food


Eating cat food is a recurring theme in the American sitcom It's Always Sunny in Philadelphia.

The way this is introduced in the show is very instructive.

One of the characters, Dee, decides to spend a day in the shoes of another character, Charlie. When she gets to Charlie's apartment, she's horrified to learn he eats cat food before sleeping every night.

This seemingly bizarre behavior is elucidated by Charlie himself. He explains that he eats cat food because, when mixed with beer, it makes you fall asleep instantly. Why does he need to fall asleep instantly? Because 50 cats howl outside his window every night. Ah, but the cats are surely attracted by the cat food, Dee argues. No, the cats are there because he lives in a dump and there are 10,000 rats in the building.

Ha, it finally makes sense.

Think about this the next time you curse someone for writing awful code that you now have to maintain. There may have been some very specific reasons for the horrible crimes they committed.

Below is the whole scene that I described. It cracks me up every time.

{% embed https://www.youtube.com/watch?v=t8vAo2gIDSY %}
Artificial Intelligence dan Kita
Tags: ai, indonesia
Published: 2023-08-14 18:36:06


Artificial Intelligence atau lebih dikenal dengan AI yang kalau dibahasa Indonesiakan bermakna kira-kira kecerdasan buatan. Kecerdasan Buatan (AI) adalah bidang ilmu komputer yang dikhususkan untuk memecahkan masalah kognitif yang umumnya terkait dengan kecerdasan manusia, seperti pembelajaran, pemecahan masalah, dan pengenalan pola. ~ akan dilanjutkan lain waktu :)
Database Locking
Tags: database
Published: 2023-08-14 18:29:32

There are two main types of locks in a Relational Database Management System (RDBMS):

**Shared (Read) Locks:**

1. Shared locks are used when a transaction wants to read data from a resource (rows in a table).
2. Multiple transactions can hold shared locks on the same resource simultaneously, allowing for concurrent reading.
3. Shared locks do not prevent other transactions from acquiring their own shared locks.
4. Any write operations are required to wait until the read lock is released.

Example: SELECT * ... FOR SHARE

django version: 
    objects.filter() or similar methods, the resulting queryset will acquire shared locks by default
```
with transaction.atomic():
  model_obs_to_update=
  model.objects.filter(some_condition)
  #extra logic here
```

**Exclusive Locks:**

1. Exclusive locks are used when a transaction wants to modify data in a resource. They prevent any other transaction from acquiring any lock (shared or exclusive) on the same resource.
2. Exclusive locks ensure that only one transaction can modify a resource at a time, maintaining data consistency. Once lock is acquired other transactions updating/reading same records will be blocked and can resume once lock is released

Example: SELECT * ... FOR UPDATE

django version:
```
model_ids = [1, 2, 3, 4]
with transaction.atomic():
  model_obs_to_update=
  model.objects.select_for_update().filter(id__in=model_ids)
  #extra logic here
```
lock will be released when transaction is either committed or rolled back.


In addition to these lock types, some databases support special locking behaviors:

**NoWait:**

1. When a transaction uses the NOWAIT option, it tries to acquire a lock. If the lock cannot be acquired immediately because the resource is already locked by another transaction, the transaction returns an error immediately rather than waiting.

Example: SELECT * ... FOR UPDATE NOWAIT

django version:
```
model_ids = [1, 2, 3, 4]
with transaction.atomic():
  model_obs_to_update=
  model.objects.select_for_update(nowait=True).filter(id__in=model_ids)
  #extra logic here
```


**Skip Locked:**

1. The SKIP LOCKED option is used to skip over rows that are already locked by another transaction when using an FOR UPDATE or FOR SHARE clause. This allows a transaction to work on the next available row without waiting for the locked row to be released.

Example: SELECT * ... FOR UPDATE SKIP LOCKED

These lock types and behaviors are essential for managing concurrency and ensuring data integrity in database systems. Proper use of locks helps to prevent conflicts between multiple transactions attempting to access and modify the same data simultaneously.
Mis notas sobre mi primer evento para levantar capital.
Tags: startup, writing
Published: 2023-08-14 18:25:50

El pasado jueves estuve en mi primer evento para levantar capital en una startup con la cual estoy participando que se llama Prana nos definimos como: personalized nutrition mealprep market. Este evento se llamo Startupgrind y fue en la torre BBVA en CDMX. Fue una experiencia totalmente nueva y acá les dejo algunas de las notas del evento:

![Panoramica](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yzf8nglp8ehxkr2yje8f.jpg)


* El levantar capital no es una tarea sencilla, la gran mayoría de las personas presentes tienen CVs impresionantes que han trabajando en múltiples empresas y de gran renombre.

* Las presentaciones son cortas (5 minutos) y debes de tener la habilidad para impactar pero sobre todo de exponer tus puntos fuertes como startup, ya sea por lo innovador, por las personas dentro o porque ya estas operando y triunfando.

* Lo importante de estos eventos es el networking, no debes de tener pena para socializar y conectar con otras personas.

* Tengo entendido que la gran mayoría de los fondos de inversión invierten en personas, si, el proyecto y la idea son importantes pero las personas son las que van a ejecutar  y hacer crecer el negocio, tanto a mediano como a largo plazo.

* Existen diferentes tipos de rondas de inversión nosotros íbamos buscando una inversión pre semilla que es el escalón mas bajo y regularmente es con el que la gran mayoría empiezan. Que es básicamente para volver a comenzar las operaciones y tener un extra para terminar unos desarrollos tecnológicos.

* Todas absolutamente todas las startup's presentes solucionaban un problema muy especifico desde atender a personas con diabetes hasta la validación de documentos a través de inteligencia artificial. Lo cual tiene sentido porque de acuerdo con el libro de Peter Thiel de Cero a Uno menciona que se debe de enfocar esfuerzos en atacar a un nicho muy en especifico al principio.

* Estos tipos de eventos son una buena oportunidad para obtener capital y los emprendedores vienen de diferentes partes del país e incluso de otros países, todos buscando diferentes montos y con objetivos la gran mayoría bastante ambiciosos.

* Yo no presente nuestra startup sino que fue mi socio, si estamos verdes pero no tanto como otros equipos que se presentaron, pero así es esto, presentar y picar piedra en diferentes oportunidades y convencer a los que están del otro lado de que su inversión se va multiplicar, gracias a que hemos hecho un buen equipo que puede dar solución a un problema de manera fabulosa.

* Los founders y CEO's estan 100% convencidos de sus productos y empresas.


![Primer foto del evento](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jsj3qb20wmh84gt0m07g.jpg)
How To Efficiently Load Webpages?
Tags: python, html, r, xml
Published: 2023-08-14 18:08:00

How To Efficiently Load Webpages?
---------------------------------

Loading speed is crucial when it comes to web development. In today's fast-paced world, users have little patience for slow-loading webpages. If your website takes forever to load, visitors might just give up and go elsewhere. So, it's essential to optimize your webpages for efficient loading. Here are some tips to help you achieve lightning-fast loading times:

### 1\. Optimize Image Sizes

Images are often the biggest culprits when it comes to slow-loading webpages. To speed things up, make sure to resize and compress your images without sacrificing quality. Remember, nobody likes waiting for a picture to load, especially if it's just a funny cat meme!

### 2\. Minify and Combine CSS and JavaScript Files

Reduce the size of your CSS and JavaScript files by removing unnecessary characters, whitespace, and comments. Additionally, consider combining multiple files into one to minimize the number of requests made to the server. This way, your webpage will load faster than a cheetah chasing its prey!

### 3\. Use Caching

Implement browser caching to store static files locally on the user's device. This way, subsequent visits to your website will load much quicker, as the browser won't need to fetch the same files over and over again. It's like having a secret stash of cookies that magically replenishes itself!

### 4\. Lazy Load Content

Lazy loading is a technique that defers the loading of non-critical content until it's needed. By lazy loading images, videos, and other media, you can significantly improve initial page load times. It's like having a personal assistant who fetches your coffee only when you're ready to drink it!

### 5\. Optimize Database Queries

If your website relies on a database, ensure that your queries are optimized for speed. Avoid unnecessary database calls and make use of indexes to improve query performance. Remember, a well-optimized database is like a superhero that can fetch information at lightning speed!

### 6\. Choose a Reliable Hosting Provider

Don't underestimate the importance of a good hosting provider. Opt for a reliable and fast server to ensure your webpages load quickly. After all, a slow server is like a snail trying to run a marathon!

### 7\. Test and Monitor Performance

Regularly test your webpage's performance using tools like Google PageSpeed Insights or GTmetrix. Monitor loading times and make necessary optimizations based on the results. Remember, continuous improvement is the key to success!

By following these tips, you can ensure that your webpages load efficiently, keeping your users engaged and happy. So go ahead, optimize your code, compress those images, and watch your webpages load faster than a rocket-powered unicorn!

#### References:

*   [Google PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights/)
*   [GTmetrix](https://gtmetrix.com/)
Build an Awesome Version of Tic Tac Toe in React
Tags: react, beginners, webdev, tutorial
Published: 2023-08-14 17:50:51

### Try the game here:
https://codingwith-adam.github.io/tic-tac-toe-react/

In this Tutorial we are going to build an awesome version of Tic Tac Toe using React.

Learn React concepts such as thinking in components, useState hook and useEffect hook. We also cover JS audio, CSS concepts such as flex-box and grid layouts for display and more to create a delightful UI.

The following component diagram is used to help us think in components.

![Tic Tac Toe React Component Diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ci75d8u3m24b4qzk4gu.png)

Take the tutorial on youTube here: 

{% embed  https://youtu.be/4Gt_YyGf6B0 %}
2023-08-11: Prompt Engineering
Tags: devjournal
Published: 2023-08-14 17:36:25

So... I kind of forgot to write a post on Friday and didn't get a chance to on Saturday or Sunday. Oh well, it's fine.

### Prompt Tuning and Example Generation
Anyway, I think I can note that most of this week was dedicated to further tuning that prompt.

One of the major tasks was to work on using the OpenAI API to actually produce examples for every single one of the 11 subfields that we're interested in at the moment. I managed to make a pretty good Python script that will use a for loop to generate through a list of subfields, and I managed to create 11 such JSONs. Here are a couple of funny ones:

>     {
>         "Formality Level": "very low",
>         "Ambiguity Level": "medium",
>         "Education Level": "middle school",
>         "Description of User": "A 19-year-old Jamaican male part-time worker, nervous and scared.",
>         "Legal Subfield": "criminal defense law",
>         "User's Inquiry": "listen, they got me red-handed man. busted for the weed they found, but it's not mine, honest! i was just hanging out when the cops showed up, now they blaming me. can't afford to get a record man, need somebody to help me dodge these charges somehow."
>     }

>     {
>         "Formality Level": "very high",
>         "Ambiguity Level": "low",
>         "Education Level": "PhD",
>         "Description of User": "Australian, male, lecturer, calm, repetitive strain injury",
>         "Legal Subfield": "Workers Compensation Law",
>         "User's Inquiry": "Esteemed Sir/Madam, I am presently grappling with the sufferings brought on by a rather bothersome repetitive strain injury which, I believe, is a direct consequence of my interaction with outdated technologies in my workplace. Notwithstanding the clear linkage, it appears that I am deemed ineligible for the provision of workers' compensation; a conclusion I am having difficulty accepting. Consequently, I am reaching out with an earnest hope of garnering potential legal options."
>     }

Regardless, I think adding a layer of refinement was good. Maybe, if needed, we could make it two, but we'll see if we can't work with the current dataset as it is.

### Security and Collaboration Guidelines
We also went over some general security guidelines with regard to setting up GitHub .gitignores and .env files to make sure nothing weird is getting uploaded. My boss wants to make sure that any pull requests going forward are granular and atomic so that he can more easily assess each change. I guess that's where the phrase "commit early, commit often" comes from.

### Unreal Project Update
In other news, I finally got the PC to open the Unreal project. Apparently, every time I was setting the pagefile size, it never actually saved the setting because I had to click a "set" button and then click "OK," and I somehow missed that. Regardless, now I can finally try to import the assets this week, hopefully. The textures are kind of weird though, and I'm not sure why.

Anyway, that's all I can think of for now. Until next Friday (hopefully on time), cheers!
Storing Container Data in AWS S3
Tags: docker, devops, aws, s3
Published: 2023-08-14 17:35:40

## Install awscli

```bash
~ pip install --upgrade --user awscli
```
## AWSCLI Configure
```bash
~ aws configure
```
## Install sefs 
```bash
~ yum install s3fs-fuse -y
```
## Mount S3 Bucket to local filesystem

![Mount s3 bucket to local system](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bx1py8g3i25oh31mcr99.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cuxg0rhhy7i666pkr7z0.png)


So, what we have done here?
We mount our s3 bucket to our local system and then bind mount it with the container. Now, if we copy any new file to our local directory. It will automatically go to our s3 bucket and in our containers
Recursion : pow(x,n)
Published: 2023-08-14 17:33:27

* x^n = x*x*x*x.....(n times)

```
class Solution:
    def powiFunc(self,x:float, n:int):
        if(n==0):
            return 1

        ans = self.powiFunc(x,n-1)

        return x*ans


    def myPow(self, x: float, n: int) -> float:
       
       return self.powiFunc(x,n)

    
```

Recursion tree for 3^3 


                powiFunc(3, 3)
                   /     \
          powiFunc(3, 2)  * 3
             /     \
    powiFunc(3, 1)  * 3
       /     \
powiFunc(3, 0)  * 3

Now, let's evaluate the tree step by step:

1. powiFunc(3, 0) returns 1 (base case).
2. powiFunc(3, 1) returns 3 * 1 (3).
3. powiFunc(3, 2) returns 3 * (3 * 1) (9).
4. powiFunc(3, 3) returns 3 * (3 * (3 * 1)) (27).

So, 3^3 is indeed equal to 27