teleren/devto huggingface dataset:
Making it Easier to Work With Local npm Packages
Tags: node, javascript, npm, todayilearned
Published: 2020-03-02 13:12:40

---
title: Making it Easier to Work With Local npm Packages
published: true
date: 2020-03-01 21:16:08 UTC
tags: nodejs,javascript,npm,til
canonical_url: https://www.aaron-powell.com/posts/2020-03-02-making-it-easier-to-work-with-local-npm-packages/
---

I was recently doing some work to fix a bug in the [Azure Functions Durable JavaScript package](https://github.com/Azure/azure-functions-durable-js) that required changing the surface area of an API. I'd done everything that I could to test it, I'd created a new sample, I'd added a unit test for the bug I'd hit and ensured it passed while not breaking the existing tests over the API, all that sort of thing. But I wanted to make sure that the change, while seemingly fixing my issue, would **actually** fix it, so I wanted to drop the code into project.

So I've got two git repos on my machine, one with my application in it and one with the updated Azure Functions code, and I want to use that over the package that would come down from npm when I do an `npm install`.

When you look at npm's docs it says that I should be using [`npm link`](https://docs.npmjs.com/cli-commands/link.html) to setup a symlink between the code I want and the `node_modules` folder in my application, but I've always struggled to get it working right, and that's probably because symlinks on Windows aren't quite as simple as on \*nix (and maybe I've been burnt too many times to trust them! 🤣).

But, I found a simpler solution! It turns out that in your `package.json`'s `dependencies` (and `devDependencies`) rather than specifying a package version you can specify a file system path, like so:

```json
{
    ...
    "dependencies": {
        "durable-functions": "file:../azure-functions-durable-js",
        ...
    }
    ...
}
```

This path that I've set is the path to where the `package.json` for the dependency lives and by using `file:` it tells the dependency resolver to look for a file system path rather than a locally referenced package. Also, `npm install` knows not to download something from the registry.

Using this pattern can also be useful for doing samples within a repo as the sample can refer to the package by name (doing `import something from 'my-package';`) rather than using using paths within the sample files (`import something from '../../';`) which can make the samples match better with how someone would consume the package.

It can also be useful to test out if your change does fix the bug that you've found by redirecting where your project resolves and not changing your codebase itself.

I hope this has been a helpful tip and can make it easier for you to work with local packages and also make it easier to test fixes you want to contribute. There's more information on [npm's docs](https://docs.npmjs.com/files/package.json#local-paths) about this and the other kinds of special paths you can define, such as git repos and HTTP endpoints.
12+ ways to Fibonacci 
Tags: javascript, solidity, computerscience
Published: 2020-03-01 20:51:12

This morning I came across a great [little paper](https://arxiv.org/abs/1803.07199) showing twelve algorithms to compute Fibonacci numbers in Python. I had to share!


Calculating fibonacci numbers recursively is used to [benchmark computer languages](https://github.com/drujensen/fib) and sometimes by interviewers trying to impress job seekers. More importantly, it inspired one of the [greatest songs](https://www.youtube.com/watch?v=uOHkeH2VaE0) ever so it's worth remembering a few of these algorithms and spiral out :o)

Not to repeat the python examples from the paper, let's instead look at four ways to compute the fibonacci number of N in Javascript. 

````javascript
//ES6

// using recursion
const fibonacci = n => n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);

// using cache
const fibCached = (n, cache = {1: 1, 2: 1}) => cache[n] ? cache[n] : cache[n] = fibCached(n - 1, cache) + fibCached(n - 2, cache);

// using tail recursion
const fibTailRecursed = (n, sum = 1, prev = 1) => n <= 2 ? sum : fibTailRecursed(n - 1, sum + prev, sum);

// using Binet's formula
const fibBinet = n => Math.floor( (((1 + Math.sqrt(5)) / 2 ) ** n) / Math.sqrt(5) + 0.5);
```

This very interesting formula discovered by [Binet](https://en.wikipedia.org/wiki/Fibonacci_number#Binet's_formula) had caught my eye a few years ago when I [found out](https://medium.com/coinmonks/fibonacci-in-solidity-8477d907e22a) it could be used in Solidity smart contracts. 

The Ethereum Virtual Machine is a resource constrained environment where every operation is metered and payed for, which discourages using recursion or iteration, but understanding it in depth does make one a better programmer imho.


````javascript
//Solidity v0.5+

function fibBinet(uint n) external pure returns(uint a) { 
    if (n <= 2) return 1;   
    
    uint h = n / 2; 
    uint mask = 1;

    // find highest set bit in n
    while(mask <= h) mask <<= 1;
    
    mask >>= 1;
    a = 1;
    uint b = 1;
    uint c;

    while(mask > 0) {
        c = a * a + b * b;          
        if (n & mask > 0) {
            b = b * (b + 2 * a);  
            a = c;                
        } else {
            a = a * (2 * b - a);  
            b = c;                
        }
        mask >>= 1;
    }
    return a;
}
```

Definitely not as elegant as the ES6 fat arrow version but this is because  of how Ethereum [type system](https://solidity.readthedocs.io/en/develop/types.html#fixed-point-numbers) works.
vuejs or react 2020
Tags: vue, react, javascript, vscode
Published: 2020-03-01 20:25:14

Vuejs is better than React when smaller, flexible and faster applications are required. When there is a requirement for a lightweight, faster, and modern UI library for crafting a topnotch SPA (single-page application), one must use VueJs. This is beneficial for developers who are used to working with HTML.
Front-end roadmap 2020:
Tags: vue, php, css, javascript
Published: 2020-03-01 20:23:10

Download VSCode, setup your fav terminal, install Chrome, have a decent internet.

- HTML, CSS, JavaScript (core concepts, please don't skip them)
- SASS, ES6 (and above)
- Prettier, ESLint (please learn to configure them)
- git (please learn the other commands)
- Webpack (just understand what it is & what it does)
- React, Vue or Svelte (Pick one)
- CSS in JS (Styled-components or emotion)
- Gatsby, Next or Nuxt, Gridsome (dunno about Svelte frameworks) (Please stop using CRA when your web app is meant to be used by the public)
- ZEIT now, Netlify & other static hosting cloud platforms
- Headless CMS like Contentful, Wordpress etc...
- Serverless functions
- PWA, AMP
- SEO
- a11y
- i18n

⚠️ Avoid continuously jumping to hypes, keep coding more than talking

With everything above, you'll become a JAM stack engineer actually and you will able to build scalable web apps without the need to learn anything related to backend development, databases & Devops.

Paying those services costs less than paying a full engineering team.
Contributing to JS/React Open Source ♡
Tags: react, testing, javascript, opensource
Published: 2020-03-01 20:22:35

Hi everyone 👋 I've been writing Open Source for ~10 years and it has been immensely useful for me in many ways, so I'd love to help others get started. I have prepared [`react-test`](https://www.npmjs.com/package/react-test) so that anyone who knows the basics of Javascript can contribute. The library looks a bit like jQuery+React together:

```js
import $ from "react-test";

it("increments the counter when clicked", async () => {
  const counter = $(<Counter />);
  expect(counter.text()).toEqual("0");
  await counter.click();
  expect(counter.text()).toEqual("1");
});
```

While it is not an official facebook/react project, I think it'd be pretty cool for others to have a project like this on their resume while learning how to contribute to Open Source. So I've been writing the [Getting Started](https://github.com/franciscop/react-test/blob/master/readme.md#getting-started), [Contributing guide](https://github.com/franciscop/react-test/blob/master/Contributing.md), and prepared few [beginner-friendly issues in Github](https://github.com/franciscop/react-test/labels/good%20first%20issue).

I will be helping anyone who wants to contribute, in general the methods are similar to [jQuery](https://api.jquery.com/)/[Umbrella JS](https://umbrellajs.com/documentation), so please follow that API where possible. If you have any question, please just ask anything in Github.

I am working fulltime so I will only be able to help few hours per day, but I will definitely get back at you. For me this is more work than implementing those methods myself, but it's also a lot of fun helping others and seeing people improving and contributing to projects.

So please come over to the issues, ask questions and send a Pull Request. I'll be over here helping:

[**Good First Issue**](https://github.com/franciscop/react-test/labels/good%20first%20issue)
Kafka: quantas partições por tópico?
Tags: kafka, confluent, brasil, kafkabr
Published: 2020-03-01 19:19:22

Umas das grandes dúvidas ao utilizar o Kafka é saber quantas partições são necessárias ao criar novos tópicos. Bem, não existe uma fórmula geral, o que temos é uma aproximação detalhada neste excelente artigo [How to choose the number of topics/partitions in a Kafka cluster?](https://www.confluent.io/blog/how-choose-number-topics-partitions-kafka-cluster/), escrito por Jun Rao. Outro artigo muito relevante é o [Benchmarking Apache Kafka: 2 Million Writes Per Second](https://engineering.linkedin.com/kafka/benchmarking-apache-kafka-2-million-writes-second-three-cheap-machines), escrito por Jay Kreps. Nele são revelados resultados importantes sobre a taxa de transferência para _producers_ e _consumers_.

Então, com base no artigo de Jun Rao, temos a fórmula aproximada para determinar o número de partições:


```
  MAX(t/p, t/c)
```

Onde:

- `t`: taxa de transferência desejada
- `p`: taxa de transferência do _producer_
- `c`: taxa de transferência do _consumer_

Como o artigo sugere, o valor para a taxa de transferência do _consumer_ depende de como ele processa os registros e por esse motivo devemos realizar nossas próprias medições ao invés de utilizar o valor-base descrito no artigo de Jay Kreps. Já para o valor referente ao _producer_, podemos tomar como base àquele revelado pelo artigo.

> Uma dica é você realizar todas as medições, assim você também entenderá como é a sua infra kafka.

## Aplicando a fórmula

Primeiro temos de definir qual é a unidade da nossa taxa de transferência, que poderia ser MB/s ou Mensagens/s. Mas as mensagens tem tamanhos variados e utilizá-las nas medições talvez não conduza a resultados realistas, então, `MB/s` é uma boa unidade de medida para aplicação da fórmula.

- Unidade: `MB/s` (megabytes por segundo)

A medição é realizada empregando um _producer_ e um tópico com apenas uma partição. Então, digamos que o resultado para nosso `p`, foi:

```
89 MB/s
```

A medição para taxa de transferência do _consumer_ é similar, ou seja, apenas um tópico com uma única partição. Então, digamos que o valor de `c` é:

```
75 MB/s
```

Imagine que nosso alvo com relação a taxa de transferência seja `450 MB/s`. Aplicando a fórmula de aproximação temos:

```
p = 89
c = 75
t = 450

  MAX(450/89, 450/75)

  MAX(5.1, 6) = 6
```

Portanto, o número de partições é `6`.

> Notadamente, não trata-se de uma fórmula para qualquer caso de uso, porém, agora temos um ponto de partida e não somente números mágicos.

Realize testes e coloque nos comentários quais foram os resultados, suas observações são valiósas.

Até o próximo artigo!
A bit of git.io url fun for your sunday
Tags: git, github, url, fun
Published: 2020-03-01 18:28:49

I was bored and browsing around today and happened to find this old [gist](https://gist.github.com/defunkt/1209316) from GitHub's cofounder for generating a more personalized git.io url

I thought it was cool — _although for some reason the script wasn't working for me_ — so I just extracted the important part:

```bash
curl -i https://git.io -F 'url=<YOUR_GITHUB_URL>' -F code=<YOUR_CODE>
```

Then it occurred to me I could just use a `#` identifier used for scrolling to generate a more ~~_useless_~~ personalized fun url for myself

Try going to [https://git.io/fifo](https://git.io/fifo)

Hopefully you see this cool greeting like I do in Firefox

![👋](https://dev-to-uploads.s3.amazonaws.com/i/qtypu4vmfucumo336f0s.png)

Anyways, all I had to do was get the url encoded value of the 👋 emoji which is `%F0%9F%91%8B` and use that in the curl request

```bash
curl -i https://git.io -F 'url=https://github.com/this-fifo/#%F0%9F%91%8B' -F code=fifo
```

Hope you enjoy your sunday!

ʕ •ᴥ•ʔ
Using Mixins with PugJS
Tags: javascript, pugjs, express, node
Published: 2020-03-01 18:27:38

This post is the fifth in a short series on using the PugJS templating engine with nodejs and expressjs. In the [last part](https://dev.to/nkratzmeyer/using-includes-partials-in-pugjs-19fa), I covered using using "partials" in PugJS. In this post, I will demonstrate how to use Pug to create reusable blocks of code with mixins. Let's get started! 

## Starting Code
For brevity, I won't list our starting code here. To follow along, be sure your code is up to date with the [last part](https://dev.to/nkratzmeyer/using-includes-partials-in-pugjs-19fa). Final code is on GitHub [here](https://github.com/nkratzmeyer/pugjs-articles).

## Adding a Mixin
Let's say you have a form element that you want to use in multiple places throughout your application. Furthermore, let's say you want to be able to style the form independently in each place. How might we do this? We could probably figure out a way to do this with conditional logic as described in part 3. However, this would probably not be the most efficient way to go about it. This is an excellent use-case for PugJS mixin functionality documented [here](https://pugjs.org/language/mixins.html). We're going to skip some of the basic examples and go to a slightly more advanced one, using attributes in mixins. First, let's create a partial file to declare our mixin. Under the **partials** folder, create a new file called **mixins.pug** with the following content.
```
mixin user-form
    form(action="/", method="post" class!=attributes.class)
        input#user-email(type="email", name="user-email")
        button(type="submit") Submit
```
Here we've **declared** our user form mixin. The interesting part is **class!=attributes.class**. As described in the Pug docs, mixins get an implicit 'attributes' argument which we will use to add attributes to our form. Now let's put our form to use. In **main-layout.pug**, at the very top above the DOCTYPE declaration, add this line:
```
include ../partials/mixins
```
This will give us access to our mixin from any file that extends **main-layout**. In **index.pug** add the mixin by adding this line to the bottom of the file (be sure to indent properly):
```
    +user-form
```
Now if you visit the home page in your browser, you should see your form at the bottom of the page. Notice that there is no class added to the form. Now let's add the form in a different spot and give it a class. In **about.pug**, add the following as the last line of the file. 
```
    +user-form()(class='modal')
```
With this usage, we have specified that we want to apply a class of 'modal' to the form. Now if you visit the 'about' page, you should see the form with the correct class applied. 

## Conclusion
In this post I've gone over using mixins with PugJS. We've seen how to create reusable blocks of code to which we can apply different attributes depending on context. 
Hope this was helpful and corrections/comments/critiques are welcome!
react router v5 multiple layouts
Tags: react, layout, multiple
Published: 2020-03-01 18:13:46


[Repository Github](https://github.com/xavivzla/multi-layout-react-router-v5)

# React Router V5 multiple layouts


If you want to test the project you can go to this  [![Edit React Router V5 Multiple Layout](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/react-router-v5-multiple-layout-d5yfw?fontsize=14&hidenavigation=1&theme=dark)  or clone the repository

```bash
  yarn or npm install
```

with this router structure the re-rendering that is caused when changing routes is avoided

In this demo we have two layouts:
  - Admin
  - Main

The routes
  - /
  - /about
  - /login
  - /admin
  - /admin/setting

### Example file router


```javascript

import React from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

import Main from '../containers/layouts/Main'
import MainAdmin from '../containers/layouts/MainAdmin'

// views
import About from '../containers/views/Main/About'
import Home from '../containers/views/Main/Home'
import Login from '../containers/views/Main/Login'

// admin Views

import Dashboard from '../containers/views/Admin/Dashboard'
import Setting from '../containers/views/Admin/Setting'


export default () => {

  return (
    <Router>
      <Switch>
        <Route path='/login' component={Login} />


        <Route path='/admin/:path?' exact>
          <MainAdmin>
            <Switch>
              <Route path='/admin' exact component={Dashboard} />
              <Route path='/admin/setting' component={Setting} />
            </Switch>
          </MainAdmin>
        </Route>
        
        <Route>
          <Main>
            <Switch>
              <Route path='/' exact component={Home} />
              <Route path='/about' component={About} />
            </Switch>
          </Main>
        </Route>


      </Switch>
    </Router>
  )

}
```

### structure folder routers

```bash

  └── src
      ├── components
      │   └── Common
      │       ├── Header
      │       └── Footer
      ├── containers
      │   ├── views
      │       ├── Main.jsx
      │       └── MainAdmin.jsx
      │   └── views
      │       └── Admin
      │           ├── Dashboard
      │           └── Setting
      │       └── Main
      │           ├── About
      │           ├── Home
      │           └── Login
      ├── routes
      │   └── index.js
```

[![Edit React Router V5 Multiple Layout](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/react-router-v5-multiple-layout-d5yfw?fontsize=14&hidenavigation=1&theme=dark)
Celebrating My Wins of Feb 2020
Tags: career, webdev
Published: 2020-03-01 17:46:24

![janitor saying "so ready for a new job"](https://media.giphy.com/media/ZDtmE6Sk2EoUFhDgRa/source.gif)
#My wins of February are...

* Taking the initiative of turning web development as a hobby to web development as a career.

* Taught myself Docker so I could transition deploying my apps from Heroku to DigitalOcean (Saving a bunch of money each month)

* Attended a coding meetup where I actually engage with other members

* Created my portfolio design from scratch and deployed a pixel-perfect copy that was mobile responsive.

* Sent out my first resume

-----

Web development has been a hobby of mine for the past 4 years. I have some "client" work in the past, but most of my projects on Github are really just crazy experiments from the result of exploring and learning web development. Because I am self-taught, imposter syndrome really affected me. It wasn't until I attended a coding meetup that I got cured. I got to talk to so many amazing developers while feeling confident in my web dev knowledge, as well as feeling like this is an environment I belong in.

------

I am currently trying to improve my resume and portfolio in hopes of getting at least one interview. I can code, solve algorithms all day, but I now want the experience to confidently present myself as a great candidate for a web development position under pressure.
Python ord and chr
Tags: python, beginners
Published: 2020-03-01 17:43:43

Converting the character into encoded ascii or unicode can be done with ord() and chr(). <a href="https://en.wikipedia.org/wiki/Ascii_table">Ascii</a> is very old computing standard, which gives every latin character a number in the computer.

The ascii table is shown below (you may note non english characters are missing, this is because at the time computing was mostly a US thing)

![ascii table](https://dev-to-uploads.s3.amazonaws.com/i/rsgyi52di0qfuiidcb1y.png)

You can convert python text characters into ascii character values.
In the conversion process, you can use the methods ord() and chr()

```python
>>> print(ord('a'))
97
>>> print(chr(97))
a
>>>
>>> # reverse order
>>>
>>> print(str(ord('a')))
97
>>> print(chr(ord('a')))
a
>>>
```

You can also do this for <a href="https://pythonbasics.org/strings/">strings</a>:

```python
>>> s = "hello"
>>> for item in s:
...     print(ord(item))
... 
104
101
108
108
111
>>> 
```

In practice you'll likely not be using ascii tables so much, as Python is a high level programming language. This was very common during the early days of computing but now rarely is used. However, it's good to know about it.
which education program I should choose to become Frontend web developer?
Tags: degree, frontenddeveloper, webdesigndegree
Published: 2020-03-01 17:29:03

I'm from India, 
My problem is that I can't decide which education program I should choose.
I was thinking to purse computer science degree but I don't want to learn back end languages or programming languages.
Does computer science degree help me to become front end developer?
If not then what degree should I purse?
Chaining async await API calls in Redux
Tags: redux
Published: 2020-03-01 16:53:44


## Chaining async await API calls in Redux

![](https://cdn-images-1.medium.com/max/10954/1*CRnXksTZ2wN8XC1_CUSUPw.jpeg)

While learning Redux I encountered several problems from which I will share the solutions to you in this article.

Let’s say you want to fetch data from the Pokémon API [https://pokeapi.co/](https://pokeapi.co/) using Redux.

Example: [https://master.d1or1a1srkom3l.amplifyapp.com/](https://master.d1or1a1srkom3l.amplifyapp.com/)
Github repo: [https://github.com/sanderdebr/pokedex](https://github.com/sanderdebr/pokedex)

We will handle these async API calls outside of our main reducers of actions, instead we will use Redux Saga.

Inside our saga we have a watcherSaga and workerSaga, everytime the action DATA_REQUESTED gets called it will fire our workerSaga which fetches the return of our API call.

Our fetch function fetchAll() is an async function that retrieves a list of pokemon names. Based on this list we retrieve details for every pokemon by nesting API calls within fetchAll(). The function returns aPromise.all object that contains nested fetches described in another function called fetchPokemon().

Besides that I’ve included a timer that returns the milliseconds it took to fetch the data.

{% gist https://gist.github.com/sanderdebr/18b04a121c61df2013b9f9c7d90b460d %}