teleren/devto huggingface dataset:
Count Sorted Vowel Strings
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 15:00:41

Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._

A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet.

**Example 1:**

**Input:** n = 1
**Output:** 5
**Explanation:** The 5 sorted strings that consist of vowels only are `["a","e","i","o","u"].`

**Example 2:**

**Input:** n = 2
**Output:** 15
**Explanation:** The 15 sorted strings that consist of vowels only are
\["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"\].
Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.

**Example 3:**

**Input:** n = 33
**Output:** 66045

**Constraints:**

*   `1 <= n <= 50` 

**SOLUTION:**

    class Solution:
        def cvow(self, n):
            if n == 1:
                return [5, 4, 3, 2, 1]
            curr = self.cvow(n - 1)
            op = [curr[-1]]
            for i in range(3, -1, -1):
                op.append(op[-1] + curr[i])
            return op[::-1]
        
        def countVowelStrings(self, n: int) -> int:
            return self.cvow(n)[0]
Auto-Format Stylesheet On Save Using WebStorm with 3 Steps
Tags: webdev, jetbrains, linter, scss
Published: 2022-06-04 14:40:58

## Intro
Linter tools can help keep code clean and consistent, but can get annoying if the issues aren't caught until committing or pushing to remote repository. This article is to omit such pain by utilizing Stylelint.

![Linter complaining](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdmbvzxxfpt8z1hg9xoq.png)

The author used SCSS as the stylesheet format, but the same idea is also applicable with other formats like CSS.

## Setup
- Mac
- WebStorm
- SCSS

## 1. Download dependencies
If using npm:
```
npm i stylelint stylelint-config-standard-scss -D
```

If using yarn:

```
yarn add stylelint stylelint-config-standard-scss -D
```

## 2. .stylelintrc
Create `.stylelintrc.json` at the root of the project, and add below:
```
{
  "extends": "stylelint-config-standard-scss"
}
```

## 3. Setting
- Go into Webstorm > Preferences
- Under Tools > File Watchers:
  - Click `+` to create new
  - Select `SCSS`
  - Set up the configs as below:
![File Watcher configs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hkvkbkz1jmteezwfosz.png)

1. File type: SCSS style sheet
2. Scope: Project Files
3. Program: `/<PATH_TO_PROJECT>/node_modules/stylelint/bin/stylelint.js`
4. Arguments: `$FileName$ --fix`
5. Output paths to refresh: `$FileName$`
 

...and see the lint in action as you save your stylesheet 🎉🎉🎉
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dxwo5gpubjyc88w7ojc9.gif) 

