teleren/devto huggingface dataset:
Diferenças entre let e var. Javascript
Tags: javascript, let, var, const
Published: 2020-01-02 17:05:23

O ES2015 introduziu o conceito de **Block scope** que permite termos variáveis dentro de blocos **{ }** que existem apenas dentro deste scope e não podem ser acedidas fora dele.
Simplificando:
Quando declaramos uma variável utilizando *var* dentro de um bloco, a mesma ficará disponível globalmente, enquanto *let* e *const* não. Isso permite um maior controlo sobre cada uma de nossas variáveis, evitando assim alterações de valores de maneira errada.

```javascript
var a = 1;
let b = 2;

{
  console.log(a);
  console.log(b);
}
{
  var c = 3;
  let d = 4;
}

console.log(c);
console.log(d);
```
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/3ffhcybuhc6senjw2mrs.png)

No exemplo abaixo, onde temos uma função, o valor de car que foi declarado utilizando *let*, irá ser alterado de Audi para VW apenas dentro da função. O valor de truck que foi declarado como *var* será alterado de Volvo para Scania.
Em ambos os casos, este valor foi alterado apenas dentro da função, ou seja: ficou restrito ao seu scopo.
Então temos 2 variáveis de cada, cada uma a "viver" no seu escopo. Uma no global e outra no scopo da função.
```javascript
let car = 'Audi';
var truck = 'Volvo';

let WhatsTheValue = () => {
  let car = 'VW';
  var truck = 'Scania';
  console.log('The "let car" inside is:', car);  
  console.log('The "var truck" inside is:', truck);   
}
 
WhatsTheValue();

console.log('The "let car" outside is:', car);
console.log('The "var truck" outside is:', truck); 
```
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ntmzhrxi6teq4hiz1jz5.png)

No próximo exemplo, o valor de car é alterado de *Audi* para *VW*, como acontecia anteriormente, e o valor de truck também irá alterar de Volvo para Scania, mas repare que agora temos o mesmo valor no log inside e outside para a variável truck.
Diferente de quando utilizamos uma função, utilizando apenas **{ }** o *let* manteve o seu comportamento, enquanto *var* passou a subscrever a variável do scopo global.
Neste caso deixamos de ter 2 variáveis de cada e passamos a ter 2x *car* e apenas uma *truck*.
```javascript
let car = 'Audi';
var truck = 'Volvo';

{
  let car = 'VW';
  var truck = 'Scania';
  console.log('The "let car" inside is:', car);  
  console.log('The "var truck" inside is:', truck);   
}

console.log('The "let car" outside is:', car);
console.log('The "var truck" outside is:', truck); 
```
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/odd63jmulqnlyk0q04uh.png)

Utilizar *var* não é errado, de todo, mas como o *let* nos permite um maior controlo sobre onde realmente estão nossas variáveis, em muitos casos é recomendado na sua utilização, de maneira a evitar bugs porque alteramos o valor de uma variável que não era suposto ser alterada.
Daily Challenge #152 - Strongest Number in an Interval
Tags: challenge
Published: 2020-01-02 14:30:16

---
title: Daily Challenge #152 - Strongest Number in an Interval
published: true
series: Daily Challenge
description: What is the strongest number between n and m?
tags: challenge
---
###Setup
The strength of an even number is determined by the amount of times we can successfully divide by 2 until we reach an odd number. 

For example, if `n = 12`, then:
`12 / 2 = 6`
`6 / 2 = 3` 
We have divided 12 in half twice and reached 3, so the strength of 12 is `2`. 

Given a closed interval [*n*, *m*], return the strongest even number in the interval. If multiple solutions exist, return the smallest of the possible solutions. 

###Examples

for `[1, 2]`, return `2`. (1 has a strenght of 0; 2 has a strength of 1)
for `[5, 10]`, return `8`.

###Tests
`[48, 56]`
`[129, 193]`

