teleren/devto huggingface dataset:
How To Improve Your Developer Experience (DX) With React, Hooks And Redux-Toolkit (rtk)
Tags: react, redux, reduxtoolkit, cleancode
Published: 2021-07-04 17:29:21

In few of my [previous articles on React Hooks] I mention how I'm using hooks (in my practicing english reading app - [ReadM]) to encapsulate features and making it reusable in apps. I consider state to be an important feature in app - and that's why I prefer to have some kind of a central state management that the client code can speak with as one source of truth.

Nowadays, Redux is still **my** preferred solution for front end central state management. Some of its benefits I appreciate include:

1. Well designed implementation
2. Maturity
3. Integrated Devtools
4. Community
5. Extendability

With Extendability, a while back, the team introduced **Redux-Toolkit** - taking redux usage to a higher level and making it simpler and developer friendly - or what i like to call - a great Developer Experience in the same way as User Experience (where the user is the developer).

[Read the rest of this article on my blog].

[Read the rest of this article on my blog]: https://orizens.com/blog/how-to-improve-your-developer-experience-(dx)-with-react-hooks-and-redux-toolkit-rtk/
[previous articles on react hooks]: https://orizens.com/tags/hooks
[ReadM]: https://readm.netlify.app
Dump tmux pane history to a file
Tags: tmux, shell
Published: 2021-07-04 17:22:00

Consider you have executed a long lasting command that produced many lines of output; or that you were trying to reproduce a non-deterministic issue with your software that has finally reproduced, and you have hundreds of log lines to analyze. The problem is you forgot to redirect the output to a file 😒.


Your terminal can help to dump its buffer to a file. Alternatively you can select and copy all the lines manually but that is inconvenient and error prone. Another option is to take advantage of terminal multiplexer capabilities, in case you are using one.


With `tmux` you can save last `N` lines of current pane to a file with two consecutive commands:


```tmux
:capture-pane -S -N
:save-buffer ~/filename
```

Replace `N` with desired number, or capture whole pane history with `:capture-pane -S -`.
That can be reduced to a single command when you invoke the `capture-pane` from the command line, like this:


```bash
tmux capture-pane -pS -10000 > ./last-10000-lines.out
```


Or this:


```bash
tmux capture-pane -pS - > ./pane-history
```


Another advantage of using command-line version is that you can store it as a function or alias in your shell, like in bash:


```bash
alias tmux-save-pane='tmux capture-pane -pS -'
```


Now the use is really simple:


```bash
tmux-save-pane > ~/tmux-pane-history
```


That command has helped me in trouble many times, I hope you also find it useful. If you are not using a terminal multiplexer, I really advise to start using one. `tmux` is the multiplexer I use, but as a `vim` addict I can't live with the default `C-b` prefix. First thing to do in my [.tmux.conf](https://github.com/maniowy/dotfiles/blob/master/.tmux.conf) is to change the binding to `C-a` 😉.
All the things you need to know about the GitHub Copilot !
Tags: github, webdev, javascript, python
Published: 2021-07-04 17:10:33

<h2>Q. So what is GitHub Copilot ?<br>
Q. Will it replace the developers with AI machines ?<br>
Q. Is it the start of the end?
</h2>


![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/arq4o93ogt7m6ko4w77g.png)


 

There can be many kind of things that you can say about it, here I can be a pragmatic man and say that its gonna take developer's jobs and I don't know one day it might even happen !!

*But its nothing happening anytime soon that's for sure !! 
So don't worry you and your jobs are secure.* 

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/itiiypa8rmzl2x29t0it.png)
 
<h1>But lets know what actually is GitHub Copilot !</h1>


###So Its is a **AI based application** that predicts your code by just reading the function name you have declared, it actually works by reading through all the open source code on the GitHub repos worldwide and then collect the data and tries to find the best possible code related to it !

###This Application is being developed by a company called Open AI. If you have ever used Kite/Tabnine as a AI extension in your IDE, you might have a slight idea about how the GitHub copilot works.

#As far as I know the GitHub copilot works on the algorithm *GPT-3*
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmu2jbz50s4r8nge1djg.png)

##*It is currently the one of "The" best algorithm in AI right now in the world if not the best.* 


