teleren/devto huggingface dataset:
RN Web3 Auth
Tags: security, web3, auth, reactnative
Published: 2022-12-10 04:01:08

In keeping with our vision for user-owned authentication, we expended a lot of effort to get wallet based login to work -- a hefty feat in mobile. 

AllSpark uses Web3Auth to create a public private key pair. The newly created / already existing wallet is associated with your preferred social       login account. The sensitive application data is then encrypted in-device with a key derived from your wallet. 

In the near future the wallet login will allow us to do a few exciting things:
1. Direct blockchain rewards to your account. 
2. Wallet phrase based login
3. Wallet connect integration once we have replacement protocols for eth_getEncryptionPublicKey 
4. Wallet connect APIs for generating a similar flow. 

Since an application is in an untrusted space, it creates a challenge for correctly setting up any form of authentication gates. In AllSpark the idea is that authentication is just the capability to decrypt the database (have access to decryption key from touchId or provision device with Web3Auth private key. 

Web3Auth provided a working solution after attempting and failing with a few different providers. The focus for dapps seems to create a selection bias for browser based login. 
1) Rownd.com
2) Magic.link
3) Moralis 
4) stych

In a follow up post we will discuss our future plans and a more detailed write up with the issues encountered with these providers. 

Best,
-Yonz
AdventJS - Reto #2: Nadie quiere hacer horas extras
Tags: javascript, typescript, adventjs, adventofcode
Published: 2022-12-10 03:34:17


