teleren/devto huggingface dataset:
How to setup Gulp with ES6
Tags: javascript, beginners, taskrunner, gulp
Published: 2022-08-14 10:46:00

[Gulp](https://gulpjs.com/) is a tool that runs on [Node.js](https://nodejs.org/en/) which helps us automate many development tasks, we can use it for automating slow and repetitive work.

## How Gulp works
Gulp reads files as streams and pipes those streams to different tasks. These tasks are code-based and use plugins in order to build production files from source files.

## Prerequisites
[Node.js](https://nodejs.org/en/download/)
[npm](https://www.npmjs.com/)

## How to install Gulp

### Install the gulp command line

```
npm install --global gulp-cli
```

### Create a new project directory and navigate into it

```
npx mkdirp my-project
```

```
cd my-project
```

### Create a package.json file

```
npm init
```

### Install the gulp in your devDependencies

```
npm install --save-dev gulp
```

### Transpilation
we have to rename our gulpfile extention `gulpfile.js` to `gulpfile.babel.js` for Babel transpilation and have to install the [@babel/register module](https://www.npmjs.com/package/@babel/register).

### How To Create Tasks in Gulp
Gulp gives two composition methods `series()` and `parallel()` ,Both Methods takes n numbers of task functions or composed operations. this two methods can be nested within themselves or each other to any depth.

#### Tasks in series() method
`series()` method is used when you we have to run tasks in order.

##### Example

```
import { series } from "gulp";
const funA = (cd) =>{
cb();
}
const funB = (cd) =>{
cb();
}
export default series(funA ,funB)
```
#### Tasks in parallel() method
`parallel()` method is used when you we have to run tasks in concurrency.

##### Example

```
import { parallel } from "gulp";
const javascript = (cd) =>{
cb();
}
const css = (cd) =>{
cb();
}
export default parallel(javascript ,css)
```
Did You Know JSON.stringify() Eat This Specific Value
Tags: javascript, webdev, tutorial, programming
Published: 2022-08-14 10:17:00

Hi there,
Have you ever encountered a situation when trying to convert an object containing a function as a value to a string using JSON.stringify()? and noticed by printing the resultant value that the key containing the function value is gone along with its key? 

Well, that is because JSON.stringify() marks it null. It can not convert a function value to a string, thus keeping it null. Now your whole object is changed. Here is an **example** if you don't know how to include it or convert it back to function.

```javascript
const obj = {
  author: "Fahim Zada",
  love: "0's and 1's",
  eat: () => console.log("Red Apple")
}

console.log(JSON.stringify(obj)) 
//"{'author':'Fahim Zada','love':'0's and 1's'}"
//Let us try to fix it by converting that key to string
obj.eat = obj.eat.toString()
console.log(JSON.stringify(obj))
//"{'author':'Fahim Zada','love':'0's and 1's','eat':'() => console.log(\'Red Apple\')'}"

//Converting back to js object 
const stringify = JSON.stringify(obj)
const convert = JSON.parse(stringify)
//Now you can access primitive values as normal
console.log(convert.author) 
//"Fahim Zada"
//For our function, we will do this with "new" keyword or without
//Invoking the function with ()
//Will return our function and now we can call it
const myFunc = new Function("return " + convert.eat)()
console.log(myFunc())
```

Thanks for reading.
JavaScript function initialization Shortcut
Tags: javascript, beginners, programming
Published: 2022-08-14 09:52:00

An arrow followed by a greater than key could be used as a shortcut of initializing a function in JavaScript. Wow I tried and it worked check the image above and try it for yourself.

```
//function
function playMusic (music){
  console.log( "I love Playing "+ music);
}
playMusic("Jazz");


//function shortcut
const playMusic1 = music1 =>console.log( "I Love playing " +music1);
playMusic1("Jazz")
```

![JavaScript function initialization shortcut](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/77t1j53nld31fo1zicxu.png)
Rabin-Karp in JavaScript
Tags: javascript
Published: 2022-08-14 09:51:00

## Check if two string are same:
```JS
const areStringEqual = function (firstString, secondString) {
  if (firstString !== secondString) {
    return false;
  }
  for (let i = 0; i < firstString.length; i++) {
    if (firstString[i] !== secondString[i]) {
      return false;
    }
  }
  return true;
};
```

## Hash creating logic
```js

const calculateHash = function (myText, largePrime, randomNumber) {
  let hash = 0;
  for (let i = 0; i <= myText.length - 1; i++) {
    hash = (hash * randomNumber + myText.charCodeAt(i)) % largePrime;
  }
  return hash;
};
```

## Search Text using Functions 
```js
const searchText = function (sentence, stringToSearch) {
  let largePrime = 337;
  let randomNumber = 50;
  let stringPositions = [];
  let stringToSearchHash = calculateHash(
    stringToSearch,
    largePrime,
    randomNumber
  );
  let text;
  let sentenceHash;
  // Loop through our sentence
  for (let i = 0; i <= sentence.length - stringToSearch.length; i++) {
    text = sentence.slice(i, i + stringToSearch.length);
    sentenceHash = calculateHash(text, largePrime, randomNumber);
// If the hash is not same, then continue to next step
    if (stringToSearchHash !== sentenceHash) continue;


    if (areStringEqual(text, stringToSearch)) {
      stringPositions.push({ position: i });
    }
    
  }
  return stringPositions;
};
```
The Palindromic Prime Cyclops Algorithm
Tags: perl, python, theweeklychallenge
Published: 2022-08-14 09:37:12

## Weekly Challenge 177

[Challenge](https://theweeklychallenge.org/blog/perl-weekly-challenge-177/), [My solution](https://github.com/manwar/perlweeklychallenge-club/tree/master/challenge-177/sgreen)

## Task 1: Damm Algorithm

### Task

You are given a positive number, `$n`.

Write a script to validate the given number against the included [check digit](https://en.wikipedia.org/wiki/Damm_algorithm).

### My solution

Thanks to the Wikipedia link provided, this proved a pretty straight forward task. Starting with 0, change the row that corresponds with the value of that digit in the current row. Repeat until we have processed all digits. If the last row is 0, it's validated. If it is something else, you've got dodgy data.

### Examples

```bash
$ ./ch-1.py 5724
1

$ ./ch-1.py 5727
0
```

## Task 2: Palindromic Prime Cyclops

### Task

Write a script to generate first 20 Palindromic Prime Cyclops Numbers.

A cyclops number is a number with an odd number of digits that has a zero in the center only.

### My solution

Rather than checking if number is a palindrome with only a 0 in the center, I generate the left side of the number, and then add a zero and the number reversed. This is easier and quicker IMO. YMMV

Then I need to check that the number does not contain any other zeros, and if it is prime.

I then wrap this in a loop that increments the number by one, and continues until we find 20 solution. Finally, I print out the results.

### Examples

```bash
$ ./ch-2.py 
101, 16061, 31013, 35053, 38083, 73037, 74047, 91019, 94049, 1120211, 1150511, 1160611, 1180811, 1190911, 1250521, 1280821, 1360631, 1390931, 1490941, 1520251

$ ./ch-2.pl 
101, 16061, 31013, 35053, 38083, 73037, 74047, 91019, 94049, 1120211, 1150511, 1160611, 1180811, 1190911, 1250521, 1280821, 1360631, 1390931, 1490941, 1520251
```
Mean value calculator
Tags: javascript, webdev, programming, tutorial
Published: 2022-08-14 09:12:16

This is the mean value calculator program of table mean values using formula like (you can give the xi and fi values) and it will calculate the overall mean values by using simple formula (sigma fixi / sigma fi). This is the advance version of mean calculator.you can calculate or find any mean here. Thanks for reading this and using this program.....😇 
.
.
🔗Link of the code - [(https://replit.com/@YuvrajSingh133/Advance-mean-value-calculator)]
why i can not get {children} from props
Tags: react, typescript
Published: 2022-08-14 09:04:04


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xg15i9xkc01yn90zq4i6.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hpcmptzq5gsf3bez4m3o.jpg)
LEARN NEW-AGE DIGITAL MARKETING
Tags: digital, webinar, beginners, productivity
Published: 2022-08-14 08:58:21

Digi Marketers Academy- Webinar
Australia’s #1 Digital Marketing Agency is bringing to you an innovative take on learning new-age Digital Marketing in this one-of-a-kind webinar.
Price: Free
Date: August 17, 2022
Time:6 PM IST
Want to Attend the Webinar for Free?
Grab Your FREE Spot Now
Limited FREE Seats Available*
https://www.digimarketersacademy.com/courses/webinar
Left Most Repeating Character
Tags: javascript, leetcode
Published: 2022-08-14 07:43:42

```
var leftMostRepeatingCharacter = function (s) {
  let map = {};
  for (let i = 0; i < s.length; i++) {
    map[s[i]] = (map[s[i]] || 0) + 1;
  }
  if (Object.keys(map).length > 0) {
    for (let val in map) {
      console.log(val);
      if (map[val] > 1) {
        console.log(val);
        return val;
      }
    }
  }
};

console.log(leftMostRepeatingCharacter("ahbhagdc"));
```
DART FUNCTIONS YOU NEED TO KNOW.
Tags: dart, flutter, programming, beginners
Published: 2022-08-14 07:38:54

Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task.

## 🌟ForEach( ):
**Iterate through entire elements in the list.**

Use it when you need to scan all the elements and certain actions over individual elements.

```
List<String> perfumeBrand =
[ "claira", "Blue wales", "Vagas" ];
perfumeBrand.forEach((brand) => print(brand));

//Output
claira
Blue wales
Vagas
```

------------------------------

## 🌟Sort( ):
**Sort the elements in the list.**

Use it with the combination of the reversed() method to filter data in the list.

```
List<int> nums = [ 1-, 6, 8 ];
nums.sort( );

//Output ==> [-1, 6, 8]

**************************************************************

List<String> number = [ "Four", "Six", "Two" ];
number.sort((x, y) => x.length.compareTo(y.length));

//Output ==> [Two, Four, Six]
```

----------------------------------

## 🌟Skip( ):
**Skips defined items from any List.**

Use it when you need to remove any blacklisted element from an array of items (from your list).

```
int elementToSkip = 3;
List<int> elements = [1,2,3,4,5,6,];
List<int> skippedList = elements.skip(elementToSkip).toList();

//Output ==> [1,2,4,5,6,]
```

-------------------------------------

## 🌟ToSet( ):

**Removes duplicates and iterates with the same items.**

Use it when don’t need users having the same email address or if you need to add unique elements.

```
List<int> nums = [1,1,4,5,4,];
nums.toSet( ).toList( ).sort( );

//OUTPUT ==> [1,4,5]
```

---------------------------------

## 🌟Any( ):
Scans the elements in the list & produces boolean output depending on the provided condition.

```
List<String> perfumeBrand =
[ "claira", "Blue wales", "Vagas" ];
perfumeBrands.any(brand) => brand.startsWith("B"));

//Output ==> TRUE

perfumeBrands.any(brand) => brand.startsWith("ht"));

//Output ==> TRUE
```

-------------------------------

## 🌟Shuffle( ):
**Arranges elements in a random order/ sequence.**

```
List<int> nums = [2,4,6,8,10];
nums.shuffle( );

//Output ==> [10,2,6.4.8]
```
External JavaScript
Tags: javascript, webdev, beginners, tutorial
Published: 2022-08-14 06:59:07

# External JavaScript file
We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in several html pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript files into a single file. It increases the speed of the webpage.

Let's create an external JavaScript file that prints 'Hello JavaScript' in a alert dialog box.

## message.js

```
function msg(){  
 alert("Hello JavaScript");  
}  
```
Let's include the JavaScript file into html page. It calls the JavaScript function on button click.

## index.html

```
<html>  
<head>  
<script type="text/javascript" src="message.js"></script>  
</head>  
<body>  
<p>Welcome to JavaScript</p>  
<form>  
<input type="button" value="click" onclick="msg()"/>  
</form>  
</body>  
</html> 
```

# Advantages of External JavaScript

There will be following benefits if a user creates an external JavaScript:

- It helps in the reusability of code in more than one HTML file.
- It allows easy code readability.
- It is time-efficient as web browsers cache the external js files, which further reduces the page loading time.
- It enables both web designers and coders to work with html and js files parallelly and separately, i.e., without facing any code conflictions.
- The length of the code reduces as only we need to specify the location of the Js file.

# Disadvantages Of Using External JavaScript
There are the following disadvantages of external files:

- The stealer may download the coder's code using the url of the js file.
- If two js files are dependent on one another, then a failure in one file may affect the execution of the other dependent file.
- The web browser needs to make an additional http request to get the js code.
- A tiny to a large change in the js code may cause unexpected results in all its dependent files.
- We need to check each file that depends on the commonly created external javascript file.
- If it is a few lines of code, then better to implement the internal javascript code.

**## [Source Code](https://github.com/kavya-rgb/JavaScript-Learning)
**
How To Make compose() and pipe() In Javascript
Tags: javascript, webdev, programming, tutorial
Published: 2022-08-14 06:56:19

Hi there,
The most encountered situation while building a complex functionality is where we need to pass a value to the function, and the return (result) value is required input for another function . It might sound okay if you have 2 - 3 **functions**, but when you have more than that, your code becomes messy and non-readable. To solve this issue, here comes the **function composition**.

It is a mechanism for combining functions, in which the output of each function is passed into the next one, and the output of the last function is the final result. Applicable to every programming language, not just JavaScript.

We can do it in two different ways. However, one thing to keep in mind is that the sequence matter, and it will change your **final** result.

## Compose

Passing your functions in the right to left order for execution. Example (f4,f3,f2,f1 )

```javascript
//Compose function using reduceRight()
const compose = (...args) => (value) => args.reduceRight((prev, fn) => fn(prev), value);
// Increment the passed value by 2
const increment = (n) => n + 2;
// Triples the passed value
const double = (n) => n * 3;
//Divide it by 2
const divide = (n) => n / 2;
// Using our composition function
console.log(compose(divide, double, increment)(2));  // 6
```

## Pipe

Passing your functions in the left to right order for execution. Example (f1,f2,f3,f4 )

```javascript
//pipe function using reduce(), default left to right execution
const pipe = (...args) => (value) => args.reduce((prev, fn) => fn(prev), value);
// Increment the passed value by 2
const increment = (n) => n + 2;
// Triples the passed value
const double = (n) => n * 3;
//Divide it by 2
const divide = (n) => n / 2;
// Using our pipe function
console.log(pipe(increment, double, divide)(3));  // 7.5
```

**Tip**: As already mentioned, the sequence matters, so you can create only a compose function and use it as a pipe by passing your functions in left to right order.

Thanks for reading.
[Algorithms] 11 - Dynamic Programming
Published: 2022-08-07 00:44:33

Dynamic Programming is hard. But there are some ways that let us approach the problem more smoothly.

## 1. Identify if the problem needs Dynamic Programming

It is very important to find out whether the problem needs Dynamic Programming or not. Following cases normally requires Dynamic Programming.

- When you need to try every single case to find the result.
- When you need to find the possible smallest, biggest, longest, or shortest ... etc case (optimization problems).

Following list is from Neetcode's 5 Dynamic Programming Patterns [Link](https://www.youtube.com/watch?v=mBNrRy2_hVs):

#### 1. Fibonacci

  - When you need previous results to calculate the current result.
  - Normally can be solved by updating two values recursively.


#### 2. Zero/one knapsack

  - Visualizing the problem as a n-ary tree can be helpful.
  - Two possible cases: whether we take it or not.
  = Therefore, we do not need to consider some other cases.

#### 3. Unbounded knapsack

  - Visualizing the problem as a grid(like a chessboard) can help be helpful.
  - Hash map is used.
  - Need to consider every case to come up with the last answer.


#### 4. Longest Common Subsequence
#### 5. Palindromes


## 2. Figure out the subproblems

This is the most important step of the Dynamic Programming. Finding the subproblems and proving recursively solving those subproblems will lead to the answer are very hard. To shape the subproblems, we need to read the problem very thoroughly. 

It is good to start from finding how many possible choices that each recursive step has. (e.g. The robot can go either left or bottom. There are only two options for each step.)Also, visualizing the solution as tree graph can help this step. 

If there are too many options for each step, (e.g. Queen can move to any grid that is diagonal or adjacent. There are so many possibilities) we need to consider memoization.

## 3. Practice memoization

Most of the Dynamic Programming questions require to use memoization since the computation tend to have exponential time complexity. It is good to learn how to use 2D arrays, maps or sets.
Ring progress bar
Published: 2022-08-14 06:37:40


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

```html
<RingProgressBar :progress="progress" :rotate-angle="-90"/>
<input type="number" v-model="progress" step="10" min="0" max="100">
```

```html
<script setup lang="ts">
import { computed } from 'vue';

interface Props {
  progress: number; // 0 ~ 100
  size?: number;
  rotateAngle?: number; // start angle 0 ~ 360
  strokeWidth?: number;
  bgStrokeColor?: string;
  strokeColor?: string;
}

const props = withDefaults(defineProps<Props>(), {
  size: 100,
  rotateAngle: 0,
  bgStrokeColor: '#EAEFF4',
  strokeColor: '#ffaa00',
  strokeWidth: 8

})

const r = 43
const perimeter = r * 2 * Math.PI
const dashoffset = computed(() => {
  let progress = props.progress
  if(progress > 100) progress = 100
  if(progress < 0) progress = 0
  return perimeter * (1- progress/100)
})
</script>

<template>
  <svg :width="size" :height="size" :style="{'color': strokeColor}" viewBox="-50 -50 100 100">
    <circle cx="0" cy="0" :r="r" :stroke-width="strokeWidth" fill="none" :stroke="bgStrokeColor" />
    <circle cx="0" cy="0" :r="r" :stroke-width="strokeWidth" fill="none" stroke="currentColor"
      :stroke-dashoffset="dashoffset"
      :stroke-dasharray="`${perimeter}, ${perimeter}`"
      stroke-linecap='round'
      :transform="`rotate(${rotateAngle})`"
    />
  </svg>
</template>

<style scoped>
</style>

```
Como puedo centrar un < div > ...?
Tags: webdev, beginners, spanish, tutorial
Published: 2022-08-14 06:30:00




# Vamos a centrar un div 
En esta entrada te muestro tres métodos diferentes para centrar el contenido de un div like a pro 


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


Los métodos para centrar < div > son:

 1. position: absolute;
 2. display: flex;
 3. display: grid;

 

 

---


# Position: absolute..?
La propiedad 'position' de CSS especifica la manera en que un elemento es posicionado en el DOM. Las propiedades que tenemos disponibles son: 

> top, right, bottom, left

Estas propiedades establecen la position final de los elementos. Existen varios tipos de position, los mas comunes son.


> static, relative, absolute, sticky


## Centrar < div > con position: absolute;
```
    div{
	    position: absolute;
	    top: 50%;
	    left: 50%;
	    transform: translate(-50, -50);
	    }
```

---
 
# Display: flex...?

Desde el inicio, display flex es parte de FlexBox, es un set de propiedad 'nuevas' de HTML5, nos permite maquetar nuestros proyectos web de una manera mas sencilla e intuitiva (es mi propiedad favorita). FlexBox funciona como un elemento contenedor (flex container) que ordena y posiciona todos los elementos contenidos segun se le indique. 
 
## Centrar un < div > con display: flex;
```
    div{
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    }
```



---

# Display: grid...?

A mi manera de entender como funcionan las cosas puedo decir que grid y flex son iguales y tienen el mismo objetivo, pero funcionan de manera diferente. Las propiedades Grid también se crearon para HTML5 y funciona como una cuadricula. 

## Centrar un <div> con display: grid;

```
    div{
	    display: grid;
	    display: grid;  
	    justify-content: center;  
	    align-content: center;
	    }
```

o

```
div{
    display: grid;
    place-items: center;
    {
```
[Ruby][Sorbet] T::Struct == is an identity comparison, not an equivalence comparison
Tags: sorbet, ruby, rails
Published: 2022-08-21 04:18:34

---
title: [Ruby][Sorbet] T::Struct == is an identity comparison, not an equivalence comparison
published: true
date: 2022-08-14 06:22:17 UTC
tags: ["Sorbet", "Ruby", "Rails"]
canonical_url: https://note.hiko1129.com/posts/1660458137/
---

<a href="https://note-hiko1129-com.translate.goog/posts/1660458137/?_x_tr_sl=ja&_x_tr_tl=en&_x_tr_hl=ja&_x_tr_pto=wapp" target="_blank" rel=”noopener noreferrer”>Translate ja to en</a>

T::Structの==は、hashや通常のStructと異なり同値性ではなく同一性比較になっています。

```
class Hoge < T::Struct
  const :hoge, Integer
end

a = Hoge.new(hoge: 1)
b = Hoge.new(hoge: 1)

a == b # => false
a == a # => true
```

issue: https://github.com/sorbet/sorbet/issues/1540
同値性比較用のgem: https://github.com/bellroy/sorbet-struct-comparable