At the end, I don't think its really that much threating right now, but you never know moving forward what does the future hold for you, in my opinion this AI based application will take a while to get really good at getting every code to the mark.
 
So Chill and keep CODING.


#HAPPY CODING 🚀
Playing with GitHub Co-Pilot
Tags: github, programming, tooling
Published: 2021-07-04 16:45:36

{% youtube I41wc24XVlA %}

This video is an abbreviated version of my Twitch live stream where we were playing with Github Co-Pilot.


Check out Github Co-Pilot at [https://copilot.github.com](https://copilot.github.com/?WT.mc_id=AZ-MVP-5003399)


Give me a follow on Twitch to watch me live: https://twitch.tv/talk2megooseman
Laravel Sessions with Vue.js
Tags: laravel, vue, typescript
Published: 2021-07-04 16:25:06

I'm working on an app that uses a Laravel REST API on the back-end and Vue.js 3 with Typescript on the front-end. My issue was keeping the session after a new request. I got it working with Postman, but it took me a while to figure out why it wasn't working with Vue.js. I didn't find much info on the web (maybe my search queries were poor) and what I found was  mostly about using Laravel Passport or Sanctum, but that's used with authentication and not necessary for my app. The session id gets stored in a cookie, but I didn't know in the beginning that Laravel actually handles setting the cookie for you when things are set up properly. These are the steps taken that ended up working. 

**Laravel:**

1) In Kernel.php add StartSession to the middleware:
```
$app->middleware([
    App\Http\Middleware\StartSession::class,
```

2) Set the session when calling the store endpoint in `SelectController`:

```
 public function store(SelectionRequest $request)
 {
        $userSelection = $this->objectRepository->getObjectByName($request->selection);
        Session::flush();
        Session::put("selection", $userSelection);
       ...
 }
```

3) In `config/cors.php` one needs to set allow supporting credentials:

```
'supports_credentials' => true,
```

**Vue.js with Typescript**

After comparing the header in Laravel of the Postman request and the Vue.js request I finally figured out that I needed to add `credentials: 'include'` to the Post request as Vue.js otherwise didn't send the cookie. This is the blog post that saved me: http://niraj-meegama.info/vue-js-cookie-not-set-request-headers (thanks Niraj!). 

I have this helper function in a TypeScript file called http.ts:
```
export async function post<T>(
    request: any,
    body: any
  ): Promise<T> {
    const response = await fetch(process.env.VUE_APP_BACKEND + request, {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Request-Headers': '*',
        'Access-Control-Request-Method': '*',
      },
      credentials: 'include',
      body: JSON.stringify(body)
    });

    return await response.json();
  }
```

Now everything works. If anything remains unclear or you know of a better way, then please let me know in the comments.
Day 131
Tags: 100daysofcode, programming
Published: 2021-07-04 15:59:46

Day 131/200 of #200DaysOfCode #100DaysOfCode 

- Solved two problems on Codewars.

1 -   Higher-Order Functions Series - Prepare the count of languages (7 kyu)
2 -   Higher-Order Functions Series - Can they code in the same language? (7 kyu)
Como a internet funciona?
Tags: beginners, ptbr
Published: 2021-07-04 15:52:04

Internet é algo que usamos todos os dias, mas nem todo mundo sabe como ela funciona ou pior, sabe, mas ainda não entendeu 😱

Partindo do contexto mais simples "uma rede de computadores mundial" que reflete claramente o símbolo escolhido para representar a internet 🌐. Mas quando pensamos o que é a internet na prática descobrimos alguns papeis fundamentais no processo: 

![Backbone para Provedores de acesso para Provedores de Serviço para sua Casa](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/33i1gex3zktrk7pfs83r.png)

