teleren/devto huggingface dataset:
MongoDB for Express.js
Tags: npm, node, javascript, mongodb
Published: 2020-02-29 20:12:36


<u>Persistence.</u>
Persistence in nodejs basically means a way of storing data.It can be in any of the 3 ways:
<ul>
<li>FileSystem</li>
<li>Cloud</li>
<li>Database</li>
</ul>

Filesystem is not secure at all when it comes to deploying your web app to the online world.

Cloud persistance is becoming more popular.I would basically recommend Mongo Atlas (what is been called Mongo on the cloud).It is more secure and inexpensive.It's free for simple applications.

Database persistence has been there for years,mainly on relational databases such as MySQL ,Oracles,Postgres etc.NoSQL databases such as mongodb,cassandra and couch are currently challenging RDBMS.Mongodb is more popular that's why it is a good start.

Create a _models_ folder.Inside it ,create a _users.js_ file.Now ,we will have to install an Object document mapper for mongodb.In this case,it's mongoose.Install it:

>npm install --save mongoose

Mongoose introduces schemas and models.When combined ,it is similar to object-oriented programming.

```javascript
const mongoose = require("mongoose");

//create a schema
var userSchema = mongoose.Schema({
      name: String,
      email:String,
      password : String,
      date:Date,
});

//create a model
var User = mongoose.model("User",userSchema);

module.exports = User;
```
Now let's head over to our main app.js and introduce our database and save each item(name & password) to the database.

```javascript
//import the express module
const express = require("express");
const app = express();
//body-parser middleware
app.use(require("body-parser")());

//link mongoose and connect
const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/webApp', {useNewUrlParser: true});

//link the user model
var User = require("./model/user");



//set up handlebars
const handlebars = require('express3- handlebars')
              .create({defaultLayout:'main'});
app.engine('handlebars',handlebars.engine);
app.set('view engine','handlebars');

//set the port number to listen on
app.set('port',process.env.PORT || 8080);

//our slash route will render the home view
app.get('/',(req,res)=>{
    res.render('home');
});

//get user input and display it
app.post("/process",(req,res)=>{
        const name = req.body.name;
        const email= req.body.email;
        const password = req.body.password;

        User = new User({
            name:name,
            email:email,
            password:password
        });
        User.save(user,err)
        .then(user=>console.log('saved'))
        .catch(err=> console.log(err));
});

//our about route will render the about view
app.get('/about',(req,res)=>{
    res.render('about');
});

//create a callback for listening on the server
app.listen('port',()=>{
    console.log(`Listening on port ${app.get('port')}.Press CTRL Z to cancel.`);
}):
```

Done!
As you have seen,I haved the user and logged that in my console,but what happens thereafter is redirect the user to the login page if you have one.
The new user's details have been saved.Great day all!
I built a tool to quickly preview all iOS keyboards
Tags: showdev, ios, swift
Published: 2020-02-29 20:11:04

#### Prelude

iOS offers developers pretty extensive options to customize keyboard for text input. If you want user to enter only numbers, you can select keyboard with big number keys, consequently when user should enter email address, you can offer keyboard that has easily accessible @ sign.
Another point of customization is the return key. It can be changed to show “Done” in blue color and thus indicate that tapping it will submit a form for example.

Lastly there is Content Type settings which can be set to things like different names _(middle name, family name..)_, location, phone number or password. iOS can then offer suggestions and in a case of password allow to fill it with either iCloud Keychain or any other 3rd party password manager.

With so many options it is not possible to remember what all the keyboards look like (we have to also consider other languages) and if you want to quickly check what particular settings is going to look like, you need to run the app, go to the screen with text input you changed and then check the keyboard. It is quite long process.

## The solution

With **Keyboard Preview**, you can preview all options quickly and without much effort. Keyboard is updated in real time when switching options.

