teleren/devto huggingface dataset:
Palindrome Revision
Tags: javascript, beginners
Published: 2022-02-10 15:54:28

## METHOD 1: Using built-in Reverse
Most straightforward but most inefficient, worst-case minimally a O(n) or O(n+k) linear time.
```JavaScript
const isPalindrome = (str) => {
  return str === [...str].reverse().join("");
};
```

## METHOD 2: Using Decrementing For Loop
Not efficient as well, O(n) linear time
```JavaScript
const isPalindrome = (str) => {
  let newStr = "";
  for (let i = str.length - 1; i >= 0; i--) {
    newStr += str[i];
  }
  return str === newStr;
};
```

## METHOD 3: Using Recursion
We can check the front and back of the str recursively from outer to inner elements.
```JavaScript
const isPalindromeRec = (str) => {
  const sLen = str.length;
  if (sLen === 0 || sLen === 1) return true;
  // check front & back recursively
  if (str[0] === str[sLen - 1]) {
    return isPalindromeRec(str.slice(1, sLen - 1));
  }
  return false;
};
```

## METHOD 4: Using Loop to compare
Will be approximately twice more efficient than method 1 and 2, as we are only checking half the length.
```JavaScript
const isPalindrome = (str) => {
  const sLen = str.length;
  for (let i = 0; i < sLen / 2; i++) {
    if (str[i] !== str[sLen - 1 - i]) {
      return false;
    }
  }
  return true;
};
```
What are the qualities of a Principal Engineer (or equivalent title)?
Tags: discuss, career
Published: 2022-02-10 15:48:43


What, in your mind, make for an effective "principal" level engineer — that is, say, one level above "senior". I put this in quotes because the titles are going to be flexible from place to place, but what in your mind does it mean to be that level above senior.

I think about this because we are hiring for a principal role at Forem, and we have our own criteria, but I think at the end of the day it is a matter of organizational expectations _and_ personal expectations. So I'm wondering what you think.

{% tweet 1491476633169149953 %}
My extension got 3000 installs out of nowhere in one night and I don't have a clue
Tags: vscode, webdev, frontend, extensions
Published: 2022-02-10 15:35:47

Hello everyone. I made a VS Code extension for front-end developers 3 months ago and listed it on Marketplace with very high hopes. Though I self-marketed the extension in various ways, the start was kind of slow and steady. I got around 1500 installs in the first 3 months. Yesterday night I slept after checking the marketplace since its the part of my routine now and everything was normal. I woke up the next day getting ready for the office, checked the marketplace again, and was shocked to see the install count reached up to 4500. Both happy and confused me didn't have a clue about what had just happened. I don't know if that's common or what. So I thought I'd tell you guys and get your responses.