## Resources
- Linter for stylesheet:
[stylelint
](https://stylelint.io/)

- The standard shareable SCSS config for Stylelint:
[stylelint-config-standard-scss](https://github.com/stylelint-scss/stylelint-config-standard-scss)
Glossary of Crypto - 10 Terms that you should know - Part 1
Tags: blockchain, ethereum, defi, bitcoin
Published: 2022-06-04 14:34:13

The word “crypto” is an umbrella term used to describe the industry as a whole but there may be some industry specific lingo that you’re not familiar with. This ongoing series will break down some of the other key terms used in this space.

### Blockchain
A distributed accounting system consisting of “blocks” of digital information. Blocks are created sequentially with the prior block being incorporated into the next, effectively “chaining” them together. 

### Decentralized
The opposite of centralized. The property of having a system structured in a way where there is no single point of control.

### Cryptocurrency
Digitally native currency using cryptographic technology that allows transactions to take place securely without an intermediary.

### Bitcoin
The first widely adopted cryptocurrency. A decentralized digital currency used for peer to peer transactions on the bitcoin blockchain. Invented by an unknown individual named Satoshi Nakamoto in 2008. 

### Ethereum
An open-sourced decentralized blockchain network with expanded functionality. Using smart contracts which allow for programmable cryptocurrencies. Developed in 2013 by Vitalik Buterin and Gavin Wood

### Wallet
A place where digital assets are stored, sent and received. Wallets can come in the form of a device or application.

### Altcoin
Bitcoin was the first iteration of cryptocurrencies but since then there have been 1000s of duplicates which have now been labeled as “altcoins” as in “alternative coins”.

### dApp
Decentralized applications(dApp) are blockchain native applications. Adding the functionality of blockchain systems to regular applications allows for security, transparency  and censorship resistance.

### NFT
Non-fungible token(NFT) A digital asset represented by a unique signature on the blockchain. Uses blockchain technology that allows for digital authenticity as well verification of ownership. Currently the most popular forms of NFTs are images, audio files and documents.

### DeFi
Decentralized Finance(DeFi) a system developed as an alternative to centralized forms of financial services. Offering similar banking services such as earning interest, borrowing, lending and trading but using blockchain technology to remove intermediaries.

If you got something out of this and want to learn more about **cryptocurrency, web3 & finance**:

Follow me [@jamiesventures](https://twitter.com/jamiesventures)
How to invert a string
Tags: javascript, webdev, tutorial, beginners
Published: 2022-06-04 14:33:22

First, we need to transform the string into a list of characters. We can use the split() method to do that.
```js
const str = 'Hello World';
const chars = str.split('');
console.log(chars); // ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
```

Then, we need to reverse the list of characters. We can use the reverse() method to do that.
```js
const chars = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'];
const reversedChars = chars.reverse();
console.log(reversedChars); // ['d', 'r', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'o', 'e', 'l', 'l', 'H']
```

Finally, we need to join the list of characters back into a string. We can use the join() method to do that.
```js
const reversedChars = ['d', 'r', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'o', 'e', 'l', 'l', 'H'];
const reversedStr = reversedChars.join('');
console.log(reversedStr); // 'dlrow olleH'
```
So, we have a string that is the reverse of the original string.
```js
const str = 'Hello World';
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // 'dlrow olleH'
```
Sort Characters By Frequency
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 14:30:40

Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string.

Return _the sorted string_. If there are multiple answers, return _any of them_.

**Example 1:**

**Input:** s = "tree"
**Output:** "eert"
**Explanation:** 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

**Example 2:**

**Input:** s = "cccaaa"
**Output:** "aaaccc"
**Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
Note that "cacaca" is incorrect, as the same characters must be together.

**Example 3:**

**Input:** s = "Aabb"
**Output:** "bbAa"
**Explanation:** "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

**Constraints:**

*   `1 <= s.length <= 5 * 105`
*   `s` consists of uppercase and lowercase English letters and digits.

**SOLUTION:**

    import heapq
    
    class Solution:
        def frequencySort(self, s: str) -> str:
            n = len(s)
            freq = {}
            for c in s:
                freq[c] = freq.get(c, 0) + 1
            nlargest = heapq.nlargest(len(freq), [(value, key) for key, value in freq.items()])
            return "".join([c * k for k, c in nlargest])
Python daily exercise 3: reverse a string
Tags: python, beginners, string
Published: 2022-06-04 14:24:26

## Question
- write a program to reverse a given string
```python
str1 = "PYnative"

```
- Expected output
```python
evitanYP
```

## My attempt
```python
str1 = "PYnative"
reversed_string = str1[::-1]
print(reversed_string)
```
## Recommend solution
```python
str1 = "PYnative"
print("Original String is:", str1)

str1 = ''.join(reversed(str1))
print("Reversed String is:", str1)
```
## My reflection
I only know how to reversed a string using string slicing method, but do not know the reverse() and the join().
Day 7 - Functions
Tags: 100daysofcode, solidity, web3, blockchain
Published: 2022-06-04 14:14:00

{% embed https://github.com/Envoy-VC/30-Days-of-Solidity noreadme %}

This is Day `7` of `30` in Solidity Series
Today I Learned About Functions in Solidity.

A function is basically a group of code that can be reused anywhere in the program, which generally saves the excessive use of memory and decreases the runtime of the program. Creating a function reduces the need of writing the same code over and over again.

Syntax -
```solidity
function function_name(parameter_list) scope returns(return_type) {
       // block of code
}
```

eg-

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract MyContract {
    function add() public view returns (uint256) {
        uint256 num1 = 10;
        uint256 num2 = 16;
        uint256 sum = num1 + num2;
        return sum;
    }

    function sqrt(uint256 num) public pure returns (uint256) {
        num = num**2;
        return num;
    }
}
```

`view` in a function ensures that they will not modify the state of the function.

---
Longest Harmonious Subsequence
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 14:00:47

We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`.

Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_.

A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.

**Example 1:**

**Input:** nums = \[1,3,2,2,5,2,3,7\]
**Output:** 5
**Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\].

**Example 2:**

**Input:** nums = \[1,2,3,4\]
**Output:** 2

**Example 3:**

**Input:** nums = \[1,1,1,1\]
**Output:** 0

**Constraints:**

*   `1 <= nums.length <= 2 * 104`
*   `-109 <= nums[i] <= 109`

**SOLUTION:**

    class Solution:
        def findLHS(self, nums: List[int]) -> int:
            nums.sort()
            pos = {}
            for i, num in enumerate(nums):
                if num in pos:
                    pos[num][1] = i
                else:
                    pos[num] = [i, i]
            mlen = 0
            for num in pos:
                if num + 1 in pos:
                    mlen = max(mlen, pos[num + 1][1] - pos[num][0] + 1)
            return mlen
3 Must Have AI Tools for Bloggers & Marketers
Tags: ai, tools
Published: 2022-06-04 13:29:37

Hey guys,

I'm Aman, a junior civil engineer from New Delhi. I've heard a lot about this platform - but as I belongs from Civil background, I don't have much to contribute on this platform.

So, here I'm sharing a topic which I've understanding on with this Dev family <3  

I hope you like it...

----
As a blogger or marketer, you know the importance of staying ahead of the curve and being able to produce content quickly and efficiently.

One way to do this is to utilize AI tools to help with your content creation. Here are three AI tools that every blogger and marketer should have in their toolkit:

##1. ClosersCopy

ClosersCopy is an AI tool that helps you write better headlines, Call-to-Actions (CTAs), and product descriptions. It uses natural language processing (NLP) to analyze your text and suggest improvements.

They're running a [lifetime deal on their website](https://thelifetimedeal.com/closerscopy-lifetime-deal/) right now, so it's a great time to check them out!

##2. Rank Math

Rank Math is an AI-powered SEO plugin for WordPress that helps you optimize your content for better search engine rankings. It analyzes your text and suggests changes to improve your SEO.

##3. WriterZen

WriterZen is an AI tool that helps you come up with ideas for blog posts, articles, and social media posts. It uses keyword analysis to come up with ideas based on what people are searching for online.

These are just a few of the AI tools available to help you with your content creation. If you're not using AI tools, you're missing out on a huge opportunity to improve your content and save time.

Follow our website [thelifetimedeal.com](https://thelifetimedeal.com/) for more information on SaaS deals, lifetime deals, and other such tools. We will be regularly posting about different AI tools that can help you in your blogging journey. 

Stay tuned!
O que há de novo no Android 13?
Tags: android, jetpack, mobiledevelopment
Published: 2022-06-04 13:48:55

Chegou aquela hora feliz do ano em que temos uma versão nova do Android. Anunciado no Google I/O, o Android 13 tem uma séries de melhorias e mudanças que afeta não só a vida do usuário final, como a vida de nós desenvolvedores. Eu separei algumas das mudanças que afetam mais a vida do desenvolvedor até agora:

Primeiro e principalmente, quando deve sair:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8w5o72sbj8bb90ajmidv.png)
Já podemos baixar e começar a adaptar os nossos recursos, para o release em Julho!

E o que mais?

1) JetPack Compose 1.2: O JetPack Compose traz uma série de ferramentas para ajudar a montar interfaces mais ricas e fluídas de forma mais simples. Ele traz nessa nova versão recursos como Downloadable Fonts, onde o sistema busca e baixa diretamente fontes do Google Fonts, ajudando a diminuir o tamanho final do apk. Outro recurso interessantes é o Lazy Grid, permitindo montar grids de objetos em tamanho diferentes e não padronizados com menos linhas de código.

2) Melhorias no Android Studio: com o lançamento do AS Dolphin e o Eletric Eel em Canary, temos um monte de recursos novos chegando.
* LogCatV2: LogCat remodelado, ajudando na visualização, busca e filtro de registros
* Gradle Managed Devices: tudo o que você precisa fazer é descrever o device que precisa pra rodar os seus testes e o GMD cuida do resto pra você! Ele baixa o SDK, provisiona, executa os testes, desmonta o ambiente. 
* Live Edit: todo o código que você altera, visualmente no Compose, pode ser visto em tempo real, não só na tela de preview como também no emulador e no device físico!
* Baseline Profiles: ele permite que apps e bibliotecas adicionem metadados em vistas a ajudar o compilador ahead-of-time a priorizar certos caminhos de código em vistas a deixar a experiência inicial do usuário mais rápida. Essa técnica já está sendo usada em libs como Fragments e Compose e também no app da Play Store, que já reportou ganho de velocidade de 40%

3) Outras melhorias gerais como:
* Privacy Sandbox: um novo conjunto de APIs, ainda em preview, para disponibilização de conteúdo para o usuário de forma mais fácil e sem conflitar com as suas preferências de privacidade
* Google Wallet: o Google Pay Passes está integrando ao serviço de pagamentos agora chamado Google Wallet. A nova API agora permite a gravação de passes genéricos e o agrupamento em vouchers
Scope in Javascript
Tags: javascript, scope, tutorial, programming
Published: 2022-06-04 13:32:47