Claro, existem outros serviços, como o [📌 VoIP](https://www.techtudo.com.br/noticias/noticia/2015/03/entenda-o-voip-tecnologia-que-permite-apps-ligarem-pela-internet.html) e o [📌 P2P](https://www.voitto.com.br/blog/artigo/o-que-e-rede-p2p), mas a ideia é entender o básico primeiro. 

Quando você envia uma mensagem através da internet, existe um identificador para onde aquele conteúdo precisa ir, através dos IP, seu dispositivo tem um, seu roteador outro e eles vão se completando, até o caminho final da sua mensagem [📌](https://www.youtube.com/watch?v=7_LPdttKXPc), e a resposta, faz o caminho inverso até você. O nome desse protocolo é TCP/IP, mas não é uma regra, muito do que usamos no dia a dia utiliza outros protocolos de comunicação como o UDP [📌](https://www.alura.com.br/artigos/quais-as-diferencas-entre-o-tcp-e-o-udp?gclid=CjwKCAjwuIWHBhBDEiwACXQYsUFHZSxLP7Q8mum13JaoJHEVpHwqQPe1jpWVb5wRdMTjk0L7k0TagxoCdZUQAvD_BwE), de forma bem resumida o TCP é mais confiável para no transporte de dados e o UDP é mais rápido, muito utilizado para streams e jogos online.

O identificador acaba sendo muito inviável de decorar, acabamos por decorar seu domínio, assim ao invés de chamar 142.250.218.110 podemos chamar google.com (que inclusive tem vários IP's diferentes para suportar o número de acessos).

---

Agora, você já está pronto para pesquisar mais sobre o assunto:

[📌 Tech Mundo](https://www.techtudo.com.br/noticias/noticia/2011/07/como-internet-chega-na-sua-casa.html)

[📌 Developer](https://developer.mozilla.org/pt-BR/docs/Learn/Common_questions/How_does_the_Internet_work)
Giving back
Published: 2021-07-04 15:38:55

Originally published on [mccricardo.com](https://mccricardo.com/giving-back/).

The last two and half months have been intense. Nine conference talks, starting on a new role and a lot of reading have consumed a lot of time. Talks in particular take a lot of time. From thinking about a topic, building the presentation, to practicing, a lot of effort goes into making something with enough quality to be accepted at a conference. Coupled with regular blogging, it's like having a second job. So, why do I do it? And more importantly, why should most of us give it a try?

## Paying it forward
Most of my career has been built on the shoulders of giants. Everything from open-source software, splendid blog posts, to videos on complex topics have helped me progress and getter better at what I do. It's only fair to contribute back and help others. While once upon a time I contributed directly to [a](https://github.com/mozilla-b2g/mozbench/graphs/contributors) [couple](https://github.com/mozilla-services/pulseguardian/graphs/contributors) of OSS projects, nowadays I feel I add more value by blogging and giving talks. I still do the occasional contribution now and then.

## Helping us learn
Blogging and giving talks also help us learn. Often when I want to learn about a topic I decide on giving a talk and/or blog about it. Curiously, the fact of forcing ourselves to explain something to people helps us reason more clearly about that topic as well as understanding it more deeply.

## Building a personal brand
Putting ourselves out there makes people aware of we who are and what we do. Over time we start to build a personal brand and get known by the value we provide. It can help our professional careers as well as our self-confidence.

## Impostor syndrome
"Impostor syndrome refers to an internal experience of believing that you are not as competent as others perceive you to be" and this one of the main reasons people don't blog or give talks. Fun fact: we don't have to be the supreme authority on a topic to deliver expertise on it; people will benefit a lot from our hard work and will thank us for it. 

## It's fun
If you're like me you'll always get a bit nervous once a new blog post gets published or your about to deliver a talk. That said, we learn to deal with that and it becomes fun. The benefits **seriously** outweigh the risks. It's hard work but it's fun!

## Why not give it a try?
We don't have to give a hundred talks a year or write a blog post every day. We can start small, see how it feels, see what works and what doesn't, find our niches. Over time things start to gain momentum and the whole world benefits from it.
Update LiveView for Alpine.js 101
Tags: todayilearned, phoenix, elixir, alpinejs
Published: 2021-07-04 15:24:34

Today I tried to upgrade Alpine.js V2 to the newly released [version 3](https://alpinejs.dev/) in one of my phoenix applications. As with major versions, the new alpine version introduces some [breaking changes](https://alpinejs.dev/upgrade-guide).

First, you need now to explicitly [start alpine](https://alpinejs.dev/upgrade-guide#need-to-call-alpine-start) with `Alpine.start()`.

```javascript
import Alpine from "alpinejs";
window.Alpine = Alpine;
Alpine.start();
```

Second, and this took me some time to figure out, as it is not documented on the changes page, you need to adapt how alpine [integrates](https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks) with LiveView. Before alpine elements had a property `__x`, that now changed so that you filter now for elements with the `_x_dataStack` property.

```javascript
let liveSocket = new LiveSocket("/live", Socket, {
  ...,
  dom: {
    onBeforeElUpdated(from, to){
      if(from._x_dataStack){ 
        window.Alpine.clone(from, to); 
      }
    }
  },
})
```

That's it! I hope this works for you as well and saves you some time.
AWS elb sticky session over IP
Tags: aws, elb
Published: 2021-07-04 15:17:44

Hi all,

I am facing a challenge in configuring sticky session on AWS ELB. The problem statement which I have is, I want sticky session over IP and not over application. What I mean by that is, if  a request is coming from same IP of a particular user , like even though browser tab/window change, the sticky session should work. 

In my application (which runs on say https://app.in), the authentication method uses third party app (which runs on say, https://auth.in). So when the login page loads, the session gets created at the server (say  box1 - one of EC2 boxes). The user clicks on login button and a new window pops up (with domain https://auth.in). The user now has to enter credentials details in https://auth.in and the verification request should go to box1 only (backend for auth and app both are running on all the boxes). But what is happening is, as soon I setup ELB, the session gets created at box1 but the verification request goes to Box2. Due to which the user never gets verified. 

Can this scenario be solved using sticky session? 

TIA.
Minha visão para APIs
Tags: javascript, database
Published: 2021-07-04 15:04:32

**API ( Application Programming Interface )**

**API, nada mais é, do que uma forma de expor as informações e/ou funcionalidades que ficam(ou não) dentro de um banco de dados.** Se ela for uma **API REST, é uma API que fica em "descanso" ou "em ponto morto", esperando apenas uma requisição ser feita para ela entrar em ação**. Como por exemplo: uma requisição que é feita para você fazer login. O back-end do site faz essa requisição, e se ela estiver dentro do banco de dados e tiver como uma API exposta, ela retorna com as informações que foram requiridas normalmente em formato **[JSON](https://twitter.com/lomar_newton/status/1411677984512151553)**.

Essas informações podem ser requiridas de diversas formas com os métodos: 

**GET - Pede dados de um objeto para a API.**

**POST - Cria um objeto com dados.**

**PUT - Atualiza necessáriamente todos os dados do objeto.**

**PATCH - Atualiza um ou mais dados do objeto.**

**DELETE - Exclui dados ou objetos.**
Deploy Express.js app to Vercel
Tags: javascript, vercel, express, node
Published: 2021-07-04 14:57:05

After research how to deploy Express.js app to [Vercel](https://vercel.com/). Finally, I found and got have an application has deployed to Vercel. It's take a lot of time from me but I am happy and hope this article will help something to you.

#### I. First of all, creating new Github repository and init new project nodejs.
![Clone and init project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j6r4hs7nu3c8x7lfieip.png)

#### II. Creating new project in `Vercel`
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hhyvrnx7wxef0oj9m04x.png)
 

#### III. Installing package `express` to nodejs app.
![install express package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evsbzwejqju0wg0aa02c.png)

#### IV. Creating and endpoint file `index.js` in root source.

![Creating index.js file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmpkaunf111gn6mgpw7g.png)

#### V. Creating APIs in `./api` folder or you can rename anything which you like.
- Here is an example for manage product from `./api/product`.

![API folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f5rpbgxcxbp9f9e24qen.png)

#### VI. Testing before commit source to Github.
![Testing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ov29bcq12r7glw72m2c.png)
- After testing is 👌. Commit them to git to see something awesome.

#### VII. Ready to serve in Vercel.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sdpe8aojr6mrpt1w2pvg.png)
 
#### VIII. Something went wrong in Vercel.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pthqgr98fg1ema8ky4dd.png)

- Because Vercel just supports API from Framework JS as NEXT.JS, Nuxt.JS,... So if we develop a standalone application we need to configure or tell the server of Vercel how is it work by vercel.json file.

#### IX. Add new `vercel.json` file to root source.
- Commit it to GitHub and make sure `version` is `2` - this is required from Vercel.

![Vercel.json file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oex8eqfvg0xuom4rp627.png)

#### X. Done, enjoy your moment.

Thanks for reading.
And I hope something good to you.
Here is [repository](https://github.com/hatuanem199801/express-vercel) which use in this post.

<a href="https://www.buymeacoffee.com/hte305" target="_blank">
![Buy me a coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ddtyyk0zuud3h7o0sjpq.png)
</a>

#### XI. Or you can follow this tutorial in youtube.
{% youtube C1Sf_ntbqZQ %}
Vim: The Best Way to Write Code?
Tags: vim, linux
Published: 2021-07-04 14:50:40

vim (aka Vi IMproved) is a highly efficient text editor that has inspired other editors like it, most notably [MacVim](https://github.com/macvim-dev/macvim) (which I will refer to as vim from here on) and [gVim](https://gvimeditor.blogspot.com/2013/03/gvim-basics.html).

You see, I use a code editor called Vim, which is sort of like an operating system for writing code.  I know it might seem bizarre, but there's a method to my madness:  Vim lets me write code very quickly and with very little effort. It's a great way of working that I wake up excited to do every day.  

![gvim](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9m0tgi719lt700g85z2z.png)

## Why vim?

Vim is one of the most popular text editors, which is why you’re either using it or wondering why you should be using it. But if you’re not a programmer, why should you care?

**It's a matter of preference**, but 

* You don’t have to open vim to write code

If you’re like us, you don’t want to have to switch between your text editor and your terminal while you write your code.

* You can use it over an SSH connection

This is a big plus. With a few commands you're inanother computer and can edit right away

* It works on all operating systems

Even the most obsecure operating systems support vim. Like some router with busybox installed

* It's completely controlled by key presses

You don't need to use the mouse, vim is controlled by key presses. However if you like clicking around, there's gvim.

Vim does have a steep learning curve, but you can practice vim on sites like [vim.is](https://vim.is/)
Adding FIREWALL to Docker
Tags: devops, docker, beginners, linux
Published: 2021-07-04 14:48:18

This is going to solve problems of many Devops engineers looking for Firewall Security for their containers. 

Following are my previous articles on Docker Security:

{%link https://dev.to/manishfoodtechs/why-hackers-first-love-a-docker-container-hacking-docker-l97 %}

and 

{%link https://dev.to/manishfoodtechs/rootless-docker-kick-docker-hackers-and-make-docker-more-secure-new-concept-70g %}

Docker does not prevent one from doing Host Firewall implementation; rather, it adds to the complexity. This guide is indented to add host firewall to docker.

###STEP 1
(a)Navigate to /etc/systemd/system/ and create a directory named docker.service.d 
(b) create a file noiptables.conf and add the following content:

```
[Service]
ExecStart=
ExecStart=/usr/bin/docker daemon -H fd:// --iptables=false
``` 
###STEP 2
(a) Restart Docker
(b) check iptables -L -n -v (If everything Okay you will not see any rules :) )

###STEP 3
(a) RUN apt-get install iptables-persistent

After running this, you will be prompted to save your IPv4, and then your IPv6 rules to two files, /etc/iptables/rules.v4 and /etc/iptables/rules.v6 respectively.

In order to give IPv4 Internet Access to all the containers, the server must perform NAT.To do that, in the beginning of the rules.v4 file, add the following:
```
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -o eth0 -j masquerade
COMMIT
And then below it, 
```
After you’re finished, your rules.v4 / rules.v6 file will look something like this:

```
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]

-A POSTROUTING -o eth0 -j MASQUERADE

COMMIT

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]

# Allow localhost
-A INPUT -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT

# ICMP
-A INPUT -p icmp -j ACCEPT

# Docker
-A FORWARD -i docker0 -o eth0 -j ACCEPT
-A FORWARD -i eth0 -o docker0 -j ACCEPT

# Incoming
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -j DROP

# Outgoing
-A OUTPUT -j ACCEPT

# Routing
-A FORWARD -j DROP

COMMIT
```
Of course, you must replace eth0 with your outbound network interface if it is different than eth0.
After you complete that, restart the firewall via netfilter-persistent reload, and you’re good to go!

##[Click here for joining my team](https://forms.gle/pSCALuEWHus3pg9F6)

######Read More [here](https://blog.daknob.net/debian-firewall-docker/)