teleren/devto huggingface dataset:
Paracetamol.test.js🧪| #3: Testea este código JavaScript
Tags: javascript, testing, webdev, jest
Published: 2022-06-14 23:54:43

## **<center>Testea el siguiente código JavaScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark></center>

```js
//index.js
export const saludo = (nombre) => {
  return `Hola ${nombre}`;
};
```

```js
//operaciones.test.js
test('Debe regresar Hola Juan', () => { 
  const respuesta = saludo("juan");
  expect(respuesta).toBe("Hola Juan");
})
```

A. `❌ FAIL tests, Debe regresar Hola Juan`, `Expected: "Hola Juan", Received: "Hola juan"`
B. `✅ PASS tests, Debe regresar Hola Juan`

Respuesta en el primer comentario.

---
Diameter of Binary Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 23:30:36

Given the `root` of a binary tree, return _the length of the **diameter** of the tree_.

The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`.

The **length** of a path between two nodes is represented by the number of edges between them.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg)

**Input:** root = \[1,2,3,4,5\]
**Output:** 3
**Explanation:** 3 is the length of the path \[4,2,1,3\] or \[5,2,1,3\].

**Example 2:**

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

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 104]`.
*   `-100 <= Node.val <= 100`

**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 maxDepth(self, root):
            if not root:
                return -1
            a = 1 + self.maxDepth(root.left)
            b =  1 + self.maxDepth(root.right)
            self.md = max(self.md, a + b)
            return max(a, b)
        
        def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
            self.md = float('-inf')
            self.maxDepth(root)
            return self.md
Error: Cannot find module 'core-util-is'
Published: 2022-06-14 23:29:10

This npm error can be solved via another package manager, in this article we will solve it with the command


```
pnpm install --save core-util-is
```

If you dont have pnpm in youre environement please follow our article : [https://dev.to/mrhili/what-is-pnpm-2l87](https://dev.to/mrhili/what-is-pnpm-2l87)
What is pnpm?
Tags: pnpm, node, windows, linux
Published: 2022-06-14 23:21:13

{% embed https://www.youtube.com/watch?v=d1E31WPR70g %}


PNPM try to be fast and use symlink for duplicated files so try it

The fastest way to install pnpm is to have node.js  version  >=16.10

to do the easiest command:

```
corepack enable
```

if less

```
npm i -g corepack
```

if those command dont work and you are in windows use this command in powershell :

```
iwr https://get.pnpm.io/install.ps1 -useb | iex
```

in macOS or linux  using curl or wget , youre choice:

```
wget -qO- https://get.pnpm.io/install.sh | sh -
```

```
curl -fsSL https://get.pnpm.io/install.sh | sh -
```
Cómo borrar caché en Laravel 9*
Tags: laravel, artisan, php, cache
Published: 2022-06-14 23:16:37

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2y0na6a0q9z76j40kwhp.png)
[Ver tutorial completo en youtube](https://www.youtube.com/embed/0g326EbhO7E)
---
Ahora aprenderemos cómo borrar el **caché en Laravel**. Comando: php artisan cache: clear. Básicamente, hay dos formas de borrar el caché en Laravel uno a través de linea de comandos y el otro a través de rutas dentro de tu archivo web.php.

Si te enfrentas a este desafío, no te preocupes, ya que hablaremos sobre el comando borrar caché de Laravel, que se puede resolver con Artisan.

estos comandos son compatibles para las versiones de Laravel 6.x, 7.x, 8.x, 9.x, etc.

La **CLI Artisan de Laravel** puede borrar el caché no solo de vistas, sino también de rutas, configuraciones, etc. 
Veamos un ejemplo con una interfaz de línea de comandos (CLI) y Rutas.

##  - Borrar caché de aplicaciones
Ejecute el siguiente comando para borrar el caché de la aplicación de Laravel.

```
php artisan cache:clear
```

## - Para borrar el caché de ruta de su aplicación Laravel, ejecute el siguiente comando desde el terminal.

```
php artisan route:clear
```

## - Para borrar caché de configuración para borrar el caché de configuración de la aplicación Laravel.

```
php artisan config:clear
```

## - Borrar caché de vistas compiladas, borra los archivos de vista compilados, ejecute el siguiente comando desde la terminal.

```
php artisan view:clear
```

## - Borrar caché usando clase reoptimizada

```
php artisan optimize:clear
```

## Borrar caché en Laravel a través de rutas en el navegador web usando un sencillo script PHP
_La mayoría de los proveedores de alojamiento compartido no brindan acceso SSH al sistema. En este caso, puede borrar el caché de Laravel llamando a la URL en su navegador. Simplemente puede poner el siguiente código en el archivo route/web.php de su aplicación Laravel. Luego visite esta URL en su navegador para borrar el caché de la aplicación Laravel._

```
 //Clear route cache
 Route::get('/route-cache', function() {
     \Artisan::call('route:cache');
     return 'Routes cache cleared';
 });

 //Clear config cache
 Route::get('/config-cache', function() {
     \Artisan::call('config:cache');
     return 'Config cache cleared';
 }); 

 // Clear application cache
 Route::get('/clear-cache', function() {
     \Artisan::call('cache:clear');
     return 'Application cache cleared';
 });

 // Clear view cache
 Route::get('/view-clear', function() {
     \Artisan::call('view:clear');
     return 'View cache cleared';
 });

 // Clear cache using reoptimized class
 Route::get('/optimize-clear', function() {
     \Artisan::call('optimize:clear');
     return 'View cache cleared';
 });

```
Si llegaste hasta aquí no olvides compartir este post muchas gracias.
Rotate Image
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 23:00:40

You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).

You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.

**Example 1:**

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

**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]