Today, we are going to try to understand scope in javascript.

<p> In Javascript, Scope refers to the current context of code, which determines the accessibility of variables to javascript. Which means variables are accessible only in the environment in which they were created, and are also accessible by their children.</p> 


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

There are two types of scope, global and local scope.

### Global scope
Global scope, it is also known as **window object**. It is the entire javascript execution environment. 

Any variable defined in the global scope will be accessible 
throughout the entire program.

Any variable assigned without an explicit scope (using the `var`, `let`, or `const` keywords) automatically become global variables. The same is true for functions. [reference](https://www.udacity.com/blog/2021/06/javascript-global-variable-scopes.html#:~:text=The%20Javascript%20global%20scope%20is%20the%20context%20where%20everything%20in,the%20entire%20Javascript%20execution%20environment)

```javascript
// index.js

const myName = "Mark Zuckerberg" // global scope

console.log(myName) // Mark Zuckerberg

```

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

### Local scope
Local scope is also known as function scope, if you define variables inside a function, they are only accessible within that particular function, they can not be accessed outside of that function.

```javascript
// index.js

function getAge() {
   const myAge = 34;
   console.log(myAge); // 34
}

console.log(myAge) // ReferenceError: myAge is not defined

```
## scope chain

Javascript uses a scope chain to find variables accessible in a certain scope. Which means when a variable is referred to, Javascript will look for it in the current scope and continue to the parent scope until it reaches the **global** scope.

```javascript
// global scope
const a = 10; // accessible to everyone

const outerFunc = () => {
  var b = 20;  // a and b is accessible
  console.log(a, b);

  const innerFunc = () => {
      var c = 30;  // a, b and c is accessible
      console.log(a, b, c);
  }

  innerFunc();
}

outerFunc();

```

To run the codes `node index.js`

**Thank You, please follow me**

[<img align="left" alt="linkedin.com/in/ifeanyi-thankgod-chima/" width="22px" src="https://cdn.jsdelivr.net/npm/simple-icons@v3/icons/linkedin.svg"/>][linkedin]
[<img align="left" alt="https://twitter.com/ifeanyiTchima" width="22px" src="https://cdn.jsdelivr.net/npm/simple-icons@3.13.0/icons/twitter.svg" />][twitter]


[linkedin]: https://www.linkedin.com/in/ifeanyi-thankgod-chima/
[twitter]: https://twitter.com/ifeanyiTchima


<a href="https://www.buymeacoffee.com/ifeanyichima" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>
TypeError: Cannot read properties of undefined (reading 'forEach')
Tags: javascript, webdev, tutorial, programming
Published: 2022-06-04 13:32:05

Have you ever encountered this error in javascript before ``TypeError: Cannot read properties of undefined (reading 'forEach')`` there are many a causes for this error, but today, we would look at one. Take a look at the code below.
```javascript
// index.js
const printNumbers = {
    phrase: "The current value is",
    numbers: [1, 2, 3, 4],
    loop: () => {
        this.numbers.forEach((number) => {
            console.log(this.phrase, number)
        })
    }
}

printNumbers.loop();
```
to run this code **open terminal** and run ``node index.js``. It will throw an error 

```javascript 
TypeError: Cannot read properties of undefined (reading 'forEach')
```


![BMC](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2ft5zxdxheuwhlkyzwu.gif)

## Cause
To understand what caused the error, we need to understand **scope** and **arrow functions** in javascript. 
<p>In javascript, Scope refers to the current context of code, which determines the accessibility of variables to javascript. There are two types of scope, Global and Local scope. </p>

please refer to my other tutorial to understand [more about scope](https://dev.to/masterifeanyi/scope-in-javascript-2nf6).

An Arrow function doesn't have its own `this` value. It uses the `this` value of the enclosing lexical scope. In the code above, the `this` keyword in arrow function should refer to properties and methods (function) of the `printNumbers` object. However, objects in javascript do not have a lexical scope, therefore an arrow function will look outside (beyond) the object for the value of `this`, **what is outside ?** the `global` scope (window object) which does not have the `numbers` property. Therefore, the Javascript engine adds the `numbers` property to the `window` object and sets its value to `undefined`.

To fix the issue, you should use traditional functions as the method (function) of the object.

here is the same code, modified

```javascript 

// index.js
const printNumbers = {
    phrase: "The current value is",
    numbers: [1, 2, 3, 4],
    loop(){ // ==> changes made
        this.numbers.forEach((number) => {
            console.log(this.phrase, number)
        })
    }
}

printNumbers.loop();

```

## answer

The traditional function re-binds `this` keyword.

**Thank You, Please follow me**

[<img align="left" alt="linkedin.com/in/ifeanyi-thankgod-chima/" width="22px" src="https://cdn.jsdelivr.net/npm/simple-icons@v3/icons/linkedin.svg"/>][linkedin]
[<img align="left" alt="https://twitter.com/ifeanyiTchima" width="22px" src="https://cdn.jsdelivr.net/npm/simple-icons@3.13.0/icons/twitter.svg" />][twitter]


[linkedin]: https://www.linkedin.com/in/ifeanyi-thankgod-chima/
[twitter]: https://twitter.com/ifeanyiTchima

<a href="https://www.buymeacoffee.com/ifeanyichima" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>
Count Good Meals
Tags: leetcode, dsa, theabbie
Published: 2022-06-04 13:30:40

A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two.

You can pick **any** two different foods to make a good meal.

Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`.

Note that items with different indices are considered different even if they have the same deliciousness value.

**Example 1:**

**Input:** deliciousness = \[1,3,5,7,9\]
**Output:** 4
**Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9).
Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.

**Example 2:**

**Input:** deliciousness = \[1,1,1,3,3,3,7\]
**Output:** 15
**Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.

**Constraints:**

*   `1 <= deliciousness.length <= 105`
*   `0 <= deliciousness[i] <= 220`

**SOLUTION:**

    from collections import Counter
    
    class Solution:
        def countPairs(self, deliciousness: List[int]) -> int:
            deliciousness = Counter(deliciousness)
            ctr = 0
            for i in range(22):
                total = 1 << i
                for d in deliciousness:
                    if total - d in deliciousness:
                        if 2 * d != total:
                            ctr += deliciousness[d] * deliciousness[total - d] / 2
                        else:
                            ctr += deliciousness[d] * (deliciousness[d] - 1) // 2
            return int(ctr) % (10 ** 9 + 7)