teleren/devto huggingface dataset:
PropTypes
Tags: react, beginners
Published: 2021-12-22 15:37:07

Developers usually use Typescript to point out mistakes that we make unknowingly while coding.
If we ever make a mistake while coding with Typescript, it gives us a warning in the middle of the coding. Now the question is can we check the code while doing our coding without Typescript? The answer is yes. But yes, I will not talk about other more detailed frameworks, just try to explain the issues with some simple examples of React. There is a thing called PropsTypes for type checking in React that you can use between class component and functional component but there are some differences. I will try to explain to you with some examples. npm install prop-types --save The package must be installed on your project. And must be imported into your project file 
import PropTypes from 'prop-types';

Let's start with the class component

import Pt from 'prop-types';
class Friend extends Component {
  render() {
    return (
      <h1>Hello Friends, {this.props.name}</h1>
    );
  }
}
Club.propTypes = {
  name: Pt.string
};
Here we will send the props in the same way as if they were not sent from another component then the error will be given. Here we have said PropTypes.string. Will give
It is understood that we have to send what we want to receive.

Basic PropTypes:
PropTypes.any: The prop can be of any data type
PropTypes.bool: The prop should be a Boolean
PropTypes.number: The prop should be a number
PropTypes.string: The prop should be a string
PropTypes.func: The prop should be a function
PropTypes.array: The prop should be an array
PropTypes.object: The prop should be an object
PropTypes.symbol: The prop should be a symbol
Using the same system can be used between functional components, for example.
import React from 'react';
import Pt from 'prop-types';
const student = (props) => {
  return (
    <div>
      <h1>Student Name: {props.name}</h1>
      <h1>Age: {props.age}</h1>
    </div>
  );
};
student.propTypes = {
  name: Pt.string,
  age: Pt.number
};
export default student;
React JSX
Published: 2021-12-22 15:35:15

Respond accepts the way that delivering rationale is innately combined with other UI rationales: how occasions are taken care of, how the state changes over the long haul, and how the information is ready for the show.

Rather than falsely isolating advances by placing markup and rationale in independent documents, React isolates worries with inexactly coupled units called "parts" that contain both. We will return to parts in a further segment, however assuming you're not yet open to placing markup in JS, this discussion may persuade you in any case.

Respond doesn't need to utilize JSX, however, a great many people think that it is useful as a visual guide when working with UI inside the JavaScript code. It additionally permits React to show more helpful mistakes and cautioning messages.
React PropTypes
Published: 2021-12-22 15:33:49

Respond prop types are a method for guaranteeing that the sorts passed to your capacities match those you planned the capacity to take. Prop types hold you back from settling on an unseemly strategy decision, especially when joined with unit testing.

It isn't exceptional to track down a capacity in your code, long in the wake of composing it, and understand that it doesn't exactly match what you want. For instance, assuming a strategy dependably returns a string-based ISO timestamp and you are performing math on numeric UTC timestamps, the outcome is a bothersome vague worth sooner or later your capacity call.

In the engine, React checks the property types passed to a part against those you characterize. The structure logs an admonition to the control center when they don't coordinate.
MongoDB Aggregation
Tags: mongodb, aggregation
Published: 2021-12-22 15:32:22

When MongoDB users want to gather computed data from various documents like sum, average, minimum, maximum, etc from a MongoDB database, MongoDB aggregation can be used. The concept of aggregation mainly clusters out your data from multiple different documents which are then used to perform different types of operations. 

In MongoDB there are three ways to perform aggregation : 

- Aggregation pipeline
- Map-reduce function
- Single-purpose aggregation methods



## Aggregation pipeline

 In MongoDB, the aggregation pipeline consists of many stages and each stage transforms the document. In each stage, it takes some documents as input and produces a result as a set of documents. In the next stage, it takes the previous result as input and produces a result. This process continues till the last stage.

There are many stages in MongoDB. Each stage starts with a stage operator. Some stage operators are given below - 

$match: It is used for filtering the documents. It can reduce the number of documents that are given as input to the next stage.
 
