teleren/devto huggingface dataset:
MongoDB Connection using Mongoose
Tags: mongodb, webdev, javascript
Published: 2022-06-18 11:20:17

An important step in the process of Development is connecting with the database. This has been made easy with `mongoose`, which is an npm dependency. 

After you have initialized your express app, install mongoose using the following npm command : 

npm install mongoose


Mongoose can be used in 3 simple steps : 
## Setting up a port
Since `mongoDB` runs on a server, we need to run a mongoDB server locally. If you have mongoDB installed locally, just head to your preferred terminal and run : 

mongod

Your mongoDB server is up and running on *port: 27017*

## Importing Mongoose
You can import and use mongoose in 2 places : 
### In the `server.js` file
You can import and use mongoose in the main server file itself : 
javascript
const mongoose = require("mongoose");


### In a Separate Database Folder
You can also implement the modular approach where you can create a separate `db` folder and setup connection inside it in a `connections.js` file.

## Connecting To Server
The final step is to initialize and setup the mongoDB connection. 
The process is to initialize the mongoose connection and listen for the result returned.

javascript
const mongoose = require("mongoose");

mongoose
  .connect(process.env.DB_URL, {
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true
  })
  .then((result) => {
    console.log("Database connected at port : "+process.env.DB_URL);
  })
  .catch((err) => {
    console.log(err);
  });


Now the question is what are these terms : 
javascript
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true

These are optional arguments being passed to the connection method.
### 1. `useNewUrlParser`
The underlying MongoDB driver has deprecated their current connection string parser. Because this is a major change, they added the useNewUrlParser flag to allow users to fall back to the old parser if they find a bug in the new parser. You should set
javascript
useNewUrlParser: true
 
unless that prevents you from connecting.

### 2. `useFindAndModify`
`true` by default. Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify().

> `findOneAndUpdate` allows for just updates - no deletes or replaces etc.

> `findAndModify` can do a lot more including replace, delete and so on.

### 3. `useUnifiedTopology`
`false` by default. Set to true to use the MongoDB driver's new connection management engine. This option should always be set to true, except for the unlikely case that it prevents you from maintaining a stable connection.

There we go! We have successfully setup a mongoDB connection.
Happy Hacking!!
Web Sockets : The Handshake Technology
Tags: webdev, javascript
Published: 2022-06-18 11:16:50

We all have used Instagram or WhatsApp to have a healthy chat with our friends. Being a developer, I always wondered how this happens so fast without reloading. The answer is Web Sockets.

## Web Sockets vs HTTP
Why Web Sockets you might ask? Well what happens in HTTP is that a connection is established and once the request result process is completed, the connection is terminated.
So if we use this process for real time messaging, it would take some time to create new connections, thus making our chatting process slower. No one would like that, right?

This is where Web Sockets come in. The major difference is that the connection once established, is not destroyed until there is no more need for it. 

### Pipelines in Web Sockets
This might feel like one of those tech terminologies which scare us. But in simpler terms, pipelines in tech are same as real life pipelines. A connection through which things can be passed in any direction easily. 
This is how Web Sockets work, through pipelines.


![How web sockets work](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j7rzkaxcy9syusdtbpdb.png)
 
There are many libraries that help with the implementation of Web Sockets like Socket.io
Best Free React Resources
Tags: react, webdev, beginners, tutorial
Published: 2022-06-18 11:09:23

Here is a list of free resources to learn React.

I tried some of them, I devoured some others, in a few cases I just needed parts of them.

If you know more, feel free to share in a comment and I will make sure to add them to the list with your name:)

## Official React Documentation
This is worth mentioning because the team did and is doing a very good job to keep it simple and useful.