Good luck~!

***
_This [challenge](https://www.codewars.com/kata/5d16af632cf48200254a6244) comes from alexmate on CodeWars. Thank you to [CodeWars](<https://codewars.com/>), who has licensed redistribution of this challenge under the [2-Clause BSD License](<https://opensource.org/licenses/BSD-2-Clause>)!_

_Want to propose a challenge idea for a future post?  Email **yo+challenge@dev.to** with your suggestions!_
The New Years Resolution That Changed My Career
Tags: career, productivity
Published: 2020-01-02 16:38:19

I made a New Years resolution about five years ago to read at least one technical article _in full_ every day.

I seemed to already read a lot for my coding career in general, _how can one not?_ But I was, and still am, a notorious skimmer. I am easily distracted and often don't truly read what I am reading.

So one year I decided to truly read articles online in full, and commit to it. I eventually fell off from the every day part of the resolution, but in getting involved I just learned so much—not just about the code, but about my career and the software industry in general. I learned about how blogging keeps the networked learning happening, and eventually it really did lead me to building this website, [dev.to](/).

I think of New Years resolutions as both corny and invaluable. It is a great time of year to reflect, look ahead, and identify the nudges you need.

It's January 2nd, and not too late to adopt _truly reading_ as a goal. I am making it one of my resolutions again this year. My other resolutions include _asking for help_ more often, and _communicating my routine to others in order to set expectations_.

Hope this helps somebody out there.
Quickly set up a PostgreSQL environment on GCP
Tags: postgres, gcp, docker, database
Published: 2020-01-02 16:38:18

This quick-start guide is part of a series that shows how to set up databases on Google Cloud Platform, for developing and testing purposes.

This guide will show you how to create a PostgreSQL environment running inside your Google Cloud Project. This make sense when you want to have more control over your PostgreSQL instance, otherwise you can just use the GCP managed version, Cloud SQL: https://cloud.google.com/sql/docs/postgres/

## Create a Compute Engine VM

Using Cloud Shell:
```
# Create the PostgreSQL GCE instance
gcloud compute instances create postgresql \
  --zone=us-central1-c \
  --machine-type=n1-standard-1 \
  --image-project=debian-cloud --boot-disk-size=10GB \
  --image=debian-9-stretch-v20190916 \
  --boot-disk-type=pd-standard \
  --boot-disk-device-name=postgresql \
  --scopes=cloud-platform 
```

## Configure your VM with PostgreSQL

Using Cloud Shell:
```
# Connect to the PostgreSQL VM
gcloud compute ssh --zone=us-central1-c postgresql

# Login as super user
sudo -s

# Install Docker
curl -sSL https://get.docker.com/ | sh

# Install postgresl client
apt-get install postgresql-client

# Build and run
mkdir -p /tmp/pgdata/
docker run -d -p 5432:5432 --name postgresql -v /tmp/pgdata:/var/lib/postgresql/data postgres:9.6
```

## Load your PostgreSQL database with data

Using Cloud Shell:
```
# Verify PG is installed and started up successfully
docker ps -a
docker logs --follow <PG_CONTAINDER_ID>

# Wait for the message to appear:
# LOG:  database system is ready to accept connections

# Leave the logs command, by pressing CTRL + C

# Log into the PG container
docker ps
docker exec -it <PG_CONTAINDER_ID> bash

# Log as the postgres user
su postgres

# Connect to postgres database
psql postgres

# Create tables and populate with Data
CREATE TABLE Users (uid INTEGER PRIMARY KEY,
                    name VARCHAR);
INSERT INTO Users
  SELECT generate_series, random()
  FROM generate_series(1, 100000);

CREATE TABLE Messages (mid INTEGER PRIMARY KEY,
 uid INTEGER REFERENCES Users(uid),
 ptime DATE, message VARCHAR);

INSERT INTO Messages
   SELECT generate_series,
          round(random()*100000),
          date(now() - '1 hour'::INTERVAL * round(random()*24*30)),
          random()::text
   FROM generate_series(1, 100000);
```

And that's it!

If you have difficulties, don’t hesitate reaching out. I would love to help you!
Best Books for Python Learning
Tags: python, programming, books
Published: 2020-01-02 16:26:37

Python Programming was initially developed by Guido Von Rossum as a fun project and was named after his favorite show Monty Python’s Flying Circus. It was developed in 1991, but it started becoming popular around 2008. A major contributor to this popularity was Google, which has developed a number of platforms using Python. Recently, Python Programming has been popularized by cloud, DevOps, data science, data analytics, machine learning, and natural language processing. With more and more data harvesting and data processing, people want to get into new types of job roles, which require basic programming skills, and Python perfectly suits all the categories of job work.
Here is list of Best books for learning Python:

1. Python Programming – An Introduction to Computer Science
2. A Practical Introduction to Python Programming
3. Learn Python in 7 Days
4. Python Crash Course
Free to use Portfolio
Tags: opensource, help, design, contributorswanted
Published: 2020-01-02 16:24:20

Hello Fellow Devians,
I have created a website portfolio, which is fully opensource.
Now I want to share it with developers who need a boilerplate for their portfolios.
##Also I was looking for helpers, who could help me make it look more better and friendly. The portfolio is free to constructive criticism.

###Hosted Version
https://smammar.github.io/my_portfolio/

###Github repository
https://github.com/SMAmmar/my_portfolio

Looking forward to your suggestions and contributions :)
Mobile Learning?
Tags: beginners, discuss
Published: 2020-01-02 16:14:31