![Reto #2: Nadie quiere hacer horas extras](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o1v6ofnsh9pjrdesokde.png)

### [Reto #2: Nadie quiere hacer horas extras](https://adventjs.dev/es/challenges/2022/2)

**Instrucciones:**

Un millonario ha comprado una red social y no trae buenas noticias. Ha anunciado que cada vez que una jornada de trabajo se pierde por un día festivo, habrá que compensarlo con dos horas extra otro día de ese mismo año.

Obviamente la gente que trabaja en la empresa no le ha hecho ni pizca de gracia y están preparando un programa que les diga el número de horas extras que harían en el año si se aplicara la nueva norma.

Al ser trabajo de oficina, su horario laboral es de lunes a viernes. Así que sólo tienes que preocuparte de los días festivos que caen en esos días.

Dado un año y un array con las fechas de los días festivos, devuelve el número de horas extra que se harían ese año:

```javascript
const year = 2022
const holidays = ['01/06', '04/01', '12/25'] // formato MM/DD

// 01/06 es el 6 de enero, jueves. Cuenta.
// 04/01 es el 1 de abril, un viernes. Cuenta.
// 12/25 es el 25 de diciembre, un domingo. No cuenta.

countHours(year, holidays) // 2 días -> 4 horas extra en el año
```

**Mi solución**:

```javascript
function countHours(year, holidays) {
  const weekendDays = [0, 6];
  let hours = 0;
  
  holidays.forEach( function(holiday) {
    let date = new Date(`${holiday}/${year}`);
    if(!weekendDays.includes(date.getDay())) {
      hours += 2;
    }
  });
  
  return hours;
}
```

**Explicación**:

- `const weekDays = [0, 6];` Almaceno en un arreglo los días que nos han indicado que son fines de semana.
- `let hours = 0;` Arranco el contador de horas en cero.
- `holidays.forEach( function(holiday) {}` Recorro el arreglo para verificar los datos.
- `let date = new Date(`${holiday}/${year}`);` Creo la fecha con el formato corto (MM/DD/YYYY)
- `if(!weekendDays.includes(date.getDay()))` Verifico si el valor que me trae la función getDay() no se encuentra dentro del arreglo de `weekendDays`, es decir, si no es un fin de semana para sumar 2 horas al contador final.
- `return hours;` Devuelvo la cantidad de horas calculadas.

**Resultado:**

- 107 puntos
- Complejidad cognitiva: 1.5
- 2712 ops/s

**Otras soluciones:**

- [Serie Advent.js 2022 de Cristian Fernando - Reto #2](https://dev.to/duxtech/adventjs-reto-2-nadie-quiere-hacer-horas-extra-2eh4)
- [Canal YouTube asdex dev - Reto #2](https://www.youtube.com/watch?v=hlplyXbFhUM&list=PLtJA_0pDlZIYVrRo3shhObGmJqwxYMJq5&index=2)

Nos leemos en el siguiente reto.
【Laravel】How to fix error "file_put_contents: Failed to open stream: No such file or directory"
Tags: laravel
Published: 2022-12-10 02:56:35

If you encounter a error message that says "file_put_contents: Failed to open stream: No such file or directory" in Laravel, here is what you should do.
##What happened to my Laravel project##
My XAMPP had a problem and never started again. So, I installed a new XAMPP into my PC and moved my Laravel project directory from my old XAMPP to a new one. Then I saw this error message.
##Why this error message is shown?##
This error message is shown when directories/files/classes are missing in the paths where they were supposed to be by moving directories, changing file names or deleting class names.

##Execute these commands##

###1. php artisan cache:config###

In order to speed up processing, Laravel creates cache files according to the settings in .env or files in the config directory. Therefore, as long as Laravel has these cache files, the .env or files in the config directory are not loaded.
Laravel starts creating cache files by executing this command.

###2.php artisan cache:clear###
Laravel deletes the cache files.

###3.composer dump-autoload -o###
Laravel loads the libraries in vendor directory automatically. It makes Laravel reload the classes (defined with namespace).
##Result##
My error message has gone!! Yay!!
ERC-20 token VS NFT
Published: 2022-12-10 02:33:23

An **ERC-20** token is a type of digital asset that is built on the Ethereum blockchain. ERC-20 tokens are often used to raise funds for new projects through an initial coin offering (ICO). These tokens follow a set of rules that define how they can be transferred and how they interact with other contracts on the Ethereum network.

An **NFT**, or non-fungible token, is also a type of digital asset, but it is not necessarily built on the Ethereum network. An NFT is unique and cannot be replaced by another token. This is in contrast to a cryptocurrency like Bitcoin, which is fungible and can be easily exchanged for other tokens of the same type. _NFTs are often used to represent unique items like digital art or collectibles.
Final thoughts on contribution
Tags: webdev, opensource, beginners, programming
Published: 2022-12-10 02:27:31

Hi,

This week I've been wrapping up and polishing my PRs.

**Today I would like to go over 3 PRs that I did.**

### Icons

For the [following PR](https://github.com/humphd/my-photohub/pull/29) I had to come up with logo for the project.

Here is what I come to the end:

![Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0j8f64m40v0pickxxdhm.png)

I would say that creating a logo is very creative work to do. Of course, you might take a look at other logos for inspirations, but you need to create one from scratch, because you want the project to be unique and don't have any similarities with the ones that already exist.

For another Full stack project I have been collaborating with project maintainer and discussed possible improvements. It was very nice talking to Full stack developer and listening to his ideas. **How many great people around us, who seem to be total stranger but are very nice!**

### UI improvements

For [another PR](https://github.com/thevahidal/novel/pull/38) I was doing overall UI and accessibility improvements. Personally, I really like when people spent some time one designing the website and you can see the effort.

In the following PR I made basic but very important improvements:

#### Added some hierarchy:

- Positioned elements so that they are easily visible

![Sign up page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/phzyivhsi1xsebe3efb3.png)


- Made certain elements attract your attention, so that you understand what to do on the website

- Added some beautiful animations, so that user understands that he interacts with buttons, links, etc.

**It's a great practice to give user sort of response on hovering over a card, link or a button**. It's such a pain to see some of these elements without any interactions. 

![Hover effect](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2uo64yblsc8tlff2q4mw.gif)

### Why it matters ?

Because users want to be engaged. Nobody wants just a static website without any interactions with user. With animations, hierarchy, effects, etc. we make user stay on the website and continue exploring.

### Remove useless interactions

For [another PR](https://github.com/thevahidal/novel/pull/37) after discussions with project maintainer we have come to agreement to remove useless alert of saying _you need to login in order to create a story_. Instead we simply redirect the user to the log in page and showing error message asking to log in first.

### Final words

It's amazing that people are kind and willing to help you if you struggle with something. It's been a great experience working with Full stack developer and implementing features. 

P.S. **Networking and connecting with people from your industry is amazing**, who knows what knowing this person might lead in the future. Maybe we end up working together :)

![Logo](https://media1.giphy.com/media/qgQUggAC3Pfv687qPC/giphy.gif?cid=ecf05e47404796prfuc8au2zfrkoqfr20b4altjdf1whlqfd&rid=giphy.gif&ct=g)

Thank you for reading and have a great week!
A Guide to useEffect Cleanup
Tags: react, javascript, webdev, beginners
Published: 2022-12-10 02:26:57

Currently, I am in phase two at Flatiron School and the past three weeks have been all things React. I have learned some great concepts that have definitely helped me become a better developer and one of those concepts is cleaning up the useEffect hook. 


## Why cleaning up is important

Let's say you have a function that continuously runs a timer component in the background

```
function Timer() {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    setInterval(() => {
      setTime(new Date());
    }, 1000);
  }, []);

  return <div>{time.toString()}</div>;
}
```

When this component first renders, the useEffect hook will initialize and create an interval that runs every 1 second and set the time. We could then set state and create a button that will hide and show the timer. We might imagine that this also means that the timer will stop running once it is hidden. 

```
function App() {
  const [showTimer, setShowTimer] = useState(true);

  return (
    <div>
      {showTimer ? <Timer /> : null}
      <button onClick={() => setShowTimer(!showTimer)}>Toggle Clock</button>
    </div>
  );
}
```

However, this is not the case. Once you toggle the button, you will receive an error like the one below


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

This error indicates that even though the clock is hidden, it is still running continuously in the background and re-rendering the component every second. This could potentially cause unwanted behaviors and performance issues. 

The solution to this error would be to create a clean up function that runs once the component is unmounted. With our example it would look a little something like this 

```
function Timer() {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    const timerID = setInterval(() => {
      setTime(new Date());
    }, 1000);

    // returning a cleanup function
    return function cleanup() {
      clearInterval(timerID);
    };
  }, []);

  return <div>{time.toString()}</div>;
}
```

Now once the timer is toggled off, the clean up function will run and clear the interval we set. 

## The cleanup function lifecycle

The lifecycle of our timer component without the clean up would look like this 


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

And with the cleanup function added to our component's lifecycle would now look like this once the component is unmounted upon the click of the toggle off button


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


In summary, clean up functions are a great way to optimize the performance of your web app and to avoid unwanted behaviors. However, it is not always necessary to use clean up functions with your useEffect hooks. Scenarios like running timers, clocks or a subscription to a WebSocket connection are a few use cases where a clean up function is important.
Trading Indicators Data Scrapping
Tags: webscraping
Published: 2022-12-10 02:18:23

I'm trying to scrape data on a trading website. I've got some indicators for which I need to scrape data and put it out in json. But I cannot find those data on the html file. There are only div's with no data inside. So I need to understand how chart and indicator data is rendered on a page before scrapping it.

I'm using Puppeteer which is a scrapping library in JS.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0e1hiorv5en3ngazru40.png)
You Can Count On Me
Tags: javascript, beginners, css, showdev
Published: 2022-12-10 01:28:03

Yesterday during class we were set a task to create a calculator.

It’s been about 2 years since I did anything with event listeners but I love logic, so I figured I’d enjoy working through it.

I created the buttons, elements, and was then distracted by some fun code that changed the color of the background with a click. Then after a good night’s sleep I was finally able to traverse through my saved clicks and calculate for two numbers and an operator. Yay!

My next issue was crafting logic to handle double digit or longer numbers. I solved this by traversing my saved clicks and creating a stoplight that either concated the additional numbers into one index or didn’t.

The next problem was multiple operators and thus multiple calculations. After my original result from the first three clicks (eg 8x8) I ended up then traversing by twos, starting one index after I ended (index 4) that way I could always look back and use the previous operator (index) with my current number.

I considered writing logic alerting for multiple operators at once, and although I did alert if first click was with an operator, I left the rest to sort themselves out - just like any normal calculator you’d sat on.

The brief asked for console logs of the numbers (and if you’d like to check the math, they’re still there) but I decided to update the welcome message innertext to the calculated total. It also includes a tada emoji for funsies.

All in all it was a fun challenge that pushed me to go farther in my use of JS and CSS. 

If you'd like to use it here's the Replit:
https://replit.com/@Meg-Div/Calculator#calculator.js

Here's the code: https://github.com/Meg-Div/DigitalCraftsProjects/tree/main/calculator
Javascript For Loop
Tags: javascript
Published: 2022-12-09 19:21:48

The `for` loop is a fundamental control structure in JavaScript that allows you to repeat a block of code multiple times. It is often used to iterate over the elements of an array or other data structure, performing a specific operation on each element.

The `for` loop has the following syntax:

```
for (initialization; condition; update) {
  // Code to be executed
}
```
The `for` loop consists of three parts: the initialization, the condition, and the update. The initialization typically involves declaring a variable and setting its initial value. The condition is a boolean expression that is evaluated before each iteration of the loop. If the condition evaluates to `true`, the code block within the loop will be executed. If the condition evaluates to `false`, the loop will be terminated. The update is an expression that is executed after each iteration of the loop, and typically involves modifying the value of the variable declared in the initialization.

Here is an example of a `for` loop in action:

```
// Declare an array of numbers
var numbers = [1, 2, 3, 4, 5];

// Use a for loop to iterate over the array
for (var i = 0; i < numbers.length; i++) {
  // Print the current element to the console
  console.log(numbers[i]);
}
```
In this example, we declare an array of numbers and use a `for` loop to iterate over the elements of the array. The loop uses a variable called `i` to keep track of the current element. The `i` variable is initialized to 0 and is incremented by 1 after each iteration of the loop. The condition of the loop checks whether `i` is less than the length of the array, and the code block within the loop prints the value of the current element to the console.

This `for` loop will print the following values to the console:

```
1
2
3
4
5
```
The `for` loop is a powerful and flexible control structure that is widely used in JavaScript programs. It allows you to easily and efficiently perform operations on multiple elements of an array or other data structure, making it an essential tool for many common programming tasks.

Read More About For Loop : [**Javascript For Loop By CodingClaw**](https://codingclaw.com/javascript-for-loop/)
Next.js 13 with Tailwind and MUI Boilerplate
Tags: webdev, javascript, nextjs, tailwindcss
Published: 2022-12-10 01:03:59

In this crazy boilerplate, I've prepared the setup with the latest up-to-date stack for the Frontend. Let's see what's inside.

-   **Next.js 13** with its latest features like the **app directory** (you check how it works in this [excellent article](https://blog.logrocket.com/next-js-13-new-app-directory/) by [Kapeel Kokane](https://medium.com/u/197147636da0))
-   [**Material UI (or MUI**](https://mui.com/)**)** to speed up the development with pre-made components and excellent theme support
-   [**Tailwind CSS**](https://medium.com/u/d8c8c34e2236) --- I hate writing CSS(SCSS) from scratch

For those, who, like me, like to be confident in their code and help others to follow the same set of rules, I've added must-have tools:

-   **ESLint**, to ensure you and your teammates follow the same rules that prevent you from well-known bugs like "**Invalid Hooks Call.**"
-   **Prettier** because it's just heart-breaking when you have differently formatted code across the app

> **Optionally**, among the scripts in the package.json file, you would find the "**push-check**" command I usually run before push or as a part of the CI process which checks types and linter errors. And you can take a step even further, and install the [**Husky**](https://github.com/typicode/husky) package so it runs this command automatically on push, or on commit. But it's out of the scope of this article, as I add husky only if there's a R-E-A-L need for it.

![1](https://cdn-images-1.medium.com/max/1600/1*H-UZ9O7Je3OCnoZTlee6Yg.png)

* * * * *

### Afterword

You can find the source code in my [**GitHub account**](https://github.com/serhii-kucherenko/nextjs-typescript-materialui-tailwind), and for those who like to check things from the browser, I prepared a [**DEMO of the deployed app**](https://nextjs-typescript-materialui-tailwind.vercel.app/) **(**dark mode by default).

> **Remember**: You can choose whatever framework or library or package you want, but in the end, you would be responsible for the outcomes. So choose wisely, and don't make rush decisions by blindly cloning the repo if you're not confident in what you're working with.

* * * * *

I hope the article was helpful. Please subscribe so you don't miss the following articles, and feel free to contact me if you have any questions.

[Twitter](https://twitter.com/kucherenko_web) | [LinkedIn](https://www.linkedin.com/in/sergey-kucherenko/)
Import & Export
Tags: beginners, react, javascript, jsx
Published: 2022-12-10 00:19:12

React has a feature where you code different modules(js files) to run different features/functions. Starting off with App.js being exported into index.js, and having other modules imported into App.js such as perhaps a moduleContainer.js or navBar.js. Naturally when you're exporting JSX functions, you'd want to place anything that you need for the overall global scope somewhere such as in App.js, which allows you to pass down props called in the global scope.
 
The reason for coding in this style are various things such as:
**Strict variable scoping**. You wouldn't have to worry about mixing up codes or similar variables since variables declared in modules are private, making them non-accessible from the global scope.
**Easier navigation**. Allows for code to be more readable for other developers rather than jumbling up all the different parts of the code into separate pieces. Also makes it easier to debug since you can tell where you should be adding a debugger to. Also helps produce clean code that can be reused and repurposed.
**Single-responsibility principle**. Each module being responsible for running specific parts of the code 
i.e. 
App.js, RenderContainer.js, RenderCard.js, App.js, Search.js
Solidity Data Types
Published: 2022-12-10 00:04:33


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

1. Values Types:
   - uint(Unsigned Integer), uint8,..., uint256
   - int, int8,..., int256
   - bool(Boolean)
   - address: use to stock Ethereum address
   - bytes: Holds a 30 byte value
   - enum: The data representation is the same as for enums in C       
**example**: `enum Countries{ Morocco, CANDA, ESPAIN};`
   - function: There are three types of functions; `pure`, `view` and `payable`
2. References Types:
   - Arrays: `uint[] memory a = new uint[](7);`
   - Data Location: There are three data locations; `memory`,
    `storage `and `calldata`.
   - struct: used to create new types
```
struct Funder {
    address addr;
    uint amount;
}
```
3.Mapping Types:
   - Syntax:   `mapping(KeyType => ValueType) VariableName;`
Paracetamol.js💊| #193: Explica este código JavaScript
Tags: javascript, webdev, spanish, beginners
Published: 2022-12-10 00:00:00

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark></center>


```js
const x = [1,2,3].map((item, _, arr) => {
  arr.push(4)
  return item * 2
});
console.log(x)
```

A. `[2, 4, 6, 8]`
B. `[8, 2, 4, 6]`
C. `[2, 4, 6]`
D. `Ninguna de las anteriores`

Respuesta en el primer comentario.

---

Respuesta:
C. `[2, 4, 6]`

El método `map` iterará sobre el arreglo dado originalmente; esto quiere decir que si en el cuerpo de la función callback de `map` añadimos o eliminamos un item este no tendrá efecto sobre el barrido hecho en el arreglo con `map`.