teleren/devto huggingface dataset:
How to Handle Outside Clicks in React with TypeScript
Tags: typescript, react, nextjs, javascript
Published: 2023-02-27 11:32:07


React is a powerful library for building web applications, but sometimes you need to handle events that occur outside of your components. This can be tricky because React's event handling is based on a component hierarchy, and events outside that hierarchy are not automatically detected.

There are several libraries out there that can help you handle outside clicks, such as [outsideclick-react](https://www.npmjs.com/package/outsideclick-react). However, in this tutorial, we will show you how to implement your own hook to handle outside clicks in React using TypeScript.

To create a custom hook that listens for outside clicks, we can make use of the useRef and useEffect hooks provided by React. Here's an example implementation of the useOutsideClick hook:

```
import { useEffect, useRef } from 'react';

export const useOutsideClick = (callback: () => void) => {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent | TouchEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        callback();
      }
    };

    document.addEventListener('mouseup', handleClickOutside);
    document.addEventListener('touchend', handleClickOutside);


    return () => {
      document.removeEventListener('mouseup', handleClickOutside);
      document.removeEventListener('touchend', handleClickOutside);
    };
  }, [callback]);

  return ref;
};

```

In this implementation, the `useOutsideClick` hook takes a callback function as an argument, which will be triggered when a click event occurs outside of the specified element.

The hook returns a `ref` object, which can be attached to the root element of the component that needs to listen for outside clicks. When a click event occurs outside of this element, the `callback` function will be triggered.

Here's an example usage of the `useOutsideClick` hook:

```
import { useOutsideClick } from './useOutsideClick';

export const MyComponent = () => {
  const ref = useOutsideClick(() => {
    console.log('Clicked outside of MyComponent');
  });

  return (
    <div ref={ref}>
      My Component
    </div>
  );
};

```

In this example, the `useOutsideClick` hook is used to create a `ref` object, which is then passed to the root element of `MyComponent`. When the user clicks outside of `MyComponent`, the `console.log` statement in the callback function will be triggered.

By using the `useOutsideClick` hook, you can easily handle clicks outside of a specific element in your React components. This provides a simple and effective way to handle events that occur outside of the React component hierarchy.
Fuzzy-Couscous - The CLI for a better django development experience
Tags: django, opensource, cookiecutter, python
Published: 2023-02-27 11:17:30

Hello everyone!

I'm excited to introduce you to [fuzzy-couscous](https://github.com/Tobi-De/fuzzy-couscous), my latest project designed to enhance your django 
development experience with Django.

![showcase gif](https://raw.githubusercontent.com/Tobi-De/fuzzy-couscous/main/docs/assets/cuzzy_demo.gif)

I've spent the last few months working on this command line tool, and I'm excited to share it with you and get your feedback. 
The primary feature of fuzzy-couscous is to generate a django project using a project template that I've built, inspired heavily by the popular [cookiecutter-django](https://github.com/cookiecutter/cookiecutter-django) 
project template. I simplified their template as much as I could while adding some of my favorite tools like [htmx](https://htmx.org/) and [poetry](https://python-poetry.org/).

With fuzzy-couscous, you can quickly create a new Django project using the built-in template, which includes support for either [Bootstrap](https://getbootstrap.com/) or [Tailwind](https://tailwindcss.com/). 
It also comes with a variety of convenient commands, such as launching multiple processes at once including the Django dev server, a Redis server, a worker process, and more (although I'm currently working on improving this feature), 
as well as a command to easily download the latest version of htmx. I have some exciting ideas for potential new commands, including one to generate [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) code ([#27](https://github.com/Tobi-De/fuzzy-couscous/issues/27))  and another to ensure that projects 
created with fuzzy-couscous can easily get updates from the base template ([#22]( https://github.com/Tobi-De/fuzzy-couscous/issues/22)).
I'm always looking for new ideas and suggestions, so please feel free to open a [GitHub discussion](https://github.com/Tobi-De/fuzzy-couscous/discussions) or an [issue](https://github.com/Tobi-De/fuzzy-couscous/issues/new).

This project is nothing revolutionary, but it's useful for me and I think it could be useful for other django developers out there.
If you're interested, you can find fuzzy-couscous on GitHub at https://github.com/Tobi-De/fuzzy-couscous.
I hope you'll give it a try and let me know what you think. Thanks for your time!
AWS Kafka with Node.js
Published: 2023-02-27 11:29:53

To use AWS Kafka with Node.js, use the kafkajs library which provides a client for Kafka in Node.js. Here how to use kafkajs with AWS Kafka:

Install the kafkajs library using npm:

`npm install kafkajs`

Create a new instance of the Kafka client with the AWS configuration:



```
const { Kafka } = require('kafkajs')
const kafka = new Kafka({
  clientId: 'my-app',
  brokers: ['kafka-1.amazonaws.com:9092', 'kafka-2.amazonaws.com:9092'],
  ssl: true,
  sasl: {
    mechanism: 'scram-sha-256',
    username: 'my-username',
    password: 'my-password',
  },
})
```


Create a producer to send messages to a topic:
javascript

```
const producer = kafka.producer()
await producer.connect()
await producer.send({
  topic: 'my-topic',
  messages: [
    { value: 'Hello Kafka!' },
  ],
})
await producer.disconnect()
```
Create a consumer to receive messages from a topic:

```
const consumer = kafka.consumer({ groupId: 'my-group' })
await consumer.connect()
await consumer.subscribe({ topic: 'my-topic', fromBeginning: true })
await consumer.run({
  eachMessage: async ({ topic, partition, message }) => {
    console.log({
      topic,
      partition,
      offset: message.offset,
      value: message.value.toString(),
    })
  },
})
await consumer.disconnect()
```

That's it! You should now be able to use AWS Kafka with Node.js using the kafkajs library.
Who wants to be a millionaire in Norway
Tags: python
Published: 2023-02-27 11:25:53

**Building a Quiz Game with Hints Using Python**

**Description:**
In this blog post, I will describe how I built a quiz game with hints using Python. The game includes multiple-choice questions with four possible answers and different levels of hints to help players answer the questions correctly. The game utilizes the random module to shuffle questions and answers and generate probabilities for audience votes and phone-a-friend answers.
I created this game as a Codecademy project. Although the code may not be perfect, I learned a lot from this experience and I believe it has the potential for further improvement. Thank you for understanding and for your interest in my project.

**Link to my game:** https://github.com/nikitares/who_wants_to_be_millionaire_in_Norway

**Background:**
I was inspired to build this quiz game as a fun and interactive way to test my Python coding skills while also providing an entertaining game for others to play. As an avid fan of trivia games, I wanted to create a game that incorporated elements of strategy and luck while also testing players' knowledge on a variety of topics.

**How I built it:**
To build the game, I utilized Python and the random module to generate random questions, shuffling the answers and providing a variety of hints. The hints include a 50/50 chance to eliminate two incorrect answers, a poll of audience votes with randomized probabilities, the option to phone-a-friend with a 70% chance of getting the correct answer, and the ability to switch the question with another random question.

I also utilized the global keyword to ensure each hint could only be used once per game. I created a Hint class with separate methods for each hint option and a check function to validate user input. Additionally, I utilized ANSI escape codes to change the text color to make the game more visually appealing.

Utilizing Linode for this project allowed me to deploy my code on a cloud server and easily share the game with others. While building the game, I learned new skills such as using the random module to generate random probabilities and shuffling lists, implementing global variables, and utilizing ANSI escape codes to change text color.

**Additional Resources/Info:**
For those interested in building their own quiz game with hints, I highly recommend exploring the random module documentation and practicing manipulating lists with Python. Additionally, incorporating ANSI escape codes can add an extra level of interactivity to text-based games.
What is the best way to get all product data for free without using ebay API ( ebay developer API )?
Tags: php, nodej, webdev
Published: 2023-02-27 11:01:41

Have a list of sellers and I need to all product data of them including id, price, shipping price , quantity available, sold quantity and condition.

What is the best way?

Want to write code using Node.js or PHP.
Should also make it without ebay API(ebay developer API).
Of course want simple way, for example simple API alternatives or simple web scraping code. It's also ok for free limited pricing.
Please answer with example code.
L.I.F.T - the anti-advice that could save you
Tags: webdev, codenewbie, beginners, productivity
Published: 2023-02-27 11:00:00

It's not bad advice when I say Leave It For Tomorrow!

                        Leave 

                                It 

                                        For 

                                            Tomorrow 

Seemingly controversial advice to give, but hear me out.

When coding, at least learning to code, you will not only find yourself facing brand new subject matter constantly, but often trying to implement that new thing at the same time. The code you write is always to solve a problem and there are always a multitude of ways to solve it. You'll have to choose which path you take according to other dependencies and the structure you're using. You'll need to think the desired process through and break it down into small enough steps before writing a single line. Sometimes you will require the help of an extra plugin or library and therefore you will need to understand how that works in itself so that you can use it effectively. Already we've faced more decisions than we can shake a stick at and we don't even have anything written to show for it.

So you start to write. Already slightly strained in the mental sense, you hit a snag. The code doesn't seem to work the way you predicted. Frustration sets in a bit faster than usual and you go on a tangent to try and solve this unpredictable obstacle. 15 minutes you didn't have pass and you're back on track. Another snag...

Rinse and repeat.

This is the nature of web development.

Collins dictionary defines development as:
![Collins dictionary definition of development](https://mizouzie.github.io/images/l-i-f-t-01.png)

Number 3 is my favourite. Making a basic design **gradually** better. And it is just that when you're starting out, gradual. This is why I say that it is not actually a bad thing to leave it for tomorrow. The process described above is mentally exhausting. The normal urge is to stick at it until the problem is resolved, but the problem is often rather more difficult to resolve than predicted. Do what you can, do not exhaust yourself, come back to it tomorrow.

There is a strange thing that happens when you exercise this approach. When you look upon the same project that stumped you the day before with fresh eyes, it somehow becomes much more simple and easy to overcome. Your subconscious has worked on it overnight and you are now a much more experience developer because of that and therefore much better equipped to resolve the present issue.

Over time, the necessity to do this will be reduced as you compound your experience but there will be new challenges to face as you expand your abilities and if you managed to get into good working habits and recognise when to say "enough" and take a step back, your personal development will soar.

So as un-philosophical as it may sound and as irresponsible as it may feel, leaving it for tomorrow can actually be the best thing for you. If you haven't already, I suggest you at least give it a try and see for yourself.
Journey of Developing a Cool Game Buffalo
Published: 2023-02-27 10:58:01

I am excited to share my journey of developing a cool game called Buffalo. As a passionate game developer, I always wanted to create something unique and challenging for the players. After months of hard work and dedication, I finally created the game that I am proud of , you can see it here - [https://pokieslab.net/free-online-pokies/](https://pokieslab.net/free-online-pokies/). The idea of creating Buffalo came to my mind when I saw the beauty and strength of these majestic creatures.

- The first step in developing this game was to finalize the concept and create a design document.

- Next, I moved on to the programming part of the game. 

- Finally, after months of hard work and dedication, I released the game.

- In conclusion, developing Buffalo was an incredible journey for me, and I'm excited to continue creating more unique and challenging games in the online pokies Australia industry.

Thank you for reading!
PATTERN-THRU-PRACTICAL (PTP2)
Tags: designpatterns, soa, design, webdev
Published: 2023-02-27 10:57:41

Talk of Services across all kinds of modern-day applications. Be it Application-Level/ Business-Level/Cloud-Level and many more. All of them provide Core functionalities that are consumed by end-users through different network channels. There are Systems/Organizations which architect their entire Product Offerings as Service Interfaces for Public/Private consumption. One such Architectural methodology is the "**SOA (Service Oriented Architecture)**".

**SERVICE – ORIENTED – ARCHITECTURE**
What is a Service Oriented Architecture?
![SOA_Introduction](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lo97kk7s5nctntah4ily.png)

**Basic Building Blocks of SOA:**
The below diagram depicts the basic building blocks of SOA Architecture. Different Systems/Organizations could have different variants of this and buzzwords that may be new, but overall, this captures the essence of the Architecture. Services now have transformed into **Event-Driven, Micro-Services, SOAP, REST APIs, Containerized Services, Cloud Functions**, and many others, but as new inclusion comes, the foundational concepts will remain the same and also gives that primary knowledge to understand and design better systems.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9zwl75ffcokju89n2bq.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/knnachj8bpzxh7uhiziu.png)

**REAL WORLD ANALOGY:** **MEDIA SERVICES(PRINT,ONLINE...etc)**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4lq9urc9f8shru8hf1ra.png)

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

Hope you find it simple and easy to go through. Liked to hear your comments or suggestions!
Part-2 More about Docker
Tags: docker, beginners, containers, devops
Published: 2023-02-27 10:57:18

## Docker Architecture

![Architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/52fb91jp2gbaezjprv12.png)

Docker uses a client-server architecture. The **Docker client** talks to the **Docker daemon**, which does the heavy lifting of building, running, and distributing your Docker containers. The Docker client and daemon can run on the same system, or you can connect a Docker client to a remote Docker daemon.

Docker uses a technology called **namespaces** to provide the isolated workspace called the container. When you run a container, Docker creates a set of namespaces for that container.

**Docker Daemon:**

1. The Docker daemon is a service that runs on your host operating system. 
2. The Docker daemon **(dockerd)** listens for Docker API requests from client and manages Docker objects such as images, containers, networks, and volumes. A daemon can also communicate with other daemons to manage Docker services.

![API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5tr7mwmw44rqox5bwrnr.png)

**Docker Client:**

1. The Docker client (**docker CLI**) is the primary way that many Docker users interact with Docker. When you use commands such as docker run, the client sends these commands to dockerd, which carries them out. 
2. The docker command uses the Docker API. 
3. The Docker client can communicate with more than one daemon.

**Docker Registry:**

1. A Docker registry stores Docker images. Docker Hub is a public registry that anyone can use, and Docker is configured to look for images on Docker Hub by default. 
2. You can even run your own private registry.

**Docker objects**

When you use Docker, you are creating and using images, containers, networks, volumes, plugins, and other objects.

**Images:**

- An image is a template with instructions for creating a Docker container. Often, an image is based on another image, with some additional customization.
- For example, you may build an image which is based on the ubuntu image, but installs the Apache web server and your application, as well as the configuration details needed to make your application run.

**Containers:**

- A container is a runnable instance of an image. You can create, start, stop, move, or delete a container using the Docker API or CLI.
- By default, a container is relatively well isolated from other containers and its host machine.
- When a container is removed, any changes to its state that are not stored in persistent storage disappear.

![ending of blog](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ksz6hnc7g9po21wesonx.png)

In next blogs, we will learn more about Docker commands.
TIL you can inspect Docker-Container now with the docker-cli
Tags: todayilearned, docker, skopeo
Published: 2023-05-19 20:37:27

---
title: TIL you can inspect Docker-Container now with the docker-cli
published: true
date: 2023-02-27 10:30:00 UTC
tags: TIL,docker,skopeo
canonical_url: https://www.zufallsheld.de/2023/02/27/til-you-can-inspect-docker-container-now-with-the-docker-cli/
---

When I wanted to inspect Docker-Container that existed in a remote Docker-registry, I normally used [skopeo](https://github.com/containers/skopeo):

```
skopeo inspect docker://ubuntu:latest
{
    "Name": "docker.io/library/ubuntu",
    "Digest": "sha256:9a0bdde4188b896a372804be2384015e90e3f84906b750c1a53539b585fbbe7f",
    "RepoTags": [
        "10.04",
        "12.04",
        "12.04.5",
}

```

This command show me all the information about the image that I needed to know - tags, architecture and other things. It also showed me in an simple way if I could access the registry at all.

TIL that the `docker`-cli has an experimental feature called `docker manifest`. The [docker manifest](https://docs.docker.com/engine/reference/commandline/manifest/) feature does basically the same, albeit a bit slower:

```
> docker manifest inspect ubuntu:latest
{
   "schemaVersion": 2,
   "mediaType": "application/vnd.oci.image.index.v1+json",
   "manifests": [
      {
         "mediaType": "application/vnd.oci.image.manifest.v1+json",
         "size": 424,
         "digest": "sha256:c985bc3f77946b8e92c9a3648c6f31751a7dd972e06604785e47303f4ad47c4c",
         "platform": {
            "architecture": "amd64",
            "os": "linux"
         }
      },

```
Filtering data in R
Published: 2023-02-27 10:28:49

**Base R**

- subset() function: 
```
subset(df, column_name > value)
```

- subset operator: 
```
filtered_df <- df[df$column_name > 5, ]
```
- indices in subset operator: 
```
filtered_df <- df[indices, ]
```
- which() function to extract indices:
```
# create a data frame
df <- data.frame(name = c("Alice", "Bob", "Charlie", "David"),
                 age = c(25, 35, 40, 30))

# use which() to extract indices of rows where age > 30
indices <- which(df$age > 30)

# use the indices to extract the subset of rows
subset_df <- df[indices, ]

# print the resulting data frame
subset_df
```

**Tidyverse/dplyr**

- filter() function:
filter() function filters rows based on certain conditions.
```
subset_df <- filter(df, column_name > 30)
subset_df <- filter(df, column1_name > 30 
                  & column2_name == TRUE)
```
- slice() function:
slice() function selects specific rows.
```
subset_df <- slice(df, indices)
subset_df <- slice(df, c(1,3))
```
- select() function: 
select() function selects specific columns.
```
subset_df <- select(df, column_name)
```
Advise of better and correct approach in creating object and using in Type script and angular?
Tags: angular, typescript, javascript
Published: 2023-02-27 10:21:59

```
// ********** First Approach 

class MyCarComponent {
    private car: object = { };

    constructor(){
        this.car['name'] = "AudI";
        this.car['model'] = "2017";
    }
}

// *********** 2nd Approach 
class Car {
    name: string;
    model: string;
}

class MyCarrComponent {
    private car: Car = new Car();

    constructor(){
        this.car.name = "AudI";
        this.car.model = "2017";
    }
}
```
Please comment for correct approach
What are the limitations of current AI technology, and how could that impact society in the future?
Tags: discuss, ai, watercooler
Published: 2023-02-27 10:06:00

---
title: What are the limitations of current AI technology, and how could that impact society in the future? 
published: true
description: 
tags: discuss, AI, watercooler
# Use a ratio of 100:42 for best results.
published_at: 2023-02-27 10:06 +0000
---

It's true. AI is not human, and doesn't have full human capabilities. Some of those limitations include understanding human emotion and context. How will those limitations impact society? As developers, how do we utilize AI, while recognizing its shortcomings?
PHP Tip: More useful explode with item list
Tags: php, shorttip, webdev, beginners
Published: 2023-02-27 10:05:25

Securely, you did some item list like this once, didn't you?:

```php
<?php
function to_array(string $allowed_extensions): array {
  $allowed_list = explode(',', $allowed_extensions);
  return  array_map(fn($ext)=> trim($ext), $allowed_list);
}

to_array('.pdf, .odt, .doc'); //['.pdf', '.odt', '.doc']
```

not bad, but this is better:


```php
<?php
function to_array(string $allowed_extensions): array {
    $allowed_list = str_word_count($allowed_extensions, format: 1, characters: '.');
    return  array_map(fn($ext)=> trim($ext), $allowed_list);
}

to_array('.pdf, .odt, .doc'); //['.pdf', '.odt', '.doc']
```

Why?, because now you can change list format without changing nothing more. Look!:


```php
to_array('.pdf|.odt|.doc'); //['.pdf', '.odt', '.doc']
to_array('.pdf;.odt;.doc'); //['.pdf', '.odt', '.doc']
```

Happy coding!