Good day fellow DEV's!

As I'm always looking for ways to learn I'm wondering if there are any good resources out there for learning on a mobile device, phone mostly. I know this can be clunky but I spend a lot of time on my phone and thought I could possibly ustilize this downtime better.

So, if you have done this, what resources did you find?

TIA!!
Use `fpdf` to generate PDF file as receipt - Python Tips
Tags: python
Published: 2020-01-02 16:12:00

You can use `fpdf` library to generate PDF file, for example a purchase receipt.

First install the library:

```bash
$ pip install fpdf
```

Now let's create a PDF for receipt:

```python
from fpdf import FPDF
# generate a receipt

def generate_receipt(date, amount):
  pdf = FPDF(orientation='P', unit='pt', format='A4')
  pdf.add_page()
  pdf.set_font("Times", "B", 24)
  pdf.cell(0, 80, "Purchase Receipt", 0, 1, "C")
  pdf.set_font("Times", "B", 14)
  pdf.cell(100, 25, "Payment Date:")
  pdf.set_font("Times", "", 12)
  pdf.cell(0, 25, "{}".format(date), 0, 1)
  pdf.cell(0, 5, "", 0, 1)
  pdf.set_font("Times", "B", 14)
  pdf.cell(100, 25, "Payment Total:")
  pdf.set_font("Times", "", 12)
  pdf.cell(0, 25, "${}".format(amount), 0, 1)
  return pdf.output(dest="S")
```


### Reference
* https://pyfpdf.readthedocs.io/en/latest/
* https://pyfpdf.readthedocs.io/en/latest/Tutorial/index.html
Bypassing ptrace calls with LD_PRELOAD on Linux
Tags: beginners, linux, reversing
Published: 2020-01-02 16:10:06

---
title: Bypassing ptrace calls with LD_PRELOAD on Linux
published: true
description: How to bypass ptrace calls using LD_PRELOAD
tags: beginner, linux, reversing 
---

Hello,

Here's a quick article on how to bypass calls to `ptrace` when debugging a Linux executable. 

By calling `ptrace` with the `PTRACE_TRACEME` option, a process can detect if it's being debugged and execute different instructions. This an effective anti-debugging technique.

For example, take the following C program:

```c
#include <stdio.h>
#include <sys/ptrace.h>

int main() {
    if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0) {
      printf("I'm being debugged!\n");
    } else {
      printf("Normal flow\n");
    }
    return 0;
}
```

If we execute the program from above we get `Normal flow` on our screen but if we debug it with `gdb` we get `Err: I'm being debugged!`.

```
root@kali:~/Downloads# strace ./a.out 
...
munmap(0x7fb7c945e000, 90919)           = 0
ptrace(PTRACE_TRACEME)                  = -1 EPERM (Operation not permitted)
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(0x88, 0), ...}) = 0
brk(NULL)                               = 0x55c2d37e6000
brk(0x55c2d3807000)                     = 0x55c2d3807000
write(1, "Err: I'm being debugged!\n", 25Err: I'm being debugged!
) = 25
exit_group(0)                           = ?
+++ exited with 0 +++
```

To bypass this, we can use the `LD_PRELOAD` environment variable. It lets us control the loading path of a shared library, which allows us to stub out library functions such as `ptrace`.

We can create the following file:

```c
long ptrace(int request, int pid, void *addr, void *data) {
    return 0;
}
```

And compile it as a shared library with the following command:

```bash
gcc -shared ptrace.c -o ptrace.so
```

Next, we can set the environment variable LD_PRELOAD using the following commands:

* in the shell: `export LD_PRELOAD=./ptrace.so`
* in gdb: `set environment LD_PRELOAD=./ptrace.so`

Demo:

```
gdb-peda$ file a.out 
Reading symbols from a.out...
(No debugging symbols found in a.out)
gdb-peda$ r
Starting program: /root/Downloads/a.out 
Err: I'm being debugged!
[Inferior 1 (process 1939) exited normally]
Warning: not running
gdb-peda$ set environment LD_PRELOAD=./ptrace.so
gdb-peda$ r
Starting program: /root/Downloads/a.out 
Normal flow
[Inferior 1 (process 1946) exited normally]
Warning: not running
gdb-peda$ 
```

Thanks for reading!
The Basics of Using React Hooks with D3 (Remastered for 2020)
Tags: react, beginners, d3, dataviz
Published: 2020-01-02 16:08:18

{% youtube Y-ThTzB-Zjk %}

Hey, this is a remake / remaster of the very first video tutorial I did on "Using React (Hooks) with D3". That one had poor audio quality and other things that bugged me. Enjoy this one and happy new year!

Code on GitHub:
https://github.com/muratkemaldar/using-react-hooks-with-d3/tree/01-the-basics
Join realms with user federation
Tags: help, keycloak
Published: 2020-01-02 15:34:11

---
title: Join realms with user federation
published: true
description: 
tags: help, keycloak
---

Does anyone have experience on how to setup realm in keycloak that will copy users from other realms? Basically I need realm that will allow access for all users of other realms and by default I have LDAP and kerberos which I have no idea how to integrate. Identity provider option is not possible for my case so user federation would be really good if some easy solution is possible.
F# Tip 3: Recursive sequence expressions
Tags: fsharp, dotnet, functional
Published: 2020-01-02 15:14:10

F# [sequence expressions](https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/sequences#sequence-expressions) are a great way to generate data in a loop. A simple sequence expression like this generates square numbers:

```fsharp
// 1, 4, 9, ...
seq {
    for i in 1 .. 10 do
        yield i * i
}
```

Often, however, we need to process a hierarchical data structure instead of working through a simple `for` loop. It turns out that sequence expressions can handle this as well.

For example, let's say that we have a snippet of HTML and we want to extract each node's text. So, for this HTML:

```html
<div>
    before the spans
    <span>inside the first span</span>
    between the spans
    <span>inside the second span</span>
    after the spans
</div>
```

We want to generate output that looks like this:

```
div: before the spans + between the spans + after the spans
span: inside the first span
span: inside the second span
```

