teleren/devto huggingface dataset:
Lift webframework SameSite Cookie workaround
Tags: lift, scala, web, security
Published: 2021-04-06 00:30:45

**IMPORTANT:** This post is kept only as a reference, now Lift since the 3.5.0-SNAPSHOT version supports SameSite cookie, more info at https://github.com/lift/framework/pull/1990

---

## What ?

This is a sample code on how to add the SameSite value to HTTP cookies using Lift as an alternative until SameSite is officially supported at Lift and/or Servlet level.

## Why ?

Because the major browsers set the usage of SameSite as required nowadays for enforcing better security and if you want to call an API along with your Lift application you will need something to make SameSite cookies work, even as a workaround.

## How ?

Cookies are no more than text-based headers, so in this sample workaround we are just using Netty to encode the cookie (including SameSite) as a string and then added as a "Set-Cookie" standard header

## Where ?

At https://github.com/csaltos/lift-samesite-cookie-workaround

Please review the recent commits to check how it's done using Lift base cookies and how to then use them with Netty for leveraging the SameSite cookies.

## Guide

1. Clone this repo
2. Install and run sbt
3. Execute jetty:quickstart inside SBT
4. Go to http://localhost:8080 with your favorite browser
5. Click on the Set Cookie menu item to add a cookie value
6. Click on the Read Cookie to check the cookie value is correctly read

**NOTE:** At source code level please start at CookieSnippet.scala
Subtle Button (CLICK challenge)
Tags: codepen, css, ui, frontend
Published: 2021-04-06 00:19:34

<p>This is my very first submission to a Codepen challenge! I really didn't have the faintest idea about what I wanted to do when I received the email about the challenge, so I basically just tried a few things until I stumbled upon something I liked.</p>

