teleren/devto huggingface dataset:
JSX for beginners (and how it differs from HTML)
Tags: react, javascript, html, todayilearned
Published: 2022-07-19 03:34:57

## What is JSX

JSX or JavaScript XML is an extension of JavaScript used to write [React](https://reactjs.org/) components.

**For example,** consider this code snippet below gives an illustration of what JSX typically looks like

```jsx
const greet = <h1>Hello World</h1>;
```

So JSX permits us write Javascript and HTML together. However, unlike HTML and Javascript, JSX cannot be interpreted by browsers so it needs a compiler (Babel or Webpack) to transpile it to Javascript

## Why use JSX

The very first thing you should know is that JSX is **not** a necessity. You can write React code without it.

Then why use it? Why mix the logic and the markup? JSX is **syntactic sugar**. It is designed to make things easier to read and express

**For example:** Consider a JSX expression
```JSX
<p color="red" shadowSize={2}>I'm a random sentence</p>
```

It is compiled by Babel to 

```javascript
React.createElement(
  "p",
  {color: 'red', shadowSize: 2},
  "I'm a random sentence"
)
```

The later snippet is obviously less pretty :grinning:

## How JSX differs from HTML

###1. Self-closing tags

In HTML, it's okay to write self-closing tags without closing them e.g. `<hr />` can be `<hr>`. This is **not permitted** in JSX. **All** tags must be closed.

Also, all tags can be self-close e.g. `<div />`
<br>
###2. Adding JavaScript expressions

JavaScript can be added directly into JSX markup using curly braces {...}

```JSX
{/* Output: Everybody knows 1 + 1 = 2 */}
<p> Everybody knows 1 + 1 = {1+1}<p>
```
So no need for the `<script>` tag HTML uses 
<br>
###3. HTML attributes change naming conventions

Remember JSX is writing HTML in JavaScript so certain HTML attributes like `class` and `for` which are keyword in JavaScript have to change to `className` and `hmtlFor` respectively. Take **note** of the use of **camelCasing** in the naming convention.

**All** JSX attributes follow the camelCase naming convention. So `background-color` becomes `backgroundColor`
<br>
###4. Inline CSS is an object

In HTML, you can directly add your inline CSS styles in the opening tag. However, this is not so in JSX. Here, you pass an object
For example Consider this HTML snippet 
```html
<p style="color:red;font-size:14px">Hello there!</p>
```
In JSX, it could be written as

```jsx
cont Greet = function() {
  const myStyles = {
    color:"red";
    fontSize:"14px";
    }
  return <p style={myStyles}>Hello there!</p>;
}
```
**OR** 

```jsx
return <p style={{color:"red", fontSize:"14px"}}>Hello there!</p>;
}
```
<p>I'm currently learning React. While transitioning from writing HTML to JSX, I found some key concepts and difference that everyone should be aware of. This is me just documenting my notes. Hope you found it helpful :blush:</p>
---
Header image credit: [patterns.dev](https://www.patterns.dev/posts/reactjs/)
Valid Parentheses
Tags: leetcode, algorithms, java
Published: 2022-07-19 03:31:31

**Leetcode Problem:** [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)

**Objective:**

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

---
**Pattern: Stack**

---
**Approach:** 

1. Use a hashmap to store the paired brackets: key = closed bracket and value = open bracket. 
2. If the hash map does not contain current character then it is an open bracket. Use a stack to store the open brackets. 
3. Check if the stack is empty this prevents closing brackets to be added first, in this case it is not valid. 
4. Check the top of the stack by popping it and if top character is not matched with closing bracket in hashmap then return false.  
5. If stack is empty then return true because it is a valid parentheses. 
6. If stack is not empty then return false. 

---
**Big-O Notation:** 

Time Complexity: O(n) 
We have iterate n times for each character in the string. 

Space Complexity: O(n)
We use a hash map data structures for storage. 

---
**Code:**

```java
class Solution {
    
    public boolean isValid(String s) {
        // use stack to store opening brackets
        Stack <Character> stack = new Stack<>();
        
        // use a hashmap to store pairs 
        Map <Character, Character> hashMap = new HashMap<>();
        hashMap.put(')','(');
        hashMap.put('}','{');
        hashMap.put(']','[');
        
        // iterate through s
        // add open brackets to the stack
        // if stack is empty or top char is not a match to c 
        // return false 
        
        for(char c : s.toCharArray()){
            if(!hashMap.containsKey(c)){
                stack.push(c);
            } else if(stack.isEmpty() || stack.pop() != hashMap.get(c)){
                   return false;
                }
            }
        return stack.isEmpty();        
    }
}

```
MariaDB Quick-tip #5 - Create a sequence of date and time
Tags: sql, mysql, mariadb
Published: 2022-07-19 03:15:00

## MariaDB tips and tricks

This is part of a series of quick tips and tricks I have accumulated over the year, that I think can be useful for others.
If you have similar short tips and tricks please leave a comment.

### Create a sequence of date and time

When working with data that is somehow related to dates and times you may need to generate a sequence of date to group by or select from.
The trick here is to use a recursive CTE ([Common Table Expression](https://mariadb.com/kb/en/common-table-expressions/). It can be a bit tricky to read but what the CTE does is to make a union with one additional datetime for each recursion. More [examples](https://mariadb.com/kb/en/with/) can be found in the MariaDb documentation. And the syntax is very similar to the SQL Server syntax as you can see [here](https://dev.to/coderallan/sql-quick-tip-5-create-a-sequence-of-date-and-time-4m6a).

The code below will create a sequence of datetimes with 10 minutes interval between each datetime value.

Like recursion in general, this can take up a lot of resources and be slow so I would not recommend using it in production code with high number of execution. But for data analysis and drilling into your data this trick can be very useful.

```sql
SET @stepSizeInMinutes = 10; -- Change this line to change the time interval
SET @from = '2017-01-01 00:00:00.00000';
SET @to = '2017-01-04 23:50:00.00000';

-- Create Recursive Discrete Table
WITH RECURSIVE Recursive_CTE AS
(
       SELECT @from AS TimestampUtc
        UNION ALL
       SELECT TimestampUtc + INTERVAL @stepSizeInMinutes MINUTE
         FROM Recursive_CTE
        WHERE TimestampUtc < @to
)
SELECT *
  FROM Recursive_CTE
 ORDER BY TimestampUtc
```
![DBeaver screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8h53aylkwlbgbf30bs8k.png)

### Create the sequence using MariaDB Sequence engine

As mentioned in the comments by @darkain, thanks for the tip, the date sequence can be created by using the MariaDB Sequence engine and this solution is a lot more affective than using the recursive CTE. So here is the SQL for that:

```sql
SET @stepSizeInMinutes = 10; -- Change this line to change the time interval
SET @from = '2017-01-01 00:00:00.00000';
SET @to = '2017-01-04 23:50:00.00000';

SELECT @from + INTERVAL seq * @stepSizeInMinutes MINUTE AS `Datetime sequence`
  FROM seq_0_to_99999999
 WHERE seq BETWEEN 0 and (SELECT TIMESTAMPDIFF(MINUTE, @from, @to) / @stepSizeInMinutes);

```
![DBeaver screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uc6s6o342pp5onvcjgff.png)
Intall nvm for node in linux
Published: 2022-07-19 02:53:00

1. `curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.1/install.sh | bash `
2. Si te llega a marcar un error como el siguiente: nvm: command not found, simplemente debes añadir las siguientes líneas de código dentro de tu archivo
`code ~/.zshrc `
3. `export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" `
4. Ahora ya podrá instalar cualquier version de node js

---------  COMMANDS FOR MANAGE THE VERSION OF NODE-----
1. nvm alias default 12 (para poner una version por defecto)
2. nvm i 12 (Para instalar una version de node)
3. nvm use 12 (Para usar la version de node)

OJO. en cada terminal tienes que poner vnm use ...
Linux Distro is OUT ~ Try Metis Linux
Tags: linux, programming, opensource, discuss
Published: 2022-07-19 02:41:27

Hey Linux Folks,

After a year of incubation and struggle, the first version of Metis Linux 0.1 has been launched with less bloatware and just the things you need.

## Metis Linux Intro

Metis Linux is an artix based super fast, lightweight,simple and flexible distribution that uses runit as an init system [ simply no systemD ] & super tiny scripts to install & manage the whole operating system.

Started as a hobby project by a 17 y/o Nepalese kiddo Nabeen Tiwaree with his fellow friends Yogesh Lamichhane and Safal Piya.


![Image description](https://webmatrices.com/assets/files/2022-07-12/1657644337-606284-image.png)


Our implementations are written from shell and C/C++. Metis Linux is POSIX compatible, which means our project can be easily portable to any other operating system.

[Metis Linux](https://webmatrices.com/d/1299-metis-linux-a-turbo-fast-artix-based-linux) aims at providing a stunning experience to new Tiling Window Manager users, it provides an easy gateway to the tiling window manager world with sane configs and keybinds that are easy and memorable.

[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rsazfefdckcirxr2bgzq.png)](https://blog.webmatrices.com/web-stories/linux-distro-is-out-matis-linux/)
 

The Metis Linux team wishes to make tiling window managers less intimidating by providing a polished experience out of the box.


## Features
### Fast and lightweight
Suckless's simple packages are used wherever possible. Using DWM with only the absolute required packages makes the operating system super minimalistic and only uses about 250 MBs of memory at boot that makes the OS super productive.

### Simple and Free
If anything can be simple, let's just simplify it. Our implementations should be written from shell and C/C++, and we love usable and simple package implementations, which are all freely available in Github.

### systemd-less
Stated by the unix philosophy, Make each program do one thing well, systemd includes many features that we never use; making the init system complicated. So RunIt is our init system of choice.

### POSIX compatible
We want our project can be easily portable to other operating systems.

## Default Packages
Metis Linux ships with following packages by default.
– Text Editor: nvim (Neo-VIM)
– Window Manager: DWM (Dynamic Window Manager)
– Terminal: ST (suckless terminal or simple termimnal)
– Screenshot utility: Scrot
– Bar: SlStatu
– Application Launcher: Dmenu
– brillo: Backlight (brightness) controller
– Pulseaudio: Audio Server for linux (will switch to pipewire on next release)
– JetBrains Mono Nerd Font
– Firefox as default browser

Thanks for reading...
New Feature of openGauss 3.0.0: Parallel Decoding
Tags: opensource, opengauss, database
Published: 2022-07-19 02:20:23

With the rapid development of information technology, various types of databases emerge one after another. Logical replication is increasingly important, with which data can be synchronized between heterogeneous databases. Currently, the average serial decoding performance of logical replication in openGauss is only 3 to 5 Mbit/s, which cannot meet the requirements of real-time synchronization in heavy service pressure scenarios. As a result, logs are stacked, affecting services in the production cluster. Therefore, the parallel decoding feature is designed to enable multiple threads to perform decoding in parallel, improving the decoding performance. In basic scenarios, the decoding performance can reach 100 Mbit/s.
openGauss solutions as follow.
Learn more,Please click the word"[openGauss"](https://blog.opengauss.org/en/post/2022/new-feature-of-opengauss-3-0-0-parallel-decoding/)
VS Code Tip of the Week: The Project Manager Extension
Tags: vscode, vscodetips, vscodeextension
Published: 2022-07-19 02:09:25

This week's VS Code Tip of the Week is the [Project Manager extension](https://marketplace.visualstudio.com/items?itemName=alefragnani.project-manager). This extension has been around for a while, but it's so useful. I literally use this every day.

This extension allows you to manage projects, where projects are a folder that you're project lives in.

## Pick a project to open

Press <kbd>CTRL</kbd> + <kbd>Alt</kbd> + <kbd>P</kbd> (<kbd>CMD</kbd> + <kbd>Option</kbd> + <kbd>P</kbd> on macOS) to load your list of projects then use the keyboard or mouse to select the project you want to load.

![List of projects that the Project Manager VS Code extension is aware of](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3lxmhrcuigniwmrmxjoh.png)

## Add a project to the list of projects

In a project that hasn't been added to the list of projects managed my the Project Manager extension? Press <kbd>CTRL</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> (<kbd>CMD</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> on macOS) to load the command menu and type in `save project`, The command to save a project appears. Use the keyboard or mouse to select the command.

![The VS Code command menu open with the Project Manager: Save Project command in the list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnupeg2g5vmsrhgpvwgo.png)

By default, it will populate the command menu with the project name defaulting to the folder name where the project lives. Keep the default name or rename it then press enter to save the project.

![The Project Manager extension setting the name of the project to save to the name of the folder that is currently open in VS Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8fd6ro3jv8ylro689u5u.png)

Now when you go open the list of projects, your new project will be on the list.

![List of projects that the Project Manager VS Code extension is aware of including the newly added project we just added](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p1nb5p87mx3owvzugbux.png)
npm start does not work for Reactjs
Published: 2022-07-19 02:05:49

I want create a Reactjs project,I user command as follow:
```js
npx create-react-app my-app
cd my-app
npm start
```
I have set the `C:\Windows\System32\WindowsPowerShell\v1.0` as the environment variable.

However, the command get stuck while **Starting the development server...**,the computer can't open a website automatically！

what should I do to solve this problem?
Free download (link in post)
Published: 2022-07-19 01:54:00

Download all of my articles for free [here]:https://drive.google.com/drive/u/1/folders/1FnrucEf88yIO5KY-tlCeWz_FbAF9ocns).

Do note that the free versions are all watermarked. I'm working on finding a way to sell the non-watermarked versions at an affordable price.
Automatizando a criação de requisições no JMeter utilizando Postman
Tags: testing, postman, jmeter
Published: 2022-07-19 01:51:29

Faz um tempo que não escrevo por aqui, mas hoje, enquanto estudava para resolver um problema do trampo, me deparei com uma técnica que facilitou muito a forma de criar requisições no JMeter, então decidi compartilhá-la.

Antes de mais nada, quero agradecer aos meus amigos [Jurno](https://twitter.com/ojuninrocha) e [João](https://github.com/poferrari), que me guiaram na busca pela solução.

Sem mais delongas, bora pro problema.

## O problema
Imagine que em um determinado momento, você e seu time precisarão realizar um teste de carga na aplicação que vocês desenvolvem. Entretanto, vocês possuem pouco ou nenhum conhecimento com a ferramenta JMeter, uma das mais utilizadas para esse tipo de tarefa. 
Uma das possíveis soluções é gastar um bom tempo lendo a documentação para aprender a criar as requisições uma a uma. Inclusive, essa teria sido a minha decisão, não fosse pelos conselhos dos amigos citados acima.

## A solução
É possível adicionar um elemento ao plano de teste do JMeter chamado [**HTTP(S) Test Script Recorder**](https://jmeter.apache.org/usermanual/jmeter_proxy_step_by_step.html). Ele é responsável por gravar requisições http e transformá-las em uma HTTP Request (sampler). 
![Imagem da UI do JMeter mostrando o HTTPS Test Script Recorder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gkliswkgkqjfr4upy0i.png)
Com esse elemento adicionado, basta ajustar as configurações de proxy do Postman (ou qualquer outro sistema que você utiliza) para o endereço do Test Script Recorder (localhost:8888 por default), rodar o elemento e então realizar uma requisição no sistema a ser testado. 
![Configurações de proxy do postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rcnltqf07ag0br92nhlv.png)
Fiz uma requisição de exemplo na [PokéAPI](https://pokeapi.co/api/v2/pokemon/ditto), e eis a requisição montada automaticamente no JMeter:
![Interface do JMeter mostrando a requisição montada automaticamente](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29p2sjk2d7iewegegped.png)

É possível que seja necessário realizar algumas alterações na requisição gerada, mas creio que o procedimento descrito acima seja um excelente ponto de entrada para requisições mais elaboradas.

Bem, caso haja alguma dúvida sobre o texto ou alguma sugestão de melhoria, peço que envie um comentário 😎.
Até a próxima!
Day 76/#100DaysOfCode
Tags: python, hackerrank
Published: 2022-07-19 01:42:56

Continuing to work on the 6th Hackerrank problem.

Achievements from yesterday:
1. Restated and understood the leap year problem.
2. Learned nested if Statements

The plan for today:
1. Study functions again from Python Crash Course book.
2. Move to CS Timer Solutions Statement
3. Find out what's the process of building a software professionally. 

Today I learned:
1. What was the issue before when TypeError was: "missing 2 required positional arguments". This means the function calls need to have 2 arguments like what was defined in function calls. Don't remember which exercise it was but I remembered encountering this. So in the future gotta make sure that the number of arguments defined match with the function calls.
1-line theme switching in React (with Tailwind + DaisyUI)
Tags: react, tailwindcss, nextjs, webdev
Published: 2022-07-19 01:20:00

[DaisyUI](https://daisyui.com/) is the best Tailwind components library I have worked with. Although it provides many beautiful preset themes(dark, light, cupcake, bumblebee and many more), the only tricky part was implementing theme switching with daisyUI button or toggle. 

In this post I'll show how to implement light and dark mode switching seamlessly.

Although the official tutorial on daisyUI's website says you should use the '[theme-change](https://www.npmjs.com/package/theme-change)' npm package, I found it easier to directly add the 'data-theme' attribute to the html tag(which is what the package does).

Here is what the toggle button component code looks like:

```js
const Toggle = () => {
  useEffect(() => {
    /* Sets the data-theme attribute on html tag */
    document.documentElement.setAttribute(
      "data-theme",
      localStorage.getItem("theme") === "dark" ? "dark" : "light"
    );
  }, []);

  return (
     /* Component provided by daisyUI - https://daisyui.com/components/toggle/ */
     <input
       type="checkbox"
       className="toggle"
       defaultChecked={
         typeof window !== "undefined" &&
         localStorage.getItem("theme") === "dark"
       }
       onClick={(e) => {
         let newTheme = e.target.checked ? "dark" : "light";
         localStorage.setItem("theme", newTheme);
         document.documentElement.setAttribute("data-theme", newTheme);
        }}
     />
  );
};
```

Since I am using NextJS I confirmed whether we are on the client side before accessing localStorage to set the defaultChecked value of the toggle.

And that's it! This will let you use the toggle button to switch themes(with built-in smooth transitions), save your theme to the local storage and use localStorage to restore the theme on further visits to the webpage.

If you wish to use different UI components to switch between themes (i.e. use buttons or a dropdown menu), you can do so in exactly the same way using the respective components from daisyUI.

To implement more themes, all you need is the name of the theme, all the theme configurations [come out of the box](https://daisyui.com/docs/themes/) with daisyUI!

Incredible, isn't it?!
GitHub Student Developer Pack...!
Tags: github, programming, beginners, javascript
Published: 2022-07-19 00:44:42

## Do you know the GitHub Student Developer Pack?

Well, if you don't know the GitHub Student Developer Pack, I'll explain it in a nutshell.

The Student Developer Pack is a set of tools, courses and community programs with an approximate value of 200k dollars, which will help you strengthen the knowledge you will acquire during your journey to become a developer.

## Don't have it yet and would like to get it? Just follow these steps.


**Step 1**
![GitHub Home Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fn66g0xig044q7aonow1.png)

 Go to GitHub homepage https://github.com/ 


**Step 2**
![GitHub Sign in](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsrf1ioqvhhnbcc2lnsm.png) Create an account or start a new section if you already have one.

You will then be asked to verify your email address if you are creating a new account.


## After having successfully created a GitHub account, we will continue with the following steps.

**Step 3**

![GitHub Education](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8rbgs8w7ot0xu1jk5m8y.png) We will then go to GitHub Education to begin the process of obtaining the GitHub Student Developer Pack. https://education.github.com/

Click in Join Global Campus.

**Step 4**
![Select area in Education GitHub](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3h8lddottbrbrutc2vsr.png) Click on Get the Student Pack.


**Step 5**

![GitHub Education](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rn0m1lw1ci8nlmlo03mh.png) Then we will be taken to this page and click on Sign Up for Student Developer Pack and Get benefits for students.

## The following steps are essential

**Step 6**

![GitHub Education](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g5y0bwbn9ap5dop8gmpz.png)

1. We enter our institutional email address

2. Enter the name of your college or university

3. Say something about how you use GitHub

**Step 7**
Finally, we only need to upload a photo of your college or university ID card, in case you do not have one, you can upload a paper that supports your enrollment in the college or university.

## Of the most popular benefits that can be found in the package are:

1. Canva free for one year.

2. One domain for one year at namecheap.

3. Free access to 25+ Microsoft Azure cloud services plus $100 in Azure credit.

4. A free subscription for students, to be renewed annually in JETBRAINS.

5. Get 6 free months of 60+ courses covering in-demand topics like Web Development, Python, Java, and Machine Learning in Educative.

6. $100 in platform credit for new users in DigitalOcean.

And many more benefits that you can find in the package.

## Thank you for your time, I hope you can use my help and also get your student package. See you guys next time.