Note that the output for each node contains text from only that node, not its children. How can we do this in F#?

Using the [HtmlAgilityPack](https://html-agility-pack.net/), we can extract the text from a given node like this:

```fsharp
let toSeqSafe (items : seq<_>) =
    if isNull items then Seq.empty
    else items

let getNodeText (node : HtmlNode) =
    let texts =
        node.SelectNodes("text()")
            |> toSeqSafe
            |> Seq.map (fun node -> node.InnerText)
    String.Join(" + ", texts)
```

Now we can use a sequence expression to process an entire hierarchy recursively:

```fsharp
let rec getHierarchyText node =
    [|
        let text = getNodeText node
        if text <> "" then
            yield node, text

        for child in node.ChildNodes do
            yield! getHierarchyText child
    |]
```

Inside the loop, we first `yield` the text for the current node, then `yield!` the sub-sequence generated by each child node. F# automatically concatenates all the sequences together for us!

We can test drive the function like this:

```fsharp
let doc = HtmlDocument()
use rdr =
    new StringReader(
        "<div>\
            before the spans\
            <span>inside the first span</span>\
            between the spans\
            <span>inside the second span</span>\
            after the spans\
        </div>")
doc.Load(rdr)

for (node, text) in getHierarchyText doc.DocumentNode do
    printfn "%s: %s" node.Name text
```

This pattern of a `yield` followed by a recursive `yield!` is something that I find comes up often when processing hierarchies. I hope it's useful for you as well.
TypeScript: 6 Pros and 4 Cons (biased)
Tags: typescript, javascript, webdev
Published: 2020-01-02 15:11:07

In this article I will go over some of my thoughts on TypeScript. It will not be an in depth article, and I will try to keep it as short as possible. Let's start with the pros 🎉

## Pros

**1.** **Errors:** You are able to detect **errors during compile-time**. This will give quick feedback and it makes refactoring much easier. It is also helpful when scaling the project.
**2.** **IntelliSense:** There is often good support of IntelliSense. This includes **autocompletion** and **autoimports**. I also really like, that I am able to get **quick info**.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/apeefotsj9qcv3o7tuwx.gif)

