teleren/devto huggingface dataset:
Custom hooks in React
Tags: webdev, react, javascript, programming
Published: 2022-12-30 09:27:32

Custom hooks are a way to reuse stateful logic across your React components. They allow you to extract stateful logic from a component, and share that logic with other components that might need it. This can be especially useful if you find yourself repeating the same logic in multiple components, or if you want to abstract away complex logic so that your components are easier to understand and maintain.

<img width="100%" style="width:100%" src="https://media.giphy.com/media/JVsitQAP1MvAMv2cQV/giphy.gif">

To create a custom hook, you simply need to create a function that follows a specific naming convention: it must start with the word "use," and it must contain at least one call to the built-in hook useState or useEffect. Here's an example of a simple custom hook that keeps track of the window width and height:

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

function useWindowDimensions() {
  const [width, setWidth] = useState(window.innerWidth);
  const [height, setHeight] = useState(window.innerHeight);

  useEffect(() => {
    const handleResize = () => {
      setWidth(window.innerWidth);
      setHeight(window.innerHeight);
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return { width, height };
}
```

This custom hook uses the useState and useEffect hooks to keep track of the window width and height. It sets up an event listener to listen for window resize events, and updates the width and height state variables whenever the window is resized.

To use this custom hook in a component, you simply need to call it like a regular function. Here's an example of how you might use the useWindowDimensions hook in a component:

```
import React from 'react';
import { useWindowDimensions } from './useWindowDimensions';

function MyComponent() {
  const { width, height } = useWindowDimensions();

  return (
    <div>
      The window is {width}px wide and {height}px tall.
    </div>
  );
}
```

This component will display the current window dimensions whenever it renders. The useWindowDimensions hook handles all of the state management and event handling, so the component can focus on rendering the UI.

Custom hooks are a powerful tool that can help you write more reusable and maintainable code in your React applications. They allow you to abstract away complex logic and share it across multiple components, making it easier to build and maintain large, interactive applications.
Host React website with GitHub pages in ten simple steps.
Tags: react, github, webdev, host
Published: 2022-12-30 09:19:00

Using Visual Studio Code.....

Step 1. First, add your repository using source control (Ctrl+Shift+G) on GitHub.
Step 2. Open terminal
Step 3. 

```
git install gh-pages
```
Step 4.
In package.json add following in first block before "name" :

```
"homepage": "https://<githubId>.github.io/<repoName>",
```

Step 5. In package.json, inside "scripts" block, add the following after "start":

```
"predeploy": "npm run build",
"deploy": "gh-pages -d build",

```
Step 6. Save the file and open terminal

Step 7.` git add .`
Step 8. `git commit -m "deploying webpage"`
Step 9. `git push`
Step 10. `npm run deploy`
A small benchmark to compare concurrent data structures in C#
Tags: csharp, dotnet, programming, tutorial
Published: 2022-12-30 09:04:37

The advantage of using concurrent data structures is that they allow you to write highly concurrent code that can take advantage of multiple CPU cores and run faster on multi-core systems. By using these data structures, you can avoid the overhead and complexity of manually implementing synchronization in your code, which can be error-prone and lead to race conditions and other concurrency issues.


```csharp
    static void Main(string[] args)
    {
        // Set the number of iterations and threads to use in the benchmark
        const int numIterations = 1000000;
        const int numThreads = 8;

        // Create a stopwatch to measure the time it takes to complete the benchmarks
        Stopwatch stopwatch = new Stopwatch();

        // Benchmark the concurrent queue
        stopwatch.Start();
        ConcurrentQueue<int> queue = new ConcurrentQueue<int>();
        Parallel.For(0, numThreads, i =>
        {
            for (int j = 0; j < numIterations; j++)
            {
                queue.Enqueue(j);
                queue.TryDequeue(out _);
            }
        });
        stopwatch.Stop();
        Console.WriteLine($"ConcurrentQueue: {stopwatch.ElapsedMilliseconds} ms");

        // Benchmark the concurrent stack
        stopwatch.Reset();
        stopwatch.Start();
        ConcurrentStack<int> stack = new ConcurrentStack<int>();
        Parallel.For(0, numThreads, i =>
        {
            for (int j = 0; j < numIterations; j++)
            {
                stack.Push(j);
                stack.TryPop(out _);
            }
        });
        stopwatch.Stop();
        Console.WriteLine($"ConcurrentStack: {stopwatch.ElapsedMilliseconds} ms");

        // Benchmark the concurrent dictionary
        stopwatch.Reset();
        stopwatch.Start();
        ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();
        Parallel.For(0, numThreads, i =>
        {
            for (int j = 0; j < numIterations; j++)
            {
                dictionary.TryAdd(j, j);
                dictionary.TryRemove(j, out _);
            }
        });
        stopwatch.Stop();
        Console.WriteLine($"ConcurrentDictionary: {stopwatch.ElapsedMilliseconds} ms");

        Console.ReadKey();
    }

```

## Join Me

Follow me on [Twitter](https://twitter.com/volkanalkilic) and [Linkedin](https://www.linkedin.com/in/volkanalk%C4%B1l%C4%B1%C3%A7/) for more content.
Awesome Weather UI with real time and date, Backdrop filters too.
Tags: codepen, html, css, javascript
Published: 2022-12-30 08:52:51

<h1>Weather Card with real time and date.</h1>

<p>And awesome detail icons (<a href="https://fontawesome.com/" target="_blank">https://fontawesome.com/</a>, <a href="https://fonts.google.com/icons" target="_blank">https://fonts.google.com/icons</a>)</p>

<p>Real Date &amp; Time, Popups, Backdrop filters, Lines, Icons</p>

{% codepen https://codepen.io/Amiru-Weerathunga/pen/ZExZMrP %}
Introduction to Web and HTML
Tags: web, html, elements, liveserver
Published: 2022-12-30 08:37:48

**L**ong ago when world needed something to share their achievements, views, discoveries or researches they needed a medium where they could share it across the world in a very fast and convenient way, we came up with web aka internet. Now with a simple click we can read or watch almost anything that world wanted to show.

**Apache HTTP server**

Web is made up of servers. Most web page are server using a webserver called Apache2. Apache2 is free and open source that gives us web content on internet. 

**cPanel**

cPanel is a web hosting control panel which host our website in a convenient way. We can manage our webpage using cPanel. It is very user friendly.

**Live server**

We need live servers where we can run or test our webpages to check if they are running fine. Live server updates our memory in a way that if we make any changes to our webpage using the code it will update as soon as we save our work. The most popular live server is by Ritwick Dey. It is an extension and is available for many platforms such as vscode.

**HTML**

Html page is made up of different elements or tags. The main tags are head and body. Head contains hidden meta information such as charset, language, browser compatibility, size, color etc. Body tag is our main tag where we do most of the work for a webpage. It can contain h tag, p tag, img tag, a tag etc. There are maximum number of 6-h (heading) tags. 

h tag is a heading tag. It gives the text a bold and bigger look so that its easier to read.

p tag is basically a paragraph tag in which you can type out your own research or data. We can also use Lorem ipsum if we want to fill the p tag with arbitrary information.

img tag is useful in embedding images to our webpage. There are several attributes to an element. img has src i.e., source, alt, sizes and srcset attributes to it. We can adjust the size of the image using these attributes. If the image is not loading we can use alt attributes so we know that there's a image there but its not loading due to some reason. "alt" attribute is very important for screen readers. Overall a very good attribute to have if your webpage required to have accessibility features. These kinds of accessibility features or attributes are very useful while developing websites for European countries. 

a tag is used for embed hyperlinks in your website. 

We will learn more about HTML, elements and attributes in upcoming articles.
A Nice Developer Joke For Today
Tags: jokes, dailydeveloperjokes
Published: 2022-12-30 08:00:17

---
title: "A Nice Developer Joke For Today"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e125905d1ad3.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ Why do programmers always mix up Halloween and Christmas?

___A:___ Because 31 OCT == 25 DEC
 -->
AWS Community days event 2022 Pune
Tags: webdev, productivity, aws, opensource
Published: 2022-12-30 07:03:49


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

Recieved these Amazing goodies as our souvenirs as the event wrapped up. Really the AWS Community Days event had a good collection for cloud enthusiasts. Thank you Intuitive.Cloud solo.io Amazon Web Services (AWS) Trainocate India DhiWise Easebuzz

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

I was waiting since days to attend the much awaited AWS Community days event 2022 at the iconic **Hyatt Regency** at pune.The event was one huge congregation of cloudgurus and cloud pilgrims alike and was what i exactly visualised (imagined it as sort of a mahakumbh of cloud enthusiasts) before leaving for the event. The event has really helped me embrace the art and practice of learning in public and via communities and this will be my primary takeaway from here on. Following are the snapshots from the event. Huge thanks to Amazon Web Services (AWS) , AWS User Group Pune & AWS User Group India for making this happen



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

Finally had the chance to meet our AWS Container Hero and DevOps mentor **Sandip Das**. I was able to absorb a lot of DevOps stuff from him in the very little time we had to interact and what he had planned to give back to the community going forward. His Infrastructure as code technical session was really a good jumpstart for anyone new to this approach of automation in the cloud. 


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

Here is another one with our Developer Advocate and thought leader Sai Vennam who is one of the unrivalled masters in the Containers world with the expertise he brings in. Most of my basics of kubernetes have been cleared with his awesome explanations on youtube while he was with IBM Technology. His keynote on “Past Present and Future of Kubernetes at AWS” was very informative.
Did I become a better programmer in 2022?
Tags: webdev, productivity, motivation, career
Published: 2022-12-30 07:00:00


In January 2022, I wrote a post about [how I wanted to become a better programmer](https://dev.to/yuridevat/how-i-want-to-become-a-better-programmer-in-2022-5aon) by the end of the year.

I set goals, adjusted my plan after a few months, and published an update on it after 3 to 4 months.

Now the end of the year has come and it's time to recap all my achievements from 2022 and see if I got better and made progress.

## Accessibility 
Accessibility didn't seem to be part of my plan when I started it, but that has completely changed after a few months and has become my main goal.

Even though I can't call myself an accessibility expert (which would be pretty unrealistic since I've only been working on this topic for a few months), focusing on this topic has given me clear professional goals for the future, introduced me to a great community, and even allowed me to [give my first talk](https://dev.to/yuridevat/this-was-front-end-foxes-day-2022-1472).

I also started my own organization in order to spread the word, called [Accessibility First](https://www.linkedin.com/company/accessibilityfirst).

Accessibility will continue to be my main focus in 2023.

## Open Source
During Hacktoberfest, I started an organization called [Yuri's Coding Club](https://www.yuriscodingclub.com/), which aims to help career changers get started in technology by gaining real-world experience that they can put on their resume.

It is an ongoing project that is still in its baby shoes. I hope the community will have grown by the end of 2023 and that it will help many developers find a job in tech.

## Soft Skills
Consistency is still one of my best and most important skills. For more than 20 weeks I wrote 2 blog posts a week on dev.to and I don't plan to stop. I have a lot of content I want to share and so many more ideas.

## Failures
What I couldn't focus on enough was filling in my gaps when it comes to programming itself. Focusing on the above is so much fun, I didn't want to waste time on anything else.

## Conclusion
I am a community person. I like to share, help others and want to improve in these areas. I want to focus on myself and my soft skills and be a role model in combining good soft and tech skills, having good time management, staying healthy and avoiding burnout.

![Happy new year!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/il5ff245b03rw6g6t3ow.png)

With that being said, I wish all of you a good start into 2023.
React Native Display Image SVG examples
Published: 2022-12-30 06:53:24

```

import { Image } from 'react-native';

<Image
    resizeMode="contain"
    style={styles.headerImage}
    source= {{uri: 
"https://www.google.com/url?sa=i&url=https%3A%2F%2Fpixabay.com%2Fimages%2Fsearch%2Fnature%2F&psig=AOvVaw1Hnk20FKp4R6eU6GwbUTL7&ust=1672469361872000&source=images&cd=vfe&ved=0CA8QjRxqFwoTCKi5nYPgoPwCFQAAAAAdAAAAABAE"}}    //u can use any file
 />


```

## This is For SVG




```
import {SvgUri} from 'react-native-svg';

<SvgUri 
  style={styles.footerIcon}
  width={50}
  height={50}                       
  uri="https://d2h44aw7l5xdvz.cloudfront.net/assets/zero.svg"
/>



```
What is the reason behind the success of Unilevel MLM plan?
Tags: unilevel, mlm, plan, software
Published: 2022-12-30 06:51:16

---
title: What is the reason behind the success of Unilevel MLM plan?
published: true
description: One of the most popular and oldest in the industry, the Unilevel MLM plan is very easy to understand. This program maintains a chain of distributors so that all your subordinates are in the lead. 
tags: unilevel, mlm, plan, software
# cover_image: https://www.armmlm.com/wp-content/uploads/2020/10/unilevel-mlm-plan.png
# Use a ratio of 100:42 for best results.
---
[Unilevel MLM Plan](https://www.armmlm.com/unilevel-mlm-plan-software/) is a simple and easy-to-understand compensation Plan. It is more similar to the Forced matrix scheme but with the exception that this scheme allows a distributor to add any number of suppliers to their network and these suppliers will be the lead.

Almost all MLM companies now use the Unilevel program as their flagship program and are making changes to make it more attractive. Also, this program is the most advanced and powerful compensation scheme over other network marketing programs.

#### Structure and Function of Unilevel MLM Compensation Plan:

In a Unilevel MLM program, there is only one distribution line, and each new member reports to his employer. There is no concept of spillover in this scheme as there is in the binary MLM compensation scheme.
![Unilevel MLM Plan](https://www.armmlm.com/wp-content/uploads/2020/10/unilevel-mlm-plan.png)

In this MLM plan, each member can recruit as many people as they want. Each of their downline members is capable of recruiting as many people as they want. This type of project allows you to build a larger and more powerful network of participants. The number of recruits is infinite, the network expands horizontally, and the depth of the level determines the commission.

A Unilevel compensation plan is used by companies that want to follow a simple business concept. The key idea of this Unilevel MLM program is its simplicity. Since this program is easy to follow, there is no need to try to learn more about it. Also, there are no issues like distribution or other criteria and the approach is simple.

This Unilevel MLM program, as the name suggests, allows you to promote a distributor stream. There is no limit to the breadth of this program. Also, the commission is earned only on the nominal amount earned on the fixed amount. This program is ideal for part-time workers who want to increase their passive income.

In general, MLM compensation plans vary greatly from business to business. When building an MLM business, compensation benefit is important because they will determine the success of your company. This is the main reason behind the popularity of this scheme as it offers better compensation benefits to the respective distributors and suppliers in the business network.
Advanced Java Multiple Choice Questions
Tags: advancedjava, mcq, advancedjavamcq, mcqpdf
Published: 2022-12-30 06:51:13

Practice the most popular [Advanced Java Multiple Choice Questions ](https://www.onlineinterviewquestions.com/advanced-java-mcq/)to improve your skills.

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

What are the major components of the JDBC Core Components?
 
-  DriverManager, Statement, ResultSet
-  DriverManager, Driver, Connection, Statement
-  DriverManager, Connection, Statement, ResultSet
-  **DriverManager, Driver, Connection, Statement, ResultSet**
 
Which package is used for importing swing controls?
 
-  java.awt.
-  java.swing
-  **javax.swing**
-  All of above
 
In which file database table configuration is stored?
 

- .sql
-  .ora
- **.hbm**
-  .dbm

How constructor can be used for a servlet?
 

- Initialization
-  Constructor function
-  Setup() method
-  **Both a and b**
 
Hibernate XML configuration file name is?
 

-  hibernate.cg.xml
-  **hibernate.cfg.xml**
-  hibernate.config.xml

Which element in hibernate maps java.util.SortedMap property ?
 

- < set >
-  **< map >**
-  < tree >
-  < list >

Which of the following is not a Java features?
 

-  Object-oriented
-  Architecture Neutral
-  **Use of pointers**
-  Dynamic

 ____ the first web browser developed in Java?

-  Opera
-  **HotJava**
-  JDB
-  Internet Explorer
 
 ____ is used to find and fix bugs in the Java programs.
 

- JRE
-  JDK
-  **JDB**
-  JVM

Which of the following is a reserved keyword in Java?

-  main
-  object
-  system
-  **strictfp**

_____ consist a data and methods?

-  Class
-  **Vectors**
-  Variable
-  None of the above
 
Which one of the following is a java keyword?
 

-   Void
-  **Public**
-  While
-  Switch

Java declaration statement must end with
 

- Colon
-  Comma
-  **Semicolon**
-  Full stop

Which one of the following languages is pure object oriented language?
 

- C
-  C#
-  C++
-  **Java**
 
The java visibility modifier is
 

- **Public**
-  Private
-  Protected
-  All of above

JDBC-ODBC bridge is
 

- **Multithreaded**
-  Singlethreaded
-  Both A & B
-  None of the above

An Enterprise JavaBeans can be deployed in _____
 

-  Weblogic
-  Web sphere
-  J2EE server
-  **All of above**

Java Language is architechturally _______
 

-  specific
-  **neutral**
-  oriented
-  abstract

SSL stands for______

-  **Secure Socket Layer**
-  Server Socket Layer
-  Secure Server Layer
-  Session Service Layer

The business process file’s name needs to end in

-  xml
-  jpdl
-  **jpdl.xml**
-  None of the above

Thanks for reading here. Also read[ most popular java interview questions](https://www.onlineinterviewquestions.com/java/).
Hi, I am Neeraj Kumar
Published: 2022-12-30 06:17:03

I have been a programmer for more than a decade. I work on Open Web Technologies and build bespoke enterprise application. Mostly on Laravel. 

These days, I am working on [Electrik](https://github.com/electrikhq/electrik/) - an open source alternative to SaaS starter kits like Laravel Nova, Wave, AdminLTE etc.

I live in New Delhi.

Nice to meet you. Glad to be here.
O que é e para o que serve Redis ?
Published: 2022-12-30 05:33:15

Redis é um banco de dados noSQL que armazena a estrutura de dados em memória que por sua vez pode assumir diversos papéis no desenvolvimento de software. 

Redis (Remote Dictionary Server) é um banco de dados que nasceu para atender uma demanda interna que é o problema de performance.
A razão de ele ser tão querido é que ele é extremamente rápido!

Desde suas primeiras versões o Redis tem sido utilizado por várias empresas como:

- Twitter
- Gitbub
- Pinterest
- Snapchat
- Stack overflow e vários outros...

Toda essa agilidade se dá porque todas as operações acontecem em memória, fazendo isso o banco de dados não precisa acessar o disco para consultar ou gravar dados. 

Além disso, o Radis não armazena as informações em tabelas, mas sim por uma estrutura chave valor, com isso as informações podem ser armazenadas de forma otimizada para quando forem consultadas.

Ele disponibiliza de estruturas mais simples até estruturas mais complexas como:

- Hyperioglog que é uma estrutura de dados probabilística usada para contar valores únicos ou como é referido na matemática: "calcular a cardinalidade de um conjunto".

- Bitmaps que são sistemas indicados para representação de imagens com alto nível de detalhes. 

- Índices geoespaciais que podem ser utilizadas para calcular a distância de dois pontos, ou encontrar múltiplos elementos em um raio.

_E se meu servidor for desligado?_

Um fato curioso sobre o Radis é que mesmo todas as operações acontecendo em memória, é possível configurar o Radis para criar Snapshots que são cópias de todo o conteúdo em memória em intervalos de tempo pré-determinados, gravando esses dados em disco.

Sendo assim, mesmo que o servidor seja desligado, os dados serão preservados.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gj2yag2b5g26fscbgi5d.gif)


O Radis pode ser utilizado pela maioria das linguagens de programação. Por exemplo:

- NodeJs
- Dart
- C
- Elixir
- Java
- Go
- Lua
- PHP
- Python
- Ruby