[Link to my extension](https://marketplace.visualstudio.com/items?itemName=vsblox.blox)
Design (UI/UX) course for Developers?
Tags: design, developers, course, learning
Published: 2022-02-10 15:27:03

Hello World!

I'm looking for the best UI / UX design course for the developers.

Wanna learn all about design, from color theory to typography, UX for mobile especially. Content can be based on Sketch or Figma. I have some experiences with those apps.  

I've find only two but not sure if is there any that I don't know. So, please recommend some.

https://designcode.io
https://learnui.design/index.html

Cheers!
Handling missing dict keys
Tags: beginners, python
Published: 2022-02-10 15:25:42

Trying to access a non-existent key using this notation raises a `KeyError`: `dict[key]`. An easy workaround for this is to use `get(key)` instead, which returns `None` if `key` isn't found, or `get(key, default)` which returns `default` if `key` isn't found.

```sh
>>> d = {}
>>> d
{}
>>> d["x"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'x'
>>> d.get("x")
>>> d
{}
>>> d.get("x","y")
'y'
>>> d
{}
>>>
```

But what if you want to not only return a default if the key is missing, but also assign that default to the specified key in the dict? There are a couple of ways to do that.

## 1. `setdefault`

> ### setdefault(key[, default])
>
> If key is in the dictionary, return its value. If not, insert key with a value of default and return default. `default` defaults to `None`.
>
> [docs](https://docs.python.org/3/library/stdtypes.html#dict.setdefault)

```sh
>>> d
{}
>>> d.setdefault("x","y")
'y'
>>> d
{'x': 'y'}
>>>
```

## 2. `defaultdict`

> ### class collections.defaultdict(default_factory=None, /[, ...])
>
> The first argument provides the initial value for the [default_factory](https://docs.python.org/3/library/collections.html#collections.defaultdict.default_factory) attribute; it defaults to `None`. All remaining arguments are treated the same as if they were passed to the [dict](https://docs.python.org/3/library/stdtypes.html#dict) constructor, including keyword arguments.
>
> [docs](https://docs.python.org/3/library/collections.html#collections.defaultdict)

```sh
>>> from collections import defaultdict
>>> i = defaultdict(int)
>>> i
defaultdict(<class 'int'>, {})
>>> i["x"]
0
>>> i
defaultdict(<class 'int'>, {'x': 0})
>>> i["y"]
0
>>> i
defaultdict(<class 'int'>, {'x': 0, 'y': 0})
>>>
```

Note that no `KeyError` is raised despite the key not existing at first. Instead, the key is created with the default value of the type passed into `defaultdict`, in this case `0` for `int`. If we used `list` instead, the default value would be `[]`, an so on.

Further reading:

- [defaultdict Examples](https://docs.python.org/3/library/collections.html#defaultdict-examples)
- [Use cases for the 'setdefault' dict method](https://stackoverflow.com/questions/3483520/use-cases-for-the-setdefault-dict-method) (vs defaultdict)

## 3. Implement `__missing__`

This is actually what `defaultdict` does behind the scenes. Use this when `defaultdict` doesn't fit your usecase.

```sh
>>> class M(dict):
...     def __missing__(self, key):
...             value = "my default value"
...             self[key] = value
...             return value
...
>>>
>>> m = M()
>>> m
{}
>>> m["x"]
'my default value'
>>> m
{'x': 'my default value'}
>>> m["y"]
'my default value'
>>> m
{'x': 'my default value', 'y': 'my default value'}
>>>
```
Python challenge_16
Tags: python, tutorial, beginners, programming
Published: 2022-02-10 15:24:29

##Writing short code

Define a function named convert that takes a list of numbers
as its only parameter and returns a list of each number converted to a string.

For example:

the call convert([1, 2, 3]) should return ["1", "2", "3"].

What makes this tricky is that your function body must only contain a single line of code.

[Task URI](https://pythonprinciples.com/challenges/Writing-short-code/)


####My solution 
```
def convert(lists): return [str(con_list) for con_list in lists]
print(convert([1, 2, 3]))
```

####Another solution 
```
def convert(ns):
    return [str(n) for n in ns]
```

####using map
```
def convert(ns):
    return list(map(str, ns))
```

All the best to you.
Sales by Match solution in Javascript
Published: 2022-02-10 14:20:33

## Problem: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8kuz0z4i01lnunrf125h.png)
There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
**Example**
n = 7,
ar = [1,2,1,2,1,3,2]

There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.

**Function Description**

Complete the sockMerchant function in the editor below.

sockMerchant has the following parameter(s):

int n: the number of socks in the pile
int ar[n]: the colors of each sock

**Returns**

int: the number of pairs

## Solution:
The simplest way to solve this problem is by breaking it down into simple steps as follows:

1. Go through the list of items and sort them by color.
2. Once we have a collection of items of the same color, we can determine from the collection how many form a pair.

In Javascript we solve that in the following:
1. Loop through the array and assign unique values to a map. If a value already exists in the map, we will increment the value. The idea is to have a map that shows items and the number of times it appears.

`Map(4) { 10 => 4, 20 => 3, 30 => 1, 50 => 1 }`

2. From the map, we can now detemine which forms a pair.

```
function sockMerchant(n, ar) {   

    //1. Loop through array items and arrange items in a map by unique color

    let mapOfColors = new Map();
    
    for(let i = 0; i< n ; i++ ){
        // If found, increment the map value
        if(mapOfColors.has(ar[i])){
            let currentVal = mapOfColors.get(ar[i]);
            mapOfColors.set(ar[i], currentVal+1);
        }        
        // If item is not found, add it to map
        else{
            mapOfColors.set(ar[i], 1)
        }        
    }

    //2. From the map, we can now detemine which form a pair

    let pairs = 0; 

    for(let countOfColor of mapOfColors.values() ){
        // Check if it can create complete pairs
        if(countOfColor % 2 === 0){
            pairs += countOfColor/2;
        }else{
            pairs += (countOfColor-1)/2;
        }
    }
    
    return pairs;
}

const pairs = sockMerchant(9, [10, 20, 20, 10, 10, 30, 50, 10, 20]);
console.log ( pairs);
```
Subarray with 0 sum
Tags: beginners, programming, java, dsa
Published: 2022-02-10 15:18:01

Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.

<u>Example 1:</u>
Input:
5
4 2 -3 1 6
Output: 
Yes
_Explanation: 
2, -3, 1 is the subarray 
with sum 0._

This is similar to the previous question [Subarray sum equals k](https://dev.to/tishaag098/subarray-sum-equals-k-4djk) but this is **EASY** compared to that.

To solve this question click here:(https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1/)

**Approach 1:**
_Time Complexity: O(n^2)_

**JAVA CODE**
```
public static boolean subArrayExists(int arr[],int n)
    {
        for(int i=0;i<n;i++)
        {
            int sum=0;
            for(int j=i;j<n;j++)
            {
                sum+=arr[j];
                if(sum==0)
                  return true;
                
            }
        }
        return false;
    }
```

**Approach 2:**
This is similar to the previous subarray question that we solved.
_Time Complexity: O(n)_

**JAVA CODE**
```
  static boolean findsum(int arr[],int n)
    {
        //Your code here
        HashMap<Integer,Integer> hm=new HashMap<>();
        hm.put(0,1); // it is imp to put 0 initially in the hashmap
        int sum=0;
        for(int i=0;i<n;i++)
        {
            sum+=arr[i];
            if(hm.containsKey(sum))
                return true;
            
            hm.put(sum,hm.getOrDefault(sum,0)+1);
        }
        return false;
    }
```

**Approach 3:**
We have used HashSet in this as their is no need to use HashMap since we have no use of storing values in key, pair
_Time Complexity: O(n)_

**JAVA CODE**
```
public static boolean subArrayExists(int arr[],int n)
    {
         //declare a set data structure
         HashSet<Integer> res=new HashSet<>();
         int sum=0;
         
         for(int i=0;i<n;i++)
         {
             res.add(sum);//in first step it will add 0
             sum+=arr[i];
             if(res.contains(sum))
                 return true;
         }
         return false;

    }
   ```
Add Hongkong Post Root CA certificate to Java keystore
Tags: java, tls, keystore, security
Published: 2022-02-10 15:07:26

## Problem

I can't find Hongkong Post Root CA in Java 17 `cacerts`. I need to download and import it.

## Steps

1. Download from [Hongkong Post](https://www.hongkongpost.gov.hk/product/download/root/index.html)

Please download "Hongkong Post Root CA 3".

![Hongkong post cert download link](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbiwqjlfcv0wo3xhbal8.png)

2\. Execute the following command in terminal

```shell
sudo keytool -import -alias hongkongpostrootca3 -file ~/Downloads/root_ca_3_pem.cer -cacerts
```

`~/Downloads/root_ca_3_pem.cer` is the file path of certificate downloaded in previous step.

`hongkongpostrootca3` is just alias. You can give a different name.

3\. It will ask for keystore password. The default one is `changeit`.

4\. It will ask to confirm with message "Trust this certificate?". Just enter `yes`.

5\. The root CA is imported. We can check it with the following command.

```shell
sudo keytool -list -alias hongkongpostrootca3 -cacerts
```
Python #6 - estruturas de decisão
Tags: beginners, python, datascience, codenewbie
Published: 2022-02-10 14:53:48

_Esse post faz parte dos meus cadernos **pessoais** de estudos. Todas as anotações são baseadas nas aulas da Mentorama - Cientista de Dados do zero e organizadas sob o meu ponto de vista. M3A1_

---

### Estruturas de decisão 

São utilizadas quando queremos que o algoritmo siga um caminho específico a partir de uma regra/variável de interesse. 

_Exemplo lógico: Se... então._

`nota = 5
if nota >=7: 
    print("Parabéns! Você está aprovado")
else:
    print ("Você foi reprovado")`

`if`: verdadeiro 
`else`: se for falso 

o `print` vem identado 

- Verificar a idade para dirigir. Sem o else.

`idade = int(input("Qual sua idade?"))
if (idade >= 18):
    print("Idade digitada", idade)
    print("Você já pode tirar a CNH")
    print("Parabéns")`

- Ex com duas variáveis de decisão 

`idade = int(input("Qual sua idade?"))
visão = str(input("Você enxerga bem?"))
if (idade >= 18 and visão == "sim" or "Sim"):
    print("Você já pode tirar a CNH")
    print("Parabéns")`

_botei "sim" or "Sim" por conta da linguagem ser case sensitive_

- Pesquisa de produto disponível em estoque 

`produtos_disponiveis = ["arroz", "feijao", "farinha", "banana", "leite"]
produto = input("Qual produto você procura?")
if produto in produtos_disponiveis:
    print ("Oba! Temos o produto no estoque")`

- Verificação de saque no app do banco

`saldo = 1000
valor_saque = 75 
if saldo >= valor_saque:
    print("O valor de", valor_saque, "foi sacado com sucesso")
    saldo = saldo - valor_saque
    print("Seu novo saldo é", saldo)`

- Verificação de frequência de aluno para aprovação 

nota = 9 
frequencia = 77

if (nota >= 9 and frequencia >= 80):
    print ('Aprovado')
else:
    print("Reprovado!")

#### ELIF - If aninhado

`nota = 5
frequencia = 77
if (nota >= 7):
    print("Aprovado")
else:
    if frequencia >= 80:
        print("Em exame")
    else:
        print ("Você faltou, está reprovado")`

Usando o elif

`nota = 6
frequencia = 85 
if (nota >= 7):
    print("Aprovado")
elif nota >= 6 and frequencia >=80:
    print("Em exame")
else: 
    print("Você faltou e tem nota baixa. Reprovado")`
Language translation plugin for vue js
Tags: vue, localization, beginners, showdev
Published: 2022-02-10 14:48:00

Hello everyone 👋, 

I'm Ankit Zore Full stack developer from India. Currently working on laravel nova and vue js frameworks.

I have created vue language plugin which out of the box provides translation feature.

I have used different alternatives but I felt they were complex to solve just translation issues if you have custom words. So I created plugin which does it for you.

How it works?

You create the language file where you define all words which needs to be translated as key and there translations as value.

Eg:fr.js

```js
export default
    {
        "title": "titre",
        "Hello World": "Bonjour le monde"
    }
```

This file will be used by plugin to check for translations.

When you install plugin you get "translate()" out of the box which can be used in templates as well as scripts to translate words.

Plugin also provides vuex store where you can mutate the current locale variable. If locale variable is set to fr it will show translations of fr file similar for other languages.

Check [vue_language_plugin](https://github.com/ZoreAnkit/ankit-vue-language-lib) for complete installation and guide on how to use it.

This is my 1st open source project. Any suggestions, advices, help are most welcomed
Paracetamol.js💊| #50: Explica este código JavaScript
Tags: javascript, webdev, spanish, beginners
Published: 2022-02-10 14:43:25

## **Explica este código JavaScript**

```js
function getItems(fruitList, ...args, favoriteFruit) {
  return [...fruitList, ...args, favoriteFruit]
}

getItems(["banana", "apple"], "pear", "orange")
```

-     A: `["banana", "apple", "pear", "orange"]`
-     B: `[["banana", "apple"], "pear", "orange"]`
-     C: `["banana", "apple", ["pear"], "orange"]`
-     D: `SyntaxError`

Respuesta en el primer comentario.

---
IIS error (500.19)
Tags: web, config, iis, iusrs
Published: 2022-02-10 14:39:55

---
title: IIS error (500.19)
published: true
description: IIS authorization error to web.config file
tags: 'web, config, iis, iusrs'
cover_image: 'https://raw.githubusercontent.com/campelo/documentation/master/posts/iis/assets/cover.png'
canonical_url: null
id: 984891
---

###### :postbox: Contact :brazil: :us: :fr:

[Twitter](https://twitter.com/campelo87)
[LinkedIn](https://www.linkedin.com/in/flavio-campelo/?locale=en_US)

---

## 500.19-IIS error when running web application

Maybe you're trying to run an web application from VS in a company domain and then you find this error:

![Image 1](https://raw.githubusercontent.com/campelo/documentation/master/posts/iis/iis-error-500/assets/img1.png)

The problem is about the authorizations to the user which is running the application pool on IIS. That user doesn't have access to the web.config file in the project's directory.

So, you have to find the **web.config** file and give access to that user.

When you find the file, **right-click** it and then click on **Properties** and finally open the **Security** tab. You have to add a new authorization to the **IIS_IUSRS** group. *This is a local group so, if you're in a* **domain**, *you must to select your* **local computer** *to find it.*

## IIS_IUSRS group

Every user (service network, local system, etc) that your website uses. See [microsoft documentation](https://docs.microsoft.com/en-US/troubleshoot/developer/webapps/iis/www-authentication-authorization/understanding-identities#:~:text=IUSR%20%E2%80%93%20anonymous%20authentication%20Anonymous%20authentication%20allows%20users,This%20built-in%20account%20does%20not%20require%20a%20password.) for further details.

## Typos or suggestions?

If you've found a typo, a sentence that could be improved or anything else that should be updated on this blog post, you can access it through a git repository and make a pull request. If you feel comfortable with github, instead of posting a comment, please go directly to https://github.com/campelo/documentation and open a new pull request with your changes.
Do not use `pip freeze`
Tags: python, pip, freeze, piptools
Published: 2022-02-10 14:23:32

We are using `pip freeze` or `pip3 freeze` command for making `requirements.txt` for our python projects. We use `pip freeze > requirements.txt` right?  

But when we try to install our project to another machine that time we use `pip install -r requirements.txt` command to install those packages which we need for that project. But most of the time we face an error which is - **version not satisfied**. 

At first, let's try to understand what `freeze` actually is for.

"pip freeze is a very useful command, because it tells you which modules you've installed with pip install and the versions of these modules that you are currently have installed on your computer. In Python, there's a lot of things that may be incompatible, such as certain modules being incompatible with other modules."

So if we use `pip freeze` to make `requirements.txt` which list we found those all dependencies we don't need our single project. And in that list we don't know which module is compatible and which is incompatible. 

**So what should be a better approach?**  

Use `pip-compile` command. This command makes `requirements.txt` with which dependencies only you need. 

For this command at first install [pip install pip-tools](https://github.com/jazzband/pip-tools)

Suppose you want install a **django** project so what should you do - 

1. At first create virtual environment - `python-venv env`
2. Then active environment - `source env/bin/activate`
3. Now create `requirements.in` file and then write in it only 'django'.
4. Now write `pip-compile requirements.in` and hit enter. Then you will find a `requirements.txt` like -

```
#
# This file is autogenerated by pip-compile with python 3.8
# To update, run:
#
#    pip-compile requirements.in
#
asgiref==3.5.0
    # via django
backports-zoneinfo==0.2.1
    # via django
django==4.0.2
    # via -r requirements.in
sqlparse==0.4.2
    # via django

```
Now you are ready to install your Django. Just write `pip install -r requirements.txt` and hit enter. 

With exact dependencies and comments requirements.txt ready use. So now no unnecessary dependency related issues.
A cool trick to get unique items in an array in JavaScript
Tags: javascript, beginners, webdev, productivity
Published: 2022-02-10 14:16:52

```javascript
const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];

console.log(uniqueArray); // Result: [1, 2, 3, 5]
```

To learn more about arrays in JavaScript, visit [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
A public chat app which is build with reactjs and firbase
Tags: react, firebase, javascript, webdev
Published: 2022-02-10 14:15:25


#### Github : https://github.com/nisabmohd/chat-app
####Demo : https://nisabmohd.github.io/chat-app
```
star and fork the repo 😊
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gelw9t16iygm8wjjkzfc.png)
My first neovim plugin: Opener.nvim - quickly open directories/folders
Tags: neovim, vim, lua, plugin
Published: 2022-02-10 14:10:36

A very simple yet useful plugin. [Opener.nvim](https://github.com/willthbill/opener.nvim) lets you open directories / folders in neovim like in mainstream editors (vscode, atom, ...). Essentially, it changes the cwd (current working directory, like :cd) and clears all buffers, tabs and windows (of course respecting any unsaved buffers). This was you can use the same editor instance for different workspaces / projects / directories without reopening neovim. This is especially useful for people using a neovim GUI such as neovide, where it is time consuming to reopen the editor. Also, it may be useful for people using project-management plugins or session -management plugins, to open projects, which has not been open before.

Bonus: naturally opener.nvim has a built-in telescope.nvim extension for choosing directories.

Repository: https://github.com/willthbill/opener.nvim

![Showcase of opener.nvim](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wwoq25gzs9rbysxczmov.gif)

Bonus 2: you can setup hooks to run before and after opening a directory.

I posted on reddit too: [reddit](https://www.reddit.com/r/neovim/comments/sp4bva/my_first_neovim_plugin_openernvim_quickly_open/?utm_source=share&utm_medium=web2x&context=3)
Mini social network that I made as my first web app project.
Tags: react, node, javascript, webdev
Published: 2022-02-10 14:04:37

# social-network

Mini social network that I made as my first web app project.

## Demo

[social-network](http://46.101.189.55/login)

## Repository

[link to repository](https://github.com/misa-j/social-network)

## Link to a full video

[Video](https://streamable.com/5srsv)

## Screenshots

![](https://raw.githubusercontent.com/misa-j/social-network/master/screenshots/Screenshot%20from%202020-02-29%2019-07-06.png)
![](https://raw.githubusercontent.com/misa-j/social-network/master/screenshots/Screenshot%20from%202020-02-29%2019-26-42.png)
![](https://raw.githubusercontent.com/misa-j/social-network/master/screenshots/Screenshot%20from%202020-02-29%2019-07-23.png)