**Example 2:**

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

**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]

**Constraints:**

*   `n == matrix.length == matrix[i].length`
*   `1 <= n <= 20`
*   `-1000 <= matrix[i][j] <= 1000`

**SOLUTION:**

    class Solution:
        def rotate(self, matrix: List[List[int]]) -> None:
            n = len(matrix)
            cache = {}
            for i in range(n):
                for j in range(n):
                    cache[(i, j)] = matrix[i][j]
            for i in range(n):
                for j in range(n):
                    matrix[j][n - i - 1] = cache[(i, j)]
Best macOS apps for boosted productivity
Tags: programming, macos, productivity, apps
Published: 2022-06-14 22:41:19

Here are some of my top recommended apps for developers to install to enhance their productivity.

- [iTerm2](https://iterm2.com/) - Terminal emulator
- [VSCode](https://code.visualstudio.com/) - Powerful text editor
- [Rectangle](https://rectangleapp.com/) - Move and resize windows
- [1Password](https://1password.com/) - Robust password manager
- [Discord](https://discord.com/) - Popular chat platform
- [Notion](https://www.notion.so/) - Feature rich notes
- [Raycast](https://www.raycast.com/) - Replacement for spotlight
- [Hidden Bar](https://github.com/dwarvesf/hidden) - Hide items from the menubar
- [Karabiner Elements](https://karabiner-elements.pqrs.org/) - Keyboard customizer
- [Dato](https://sindresorhus.com/dato) - Replacement clock for the menubar
- [System Color Picker](https://sindresorhus.com/system-color-picker) - Color picker that works anywhere

Feel free to comment your favorites below as well if they were not already listed 😬.
Overview of continuous Delivery
Tags: cicd, startup, circleci, git
Published: 2022-06-14 22:39:42

In a bid to deliver software solutions to costumers efficiently, companies are looking to inculcate techniques and practices that will improve the quality of their code and optimize the time and resources required for deployment. A popular approach these days is continuous delivery.

Continuous delivery is an approach where value is delivered frequently through automated deployments. It is often seen as a philosophy that facilitates the use of techniques that lets organizations build, test, and prepare code changes for release to production rapidly and efficiently. These techniques can be split in Continuous integration and continuous deployment. Continuous delivery practices can be directly translated to economic terms or metrics.

Continuous Integration is a practice where developers merge working copies to a shared mainline several times a day. This includes operations such as building artifacts, running tests and code analysis.
Continuous deployment is a practice where teams produce and release values a short time. This includes operations such as  deployment, verification and promotion to production.

These are some good practices to build a continuous delivery pipeline:
- Fail fast: This means the quicker we get to the error the less resources are wasted.
- Measure code quality: There should be metrics to measure the quality of code in our pipeline such as Lead time to production, and roll back rate.
- Only one road leads to production: All potential loopholes should be eliminated in order to utilize the pipeline.
- Maximum automation: We should automate tasks as much as possible to reduce human error and increase speed of delivery.

It should be noted that these continuous delivery practices should not be seen as an absolute pedestal but as true North that will help the organisation reach steady improvement.
CI/CD can be achieved with configuration tools like Ansible or chef and pipelines like CircleCI or Jenkins as well as version control tools like git.
Happy learning!
Create fake blockchaine to test youre smart-contract
Tags: smartcontract, ganache, etherium, node
Published: 2022-06-14 22:36:31

To create a fake blockchain wich you can test youre smartcontract written with Solidity you need Ganach software or a Ganache CLI.

Ganache is the latest version of TestRPC: a fast and customizable blockchain emulator. It allows you to make calls to the blockchain without the overheads of running an actual Ethereum node.

#Usage

Transactions are “mined” instantly.
No transaction cost.
Accounts can be re-cycled, reset and instantiated with a fixed amount of Ether (no need for faucets or mining).
Gas price and mining speed can be modified.
A convenient GUI gives you an overview of your testchain events.

To install ganache software visite this website : [https://trufflesuite.com/ganache/](https://trufflesuite.com/ganache/)

To get ganache-cli you need Node.js first


#Installation


Install it here: [https://nodejs.org/](https://nodejs.org/)


Ganache can be installed via NPM:

```
npm install -g ganache-cli

```
Using Ganache CLI
Command Line

```
$ ganache-cli <options>
```

#Note

If you have trouble using npm please try pnpm it save me alot.
I have a post discussing pnpm here: [https://dev.to/mrhili/what-is-pnpm-2l87](https://dev.to/mrhili/what-is-pnpm-2l87).
Largest Number After Digit Swaps by Parity
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 22:30:40

You are given a positive integer `num`. You may swap any two digits of `num` that have the same **parity** (i.e. both odd digits or both even digits).

Return _the **largest** possible value of_ `num` _after **any** number of swaps._

**Example 1:**

**Input:** num = 1234
**Output:** 3412
**Explanation:** Swap the digit 3 with the digit 1, this results in the number 3214.
Swap the digit 2 with the digit 4, this results in the number 3412.
Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.

**Example 2:**

**Input:** num = 65875
**Output:** 87655
**Explanation:** Swap the digit 8 with the digit 6, this results in the number 85675.
Swap the first digit 5 with the digit 7, this results in the number 87655.
Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.

**Constraints:**

*   `1 <= num <= 109`

**SOLUTION:**

    class Solution:
        def largestInteger(self, num: int) -> int:
            num = str(num)
            n = len(num)
            odds = []
            evens = []
            for i in range(n):
                if int(num[i]) & 1:
                    odds.append(num[i])
                else:
                    evens.append(num[i])
            odds.sort(key = int)
            evens.sort(key = int)
            op = []
            for i in range(n):
                if int(num[i]) & 1:
                    op.append(odds.pop())
                else:
                    op.append(evens.pop())
            return int("".join(op))
Day 67: Figma, Eish!
Published: 2022-06-14 22:26:04

Hi!
Today was all about Figma and mockup designs I was working on the user login and signup pages but Figma is so stressful and unnatural so I was so stressed the whole day, you have to think hard trying things back and forth Eish!! but I made some progress so it's not so bad. Sadly that will be the plan for the next few days therefore I won't be "coding" as often as usual but It will pass.
That's it nothing else to share 
Signing off...
Python Exercise 10: Generate a list based on odd or even index
Tags: beginners, python, exercise
Published: 2022-06-14 22:11:49

# Question
- Given two lists, l1 and l2, write a program to create a third list l3 by picking an odd-index element from the list l1 and even index elements from the list l2.

**Given**:

```python
l1 = [3, 6, 9, 12, 15, 18, 21]
l2 = [4, 8, 12, 16, 20, 24, 28]
```

**Expected Output**:

```python
Element at odd-index positions from list one
[6, 12, 18]
Element at even-index positions from list two
[4, 12, 20, 28]

Printing Final third list
[6, 12, 18, 4, 12, 20, 28]
```
# My solution
- use the list comprehension 
- use enumerate() function to generate index and value for each element in each list
- find the remainder of the index divided by two
	- if remainder is not zero mean an odd index
		- i.e. "if index % 2" is not equal to 0, so it would equal to True
	- if the remainder is zero mean an even index
		- i.e. if index % 2 is 0, so would equal to false
		- list comprehension only accept True condition,
		- so "not index % 2" is used

```python
l1 = [3, 6, 9, 12, 15, 18, 21]  
l2 = [4, 8, 12, 16, 20, 24, 28]  
odd_index_list = [num for index, num in enumerate(l1) if index % 2]  
print("Element at odd-index positions from list one")  
print(odd_index_list)  
  
even_index_list = [num for index, num in enumerate(l2) if not index % 2]  
print("Element at even-index positions from list two")  
print(even_index_list)  
  
final_list = odd_index_list + even_index_list  
print("Printing Final third list")  
print(final_list)
```
# Other solution
- use string slicing method
- for odd elements slice the string from index 1 to the end  with a step of 2
- for even elements slice the string form index 0 to the end with a step of 2

```python
list1 = [3, 6, 9, 12, 15, 18, 21]
list2 = [4, 8, 12, 16, 20, 24, 28]
res = list()

odd_elements = list1[1::2]
print("Element at odd-index positions from list one")
print(odd_elements)

even_elements = list2[0::2]
print("Element at even-index positions from list two")
print(even_elements)

print("Printing Final third list")
res.extend(odd_elements)
res.extend(even_elements)
print(res)
```

## Credit
exercise on [Pynative](https://pynative.com/python-data-structure-exercise-for-beginners/)
Binary Tree Paths
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 22:00:45

Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.

A **leaf** is a node with no children.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg)

**Input:** root = \[1,2,3,null,5\]
**Output:** \["1->2->5","1->3"\]

**Example 2:**

**Input:** root = \[1\]
**Output:** \["1"\]

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 100]`.
*   `-100 <= Node.val <= 100`

**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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
            op = []
            paths = [[root]]
            while len(paths) > 0:
                curr = paths.pop()
                if curr[-1].left or curr[-1].right:
                    if curr[-1].left:
                        paths.append(curr + [curr[-1].left])
                    if curr[-1].right:
                        paths.append(curr + [curr[-1].right])
                else:
                    op.append(curr)
            return ["->".join([str(node.val) for node in path]) for path in op]
AWS CloudFront on Rails
Tags: aws, cdn, rails
Published: 2022-06-14 21:57:43

Content Delivery Network is a useful tool to reduce the latency of delivering images, scripts, and stylesheets to your customer. Since we at Revealbot are using AWS as our cloud provider we decided to give Amazon's own CDN CloudFront a try. 

In this post I'll describe how to setup Rails and CloudFront to work with each other. 

On the Rails side configuration is pretty straightforward. To enable CDN we need to add one line to our production.rb config file:

```
config.asset_host = 'cdn.revealbot.com'
```

Now we need to set up CloudFront. Go to CloudFront [page](https://console.aws.amazon.com/cloudfront/v3/home) in the AWS console. Click on Create distribution. Fill in the Origin domain, with the site domain select protocol that CloudFront will use to access your sites.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28zl4q54iglng7br1ilr.png)
 
In the Settings tab enter the domain name that will be used as the CDN subdomain and request an SSL certificate to enable HTTPS.

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

Then click Create Distribution. It will take AWS a couple of minutes to roll up distribution to all regions, in the meantime, we can continue our setup. Click on created distribution and go to the Origins tab. Since we only want to serve our assets through CDN we can add additional "fake" origin `invalid.invalid` that will help us reject all requests except for assets.

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

Ok, almost done, now let's set up path rules, go to Behavior and create rules that will define how CDN is processing different paths. This is our current setup:

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

Notice that the Default (*) path is set to `invalid.invalid` that we set up earlier, this will prevent CDN from serving anything else besides assets - images, fonts, stylesheets, and js files.

And that's it, redeploy your production app and all assets will be served through CloudFront CDN.
Golang Fasthttp Middleware
Tags: go, middlewarer, fasthttp, http
Published: 2022-06-14 21:43:51

I am using [FastHttp](https://github.com/valyala/fasthttp) to implemente Http in go. Most people are using Gorilla Mux, but I decided to try a different http implementation.

There are scenarios where a request should chained, I mean, we must execute previous actions before handling the request resolver itself. The most common case is evaluating Authorization before executing the business.

Having said that, lets imagine a scenario where we must have an endpoint that must be protected by an Auth middleware, check for token and if its valid you can execute the business   otherwise you get a 401 http status.

First set up the router

```
router := fasthttprouter.New()
router.GET("/", GetProducts)
fasthttp.ListenAndServe(":5002", router.Handler)
```
The GetProducts is a function that simply respond with a product object. For example:

```
func GetProducts(ctx *fasthttp.RequestCtx) {

    product := &productModel.Product{}
    product.Id = "123890"
    product.Name = "Shoes"
    product.Price = 100.30
	
    json.NewEncoder(ctx).Encode(response)
}
```
Now we are going to create our Auth Middleware 

```
func Auth(requestHandler fasthttp.RequestHandler) fasthttp.RequestHandler {
	return func(ctx *fasthttp.RequestCtx) {
		token := string(ctx.Request.Header.Peek("Authorization"))

		if token == "" {
			return 
		} else {
		       requestHandler(ctx)
                }
	}
}
```

And now... we are going to wrap the GetProducts on router.Get method wit

```
router.GET("/", Auth(GetProducts))
```

So, if you get until here you may want to understand how it works.


-- add
Reach a Number
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 21:30:39

You are standing at position `0` on an infinite number line. There is a destination at position `target`.

You can make some number of moves `numMoves` so that:

*   On each move, you can either go left or right.
*   During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.

Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.

**Example 1:**

**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).

**Example 2:**

**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).

**Constraints:**

*   `-109 <= target <= 109`
*   `target != 0`

**SOLUTION:**

    class Solution:
        def reachNumber(self, target: int) -> int:
            target = abs(target)
            total = 0
            steps = 0
            while total < target or (total - target) % 2 != 0:
                steps += 1
                total += steps
            return steps
Instagram Advanced User Finder
Tags: instagram, webdev, github, php
Published: 2022-06-14 21:07:02

You can collect tens of thousands of users from 1 user with the features you are looking for on Instagram, collect phone numbers or e-mail addresses from their bio or communication, and then you can send them content with the text / HTML you want.
Github link : [https://github.com/suphiyasin/instagram-advanced-user-finder](https://github.com/suphiyasin/instagram-advanced-user-finder)
Can you test and evaluate?