{% codepen https://codepen.io/leacasas/pen/WNREemZ %}
Code review isn't just about code
Tags: codereview, pullrequest, practices, productivity
Published: 2021-04-09 11:04:48

---
title: Code review isn't just about code
published: true
date: 2021-04-06 00:00:00 UTC
tags: codereview, pullrequest, practices, productivity
canonical_url: https://jhall.io/archive/2021/04/06/code-review-isnt-just-about-code/
---

When you review a pull request, what do you look for?

Bugs? Misspelled words? Broken error handling? Missing unit tests?

That’s all fine and good. But there’s one aspect of pull request review that I think usually does not get enough attention: **Metadata**

![I never metadata I didn’t like](https://jhall.io/archive/images/metadata-meme.jpg)

The pull request title and description, as well as the individual commit messages (and each commit’s contents) are all important parts of a pull request, and deserve attention during a review.

To get you started thinking about this, here are some things I always look for when reviewing a PR:

- Does the content of the PR match the title?
- Does the PR description adequately explain the intention? (i.e. If you must ask for clarification, the description is probably lacking)
- Does the PR address one concern (i.e. a single bug fix, a single refactor, or a single feature)
- Does each commit message make sense in isolation? (i.e. “Bugfix” or “commit a missing file” don’t pass muster)
How to change the ownership of the file asynchronously in Node.js?
Tags: node
Published: 2021-04-06 00:00:00

---
  title: How to change the ownership of the file asynchronously in Node.js?
  published: true
  tags: Nodejs
  date: Tue Apr 06 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/change-ownership-of-file-asynchronously-nodejs
  cover_image: https://melvingeorge.me/_next/static/images/main-105a908dd74409cb91bf8f275be16e77.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/change-ownership-of-file-asynchronously-nodejs)
  
To change the ownership of a file asynchronously, you can use the `chown()` method from the `fs` (filesystem) module in Node.js.

Let's say I have a file called `myFile.txt` and want to change the owner from me to another user called `Roy`.

For example,

- The user `Roy` has the user-id (or `uid`) of `512`
- and the id of the group (or `gid`) to set ownership is `1000`.

So it can be done like this,

```js
// require fs module
const fs = require("fs");

// Change ownership of file
fs.chown("./myFile.txt", 512, 1000, (error) => {
  // in case of any error
  if (error) {
    console.log(error);
    return;
  }

  // otherwise show success message that ownership is changed
  console.log("Ownership of file has changed!");
});
```

The `fs.chown()` asynchronous method accepts 4 arguments:

- The first one is the `path` to the file.
- The second one is the user-id (or `uid`) of the user that needs to have ownership of the file.
- The third one is the group-id (or `gid`) that needs to have ownership of the file.
- The fourth argument is an error first callback function which will get executed after successfully changing the ownership of the file.

See the above code live in [repl.it](https://replit.com/@melvin2016/change-ownership-of-a-file-asynchronously-in-nodejs).

### Feel free to share if you found this useful 😃.

---
Breve introdução ao Machine Learning
Published: 2021-04-05 23:43:16

Machine Learning surgiu dentro da área de Computação Bio-Inspirada, que possui uma grande inspiração dentro da área da Biologia. Dentro dessa grande área de estudo, existem diversos algoritmos com inspiração na natureza, como: árvores de decisão, redes neurais, algoritmo genético, colônia de formigas, enxame de abelhas, etc. Entender como a natureza se comporta pode nos ajudar a entender como a máquina aprende. Ciência de Dados é uma junção de grandes dados, juntando grandes áreas do conhecimento como: Ciência da Computação, Matemática/Estatística e Domínio/Conhecimento de Negócio.

__Problema Supervisionado x Problema não Supervisionado__

Podemos dividir a área de Machine Learning em três grandes áreas do conhecimento, que são: __Aprendizado Supervisionado, Aprendizado Não Supervisionado e Aprendizado por Reforço.__

Dentro do __Aprendizado Supervisionado__, há duas grandes subcategorias, chamadas de: __Classificação e Regressão__. Na Classificação, seu objetivo é prever uma variável categórica e alguns exemplos dela são: retenção de clientes, diagnóstico, detecção de fraudes e classificação de imagem. Para a Regressão, seu objetivo é prever uma variável numérica e alguns exemplos são: previsão do tempo, estimativa de expectativa de vida, predição de aumento populacional e previsão de mercados.

Dentro do __Aprendizado Não Supervisionado__, há duas grandes subcategorias: __Clustering (Agrupamento)__ e __Redução de Dimensionalidade__. O __Clustering__ é utilizado para agrupar clientes, segmentar clientes, recomendar sistemas, entre outras coisas. A __Redução da Dimensionalidade__ é utilizada para visualização de Big Data, descobrir estruturas, entre outas coisas. O __Aprendizado por Reforço__ não é muito utilizado atualmente, possuindo um maior uso mais nas área de aprendizado de jogos e robótica.
As principais diferenças entre os tipos de problemas (supervisionados e não supervisionados) são:

· __Problemas Supervisionados__ = os registros da base de dados são acompanhados por "labels". Esses "labels" podem ser numéricos, no caso de problemas de regressão, ou categóricas, no caso de problemas de classificação.

· __Problemas Não Supervisionados__ = os registros de base de dados não são acompanhados por "labels". Nesse caso, não existe uma classe pré-definida para nenhum dos registros.

O nome __"Supervisionado"__ vem da possibilidade de supervisão no momento do aprendizado (ajuste) do modelo, possibilitado pelo histórico de valor real da coluna target, possibilitando uma acurácia bem maior que o modelo __Não Supervisionado__. Diferentemente dos __Problemas Supervisionados__, para __Problemas Não Supervisionados__ não temos uma coluna "target" nos dizendo com certeza o valor real do grupo que cada "ponto" pertence.
100 Bytes Of Wisdom: Day 38
Tags: career, journey, advice
Published: 2021-04-05 23:03:42

---
title: 100 Bytes Of Wisdom: Day 38
published: true
description: Bytes of Wisdom is a new project by Sam Jarman that brings together snippets of advice for software engineers
tags: career, journey, advice
//cover_image: https://direct_url_to_image.jpg
---

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xrm3b7lr4rq7g0p5mxw4.png)

Hmm, those two labels have the same value? That seems... unlikely? Ah yes, when I copy and pasted I didn't change the value it was meant to display.
I am *always* suspicious of duplicate, missing or unrealistic data on screen when I am testing, and when my spider senses tingle, more often than not, it's a bug. Being able to take yourself out of the developer seat and place yourself in the tester seat is a powerful tool for making quality work. Be suspicious. Be curious. 


Heads up: As with any terse bit of advice, there will be exceptions of course, and subtleties and nuance that can't possibly be captured in a Byte of Wisdom. This has been what I've experienced, I'd love to hear yours in the comments too!

You can catch up with all the other bytes at http://bytesofwisdom.com/
Where to actually find open source projects and how to approach them.
Tags: python
Published: 2021-04-05 22:44:54

People talk about contributing to open source. And I would like to. But I am not sure how to find good open source projects which need help. And if I did find one, I am not sure how to start https://trackeasy.fun/usps/.

Does anyone know a good open source python repo? If you had to contribute to it for the first time, what are a few things you would do step by step? I assume you need to fork the repository, make a branch, do something, and then see if the owner likes your changes?

Is there a website which people use to find a list of open source projects?

Thanks guys.
HTML CSS Portfolio Project.
Tags: html, css, portfolio, webdev
Published: 2021-04-05 22:35:17

This project is for HTML & CSS practice. AMY is a fictional character. She is a freelance web designer. We made this nice portfolio for her with mainly HTML & CSS. Though we used few lines of JS, the main purpose of this project is to practice HTML & CSS. We are going to learn lots of things link how to make it responsive, how we can make a nice off-canvas menu, CSS animations, CSS flex layout, and many more. Hope you will like this video. Also, You can get the source code from the link down below.

Source Code: https://github.com/ShaifArfan/AMYs-Portfolio
Check your Ruby Developer Level with simple task
Tags: ruby, challenge, rails, programming
Published: 2021-04-05 21:51:40

I just found an old post from @evanilukhin showing interview task - _Simple word calculator._ I was reading it on my mobile, so first I read his post, and decided to not look at the answer code (anyway it's impossible to understand on small android display).
{% post https://dev.to/evanilukhin/ruby-interview-tasks-simple-word-calculator-445d %}

Task is next: make this code work:
```ruby
one.plus.two.equal    # =>  3
one.minus.three.equal # => -2
```  
While you're on interview, it can be harder than it should be. Few minutes later electricity came back (some works during this morning... awful), so I decided to try to solve it (in his post I read it's good for every developer to check his skills... and it's true). You have a link to his post if you want to read it and see his results (probably better than mine, but hey, 10 minutes on android 5, and it works... :P).  

So what do you think, are you able to make this code work without reading the rest? Here's my solution (first one, fast one):  


{% collapsible My Answer %}
```ruby
  class One
    def initialize
      @num = 1
    end

    def plus
      @opt = :add
      return self
    end

    def minus
      @opt = :rmw
      return self
    end

    def two
      case @opt
        when :add then @num += 2
        when :rmw then @num -= 2
      end
      return self
    end

    def three
      case @opt
        when :add then @num += 3
        when :rmw then @num -= 3
      end
      return self
    end

    def equal
      num  = @num
      @num = 1
      return num
    end
  end

  one = One.new
  one.plus.two.equal    =>  3
  one.minus.three.equal => -2
```  
and about 10 minutes later I decided to make this more DRY, and to allow it to use 'one' chained more times (like original article code work)

```ruby
  class One
    def initialize
      @num = 1
    end

    def one
      use_number 1
    end

    def two
      use_number 2
    end

    def three
      use_number 3
    end

    def plus;  set_opt(:add) end
    def minus; set_opt(:rmw) end

    def equal
      num  = @num and @num = 1
      return num
    end

    private

    def set_opt(opt)
      @opt = opt; return self
    end

    def use_number(number)
      case @opt
        when :add then @num += number.to_i
        when :rmw then @num -= number.to_i
        else @num
      end
      @opt = nil
      return self
    end
  end

one = One.new
one.plus.two.equal # => 3
one.plus.two.minus.three.plus.one.equal => 1
```  
{% endcollapsible %}
We've created a 3D animated emoji set.
Tags: design, emoji, 3d, illustrations
Published: 2021-04-05 21:48:35

Hello community 👋

We created a 3D animated emoji set that can be wildly used for any project or product.

I am also open to some collaboration to bring the set further.

For example emoji keyboard.

More information, here: https://emojiz.design/
How do you describe your work to non-tech person?
Published: 2021-04-05 21:39:38

Hi everyone! As a freelance back-end developer in Argentina, where tech jobs are non-common yet or all are "build a software" for people, I am often challenged to explain in a simple way what I do.

I usually cite an analogy which is _"If web development were the automotive industry, I would be in charge of making or optimizing the engine for different cars of many brands."_

I don't think it's totally true, but people tend to understand it much better.

So now I want to know.
**What is your job and how do you describe it for a non-tech person?**
What was your win LAST week?
Tags: discuss, weeklyretro
Published: 2021-04-05 21:15:48

---
title: What was your win LAST week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

Hey!

Apologies for the lack of a weekly wins thread last week! Somehow I drafted this but forgot to publish it.

That said, it's never too late to celebrate your wins. Let's talk about what you're proud of from LAST week.

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Fixing a tricky bug
- Cleaning your desk ... or whatever else might spark joy ❤️ 

---

I'm looking forward to reading what you accomplished last week 🎉 

![Better Late Than Never](https://media.giphy.com/media/3oxHQM7gfxl8dI9Oso/giphy.gif)
Get server stats with bash
Tags: linux, bash, beginners, ubuntu
Published: 2021-04-05 21:11:36

This is script to get server stats printed in terminal and saved as txt output (or not). I will not explain each command, but for total beginners I will say that commands are piped with `I`, so take each command and use with `-h` in terminal to get more info.  

```bash
# example to get help for awk
awk -h

# commands are piped with |
# get free memory with 'free'
# output it to 'tail' to print last line
free -m | tail -n 1 
```  

So here's the full script, you can remove # at last 2 lines to save output and/or show notification on desktop.  

```bash
#!/usr/bin/env bash

#  Define Output Log-File (or not)

OUTPUT_LOG=~/sys-log.txt

#  Define Colors

  R="\e[0m" #reset
  U="\e[4m" #underline
  Y="\e[33m" #yellow
  RED="\e[37m" #light red

#  Format Date and Time

DATE=$(date +%m/%d/%Y)
TIME=$(date +%k:%M:%S)
DAY=$(date +%A)

#  User Logged In

USER=$(whoami)

#  System Uptime

UPTIME_S=$(uptime -s)
UPTIME_P=$(uptime -p)
UPTIME=$(uptime -s && uptime -p)

#  Free Memory

FREE=$(free -m | head -n 2 | tail -n 1 | awk {'print $4'})

#  Free Swap Memory

SWAP=$(free -m | tail -n 1 | awk {'print $3'})

#  CPU Idle

CPU=$(vmstat 1 2 | sed -n '/[0-9]/p' | sed -n '2p' | awk '{print $15}')

#  Free Disk Space

SPACE=$(df -h / | awk '{ a = $4 } END { print a }')

#  Define banner to print

  banner() {

    echo ----------------------------------------------------------------------
    echo -e "$RED" DAY: "$R"$DAY "$RED"'\t'DATE: "$R"$DATE "$RED"'\t'TIME: "$R"$TIME"$R"
    echo ----------------------------------------------------------------------
}

#  Define nice-print stats

  print_stats() {

    echo -e "$R"WELCOME:"$R"'\t|\t'"$Y"$USER

    echo -e "$R"UPTIME: "$R"'\t|\t'"$Y"$UPTIME

    echo -e "$R"FREE MEMORY:"$R"'\t|\t'"$Y"$FREE MB

    echo -e "$R"FREE SWAP:"$R"'\t|\t'"$Y"$SWAP MB

    echo -e "$R"CPU IDLE:"$R"'\t|\t'"$Y"$CPU %

    echo -e "$R"DISK SPACE:"$R"'\t|\t'"$Y"$SPACE
}

#  Define One-Line output log

  output() {

    echo "$DATE | $TIME | $USER | $UPTIME_S | $UPTIME_P | $FREE MB | $SWAP MB | $CPU % | $SPACE"
}

### ### ###

#  Execute Defined Functions

  clear && banner           # Print Banner

  print_stats               # Print Stats

#  output >> $OUTPUT_LOG     # Save Output (or not)

#  Display Desktop Notification

#  ALERT=$(notify-send -u normal "Free Space :  $SPACE   |   CPU USAGE :  $CPU %  |   Free Mem :  $FREE MB") && echo -e $ALERT
```  
![SysData Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2uc0pq7unwm70ib3a7kx.png)
Setting Up for Success: A Guide to ERD's
Tags: ruby, beginners, oop
Published: 2021-04-05 21:02:36

So, what is an ERD? To start, it stands for Entity Relationship Diagram, and it isn't actual programming. An ERD is the first step in setting yourself up for success in Object Oriented Programming (oop). As I began dipping my feet into the oop waters it quickly became clear that having a well organized plan of attack would set me up for success, this is where ERDs came in. 

In short, an ERD is a hand drawn diagram that represent relationships between objects in your program. Think of an ERD as an electrician's blueprint of how everything is connected under the hood. Your ERD blueprint will do the same thing.  Having the visualization of all of the methods needed for each class you create, and other data needed at initialization will save many head aches later down the road. 

ERD's are also important in helping other developers who may not be familiar with your project have an understand of relationships in your database. The best thing for readability is to stick to convention.

These are the notations that you should use in your ERD:
![ERD Cardinality](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ftnvlp89fwfau15gdseq.png)

 
So how does this all look when it's put together? ![Blank diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uwisybmdlbgnkdzoq7v3.png)
 

If we look at this diagram you can see that we have two classes, "User" and "Food". A User can eat many Food objects, and Food objects can be eaten by many User objects. These classes are joined by a "Meal" joiner object, a User eats many Food objects at a Meal. 

By using an ERD there is now a clear blueprint as to the data each class initializes with, the methods that will need to run on all of the classes, and the relationships that persist.

Is creating an ERD necessary? Maybe not, but hopefully this post will help you understand why it's important and how it will set you up for success on your next project.
Qué son los Closures en Javascript
Tags: javascript, closures, jsinterview
Published: 2021-04-05 20:50:54

Una de las cosas complicadas al empezar con Javascript es entender como funcionan los Closures, o al menos saber identificarlos, porque como ya habrán escuchado en videos o tutoriales, los usamos varias veces sin darnos cuenta.


Pero antes de adentrarnos en el código vamos a hablar de algunos temas importantes:

## Contexto de ejecución

En resumidas cuentas, es un lugar en donde se guardan 3 cosas importantes:

- El valor de this
- Lexical Environment
- Variable Environment

Pero estas dos últimas cosas son practicamente lo mismo, así que vamos a unirlos y llamarlo Lexical Environment.

En Lexical Enviroenment almacenamos nuestras variables con sus nombres y sus respectivos valores, el mismo caso es para las funciones, así que si tenemos el siguiente código:

```javascript
function nombre() {
    let a = 10;
    function imprimir() {
      console.log(a)
    }
  }
  foo()
```

Nuestro contexto de ejecución se vería algo así:


```javascript
execution_environment: {
  LexicalEnvironment: {
    a: 10,
    imprimir: function() {}
  },
  ValorDeThis: ...
}
```

## Lexical Scope

El lexical scope significa que en un grupo anidado de funciones, las funciones internas tienen acceso a las variables y otros recursos de su ámbito padre. Esto significa que las funciones hijas  están vinculadas léxicamente al contexto de ejecución de sus padres.
REF: [Link](https://somospnt.com/blog/120-scope-en-javascript)

Sabiendo todo esto, podemos decir que un closure es la posibilidad que tiene una o varias funciones anidadas de acceder al Lexical Environment de una función padre, y esto es posible gracias al Lexical Scope, que nos da la posibildiad de que esta o estas funciones estén vinculadas al contexto de ejecución de su función padre.
Pero eso no es todo, para que una función sea considerada como closure tampoco tiene que tener variables declaradas dentro de ellas.

Y acá el ejemplo en código de un clousure:

```javascript
function imprimir (){
    let saludo = 'Hola';

    return function comoEstas(nombre){
        console.log(`${saludo} ${nombre} como estás?`);
    }
}

imprimir()('nahuel');
```

La salida sería:

```javascript
Hola nahuel como estás?
```
Dev Request to QA (or Dev Dream, QA Nightmare)
Published: 2021-04-05 20:23:50

### EMAIL From Dev to QA:
Here's my code.  Please makes sure you test all branches.
It should be pretty easy.
![Test all branches](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/efrnyvieusxii0fd0nhl.png)

😂😄🤣

If you don't believe that is a real email, you either:
1) Have sent this type of email and were totally unaware
2) Haven't worked in IT long enough (to know it is real).

😁