- [Getting Started](https://reactjs.org/docs/getting-started.html)

But:exclamation: 
just out of the oven, here is the beta version of the new React documentations!!!! 
:blue_heart: :heartpulse: :star:  :boom: 

{% embed https://beta.reactjs.org/ %}

## Videos
:computer: [Programming with Mosh - YT](https://www.youtube.com/watch?v=Ke90Tje7VS0&ab_channel=ProgrammingwithMosh) (2018) - 77k likes - ~2h Crash course

:computer: [Travery Media - YT](https://www.youtube.com/watch?v=w7ejDZ8SWv8&ab_channel=TraversyMedia) (2021) - 49k likes - ~2h Crash course

:computer: [Codevolution - YT](https://youtu.be/QFaFIcGhPoM) (2018) 19k likes

:computer: [Coding Addict - YT](https://www.youtube.com/watch?v=iZhV0bILFb0&ab_channel=CodingAddict) (2020) - 8k likes - ~10h

:computer: [Egghead.io](https://egghead.io/courses/the-beginner-s-guide-to-react) (2017) - ~2h Crash course

:computer: [Udemy - React with Redux, React-Router, Hooks and Auth0](https://www.udemy.com/course/modern-react/?LSNPUBID=0F1O0otUXQc&ranEAID=0F1O0otUXQc&ranMID=39197&ranSiteID=0F1O0otUXQc-a.2LSUSLwjqLCEShcgUdtg&utm_medium=udemyads&utm_source=aff-campaign) - ~4h - Probably free for a limited period - will remove after

:computer: [Front-End Web Development with React - HK University](https://www.coursera.org/learn/front-end-react?irclickid=Rc900pXJxxyIUP90qtUy-RZNUkDzXf1ZDR1iWs0&irgwc=1&utm_medium=partners&utm_source=impact&utm_campaign=1137078&utm_content=b2c) on Coursera - ~36h

:computer: [Scrimba](https://scrimba.com/learn/learnreact) - ~12h


## Text
:book: [Freecodecamp.org](https://www.freecodecamp.org/)

:book: [Fullstackopen.com - University of Helsinki](https://fullstackopen.com/en/) - Best resource imho

:book: [MDN](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started)

:book: [The Odin Project](https://www.theodinproject.com/lessons/node-path-javascript-react-introduction)

:book: [Overreacted](https://overreacted.io/) - This guy knows a thing or two about React

:book: [React Book](https://softchris.github.io/react-book/#/) by [Chris Noring](https://twitter.com/chris_noring)



### Do you know other resources?

Feel free to comment and I will make sure to add them to the list with your name!
Cheers!
Get white label Rarible Clone Script
Tags: raribleclone, rariblecloneapp, raribleclonesoftware
Published: 2022-06-18 11:02:53

Starting an NFT marketplace platform like Rarible using the Rarible clone script is a very good and simple idea. It's a ready-made script so you can simply start your NFT platform within 1week.
Troniex technologies is the world's leading Blockchain and NFT development company that offers ready-to-deploy white-label Rarible clone script with additional add-ons.

**[Know more to get a free demo!](https://troniextechnologies.com/rarible-clone-script)**
Find Duplicate Subtrees
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 11:00:46

Given the `root` of a binary tree, return all **duplicate subtrees**.

For each kind of duplicate subtrees, you only need to return the root node of any **one** of them.

Two trees are **duplicate** if they have the **same structure** with the **same node values**.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/08/16/e1.jpg)

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

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/08/16/e2.jpg)

**Input:** root = \[2,1,1\]
**Output:** \[\[1\]\]

**Example 3:**

![](https://assets.leetcode.com/uploads/2020/08/16/e33.jpg)

**Input:** root = \[2,2,2,3,null,3,null\]
**Output:** \[\[2,3\],\[3\]\]

**Constraints:**

*   The number of the nodes in the tree will be in the range `[1, 10^4]`
*   `-200 <= Node.val <= 200`

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    
    from collections import defaultdict
    
    class Solution:
        def postorder(self, root, trees):
            s = "#"
            if root:
                s = f"{root.val},{self.postorder(root.left, trees)},{self.postorder(root.right, trees)}"
                trees[s].append(root)
            return s
        
        def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
            trees = defaultdict(list)
            self.postorder(root, trees)
            return [trees[s][0] for s in trees if len(trees[s]) > 1]
Count Negative Numbers in a Sorted Matrix
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 10:30:40

Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.

**Example 1:**

**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.

**Example 2:**

**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 100`
*   `-100 <= grid[i][j] <= 100`

**Follow up:** Could you find an `O(n + m)` solution?**SOLUTION:**

    class Solution:
        def countNegatives(self, grid: List[List[int]]) -> int:
            m = len(grid)
            n = len(grid[0])
            ctr = 0
            for i in range(m):
                beg = 0
                end = n - 1
                while beg <= end:
                    mid = (beg + end) // 2
                    if beg == end:
                        if grid[i][beg] < 0:
                            ctr += (n - beg)
                        break
                    elif grid[i][mid] >= 0:
                        beg = mid + 1
                    else:
                        end = mid
            return ctr
How to add push notification in a Next/React JS App?
Tags: webdev, javascript, react, nextjs
Published: 2022-06-18 10:26:01

Hello friends, Today in this post we will see how we can setup onesignal push notification with our React/NextJS application. Web push notification is the best channel to enhance user engagement, product lauch, offers & sales, etc. Unlike traditional channels like email, web push notification notify users quickly and drive traffic to your website. So I will be showing how I integrated OneSignal push notification in my website codewithmarish.com which is built on NEXT JS , optionally I will also mention the steps for React JS Apps to as the steps are very similar. Let's get Started.

You can see the live demo on our website homepage by searching for a post.

[CodeWithMarish | Become a FullStack Developer](https://codewithmarish.com/)

If you liked this please visit our website for reading this post
[Understanding Debounce by building an awesome search filter in NEXT JS](https://codewithmarish.com/post/how-to-integrate-push-notification-in-next-react-js-app)

Also please don’t forget to subscribe to our youtube channel codewithmarish for all web development-related challenges.

[Code With Marish | Youtube](https://www.youtube.com/channel/UCkPYmdVz8aGRH6qCdKMRYpA)

Posted with ❤️ from somewhere on the Earth
Como customizar o prompt do seu terminal
Tags: bash, linux, tutorial, terminal
Published: 2022-06-18 02:37:09

Salve, salve, camaradas!
Para quem usa Linux ou Mac o terminal é uma visão muito comum e familiar. Estamos acostumados a ver coisas como essa:

```
patricia@patricia-PC:~$
```
Comum, certo? Nome do usuário, nome do host e diretório atual. No entanto, você sabia que seu prompt poderia ser assim?

```
Se liga no comando muito louco que patricia vai rodar agora! > 
```
Se você não sabia, vem comigo!

### Variáveis de ambiente que controlam o prompt

Há 4 variáveis de ambiente que configuram o prompt

- **PS1**: Essa variável vai definir o que vai aparecer no prompt padrão.
- **PS2**: Essa variável vai definir o que vai aparecer quando seu comando tiver múltiplas linhas (por exemplo num comando `for`).
- **PS3**: Essa variável vai definir o que vai aparecer quando você usar o comando `select`. Não se preocupe muito com essa.
- **PS4**: Essa variável vai definir o que vai ser mostrado quando o bash for instruído a mostrar o stack trace de um comando. Não se preocupe muito com essa também.

Dessas variáveis, as que mais serão usadas são as PS1 e PS2, e a primeira muito mais que a segunda.

Bora customizar??

### Customizando o prompt

Em primeiro lugar, não fique com medo de "zoar" seu prompt. Qualquer mudança que você fizer é reversível.

Agora que estamos sem medo, vamos colocar a data atual no prompt.

```
patricia@patricia-PC:~$ PS1="\t $PS1"
20:00:05 patricia@patricia-PC:~$
```

Que que aconteceu aí?
Na primeira linha a gente modifica a variável `PS1` para receber o valor `\t $PS1`. Esse `$PS1` será expandido para o prompt atual, que no meu caso é `\u@\h:\w\$ `. Então o prompt vai ficar `\t \u@\h:\w\$ `.
Agora, como que `\t` virou a data? Essa é uma "variável" interna usada pro prompt.

- **\u** será expandido para o nome do usuário
- **\h** será expandido para o nome do host (até o primeiro ".")
- **\w** será expandido para o diretório atual (substituindo `/home/${USER}` por `~`)
- **\$** será expandido para `$` quando o usuário for comum e `#` quando o usuário for o "root"
- **\t** será expandido para a data no formato HH:MM:SS (formato de 24 horas)

Se você não gostar do que você fez, você pode ou tentar reconstruir o PS1 anterior ou simplesmente sair e voltar para o terminal. (Se você estiver usando um emulador de terminal, basta abrir uma outra aba ou fechar e abrir de novo).

[Aqui](https://tldp.org/HOWTO/Bash-Prompt-HOWTO/index.html) tem uma referência boa para ler mais sobre essas configurações, mas é bastante extensa e densa, então leia com coragem. [Essa sessão](https://tldp.org/HOWTO/Bash-Prompt-HOWTO/x157.html) e [essa sessão](https://tldp.org/HOWTO/Bash-Prompt-HOWTO/bash-prompt-escape-sequences.html) são as mais importantes!

Se quiserem, postem seus PS1's aqui embaixo nos comentários! (se mudarem PS2, PS3 ou PS4 mandem também!)

Um beijo!
GNU/Linux üzerinde Microsoft fontlarının kullanımı
Tags: font, microsoft, linux
Published: 2022-06-18 10:21:11

Özellikle arayüz sistemlerinde GNU/Linux dağıtımlarındaki en önemli sorun muhtemelen ofis belgelerinde kayma ve taşma sorunları olarak görülebilir. Bunun bir nedeni Microsoft Office ve diğer Ofis uygulamaları olduğu kadar, sistemde yer almayan fontlardan dolayı font değişimi sonrasındaki kaymalar olarak düşünebiliriz.

Oysa ki Microsoft’un çoğu fontunun kullanımı için bir problem [bulunmamaktadır](https://docs.microsoft.com/en-us/answers/questions/35519/the-legality-of-microsoft-fonts.html). Fakat tabi ki fontlar tamamen özgür lisanslarla lisanslanmadığı için detaylı kullanım için lisans sözleşmesini okumak gerekmektedir.

Microsoft TrueType core fontları
Özellikle Microsoft sistemlerde çok kullanılan fontlar Microsoft tarafından 1996 yılında “Core fonts for the Web” [projesi](https://en.wikipedia.org/wiki/Core_fonts_for_the_Web) olarak Web üzerinden kullanılabilmesine yönelik kullanıma başlanmıştır. Tabi ki bu proje özgür lisanslarla değil sahipli fontlara sahip. Ayrıca Microsoft bu projesini 2002 yılında lisans şartlarıyla ilgili problemlerden dolayı kapatmış.

Sahipli lisanslara sahip bu fontlar aşağıdaki gibi listelenebilir:

* Andale Mono
* Arial Black
* Arial (Bold, Italic, Bold Italic)
* Comic Sans MS (Bold)
* Courier New (Bold, Italic, Bold Italic)
* Georgia (Bold, Italic, Bold Italic)
* Impact
* Times New Roman (Bold, Italic, Bold Italic)
* Trebuchet (Bold, Italic, Bold Italic)
* Verdana (Bold, Italic, Bold Italic)
* Webdings

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

# ttf-mscorefonts-installer paketi

GNU/Linux sistemlerde, ki özellikle Debian tabanlı sistemlerde bu fontların indirilebilmesini sağlayan bir [paket](https://packages.debian.org/bullseye/ttf-mscorefonts-installer) **ttf-mscorefonts-installer** olarak isimlendirilmektedir.

Bu paketin içerisinde yukarıda bahsedilen fontların internet üzerinden indirilmesini sağlayan bir betik bulunmaktadır. Dolayısıyla internet erişimi olmayan bir ortamda paket çalışmamaktadır. Bu fontlar .exe olarak sourceforge sitesinde bir repo altında [bulunmakta](https://sourceforge.net/projects/corefonts/files/the%20fonts/final/) fakat indirildikten sonra TTF formatına [çevrilmekte](https://salsa.debian.org/debian/msttcorefonts/-/blob/master/update-ms-fonts) ve sonrasında işletim sistemi üzerindeki **/usr/share/fonts/truetype/msttcorefonts/** klasörüne taşınmaktadır.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5g74aj5jb8tmebotk207.png)
 

# Font özgürlüğü

Özellikle Times New Roman, Arial ve Courier fontları için özgür çeşitleri yapılmıştır. Bunun için [fonts-liberation](https://packages.debian.org/bullseye/fonts-liberation) isimli paket kullanılmaktadır. İsimlendirme olarak “Liberation” ismiyle ve Mono, Sans ve Serif tiplerini barındırmaktadır.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jqvifrkeap40rmdrls3a.png)
Newsletter Subscription using NEXT JS and Mailchimp API
Tags: webdev, javascript, react, nextjs
Published: 2022-06-18 10:07:29

Hello friends, Today in this post we will see how we can setup mailchimp newsletter subscription with our NEXT JS application. The Newsletter is one of the best way to engage with your audience as email communication is mostly preferred. So integrating newsletter in your website will help you in engaging with your audience or subscribers easily

I have implemented this in my website you can checkout in my website.
[CodeWithMarish | Become a FullStack Developer](https://codewithmarish.com)

Please read this post in my website to know how I implemented it
[Newsletter Subscription using NEXT JS and Mailchimp API
](https://codewithmarish.com/post/newsletter-subscription-using-next-js-and-mailchimp-api)

Also please don’t forget to subscribe to our youtube channel codewithmarish for all web development-related challenges.

[Code With Marish | Youtube](https://www.youtube.com/channel/UCkPYmdVz8aGRH6qCdKMRYpA)

Posted with ❤️ from somewhere on the Earth
Smallest Range I
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 10:00:47

You are given an integer array `nums` and an integer `k`.

In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`.

The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.

Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_.

**Example 1:**

**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.

**Example 2:**

**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.

**Example 3:**

**Input:** nums = \[1,3,6\], k = 3
**Output:** 0
**Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0.

**Constraints:**

*   `1 <= nums.length <= 104`
*   `0 <= nums[i] <= 104`
*   `0 <= k <= 104`

**SOLUTION:**

    class Solution:
        def smallestRangeI(self, nums: List[int], k: int) -> int:
            mn = float('inf')
            mx = float('-inf')
            for num in nums:
                mn = min(mn, num)
                mx = max(mx, num)
            return max(0, mx - mn - 2 * k)
hackerrank algorithms solution
Tags: python, datastructure, algorithms
Published: 2022-06-18 09:47:12

Given an array of integers, find the sum of its elements.
for example 

> if the array, arr = [1, 2, 3], 1+2+3 so return 6

## function discription
_Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer.

simpleArraySum has the following parameter(s):

ar: an array of integers

## input format
The first line contains an integer,n , denoting the size of the array.
The second line contains  space-separated integers representing the array's element
_

## solutions
// bin/python3
import math
import os
import random
import re
import sys

# we define a function to return an interger

def simpleArraySum(ar):
    # Write your code here
    x=0
    for i in range(0,ar_count):
        x += ar[i]
    return x
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    ar_count = int(input().strip())

    ar = list(map(int, input().rstrip().split()))

    result = simpleArraySum(ar)

    fptr.write(str(result) + '\n')

    fptr.close()

```

```
Range Sum of BST
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 09:30:41

Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg)

**Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15
**Output:** 32
**Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32.

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg)

**Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10
**Output:** 23
**Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23.

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 2 * 104]`.
*   `1 <= Node.val <= 105`
*   `1 <= low <= high <= 105`
*   All `Node.val` are **unique**.

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def inorder(self, root, low, high):
            if root:
                if root.val >= low:
                    self.inorder(root.left, low, high)
                if root.val >= low and root.val <= high:
                    self.total += root.val
                if root.val <= high:
                    self.inorder(root.right, low, high)
        
        def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
            self.total = 0
            self.inorder(root, low, high)
            return self.total
How does people know when you have opened an email?
Published: 2022-06-18 09:14:12

I think the image links are uniquely named so that when we open email, the image gets loaded from the link. This way the sender know that the email has been received.

Workaround: By default do not enable images for emails. Then you will be asked whether to display images or not from a sender.

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