*Source: [Visual Studio Code](https://code.visualstudio.com/docs/languages/typescript#_intellisense)*

**3.** **Adopting:** When you are working on existing JavaScript projects, it is really amazing, that you are able to **gradually adopt TypeScript**. TypeScript is based on JavaScript, so in practice you could just write plain old JavaScript in a `.ts` file.

> "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript." - [typescriptlang.org](http://www.typescriptlang.org/)

**4.** **Patterns:** I really like, that TypeScript from the start is guiding the user of TypeScript to use structure. When you are writing plain JavaScript, it can easily become spaghetti code. We as developers want to follow some form of patterns and structure. This can be achieved from the start using [`class`](https://www.typescriptlang.org/docs/handbook/classes.html), [`interface`](https://www.typescriptlang.org/docs/handbook/interfaces.html), [`namespace` and `module`](http://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html), amongst other things.

```ts
class Car {
  // Fields

  // Constructor

  // Properties

  // Functions
}
```

**5.** **Ability to understand:** I have talked with people both from frontend and backend. A bunch of people from backend hated JavaScript, but none of them hated TypeScript. I guess it is easier to understand when you are used to work with type heavy languages like Java or C#.
**6.** **Jobs:** TypeScript is gaining [more and more popularity](https://2018.stateofjs.com/javascript-flavors/overview/) and more companies are using the language. This gives more job opportunities surrounding TypeScript.

## Cons

**1.** **Time:** You often need a build environment, and it will therefore take more time upfront.
**2.** **Errors:** The error messages can sometimes be misleading, but you should never only just trust the IDE or editor anyway.
~~**3.** **Library support:** Not all JavaScript libraries supports TypeScript, but most of them do.~~
**4.** **Learning:** Like everything, it takes time to learn. We are only human, and I would not say, that the learning curve is that high, if you already got the basics of programming in place.

> Note for con #3: The way I wrote this was misleading. Check out [this article](https://www.detroitlabs.com/blog/2018/02/28/adding-custom-type-definitions-to-a-third-party-library/). It explains my point 😊
Display Flash Message Using Vue JS in Laravel
Tags: flash, message, laravel, vue
Published: 2020-01-02 14:59:38

Flash message using vue js in laravel: Today, I will show you how to implement flash message using Vue js in Laravel application. We will built vue flash message in Laravel website. It is awesome and not so tough to create such system in our Laravel app. Many developer creates flash message using Vue js in Laravel application to show user nice and attractive flash message .

https://www.codechief.org/article/display-flash-message-using-vue-js-in-laravel
How to create seo friendly url in laravel using vue js ?
Tags: seo, url, laravel
Published: 2020-01-02 14:59:02

Slug Generator using Vue Js: With the advent of Node.js and modern application endpoint routing, I find it surprising that there is no in-built function to convert any string into an URL-optimized slug.If your application users write content. you want to make their content searchable with anSEO-friendly URL.

https://www.codechief.org/article/how-to-create-seo-friendly-url-in-laravel-using-vue-js
Delete Multiple Records Via Checkbox Using jQuery Ajax in Laravel
Tags: laravel
Published: 2020-01-02 14:58:17

This post covered topic on Laravel tutorial for beginner step by step, and in this post we have shared simple feature like How to Delete multiple data from Mysql table via Checkbox in Laravel framework with Ajax. For do this operation we will use jQuery Ajax and HTML Check boxes input fields for delete multiple rows of mysql data in Laarvel. Mainly we have always put delete button at individual row for delete single data.

https://www.codechief.org/article/delete-multiple-records-via-checkbox-using-jquery-ajax-in-laravel
Laravel 6 Gate and Policy Example from Scratch
Tags: laravel, gate, policy
Published: 2020-01-02 14:57:32

In this tutorial we are going to see how we can protect user access from specific route using laravel gate and policy. it is pretty simple.

Think of gates and policies like routes and controllers. Gates provide a simple, Closure based approach to authorization while policies, like controllers, group their logic around a particular model or resource. We'll explore gates first and then examine policies.

Today, we're going to discuss the authorization system of the Laravel web framework. The Laravel framework implements authorization in the form of gates and policies. After an introduction to gates and policies, I'll demonstrate the concepts by implementing a custom example.

https://www.codechief.org/article/laravel-gate-and-policy-example-from-scratch
Prevent Common Password using Unicodeveloper Package in Laravel
Tags: laravel, common, password
Published: 2020-01-02 14:56:49

Today, i am going to share with you how to ignore common password to enter by user using "unicodeveloper/laravel-password" package. Using "unicodeveloper/laravel-password" package, we can simply use "dumbpwd" validation rule.

https://www.codechief.org/article/prevent-common-password-using-unicodeveloper-package-in-laravel
How to Upload Multiple Image in Laravel
Tags: laravel, image, upload, multiple
Published: 2020-01-02 14:55:59

Today, i will show you how to create simple multiple image upload in laravel. I write article step by step about multiple file upload in laravel. I also added validation with image upload in laravel. Here i will follow object oriented php structure to upload imgae.

https://www.codechief.org/article/how-to-upload-multiple-image-in-laravel
Captcha Code and Validation Example using Botdetect Package in Laravel
Tags: captcha, botdetectpackage, laravel
Published: 2020-01-02 14:54:46

How to Generate Captcha Code in Laravel is the topic, we will discuss today. Captcha stands for Completely Automated Public Turing test. . It is mainly used as a security test to ensure only human users can pass through. Computers or bots are not able of solving a captcha.

https://www.codechief.org/article/captcha-code-and-validation-example-using-botdetect-package-in-laravel