The app is open-sourced on [GitHub](https://github.com/nemecek-filip/KeyboardPreview.iOS).

![Keyboard Preview - just three of many options available](https://dev-to-uploads.s3.amazonaws.com/i/4buuzsafdj1c28ot466x.png)
Middlewares in Express.js
Tags: npm, node, javascript, html
Published: 2020-02-29 19:56:01

A middleware is a way of enclosing functionality,that operates on a HTTP to your application.In practice,it actually takes three arguments:a request object,response object and a next function.

Sometimes it might contain four arguments,the fourth argument being a err object.

Let's write an example of a middleware and use it to understand the concept of middlewares.

```javascript
app.use(function(req,res,next){
         console.log('This is a simple middleware.");
         next();
});
```
The middleware example above uses a different route handler(often called app.VERB).As you have noticed,it does not specify a path.You can add the /* path as a first parameter but this is option,since if omitted,it will still match on all paths.
The request and response objects are self-explanatory.My main concern is the next function.

Middleware in express is a matter of where they are put in the main app.js file.So what this middleware basically does is display a message,and then the next function heads over to the next route handler below this middleware.Middleware is executed in what is called a pipeline;basically following an order.

The immediate route handler following this middleware will be executed after the middleware is executed.

Let's create an error 404 middleware which will be executed incase the user visits a page that does not exist.

```javascript
//custom 404 page
app.use(function(req,res,next){ 
        res.type("text/plain");
        res.status(404);
        res.send("Error : Page not found.");
});
```

This middleware will be put below all other routes.Incase the route being sought by the user is not found,the app will head over to this middleware and implement it.

Let's experiment with the most used middleware; body-parser middleware.It is used to parse the URL-encoded body.Let's say we have a form and want to capture what the user has put.The body-parser middleware avails the req.body object so as to access the form fields.We shall create a form now.

```html
<!--form example-->
<form method="POST" action="process">
    <label for="fieldName">Full Name:</label>
    <input name="fullName" type="text">
    <label for="fieldPassword">Password:</label>
    <input name="password" type="password">
</form>
```

We install the body-parser middleware now

>npm install --save body-parser

Our form is ready,now create a route handler for this form.

```javascript
//we link the middleware to avail the req.body
app.use(require("body-parser")());

//get user input and display it
app.post("/process",(req,res)=>{
        const name = req.body.name;
        const password = req.body.password;

        console.log(name);
        console.log(password);
});
```

And that's all there is.

Note: With the latest Express version,body-parser is available even without installing it separately.Check out all about it [here](
https://expressjs.com/en/4x/api.html#express-json-middleware)

Next,I will talk about persistence in express using mongodb and the object document mapper(ODM) ,mongoose.

Stay tuned. _adios!_
When to and when not to use Redux in front-end frameworks
Tags: redux, javascript, beginners, webdev
Published: 2020-02-29 19:54:02


Before we discuss, I just need to give some points about what that Redux is.  

 
 -  Its **Flux architecture**.  

 - **Single source of truth** - Application stored data in a single store. 

 - **Pure Function** - Through functional params only we can change the store value.  

 - **Immutable** - Its read-only. Through pure function reducers only we can change the store value. 


When we do some courses in JS frameworks like React, Angular, etc... the redux will be one of the important topics for data management, so developers will think the redux will be a major part of any project.

when we start our new project, we will always start to use redux, here the problems getting occurred, if your project is small and data management is straight forward then the redux is frustration work. With that frustration, I got to see some blog comments as redux usage is a waste of time and useless work.

Before we are going to use the Redux in any application, try to ask yourself a few questions, which I do normally.  

 - Is data change need to update and show the updated data in different components in my application ?.

 - Is user interaction will need to do data change with some business logic that needs to implement internally to make display that information in your utilizing components ?.  

If your answer is **YES** for both questions, then my preference is to go to redux.  

  
Let's have example projects to check whether redux will need or not.  

- **TimeZone based Clock**: It needs only very few components, so we can do the direct store value passing without Redux.  

- **Ecommerce Wishlist/Cart**: For storing the data and retrieve and use those data, we need to handle the selected product information in many components and different pages like *(Recommendation Products, Product List Page, Product Selection Page),* so to manage those details, Redux will help to maintain the state properly and do their corresponding logics in their reducers and give the corresponding necessary data to the page.  

In Simple Words, *"if some information to pass through one or two class students we will tell directly to the class, if you need to pass that information to the school, you will use the mic to inform it"*, 

Redux is like a mic, use wisely and understand when it need then you will know why people always talking about the benefits of Redux.


**NOTE:**  As I am new to the blogging, so any comments about the blog or improvement, you can provide me those will help to do better work in the future.
What's wrong with Egghead.io?
Tags: coding, learning, discuss, education
Published: 2020-02-29 19:48:06

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/yy80nktvkdrfuzmup88m.jpg
title: What's wrong with Egghead.io?
published: true
description: 
tags: coding,learning,discuss,education
---

Hey, folks! Today i want to ask you about egghead.io. Do you enjoy it?

In December 2019 I purchased 1-year subscription and to be honest, I am disappointed. Quality of videos are good, but content is extremely shallow. Some courses are less informative than 5 mins read of documentation. Also new content appears not o often :(

Is it possible to get partial refund?

May be i missed great courses at this platform. Could you share your favorite courses?

----

If someone is interested, they do not provide refund after 30 days(
Also, i couldn't find support contacts on web-site, so used google :)
Python 3.8's Walrus Operator is (almost) perfect for Jupyter Notebooks
Tags: python, jupyter
Published: 2020-02-29 19:36:50

Assignment expressions, AKA the [walrus operator](https://realpython.com/lessons/assignment-expressions/), is (arguably) one of the coolest new features of Python 3.8. Admittedly, I first loved it simply because its name shows that goofiness remains strong in the dev community.

Then I started thinking about possible use cases for it. I read some articles, reflected a little more, and ended up with the impression that it wasn't a bad feature, but wasn't really that useful.

Fast forward to this week. I was teaching a class about basic Jupyter Notebook usage when it struck me that the walrus operator is great for notebooks! 

How often do we encounter cells such as these:

![Jupyter notebook cell with a line of Python code: variable = do_something() followed by another line of Python code: variable, followed by a DataFrame showing the result.](https://dev-to-uploads.s3.amazonaws.com/i/4g838riomiq9hsb9c5o7.png)

Essentially, what we want is to assign a value to a variable and then return it to be displayed as the result of the cell. Well, it turns out that that's exactly what the walrus operator is for: assign and return. So now we can have a more concise cell with:

![Jupyter notebook cell with Python code: (variable := do_something()) followed by a DataFrame showing the result.](https://dev-to-uploads.s3.amazonaws.com/i/l8sbo0gjnwwdwfqpxr4t.png)

And you can probably see why the title says **almost** perfect. It would be nice if this simpler version worked:

![Jupyter notebook cell with Python code: variable := do_something() followed by a SyntaxError.](https://dev-to-uploads.s3.amazonaws.com/i/bqi85wnbmdud7n1ort55.png)

However it doesn't, and such is life. Apparently there has been [some discussion over this](https://bugs.python.org/issue35224) and it will not be supported. So we will have to live with those parentheses for now.

It may still not be that exciting, but I'm happier with the walrus operator after finding this use case, so I decided to share it. Also, before writing this post I did some research and found messages from [Vedran Čačić](https://bugs.python.org/msg339098) and [Carol Willing](https://bugs.python.org/msg339131) discussing this use case, so I thought it would be nice to acknowledge them for bringing this up.
DevSecOps Saturday Vale #1
Tags: devops, evento, mvpbr, mvpbuzz
Published: 2020-02-29 19:17:48

Hoje, 29 de Fevereiro de 2020, ocorreu em SJC a primeira edição do DevSecOps Saturday aqui da região.

O evento contou com diversos palestrantes bem conhecidos na comunidade, e entregaram muito conteúdo de qualidade.

Gostaria de agradecer o apoio da [WeWork de São José dos Campos](https://www.wework.com/pt-BR/buildings/sao-joao-2405--sao-paulo), em especial ao **Eduardo Fernandes** que nos ajudou nessa parceria, esperamos levar vários eventos para lá..

Gostaria de agradecer também a parceria do [.Net SP](https://www.meetup.com/pt-BR/dotnet-Sao-Paulo/) e também do [DevOps Profissionals](https://www.meetup.com/pt-BR/DevOps-Professionals/) para a realização aqui no Vale.

A minha apresentação foi sobre GitHub Actions, onde expliquei um pouco sobre essa nova funcionalidade, fiz uma demonstração funcional, ~~e outra nem tanto~~, e também pudemos bater um papo sobre Azure DevOps.

Seguem algumas fotos da minha palestra:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nwixpt2ndfn1e7kpov25.jpeg)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/poopbeflj9py7anvjinn.jpeg)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/p44xg9s431f46fnbblbu.jpeg)

Nós contamos também, com diversas outras apresentações bem bacanas, como por exemplo:
[Claudenir Andrade](https://mvp.microsoft.com/pt-br/PublicProfile/7863?fullName=Claudenir%20Campos%20Andrade), que falou muita coisa interessante sobre Inovação, contamos também com o [Juliano Custódio](https://mvp.microsoft.com/pt-br/mvp/Juliano%20Cust%C3%B3dio-5003228), falando sobre os Primeiros Passos com o App Center, o [Ewerton Jordão](https://mvp.microsoft.com/pt-br/mvp/Ewerton%20%20Jord%C3%A3o-5003566), falando sobre Introdução ao Docker com Windows Server e também o [Renato Groffe](https://mvp.microsoft.com/pt-br/mvp/Renato%20Jos%C3%A9%20Groffe-5002142), falando sobre soluções conteinerizadas com .Net Core e Microsoft Azure.

Para quem não pode participar, ou quer rever as apresentações, o evento todo foi transmitido pelo YouTube.
{% youtube 9Ea2j_OnOEA %}
Is there a way I can use Django default auth with React with them both decoupled?
Tags: django, react, djangorestframework
Published: 2020-02-29 19:02:10

---
title: Is there a way I can use Django default auth with React with them both decoupled?
published: true
description: Django and react for authentication
tags: #django #react #djangorestframework
---

I've been avoiding JWT / Token auth and trying to explore if I can use React with Django default auth, or is it only achievable by including a React app inside a Django template?
Day37:Post JSON to API with surf - 100DayOfRust
Tags: rust
Published: 2020-02-29 18:39:22

We can use Rust's `surf` crate to post `application/json` type data to API:

Cargo.toml:
```
[dependencies]
async-std = "1.4.0"
serde_json = "1.0.48"
surf = "1.0.3"
```

main.rs
```rust
use async_std::task;
use serde_json::json;
use surf;

fn main() {
    let apiurl = "https://httpbin.org/post";
    let data = json!({
        "key": "key",
        "msg": "hello world",
        "receivers": vec!["@mario", "@link"]
    });

    task::block_on(async {
        println!("Send url to {}", apiurl);
        let mut res = surf::post(apiurl)
                           .body_json(&data).unwrap().await.unwrap();

        println!("Status:\t{} \nInfo:\t{}\n", 
                 res.status(), 
                 res.body_string().await.unwrap());
    });
}
```

Run it:
```
Send url to https://httpbin.org/post
Status:	200 OK 
Info:	{
  "args": {}, 
  "data": "{\"key\":\"key\",\"msg\":\"hello world\",\"receivers\":[\"@mario\",\"@link\"]}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "deflate, gzip", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "Transfer-Encoding": "chunked", 
    "User-Agent": "curl/7.68.0-DEV isahc/0.7.6", 
    "X-Amzn-Trace-Id": "Root=1-5e5aaf42-59eefa3ec932007880a294f8"
  }, 
  "json": {
    "key": "key", 
    "msg": "hello world", 
    "receivers": [
      "@mario", 
      "@link"
    ]
  }, 
  "origin": "63.80.139.31", 
  "url": "https://httpbin.org/post"
}
```
💾 console8, yet another chip8 emulator that runs on your command line.
Tags: chip8, emulator, javascript, node
Published: 2020-02-29 18:23:58

Hey! 👋 

I have made a chip8 emulator that allows you run chip8 roms on your command line interface and does not require any GUI.

![](https://raw.githubusercontent.com/obsfx/console8/master/media/1.gif)

![](https://raw.githubusercontent.com/obsfx/console8/master/media/2.gif)

If you want to install, see the source code or see more information about that here is the *github* repo and *npm* page;

[github.com/obsfx/console8](https://github.com/obsfx/console8)
[npmjs.com/package/console8](https://www.npmjs.com/package/console8)
How to find third parties licenses
Tags: dotnet, delice, license
Published: 2020-02-29 18:15:18

#Finding the right license

Usually most tools scanning third parties for vulnerabilities also identifies licenses but without telling you explicitly which license belong to which packages.

#Dotnet delice

[dotnet delice](https://github.com/aaronpowell/dotnet-delice) is a tool made by Aaron Powell that will identify for each package transitively the license and group them.

The tool is easy to install, but is only compatible with SDK project:

```
dotnet tool install -g dotnet-delice
```

The output is simple. As example, here is the output from the sample project based on angular template:

```
License Expression: Apache-2.0
├── There are 18 occurances of Apache-2.0
├─┬ Conformance:
│ ├── Is OSI Approved: true
│ ├── Is FSF Free/Libre: true
│ └── Included deprecated IDs: false
└─┬ Packages:
  ├── Microsoft.AspNetCore.NodeServices@3.1.2
  ├── Microsoft.AspNetCore.SpaServices@3.1.2
  ├── Microsoft.AspNetCore.SpaServices.Extensions@3.1.2
  ├── Microsoft.Extensions.Configuration@3.1.2
  ├── Microsoft.Extensions.Configuration.Abstractions@3.1.2
  ├── Microsoft.Extensions.Configuration.Binder@3.1.2
  ├── Microsoft.Extensions.DependencyInjection@3.1.2
  ├── Microsoft.Extensions.DependencyInjection.Abstractions@3.1.2
  ├── Microsoft.Extensions.FileProviders.Abstractions@3.1.2
  ├── Microsoft.Extensions.FileProviders.Physical@3.1.2
  ├── Microsoft.Extensions.FileSystemGlobbing@3.1.2
  ├── Microsoft.Extensions.Logging@3.1.2
  ├── Microsoft.Extensions.Logging.Abstractions@3.1.2
  ├── Microsoft.Extensions.Logging.Configuration@3.1.2
  ├── Microsoft.Extensions.Logging.Console@3.1.2
  ├── Microsoft.Extensions.Options@3.1.2
  ├── Microsoft.Extensions.Options.ConfigurationExtensions@3.1.2
  └── Microsoft.Extensions.Primitives@3.1.2

License Expression: MIT
├── There are 1 occurances of MIT
├─┬ Conformance:
│ ├── Is OSI Approved: true
│ ├── Is FSF Free/Libre: true
│ └── Included deprecated IDs: false
└─┬ Packages:
  └── Newtonsoft.Json@12.0.2

```
Run Kubernetes Pod with root privileges (not recommended)
Tags: kubernetes, devops, docker
Published: 2020-02-29 17:58:21

###Problem:###
Most Docker containers and the processes inside run with non-root user, because of better security. If the container process is running with root (uid 0) it will be the same root as on the host. In this case user may get access to host from the container, thus gaining the root privilege on the host. This is of course a security concern. 


However there can be a case when you need to ***run a container with root privilege*** because of permission issues of the volumes on the host. 


###Solution:###
In order to run a container inside a pod with root, add following config:

```yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: my-app
spec:
  template: 
    spec:
      containers:
      - image: my-image
        name: my-app
        ...
        securityContext:
          allowPrivilegeEscalation: false
          runAsUser: 0
```

Now when you enter the 'my-image' container with `docker exec` or `kubectl exec`, you will see that the user is root. 🙌🏼


-----------------

⭐️  [FREE Docker & Kubernetes course](https://www.youtube.com/playlist?list=PLy7NrYWoggjwPggqtFsI_zMAwvG0SqYCb)  ⭐️


I'm happy to connect with you on 🙂
- [Twitter](https://twitter.com/Njuchi_)
- [YouTube](https://www.youtube.com/channel/UCdngmbVKX1Tgre699-XLlUA?sub_confirmation=1)
- [Instagram](https://www.instagram.com/techworld_with_nana/)
VS Code - Joker Smile Theme
Tags: vscode, theme, style, editor
Published: 2020-02-29 17:57:53

Hello everyone,

I want to share with you my first VS Code theme based on **Joker's style**.

**Check it out**: Code/File ＞ Preferences ＞ Color Theme ＞ Joker Smile.

![Example](https://dev-to-uploads.s3.amazonaws.com/i/9y1uf8cwrlkywpxh23o9.png)



[VS Code Marketplace - Joker Smile](https://marketplace.visualstudio.com/items?itemName=marcosvidolin.joker-smile)

Feel free to contribute
[Joker Smile on Github](https://github.com/marcosvidolin/joker-smile)


✌️