teleren/devto huggingface dataset:
RegEx What?
Published: 2022-01-26 14:29:08

If you're anything like I was 10 minutes prior to writing this blog- you have little to no understanding of what RegEx do or when to use them. Well lucky for you, you've stumbled upon this article, and I'm here to enlighten you.

RegEx- or regular expressions- are powerful ways to search through strings or blocks of text for particular patterns. Some basic tasks they can be used for are data validation, searching, mass file renaming, and finding records in a database. Think creating emails, usernames, or passwords on a website- there's always requirements like one uppercase character, or a special symbol. Well how do you think the site knows whether or not you've typed in a valid password or email? RegEx.

There are two ways to write RegEx, either between two forward slashes: `/your regex/` or the long way by creating a regular expression object: `Regexp.new('your regex')`. Writing a series of letters or numbers in your RegEx will result in a search for the exact matches of this pattern anywhere in the string that you're searching. However- the only reason to use the plain forward slashes way of writing regex is if you want to find a specific word, or pattern within the string you're searching through. If you would like to search for multiple specific characters, like vowels, you would need to include brackets- `/[aeiou]/`. This will search the string for every instance of each of those vowels. One cool feature of RegEx is the ability to use ranges, for instance if you want to find every number in your string, rather than writing `/[0123456789]`, you could simply write `[0-9]`, and it would return the same results.

Now you're probably thinking...'okay I know how to write RegEx but how do I incorporate that into Ruby?' Well I got you. There are a few Ruby methods that you can pass your RegEx to and they'll return some different results. First- scan. It will return an array of all items in your string that match a given RegEx. See the example below:

```
"Duchess is the cutest dog ever".scan(/[aeiou]/)
=> ["u", "e", "i", "e", "u", "e", "o", "e", "e"]
```
Next is match. It will return the first item in your string that matches the RegEx as a MatchData object. Using Duchess as an example again:

```
"Duchess is the cutest dog ever".match(/\w+est/)
=> #<MatchData "cutest"> 
```
A fantastic resource for figuring out more RegEx syntax is [Rubular](https://rubular.com/). I know I haven't gone too crazy in depth into this crash course on RegEx, but I hope I've given you enough of a push in the right direction to use this in your own code. Or at least the resources to find out more information and ways to find new patterns. Happy coding!
React Markdown + MUI v5 (Material-UI)
Tags: react, markdown, mui, package
Published: 2022-01-26 14:20:33

## Table of Contents
- [About this post](#about)
- [Using Markdown in your project](#markdown)
- [About "mui-markdown" package](#mui-markdown)
- [Some of "mui-markdown" features](#features)
- [Package usage](#usage)
- [Documentations](#docs)

## <a name='about'></a> About This Post
Are you going to use markdown in your React web app? In this post, I want to introduce my new package to you. That will help you to render the markdown fast and nicely. 

## <a name='markdown'></a> Using Markdown in your project
As you know, with MD or MDX you can write rich formatted content real quick, and it's pretty readable even before you convert it to HTML. There are also some other benefits that you can read about them as well. 
So, if we are all in the same boat, chances are that like me, you need to use markdown in almost every single project. Even though you can find some npm or yarn packages that help you to render markdown as you wish, almost every time you need to configure that or write some extra CSS to gain the style you want.

## <a name='mui-markdown'></a> About "mui-markdown" package
["mui-markdown"](https://github.com/HPouyanmehr/mui-markdown) uses ["markdown-to-jsx"](https://github.com/probablyup/markdown-to-jsx) and ["mui"](https://github.com/mui-org/material-ui). I found these two working together really simple and nice. This package will be great for you if you use MUI (Formerly Material-UI). Also it is really lightweight, just 11.70Kb (Unpacked size is 87.1Kb).

## <a name='features'></a> Some of "mui-markdown" features

- Code highlight and language detect
- Inline code highlight
- Blockquote component
- MUI button component support
- Nice Links
- Flexible and Overridable

## <a name='usage'></a> Package usage

The package is available on npm and yarn.

To install it, simply run:

```bash
# with npm
npm i mui-markdown

# with yarn
yarn add mui-markdown
```

Then pass the markdown as children:

```jsx
import React from 'react';
import MuiMarkdown from 'mui-markdown';

import md from './myMarkdown.md';

const App = () => {
  return(
      <MuiMarkdown>{md}</MuiMarkdown>;
  )
};

export default App;
```

## <a name='docs'></a> Docs
To get more familiar with this package you can read the documentation on [GitHub](https://github.com/HPouyanmehr/mui-markdown) or [NPM](https://www.npmjs.com/package/mui-markdown).


---


Hi! I'm [**Hosein Pouyanmehr**](https://hpouyanmehr.com). I enjoy sharing what I learn and what I find interesting. Let's connect on [LinkedIn](https://www.linkedin.com/in/hpouyanmehr/).

See my code interests on [GitHub](https://github.com/HPouyanmehr).
Elixir :: Aninhando funções com operador pipe ( |> )
Tags: elixir, programming, beginners, tutorial
Published: 2022-01-26 14:06:43

Algumas vezes nosso código pode ficar muito confuso, principalmente quando precisamos encadear várias funções. Imagine ler um código com funções aninhadas como o exemplo abaixo:

```elixir
my_function(get_result_from(foo(new_function(other_function()))))
```

Aqui, nós estamos passando o valor **`other_function/0`** para **`new_function/1`**, e **`new_function/1`** para **`foo/1`**, **`foo/1`** para **`get_result_from/1`**, e finalmente o resultado de **`get_result_from/1`** para **`my_functoin/1`**. 

Elixir possui um modo pragmático que melhora o entendimento do código quando temos chamadas como esta, com a utilização do operador pipe. O operador pipe **`|>`**, *recebe o resultado de uma expressão e passa ele adiante*. Assim, poderiamos reescrever o código acima da seguinte maneira:

```elixir
other_function() |> new_function() |> foo() |> get_result_from() |> my_function()
```

Se você possui alguma familiaridade com shell script, o pipe do Elixir é exatamente como do shell, ou seja o valor retornado da esqueda é passado para a função da direita. 

Alguns exemplos de utilização do pipe

Posso fazer split de uma string simplesmente assim:

```elixir
iex> "Daniel Soro" |> String.split()
["Daniel", "Soro"]
```

Posso transformar uma string em caixa alta e fazer split simplesmente assim:

```elixir
iex> "Daniel Soro" |> String.upcase() |> String.split()
["DANIEL", "SORO"]
```

Com o pipe, podemos produzir código mais legívies e elegante, um operador muito legal em Elixir para deixar nosso código sinteticamente mais elegante e fácil de entender!
Spree Commerce 4.4 is here! 🚀🚀🚀
Tags: spreecommerce, ecommerce, webhooks, headlesscommerce
Published: 2022-01-26 14:05:20

This is the biggest #OpenSource release in a long time filled with new features & integrations!💪

Spree is now even more composable and customizable!

🎁 Lots of new goodies #DigitalProducts #Wishlists #Webhooks #MetaData #PlatformAPI

More info: [https://spreecommerce.org/spree-commerce-4-4-is-even-more-composable-and-customizable ](https://spreecommerce.org/spree-commerce-4-4-is-even-more-composable-and-customizable )
[JS] JavaScript Scope: Global, Local and Block Scopes
Tags: javascript, webdev, beginners
Published: 2022-01-26 14:00:37

_Scope_ is a concept that refers to where values and functions can be accessed.

Various scopes include:

* _Global_ scope \(a value/function in the global scope can be used anywhere in the entire program\)
* _File_ or _module_ scope \(the value/function can only be accessed from within the file\)
* _Function_ scope \(only visible within the function\),
* _Code block_ scope \(only visible within a `{ ... }` block\)

***

## Global Variables

```javascript
// Variable declared globally
const color = 'blue';
function printColor() {
  console.log(color);
}
printColor(); // Prints: blue
```

JavaScript variables that are declared outside of blocks or functions can exist in the _global scope_, which means they are accessible throughout a program. Variables declared outside of smaller block or function scopes are accessible inside those smaller scopes.

**Note:** It is best practice to keep global variables to a minimum.

***

## Block Scoped Variables

```javascript
const isLoggedIn = true;
if (isLoggedIn == true) {
  const statusMessage = 'User is logged in.';
}
console.log(statusMessage);
// Uncaught ReferenceError: statusMessage is not defined
```

 `const` and `let` are _block scoped_ variables, meaning they are only accessible in their block or nested blocks. In the given code block, trying to print the `statusMessage` using the `console.log()` method will result in a `ReferenceError`. It is accessible only inside that `if` block.

Block scope is a powerful tool in JavaScript, since it allows us to define variables with precision, and not pollute the global namespace. If a variable does not need to exist outside a block— it shouldn’t!

***

## Scope Pollution

 _Scope pollution_ is when we have too many global variables that exist in the global namespace, or when we reuse variables across different scopes. Scope pollution makes it difficult to keep track of our different variables and sets us up for potential accidents.

```javascript
let num = 50;
const logNum = () => {
  num = 100; // Take note of this line of code
  console.log(num);
};
logNum(); // Prints 100
console.log(num); // Prints 100
```

 Even though the reassignment is allowed and we won’t get an error, if we decided to use `num` later, we’ll unknowingly use the new value of `num`.
Show page no. in UI in Cursor pagination or infinite scroll
Tags: javascript, stripe, infinitescroll, php
Published: 2022-01-26 13:57:47

![On scroll page number are added](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/11uldy1dkrttvuaf9y4w.png)
I wanted to show stripe subscriptions details to my admin.

Stripe uses cursor based pagination. So no page available.

Load more was nice but i wanted an "on scroll  add a page number(scroll 1,scroll 2)"

So admin can check how many scroll happened,and easliy switch between scroll 1 and scroll 2 or more, 

also filter via customer id and plan type(I used per unit and tiered plan)

Here's a codepen of how the UI looks: [Link]
(https://codepen.io/sahil-kashyap/full/GRMbdvB)

Here's gist of how i used with stripe subscription pagination php laravel: [Gist](https://gist.github.com/sahilkashyap64/cfc3fbd6df7584b1c2a84d66f3c6ef49)
CSS variables: What are they and how to use them
Tags: css, webdev, codenewbie, beginners
Published: 2022-01-26 13:55:09

## What are they

CSS custom properties aka CSS variables allow you to define a property in a variable that you can use over and over again. There are a number of use cases for this: often you will use the same colors for a brand or a particular theme. The big benefit of using variables for commonly used properties is that if you need to change it further down the line you can simply change the variable. This will save you from having to find everywhere in your code that you used that property.


## How to use them

### Apply the variable to an element

You first need to declare what element it should be applied to. You can apply it to any element but it is common to apply it to the root element so it can be used anywhere in your CSS (global scope). Use the `:element {}` syntax to select the element. You can choose any name for your variables but they are case sensitive. 

```
:root {
  --bg-color: #4B6CDB;
  --text-color: #fff;
}
```

### Calling the variable

You can call the variable by using `var()`.  Instead of putting in the property name call the variable name inside the var function 

```
.myClass {
  background-color: var(--bg-color)
  color: var(--text-color)
}
```
Javascript map() function
Tags: javascript, 100daysofjs
Published: 2022-01-26 13:52:53

---
title: Javascript map() function
published: true
description: Functional JavaScript with map and lodash
tags: ["Javascript","100daysofjs"]
//cover_image: https://direct_url_to_image.jpg
---
Map merupakan sebuah fungsi yang dapat anda gunakan pada Javascript untuk membuat array baru melalui kondisi tertentu dengan inputan data yang berasal dari array yang akan dimanipulasi, kode akan terlihat lebih clean daripada menggunakan *for-loop*.

Berikut contoh kode yang buruk
```js
const students = ["Bob", "Alice", "Robert"];
const greetStudents = [];

for (let i = 0; i < students.length; i++) {
  greetStudents.push(`Hello, ${students[i]}!`);
}

console.log(greetStudents);
```
Output:
`[ 'Hello, Bob!', 'Hello, Alice!', 'Hello, Robert!' ]`

Berikut contoh kode yang clean
```js
const students = ["Bob", "Alice", "Robert"];
const greetStudents = students.map((student) => `Hello, ${student}!`);

console.log(greetStudents);
```
Output:
`[ 'Hello, Bob!', 'Hello, Alice!', 'Hello, Robert!' ]`

Contoh kode yang lain jika mengunakan lodash
```js
const _ = require("lodash");

const students = ["Bob", "Alice", "Robert"];
const greet = (student) => `Hello, ${student}!`;
const greetStudents = _.map(students, greet);

console.log(greetStudents);
```
Output:
`[ 'Hello, Bob!', 'Hello, Alice!', 'Hello, Robert!' ]`

Terlihat apabila anda menggunakan lodash, kode akan lebih mudah dibaca dan lebih terstruktur, karena bisa menghemat baris kode, agar tidak terlau panjang.

Referensi:
[Lodash - map](https://lodash.com/docs/4.17.15#map)
Extendible React Components
Tags: react, javascript, beginners, webdev
Published: 2022-01-26 13:40:11

Here's a nice React tip for you.

When creating components using TypeScript (please use TS), always extend the props type with a 
React.HTMLAttributes<HTMLDivElement>
(you can replace the DivElement with any other element you are returning from your JSX).

That will allow you to have all the properties for that component correctly typed, and you can pass them to the JSX element you are returning.

A handy use case is where we want to create a component with specific styles but make it extendible so that other consumers that install that component in their app will be able to override the styles we defined with their own styles.

According to the CSS specificity rules, for their styles to apply, you have to pass their className as the last one in order (since they are both using the class selector, the latest styles that appear are those who apply).

In the following snippet, you'll notice how we pass the className attribute we destruct from props and use the classNames library to join them nicely:

```
import React, { ReactNode } from "react";
import { Link } from "@teambit/base-react.navigation.link";
import { Arrow } from "./arrow";
import styles from "./styles.module.scss";
import classNames from "classnames";

export type BackButtonProps = {} & React.HtmlHTMLAttributes<HTMLDivElement>;

export function BackButton({ className, ...rest }: BackButtonProps) {
  return (
    <div
      {...rest}
      className={classNames(styles.backButtonContainer, className)}
    >
      <Link href="/blog">
        <Arrow />
        <span className={styles.backButtonText}>Back to Blog</span>
      </Link>
    </div>
  );
}
```

As we said, it will allow users to pass their own styles, and if there are any conflicting styles, the consumers' classes will override the default styles.

Always think about who is going to consume your component. You will probably be the first one consuming it, but you never know who else will come after you and install your component—extendible Components FTW.

---

- For more posts like this [follow me on LinkedIn](https://www.linkedin.com/in/nitsan-cohen/)

- I work as frontend & content developer for [Bit](bit.dev) - a toolchain for component-driven development (Forget monolithic apps and distribute to component-driven software).
Vote for backend framework according to your experince 
Tags: backend, laravel, node, webdev
Published: 2022-01-26 13:16:43

Hello Developers!

I'm a Frontend developer **(Vue, Nuxt)**
I wanna to learn server side framework 
I saw many developers said **Laravel** is the most productive Framework but I'm not famillier with **PHP** so I need your advice which framework better this days for productivity and job hiring.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/feu98lz6ganrsso2nm38.jpg)

1- **Laravel**
or 
2- **NodeJS framework** such as (NestJS or AdonisJS)

Thanks a lot
UFO Coin Is Starting
Tags: programming, crypto, cryptocurrency, javascript
Published: 2022-01-26 13:01:15

Ufo Coin is a new digital money system made by me. 1 ufocoin/uc$ = 0.5$. It's still in development. I also made a small team for this project. 6/7 people currently now in the team. These are the Jobs currently available:

Video Editor (25 $uc per day)
Interview Team (16 $uc per day)
Mail Responding Team (15 $uc per day)
Programmer (Frontend Dev - 30 $uc per day, Backend Dev - 35 $uc per day.)

If you want any job, please contact: ufocoinshelp@gmail.com

We will make a new post if it's published

Our logo-


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9zotrmbbqnusnbbxfj3.png)
First Post
Tags: azure, cloud, architecture, books
Published: 2022-01-26 13:00:26

Hello everybody, my name is Pedro, I'm a 20 years old Brazilian IT Architect on my way to becoming a cloud engineer.

Overall I will post cloud and system's architecture related things and I'll try to make it very simple for everyone to understand.

I would appreciate any pieces of advice from more experienced people (and from those who aren't at all) and I'll always be open to talk about cloud and other stuff.

You can connect with me on LinkedIn on this link: https://www.linkedin.com/in/pedro-ign%C3%A1cio-a97831182

I'll be writing here in the next couple of days. I'm preparing to take the AZ-104 exam on February's 19th and I would really like to share with you my experiences.

I just started reading the Cloud Architecture Patterns (O'Reilly's book) and I'll be sharing chapter by chapter the thing I've learned.

Stay safe everyone. I'll see you soon!
How does broadcast work in Laravel?
Tags: broadcast, laravel, notifications, chat
Published: 2022-01-26 11:16:38

Web sockets implement real-time, live-updating user interfaces. It provides a more robust, efficient alternative to continually polling your application for changes.

## Configuration:-
You can change all configurations inside the config/broadcasting.php file pusher channels, Redis, and log drivers supported on laravel. You would use a null driver for disabling broadcasting.

You will first need to register the broadcasting of any events in App\Providers\BroadcasrServiceProvider. Laravel echo needs to access the current session's CSRF token. You must add a meta tag in a head HTML element.

```<meta name="csrf-token" content="{{ csrf_token() }}">```

## Concept Overview:-
You are allowed to broadcast your server-side laravel events to your client-side javascript application. It sent events over channels that may specify a public or private channel. Users can subscribe to a public channel without any authentication or authorization. You can subscribe private channel if you authenticate.

### The ShouldBroadcast Interface:
Suppose users view their order status. We don't want them to reload the whole page instead of updating the status. We should create a new event that implements the ShouldBroadcast interface. Look at the below code. We have made the ShippingStatusUpdated event. You should define a broadcastOn method for broadcasts events on a particular channel.

```
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

class ShippingStatusUpdated implements ShouldBroadcast
{
    /**
     * Information about the shipping status update.
     *
     * @var string
     */
    public $update;

    /**
     * Get the channels the event should broadcast.
     *
     * @return \Illuminate\Broadcasting\PrivateChannel
     */
    public function broadcastOn()
    {
       return new PrivateChannel('order.'.$this->update->order_id);
    }
}
```

For private channels, users must authorize. You may define your channel rules in the routes/channels.php file. Following the line of code, we verify the user and order creator to show order status.

[Read Article](https://www.devrohit.com/broadcast-in-laravel/)
106. Construct Binary Tree from Inorder and Postorder Traversal
Tags: 100daysofcode, java, programming, algorithms
Published: 2022-01-26 12:50:01

# Description

Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return *the binary tree*.

## Example 1:


```
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
```

## Example 2:

```
Input: inorder = [-1], postorder = [-1]
Output: [-1]
```

## Constraints:

- `1 <= inorder.length <= 3000`
- `postorder.length == inorder.length`
- `3000 <= inorder[i], postorder[i] <= 3000`
- `inorder` and `postorder` consist of **unique** values.
- Each value of `postorder` also appears in `inorder`.
- `inorder` is **guaranteed** to be the inorder traversal of the tree.
- `postorder` is **guaranteed** to be the postorder traversal of the tree.

---

# Solutions

## Solution 1

### Intuition

### Code

```java
class Solution {
    // inorder 9,3,15,20,7
    // postorder 9,15,7,20,3
    // 1. get 3 from postorder
    // 2. find 3 in inorder, and then split inorder to two parts
    // 3. recursion 1, 2 in different part
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int m = inorder.length, n = postorder.length;
        if (m != n) {
            return null;
        }
        Stack<Integer> stack = new Stack<>();
        for (int val : postorder) {
            stack.push(val);
        }

        TreeNode root = helper(0, n - 1, stack, inorder);
        return root;
    }

    private TreeNode helper(
        int start, int end, Stack<Integer> stack, int[] inorder) {
        if (start > end || stack.isEmpty()) {
            return null;
        }
        TreeNode node = new TreeNode(stack.pop());

        // find root in inorder
        int index = start;
        for (int i = start; i <= end; i++) {
            if (inorder[i] == node.val) {
                index = i;
								break;
            }
        }

        node.right = helper(index + 1, end, stack, inorder);
        node.left = helper(start, index - 1, stack, inorder);

        return node;
    }
}
```

### Complexity

- Time: O(nlogn)
- Space: O(n)

---

## Solution 2

### Intuition

### Code

```java

```

### Complexity

- Time:
- Space:

---

# Similar Questions