**$group:** It is used to group multiple documents
 
**$sort:** It is used to sort documents.
 
**$skip:** It is used to skip n number of documents.
 
**$limit:** It is used to pass the first n number of documents.




## Map Reduce Function

To aggregate, a large amount of data Map-Reduce function can be used. The map-Reduce function has two functions which are map and reduce. The map function makes a group of all the documents and the reduce function perform an operation on those grouped documents.




## Single-purpose aggregation methods

Single Purpose Aggregation aggregate all the documents from a single collection in MongoDB. It is used when we need simple access to document like counting the number of documents or for finding all distinct values in a document. It cannot provide flexibility and capability like map-reduce and aggregation pipeline.
Strapi v4 setup with Docker Compose and MySQL
Tags: strapi, dockercompose, docker, mysql
Published: 2021-12-22 15:31:53

---
title: Strapi v4 setup with Docker Compose and MySQL
published: true
description: I tried to find any information on how to set it up with docker - and it was rather complex. Sharing my solution with Docker-compose
tags: #strapi #dockerCompose #docker #mysql
cover_image: https://blog.brazdeikis.io/_next/image?url=%2Fassets%2Fblog%2Fstrapi-v4-docker-compose%2Fstrapiv4_docker.png&w=3840&q=75
canonical_url: https://blog.brazdeikis.io/today-i-learned/strapi-v4-setup-with-docker-compose-and-mysql
---

I have to say it was confusing - today existing docker image `strapi/strapi` has v3 under the hood and there is no simple way or docs to install Strapiv4 via Docker Compose.

Today the only way to create new project Strapi v4 is to use:
```bash
npx create-strapi-app@latest strapi-project --quickstart
```
and use it natively with node with
```bash
npm run develop
```

Today, I'm sharing my solution with Docker-compose.

## Create Strapi project via Docker

Install Strapi project files:
- set node version. Here is version 16.
- set project name. I use `strapi-project`
```bash
docker run -it \
	-v $PWD:/data\
	-w=/data\
	node:16-alpine sh -c "yes | npx create-strapi-app@latest strapi-project --no-run --dbclient=mysql --dbhost=mariadb --dbport=3306 --dbname=strapi --dbusername=strapi --dbpassword=strapi"
```

