teleren/devto huggingface dataset:
please explain some conceptual part for express js and mongoose
Tags: mongodb, javascript
Published: 2020-10-03 18:21:53


 ##code is here 
if i **'const homeModel = require('../models/home')'**; define indside **'router.post'** then **homeModel**is gives me **whole home model** but when
**'const homeModel = require('../models/home');'** define in global then **homeModel** gives a **Empty Objects** / **{}**   why it is happening like that
                   

                 const router = require('express').Router();
              const userModel = require('../models/user');
             const commentModel = require('../models/comment');

         //importing middleware
         const { AuthMiddleWare } = require('../middleware/middleware');

     router.post('/comment/:id', AuthMiddleWare, (req, res) => {
	// important
	const homeModel = require('../models/home'); **<--talking about this** 

	const postId = req.params.id;
	// console.log(postId);
	const { comment } = req.body;
	console.log(homeModel);
	console.log(userModel);
	console.log(commentModel);

	homeModel.findById(postId, (err, post) => {
		if (err) {
			console.log(err);
		} else {
			//finding Current  user
			userModel.findOne({ email: req.session.passport.user }, (err, user) => {
				if (err) {
					console.log(err);
				} else {
					//founded Current user

					// post

					// create}
                                  })
                           })
Lets build a simple interpreter from scratch in python, pt.04: Comparison functions
Tags: interpreter, fromscratch, python
Published: 2020-10-03 18:19:52

In this post we are adding comparison functions to our interpreter:

```python
class Interpreter:

    # .... previous code ....

    def Lt(self,xs):
        return self.eval(xs[1]) < self.eval(xs[2])
    def Gt(self,xs):
        return self.eval(xs[1]) > self.eval(xs[2])
    def Lte(self,xs):
        return not self.Gt(xs)
    def Gte(self,xs):
        return not self.Lt(xs)
    def Eq(self,xs):
        return self.eval(xs[1]) == self.eval(xs[2])
    def NotEq(self,xs):
        return not self.Eq(xs)
    
code=[
    
    ["If",["Lte",3,5],
       ["Print","3 <= 5"],
       ["Print","3 > 5"]   
    ],
    
    ["If",["NotEq",3,5],
       ["Print","3 != 5"],
       ["Print","3 == 5"]   
    ]   
]
    
interpreter=Interpreter()

interpreter.run(code)
```
Output:
```
3 <= 5
3 != 5
```


[Part 5: Variables](https://dev.to/smadev/lets-build-a-simple-interpreter-from-scratch-in-python-pt-05-defining-variables-4hek)
Lets build a simple interpreter from scratch in python, pt.03: If/Else
Tags: interpreter, fromscratch, python
Published: 2020-10-03 18:11:37

Bite sized posts are continuing. In this post we are implementing If keyword:

```python
class Interpreter:
    
    # ... previous code ...
    
    def If(self,xs):
        _, cond, trueblock, falseblock = xs
        if self.eval(cond):
            if isinstance(trueblock[0],list):
                for x in trueblock:
                    self.eval(x)
            else:
                self.eval(trueblock)
        else:
            if falseblock:
                if isinstance(falseblock[0],list):
                    for x in falseblock:
                        self.eval(x)
                else:
                    self.eval(falseblock)
code=[
    
    ["If",True,
       # True block, 3 statements
       [["Print","answer is 42"],
        ["Print","that is 21*2"],
        ["Print","that is just an ordinary number"]],
       
       # False block
       ["Print","answer is something else"]   
    ],
    
    ["Print",["Mul","-",42]],
    
    ["If",False,
       ["Print","answer is 42"],
       ["Print","answer is something else"]   
    ]   
]
    
interpreter=Interpreter()

interpreter.run(code)
```
Output:
```
answer is 42
that is 21*2
that is just an ordinary number
------------------------------------------
answer is something else
```

[Part 4: Comparison functions](https://dev.to/smadev/lets-build-a-simple-interpreter-from-scratch-in-python-pt-04-comparison-functions-4pcc)
Reference Books...
Tags: books, beginners, python, machinelearning
Published: 2020-10-03 18:07:30

These are a few books I use for reference.
I maintain a GIT repository for the books.
I hope it comes in handy for someone!

# Sections Covered:
- Android Development
- Big Data Analytics
- Cloud Computing
- Cryptography and Network Security
- Data Structures and Algorithms[DSA]
- Data Science
- Java
- Machine Learning
- Personality development
- Python
- StartUp References
- System Design


### I keep updating the content of the repository.
### Please feel free to star the repository and add your own choice of books.

Thank You!

## The link to the repository: 
https://github.com/GopiBollineni2904/Books
So I decided to enter Web Dev
Tags: webdev, codenewbie
Published: 2020-10-03 17:28:22

After 3 long months of "Analysis Paralysis", I decided to enter the world of web dev. Now, I know there are tons of resources, tons of roadmap but I will still take the community and devs advice. Looking forward to helping and ask for help in the community. Feel free to drop advice, roadmap, tips, resources which will help me in advancing my journey in this web dev world.

P.S.: I am not a newbie, I have been learning Java and I am familiar with the concept of OOPS.
Lets build a simple interpreter from scratch in python, pt.02 Basic Arithmetic
Tags: interpreter, fromscratch, python
Published: 2020-10-03 17:28:09

There are many great tutorials about this subject on the internet written by clever people. Maybe my post will not be as great as them or academic style like them but i will always try to keep it simple as  possible as. [KISS](https://en.wikipedia.org/wiki/KISS_principle)

In this post we are adding basic arithmetic to our interpreter.
```python
class Interpreter:
    def __init__(self):
        pass
    
    def run(self,code):
        for xs in code:
            self.eval(xs)
            
    def eval(self,xs):
        if isinstance(xs,list):
            return self.__getattribute__(xs[0])(xs)
        return xs
    
    def Print(self,xs):
        if len(xs)==1:
            print()
            return
        l=len(xs)-1
        for i,x in enumerate(xs[1:]):
            e=self.eval(x)
            if i<l-1:
                print(e,end="")
            else:
                if e!=",":
                    print(e)
                else:
                    print(e,end="")

    # Basic arithmetic operations,
    # Notice how we call self.eval function recursively:
    
    def Add(self,xs):
        return self.eval(xs[1])+self.eval(xs[2])
    def Sub(self,xs):
        return self.eval(xs[1])-self.eval(xs[2])
    def Mul(self,xs):
        return self.eval(xs[1])*self.eval(xs[2])
    def Div(self,xs):
        return self.eval(xs[1])/self.eval(xs[2])
    
code=[

    ["Print","3 + 5 = ", ["Add", 3, 5]  ],
    
    ["Print","1 - 2 * 3 = ", ["Sub", 1, ["Mul", 2, 3] ] ],
    
    ["Print",["Add", "Hello ", "again "],"W",["Mul","o",10],"rld!"],
    
]
    
interpreter=Interpreter()

interpreter.run(code)
```

Output: 

```
3 + 5 = 8
1 - 2 * 3 = -5
Hello again Woooooooooorld!
```

[Part 3: If/Else](https://dev.to/smadev/lets-build-a-simple-interpreter-from-scratch-in-python-pt-03-if-else-511h)
GCP DevOps Certification - Pomodoro Seven
Tags: googlecloud, sre, devops, certification
Published: 2020-10-03 17:05:11

# The largest single source

of unreliability to a system is **change**

Now we take learning back to DevOps and understand why that friction occurred. New features, a progressive application that delivers new features competing with a stable reliable system that doesn't change. Dev and Ops.

For me, SLO's remove that personal aspect. Agreeing upfront the error budget, the level of reliability means both groups allow for each other. It is [managing expectations](https://www.psychologies.co.uk/managing-expectations-0).

And key to success is alignment of incentives between development and operations.

If a service is within SLO then you could...

![Aligning Dev and Ops incentives](https://dev-to-uploads.s3.amazonaws.com/i/y8idawtg9gixs71m0k6h.png)

One approach is only releasing features until the error budget is exhausted, then focusing development on reliability improvements until the budget is refilled. 

# No silver bullets...or are there?

Paint a real world scenario. You've spent all your error budget - can't incur any more outages or downtime but the product team really want to push out a new feature. 

We have all been there and it's a reality of development. Hint - It's not personal, don't treat it as such!

But if this situation occurs teams can furnish stakeholders with a [silver bullet](https://cloud.google.com/blog/products/management-tools/sre-error-budgets-and-maintenance-windows) token. A token that allows the bearer to propose ignoring the rules. 

The tokens don't refresh and if the release is desired to still go ahead, the token bearer provides their token to the SRE's in order to enable the release.

![SRE Silver bullets](https://dev-to-uploads.s3.amazonaws.com/i/ncxr5yqsf94p0htzy01g.png)
Yes — The Angular CLI is Creating Unit Tests Wrong
Tags: angular, productivity, webdev, tech
Published: 2021-04-27 07:10:00

---
title: Yes — The Angular CLI is Creating Unit Tests Wrong
published: true
date: 2020-10-03 15:13:11 UTC
tags: angular,productivity,webdev,tech
canonical_url: 
---

![](https://cdn-images-1.medium.com/max/1024/1*JCZp0tTOoDnsyEe56kP0Tg.jpeg)<figcaption>Photo by <a href="https://unsplash.com/@nevenkrcmarek?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Neven Krcmarek</a> on <a href="https://unsplash.com/s/photos/moon?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption>

I strongly agree with [The Angular CLI is creating your unit tests wrong](https://medium.com/thinkster-io/the-angular-cli-is-creating-your-unit-tests-wrong-4b42412e082c) article!

In fact, I’ve got both an alternative **approach** and a **tool** to **automate** a lot of the **boilerplate** :

- the tool is SCuri — [https://www.npmjs.com/package/scuri](https://www.npmjs.com/package/scuri?source=responses-----b8d05adf3fa2----0-----------------respond_sidebar-----------)
- approach described in [Opinionated approach to Angular testing](https://dev.to/gparlakov/an-opinionated-approach-to-testing-angular-492f)
- my favourite — [TestBed considered harmful](https://medium.com/angular-in-depth/angular-testbed-considered-harmful-3f91f647d1fd)
[Tutorial Linux] Terminal: Adicionando usuário
Tags: adduser, terminal, linux, usuario
Published: 2020-10-03 16:27:21

Para adicionar um novo usuário, digite no terminal

```
$ sudo adduser <nome_do_novo_usuário>
```

- **$** indica que você deve usar o **usuário comum** para fazer essa operação.

- **sudo** serve para pedir permissões de administrador temporariamente.

- **adduser** para adicionar o novo usuário.

- digite o nome do novo usuário sem os sinais **< >**.

Em seguida será pedido que seja definido uma senha para o novo usuário, além de nome completo e outros detalhes opcionais e que podem ser deixados em branco.

Após ser confirmada a pergunta, o usuário já estará disponível.

Para ver os dados do usuários do sistema, inclusive o novo, digite:

```
$ cat /etc/passwd
```

> sobre o comando [cat, clique aqui](https://dev.to/womakerscode/tutorial-linux-terminal-o-comando-cat-1196).

- no diretório **etc/** temos arquivos de configuração, scripts de inicialização, entre outros.

O arquivo **passwd** contém as seguintes informações:

```
<usuário>:<senha>:<id_do_usuário>:<id_do_grupo_primário>:<descrições_como_nome_completo_entre_outros>:<diretório_home>:<nome_do_shell>
```

Por exemplo, no meu caso temos:

```
danielle8farias:x:1000:1000:Danielle Farias,,,:/home/danielle8farias:/bin/bash
```

- **danielle8farias**, meu nome de usuário;

- **x**, indica que a senha está encriptada;

- **1000**, id do usuário;

- **1000**, id do grupo primário do qual o usuário faz parte;

- **Danielle Farias,,,**, meu nome e outras informações pessoais, que no meu caso estão em branco;

- **/home/danielle8farias**, meu diretório home;

- **/bin/bash**, o shell que estou usando, que é o Bash.
Make a fast Auto GraphQL Server with NodeJS and Postgres in 5 minutes !
Tags: node, graphql, postgres, docker
Published: 2020-10-03 16:15:59

Hello World !
Too many loves in my last post
https://dev.to/simerca/why-you-don-t-use-ansible-4olk

Today i show you how to mount a fast Auto Schema GraphQL server with **NodeJS** and **Postgres** Database in 5 minutes.

The the first thing is mount Postgres database with **Docker** !
```bash
docker run --name mydb-postgres -e POSTGRES_PASSWORD=12345 -p 5432:5432 -d postgres  
```
(default user is : postgres , default db is : postgres)

You can try to connect with **DBeaver** it's a good Postgres UI tool
https://dbeaver.io/

**NOW**!

create a folder for your NodeJS project
```bash
mkdir awesome-graphql-server
cd awesome-graphql-server
```

Init npm packages
```bash
npm init
```

Install **Express** and **Postgraphile**

**Postgraphile** is a very good tool to **auto schema your Graphql** based on your Postgres structure (*relations include , very awesome*)
```bash
npm install express
npm install postgraphile
```

so this is the simple code to have to insert in your **index.js**
```bash
touch index.js
nano index.js
```

insert this inside

```javascript
var express = require('express');

const {
    postgraphile
} = require("postgraphile");

var app = express();
app.use(
    postgraphile(
        process.env.DATABASE_URL || "postgres://postgres:12345@0.0.0.0:5432/postgres",
        "public", {
            watchPg: true,
            graphiql: true,
            enhanceGraphiql: true,
        }
    )
);
app.listen(4000, () => console.log('go to for playground graphiql http://localhost:4000/graphiql'))
```

after launch 
```bash
node index.js
```

And go to http://localhost:4000/graphiql
Welcome to your **Graphql Auto schema playground** !

The endpoint for Graphql request is 
http://localhost:4000/graphql

Thanks for your feedbacks !
Testes no Angular com Jest: Componentes e Serviços
Tags: angular, testing, jest, test
Published: 2020-10-03 16:09:19

Fiz uma apresentação esses dias sobre Testes no Angular com Jest e resolvi compartilhar fazendo um vídeo sobre!
Segue link: https://www.youtube.com/watch?v=3kwLQYDFtDE&feature=youtu.be
Unity, Arch Linux e VSCode
Tags: unity3d, arch, vscode
Published: 2020-10-03 16:08:46

---
title: Unity, Arch Linux e VSCode
published: true
description: 
tags: unity3D, Arch, VSCode
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/nacm1jidpcr653pykvb5.png
---

[Você pode pular minha introdução e ir direto pra onde eu faço a instalação das coisas.](#arrumando-a-casa)

Recentemente eu comecei a estudar desenvolvimento de jogos usando Unity3D, e como usuário do Linux a parte que mais tive problema era configurar um editor que me desse o mesmo poder que uma IDE como o [Visual Studio][4] me oferece no Windows.

Eu não queria ter que migrar pro windows.

## Porque o Unity3D?

Eu optei por usar Unity por ser bastante popular e *fácil* de achar ajuda e conteúdo na internet.

## VSCode

VSCode é um editor de texto que se tornou bem popular nos últimos anos, acredito que mais pelo seu intellisense e coisas integradas que o tornam mais parecido com uma IDE, então eu pensei que talvez ele pudesse me ajudar.

Então resolvi deixar registrado essas coisas aqui porque não foi tão simples quanto eu gostaria, vamos lá.

## <a name="arrumando-a-casa"></a> Arrumando a casa

> Observação: Eu vou assumir que você estja utilizando o Arch, você vai precisar ter instalado: [Unity3D][1] e [VSCode.][2] *(esse último eu sempre instalo usando o pacman)*

Você vai precisar instalar o Mono e a SDK do Dotnet, você pode instalar essas via pacman.

```bash
sudo pacman -S mono dotnet-sdk dotnet-runtime
```

Depois disso você vai precisar instalar a extensão do [C# pro VSCode][3]

Agora, no unity inicie seu projeto, crie um script e abra, **atenção aqui pra verificar se o seu editor padrão é o VSCode.** 

Se tudo correr bem você vai conseguir ter o intellisense funcionando.

![vscode com autocomplete pro Unity3D](https://dev-to-uploads.s3.amazonaws.com/i/qol6xqc3l1gqg56kudg4.png)

## Unity3d 2020...
Quando eu criei meu projeto no Unity eu optei por usar a versão 2019.x por ser LTS, porém eu tive um problema com a tecla de espaço, que aparentemente não funciona no linux apenas.

Então eu resolvi ir pra versão 2020.x que funcionou muito bem, mas ai o VSCode parou de funcionar o auto complete...

![why](https://media.giphy.com/media/kyrd72DC2Iwfu/giphy.gif)

Depois de algum tempo perdido na internet eu resolvi fuçar as configurações do projeto e achei a opção de gerar os arquivos *.csproj*

Pra resolver isso: *Preferences > External Tools* marque a opção: `Registry packages` e clique em *Regenerate project files* e pronto, tudo voltou ao normal.

É isso pessoal, pelo menos pra mim foi isso, minha experiência (1 mês) com Unity é que no Linux as coisas acontecem de formas esquisitas.

**obs:** eu não sei quase nada de C# então isso acaba influênciando bastante em como lido com as coisas no Unity3D

## Referências

- https://medium.com/@sami1592/set-up-visual-studio-code-for-unity-in-linux-69b7f4352e0b
- https://www.youtube.com/watch?v=btga03_gGfw

[1]: https://unity3d.com/pt/get-unity/download
[2]: https://code.visualstudio.com/download
[3]: https://code.visualstudio.com/docs/languages/csharp
[4]: https://visualstudio.microsoft.com/pt-br/
How to use https with Vue CLI for local development
Tags: vue, frontend, development, programming
Published: 2020-10-05 13:47:46

---
title: How to use https with Vue CLI for local development
published: true
date: 2020-10-03 16:00:21 UTC
tags: vue, frontend, development, programming
canonical_url: https://bharathvaj.me/blog/use-ssl-with-vue-cli-locally
---

Usually, in local development environment the Vue app is served via `http` protocol. But in the production environment, it is served via `https`. Running the local server in `https` might be needed if you consume API that is forced to be consumed only by the app served via HTTPS.

In this guide, we will be setting up HTTPS in our development environment for our Vue app with our own SSL certificate.

### Vue CLI

The most common way to scaffold a Vue project is via its [vue-cli](https://cli.vuejs.org/guide/) tooling and running the following commands

```
npm install -g @vue/cli
vue create hello-world
cd hello-world
npm run serve
```

The app runs locally at `http://localhost:8080`

![Vue Default](https://bharathvaj.me/media/vue-default.png)

Now we want the app to be served via `https`. We can do this easily by setting up our own SSL certificate in development for `localhost` using [mkcert](https://mkcert.org/)

### Step 1: Creating an SSL Certificate

To create a valid SSL certificate easily we make use of mkcert tool. Run the following commands to obtain a certificate.

```
brew install mkcert

mkcert -install
```

Now we have successfully created Certificate Authority (CA) on our machine which enables us to generate certificates for all of our future projects.

From the root of our hello-world project, run the following commands,

```
mkdir -p .certs

mkcert -key-file ./.certs/key.pem -cert-file ./.certs/cert.pem "localhost"
```

Now we have a `.certs` folder with key and cert files inside it.

_Please, make sure to add this folder to `.gitignore` so that we don’t accidently commit these files to version control._

### Step 2: Adding HTTP to vue config file

Vue CLI allows us to configure it via config file as follows

```
const fs = require('fs');

module.exports = {
  devServer: {
    open: process.platform === 'darwin',
    host: '0.0.0.0',
    port: 8080,
    https: {
      key: fs.readFileSync('.certs/key.pem'),
      cert: fs.readFileSync('.certs/cert.pem'),
    },
    hotOnly: false,
  },
};
```

Here we are pointing to CLI where our certificate file is by simply passing an object with a key and cert to devServer’s https config.

We are almost at the end of the process. Let’s restart the server again. Voila, now our app is served via `https`.

![Vue Default](https://bharathvaj.me/media/vue-default-https.png)

 ![](https://media.giphy.com/media/JqDeI2yjpSRgdh35oe/giphy.gif)

Happy solving!
Lets build a simple interpreter from scratch in python, pt.01
Tags: interpreter, fromscratch, python
Published: 2020-10-03 15:54:53

Hi!. 
In this blog series we will see that will i be sucessful or not in my attempt to  build a programming language, an interpreter, a parser, a compiler and a virtual machine. For any questions starting with 'why' the answer is always 'why not?' except theese:
* Why Python? Python lets you focus on problem  rather than fighting with language itself. 
* Why not Rust? Rust is causing hair loss while fighting against it.
* Why not C? It explodes many times in your hands. You lose your hands. 

If code that i write is not  idiomatic and tastefull for you please ignore it. 
Lets get started. 

```python
class Interpreter:
    def __init__(self):
        pass
    
    def run(self,code):
        for xs in code:
            self.eval(xs)
            
    
    # This is our magic function. It evauates xs parameter 
    # according to its first element  and calls appropriate 
    # member function and passes the parameter to that function.
    # If xs is not a list then returns xs itself:
    
    def eval(self,xs):
        if isinstance(xs,list):
            return self.__getattribute__(xs[0])(xs)
        return xs
    

    # Our first function (or opcode) is Print. If last item 
    # is a comma it doesn't print newline:  
  
    def Print(self,xs):
        if len(xs)==1:
            print()
            return
        l=len(xs)-1
        for i,x in enumerate(xs[1:]):
            e=self.eval(x)
            if i<l-1:
                print(e,end="")
            else:
                if e!=",":
                    print(e)
                else:
                    print(e,end="")

# This is AST (Abstract Syntax Tree) generated by 
# parser. Consisting of recursive lists
# (No, not lisp :P )
code=[
    ["Print","Hello World!","Sky is blue"],
    ["Print",1,","],
    ["Print",2,","],
    ["Print",3],
    ["Print","a"],
    ["Print","b"],
    ["Print"],
    ["Print","c"],
]
    
interpreter=Interpreter()

interpreter.run(code)
```
Output is: 
```
Hello World!Sky is blue
1,2,3
a
b

c
```


[Part 2: Basic Arithmetic Functions](https://dev.to/smadev/lets-build-a-simple-interpreter-from-scratch-in-python-pt-02-basic-arithmetic-5ch4)
Day 79: Eloquent Javascript
Tags: 100daysofcode, javascript, books
Published: 2020-10-03 15:30:45

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

Today was different. I started reading a book on javascript: [Eloquent Javascript](https://eloquentjavascript.net/index.html). This is the first technical book in my short history of web development. I learned a couple of new concepts, quoted below:

 Type coercion
> When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it needs, using a set of rules that often aren’t what you want or expect.

_For those of us like me that omit semicolons for no apparent reason._
> In some cases, JavaScript allows you to omit the semicolon at the end of a statement. In other cases, it has to be there, or the next line will be treated as part of the same statement. The rules for when it can be safely omitted are somewhat complex and error-prone. 

_I'll stop omitting semicolons_

A Call stack - a stack data structure that stores information about the active subroutines of a computer program.
> Every time a function is called, the current context is stored on top of this stack. When a function returns, it removes the top context from the stack and uses that context to continue execution.

I am loving the book, I was really contemplating whether to read or not but after the first three chapters I'm positive that it is worth my time.

_Thats it for Day 79_
_I'll be back tomorrow with more concepts learnt from the book_