All those CLI options are listed here on the  Strapi Github repo - [packages/cli/create-strapi-app/create-strapi-app.js](https://github.com/strapi/strapi/blob/e2cd01e8c6cbfeba15ad7787e38b6eebcbb92221/packages/cli/create-strapi-app/create-strapi-app.js) With these options the configuration is setup correctly, together with the right database driver in `package.json`:
```json
...
"dependencies": {
    ...
    "mysql": "2.18.1"
  }
...
```

## Launch with Docker compose with Mysql together

Then lets launch the docker compose. Here as an option I use MariaDb as a choise.

For reference I used this folder structure:

![Strapi Docker Compose folder structure](https://blog.brazdeikis.io/assets/blog/strapi-v4-docker-compose/Strapi-docker-file-structure.png)

Use following `docker-compose.yml`
```yml
version: '3'
services:
  strapi:
    image: node:16-alpine
    command: npm run develop
    labels:
      com.example.description: "Strapi project"
    environment:
      DATABASE_CLIENT: mysql
      DATABASE_HOST: mariadb
      DATABASE_PORT: 3306
      DATABASE_NAME: strapi
      DATABASE_USERNAME: strapi
      DATABASE_PASSWORD: strapi
      DATABASE_SSL: 'false'
    volumes:
      - ./strapi-project:/data
    working_dir: /data
    ports:
      - '1337:1337'
    depends_on:
      - mariadb

  mariadb:
    image: mariadb
    volumes:
      - ./mariadb:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: strapi
      MYSQL_DATABASE: strapi
      MYSQL_USER: strapi
      MYSQL_PASSWORD: strapi
```

## Deploy with Docker compose to the production environment

For production deployment - please change the passwords above. 

Also, it seems Strapi suggests using `strapi start` instead as launch command.

Happy content creation!
Bookmarklet for injecting scripts onto a page
Tags: javascript
Published: 2021-12-22 15:31:19

```javascript
javascript:(function() {
    let url;

    // Add frame to ensure we have access to `prompt`
    let iframe = document.createElement('iframe');
    document.body.appendChild(iframe);

    // Request data
    if (url = iframe.contentWindow.prompt('Enter script URL. Type "module" if you want loaded as a module.')) {
        var type = url.match(/\s?module\s?/) ? 'module' : 'text/javascript';
        url = url.replace(/\s?module\s?/, '');
        var x = document.createElement('script');
        if (url.toLowerCase().substr(0, 4) === 'http') {
            x.setAttribute('src', url);
        } else {
            x.innerHTML = url;
        }
        x.setAttribute('type', type);
        document.querySelector('head').appendChild(x);
    }

    // Remove
    document.body.removeChild(iframe);
})();
```

If you create a bookmark with this code in it, it'll allow you to inject a script URL into the head of the page you're viewing.

It creates a temporary `iframe` just incase the top window overrides the `prompt(...)` command to prevent you from doing this.

There are some instances where the CSP of a page will prevent you from doing this, but it still works in many cases.

When it prompts you, you can give it responses like:

```
http://localhost:8080/script/my-script.js

// adds <script src="http://localhost:8080/script/my-script.js" type="text/javascript"></script>
```

or

```
http://localhost:8080/script/my-script.js module

// adds <script src="http://localhost:8080/script/my-script.js" type="module"></script>
```
What are your goals for 2022?
Tags: discuss, watercooler, career, productivity
Published: 2021-12-22 15:24:40

While some may consider New Year's resolutions to be a bit frivolous, I think they can be a good way to reflect on your priorities.

This year I set some goals around reading, blogging, and exercising. I didn't reach any of the arbitrary numbers I came up with at the beginning of the year, but I'm still happy with what I've accomplished and did much more than I would have without those goals to guide my daily actions.

So what are your goals for 2022:
* Do you want to start a new job?
* Do you want to launch a product you've been brainstorming?
* Are you going to dedicate more time to your hobbies?
* Will you take a class and learning something new?

Let me know in the comments!
Cross-post: Threat Detection Opportunities Learned from the Ubiquiti indictment
Tags: cybersecurity, datadog, aws
Published: 2021-12-22 15:09:44

My coworker and I just published a blog post for Datadog on the techniques used by the Ubiquiti hacker. We go into detail on different threat detection opportunities you can leverage in Amazon to catch a highly technical and malicious insider.

Check it out! 

https://dev.to/anskedatadog/threat-detection-opportunities-learned-from-the-ubiquiti-indictment-56i8
React redux and context API
Published: 2021-12-22 15:08:38

Redux 


 What is redux?
Redux is a state management library for react based web applications. Redux makes a react app to manage states available from any component without the hassle of prop drilling. Redux was initially introduced by Andrew Clark in 2015.
 What redux does?
Redux actually creates a store where all the states are kept for availability from any components. instead of sending data from state to state redux can send data to any components.
Install Redux 

There are two ways to install redux in web apps 
With npm 
npm install redux
npm install @reduxjs/toolkit
With yarn 
yarn add redux
yarn add @reduxjs/toolkit 
                   Sometimes it becomes necessary to install the react-redux package by npm Install 
                   React-redux
 
 4. Creating store.
In order to store data on the store, we have t create one first. To create a store in redux we need to create some files with javascript codes .with that code we call the create store function  
 Which returns a store that is basically a javascript object. And later with the help of the reducer, we can get data stored in the store very easily and effectively.
5. Store State in redux store
 Redux is used for state storing for components. Once we need to load data in a simple react app we used to store them in state and share the states through components to components. But in redux we don’t need to use state instead we store our state to the redux store with a unique name to be identified quickly. We do that with a hook called use dispatch. Dispatch function creates a space in the redux store and sends the required data
6. Get stored data from store
 To acces stored data we need to acess thw states that are create in the redux store. In order to do that we have to use  the redux useSelector hook. 
 const products=useSelector((state)=>state.allProducts.products)
useSelector hook make a connection to the reduces and the reducer calls the store that gves a state object.insiede that state object the related state is stored.
We can use that state from any component and any where any time.
 
 context API
Context API is a system to create a way to send data among all the parent and child components. With the help of context When we need to use a single state to multiple components then we use context API make it easy to share . for that propose we need to wrap all the needing components with context Provider component and make all other components its children component to pass data through Context value. 
To create context We use createContext Hook 
ANd to get value from the context  
 Have to use Context Hook.
Conversando sobre avaliações técnicas na área de TI 🧑‍💻
Tags: programming, selectiveprocess, codereview, ti
Published: 2021-12-22 15:06:10

## Avaliações técnicas na área de TI

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

Compartilhando um pouco da minha experiência aqui...

As avaliações técnicas podem variar bastante na hora de avaliar um profissional, de acordo com o nível de senioridade, o cargo, ou a stack de tecnologias usadas. Recentemente, como avaliador, cheguei a repensar um pouco como eu gostaria de ser entrevistado, pensando num processo que não ficaria chato ou pesado para ninguém. 

Foi a partir disso que comecei seguir com um processo parecido para diversos níveis de senioridade, que até hoje me deixou bem satisfeito com o resultado.

**A ideia é criar um projeto específico para entrevista, usando a stack de tecnologias / ferramentas relacionadas a vaga, e atuar em cima dele** 🔍 

* * *

## Entrevista Técnica

Dividindo a entrevista técnica em 3 partes:

1️⃣ **code review** de um projeto (~30 min avaliação + ~30 min conversa)

2️⃣ **pair programming** para implementação de uma pequena funcionalidade no projeto (~15 min avaliação + ~30 min implementação)

3️⃣ **refinement / planning** de uma nova funcionalidade no projeto (~30 min conversa)

* * *

### Primeira Parte

Consiste em deixar o candidato avaliar a qualidade do projeto. Deixando uns minutos para o candidato fazer um code review para depois conversamos a respeito do que ele observou, faria diferente, ou poderia ser melhorado. 

_Nota: Como costumo deixar erros propositais, sempre temos assuntos para conversar, e dependendo do quanto de elementos o candidato observar, é possível ter uma noção da experiência que ele tem sobre o assunto._

### Segunda parte

Consiste em um pair programming para implementar uma pequena funcionalidade no projeto, conversando a respeito de testes unitários e do raciocínio para resolver o problema de acordo com as regras de negocio especificadas.

### Terceira parte

Conversamos a respeito de uma nova funcionalidade que poderia ser implementada, conversando sobre escalabilidade do projeto, manutenção futura, etc...

* * *

## Conclusão

Seguindo com esse processo de avaliação, deu para metrificar com clareza o nível de senioridade dos candidatos de acordo com as regras que combinamos com nossa equipe sobre os requisitos das vagas, tanto sobre hard skills, quanto soft skills.

A entrevista em si demorava um pouco mais do que de costume (em torno de 2h-2h30 no total com introdução e tudo), e recebi feedbacks bem positivos dos candidatos, que não passavam por um processo muito longo (de vários dias) nem muito estressante, e já conseguiam ter feedbacks dos examinadores na hora, antes de empresa mandar um email formal sobre ser aceito ou não para a dita vaga...

**O que acharam desse processo de avaliação técnica? Adicionariam mais algo? O que importa mais para você? 🧐**

Bora compartilhar nossa experiência! 🙂
React Component life-cycle, Redux & React Optimization Techniques
Published: 2021-12-22 15:06:00


About React Component lifecycle,

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases.
Mounting, Updating, and Unmounting.

Mounting means putting elements into the DOM.
React has four built-in methods that gets called, in this order, when mounting a component:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
The next phase in the life cycle is when a component is updated.
A component is updated whenever there is a change in the component's state or props.
React has five built-in methods that gets called, in this order, when a component is updated:
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
The next phase in the life cycle is when a component is removed from the DOM, or unmounting as React likes to call it.
React has only one built-in method that gets called when a component is unmounted:
componentWillUnmount()
 
 
 

About Redux,

Redux is a predictable state container designed to help write JavaScript apps that behave consistently across client, server, and native environments and are easy to test. While it's mostly used as a state management tool with React, can use it with any other JavaScript framework or library



Techniques to optimize react js applications,

There are many techniques to optimize react js applications.
Here are some techniques,
Using Immutable Data Structures
Function/Stateless Components and React.PureComponent
Using Production Mode Flag in Webpack
Dependency optimization
Use React.Fragments to Avoid Additional HTML Element Wrappers
Enable SMS MFA with Plivo and Auth0 Actions
Tags: security, programming, react
Published: 2021-12-22 15:05:31

#### Use Auth0 Actions to enable SMS-based MFA with Plivo.

### <br>

Logging into a website with your username and password is a straightforward way to log in and access your content. You've been doing it for years, you've created several passwords, and it works. Logging in with **just** a password isn't as secure for your users as it used to be. Hackers can steal passwords from one site and use [credential stuffing](https://auth0.com/blog/what-is-credential-stuffing/) to pose as your user and gain access to other sites. It's common for your users to re-use passwords since they have several to remember across all their applications. You can help keep your users' data secure by offering another layer of protection by enabling Multi-factor Authentication (MFA).

> To learn more, read [this guide about MFA and its different methods on the Auth0 blog](https://auth0.com/blog/multifactor-authentication-mfa/).


You've likely experienced MFA in real life. For example, if you start working for a new company, they may ask for your ID card and a birth certificate. Those are two different *factors* of identification. It helps verify you are who you say you are to make sure your paycheck goes to you and lowers the success rate of someone posing as you.

In this blog post, you'll learn how to implement SMS-based MFA with Auth0 Actions and [Plivo](https://www.plivo.com/).

## Prerequisites

- An Auth0 account
- A Plivo account
- A Plivo phone number

If you do not have a Plivo account or an Auth0 account, you can sign up for a [free Plivo account](https://console.plivo.com/accounts/register/) and a <a href="https://auth0.com/signup" data-amp-replace="CLIENT_ID" data-amp-addparams="anonId=CLIENT_ID(cid-scope-cookie-fallback-name)">free Auth0 account</a>.

If you already have an application created in your Auth0 account, you can skip to [Create Action for MFA](#Create-Action-for-MFA).

[Read more...](https://auth0.com/blog/mfa-with-auth0-actions-and-plivo/?utm_source=content_synd&utm_medium=sc&utm_campaign=mfa)
React JSX
Tags: javascript, react, webdev
Published: 2021-12-22 15:05:25

In react, there comes a point when a new developer might ask, where does HTML play a part in building an application using react? Well, writing html is not a viable option in react. THen how can we build a web page if there is no html? 

The answer is simple, using JSX. JSX stands for javascript xml . Javascript xml is used as an alternative of html in a react application. JSX is almost like html except that it's not. The syntax and everything is just like html, which means writing jsx and writing html is almost no different. The difference comes in parsing them. Html is directly parsed by the browser whereas jsx is parsed and converted into javascript first, and then it is counted as javascript by the parser. 

In earlier days, the babel transpiler was needed for this parsing task of xml, but nowadays in react it is done easily using the babel plugin so that external babel transpiler is no longer needed.
CSS Grid Layout
Published: 2021-12-22 15:00:34

A **grid container** establishes a new grid formatting context for its contents. This is the same as establishing a block formatting context, except that grid layout is used instead of block layout: floats do not intrude into the grid container, and the grid container’s margins do not collapse with the margins of its contents. The contents of a grid container are laid out into a grid, with grid lines forming the boundaries of each grid item’ containing a block. 


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

Grid containers are not block containers, and so some properties that were designed with the assumption of block layout don’t apply in the context of grid layout.