teleren/devto huggingface dataset:
Do you know why we check for response.ok while using fetch
Tags: javascript, react, codenewbie
Published: 2020-11-28 04:47:44

Take a look at the below code:

```js
fetch('https://jsonplaceholder.typicode.com/todos/4') 
 .then(response => response.json())
 .then(result => console.log('success:',result)) 
 .catch(error => console.log('error:', error));
```

Here, we’re making an API call to get a todo with id 4 and it will work because there is todo with id 4.

![API Call](https://gist.github.com/myogeshchavan97/aa75611665802aadfd3ba6bfeb0fe59b/raw/e41272d1b854eb986501200a2b0d936dbca1f98a/placeholder.png)

But what If the id does not exist or the server throws an error like 404 or 500 or any other error?

```js
fetch('https://jsonplaceholder.typicode.com/todos/2382822') 
 .then(response => response.json())
 .then(result => console.log('success:',result)) 
 .catch(error => console.log('error:', error));
```

![API Call](https://gist.github.com/myogeshchavan97/aa75611665802aadfd3ba6bfeb0fe59b/raw/ccd5e6a7334bd40c1aa837c4c07fe76ae5386fea/placeholder_error.png)

Here, we have provided a very large id that does not exist. But if you execute in the browser console, you will see that a success message is printed even though it’s clearly a 404 error.

Ideally, the `.catch` handler should be executed but that does not happen in the case of `fetch`.

`fetch` only goes into `.catch` handler when it fails to make the request for example when the network is not available or the domain does not exist.

So If you’re using `fetch` for performing the CRUD (create, read, update, delete) operation and the id does not exist then you will get an error.

This is the reason, you will find code for `fetch` written like this:

```js
fetch('https://jsonplaceholder.typicode.com/todos/4') 
 .then((response) => {
   if (response.ok) { 
    return response.json();
   }
   return Promise.reject(response); 
 })
 .then((result) => { 
   console.log(result); 
 })
 .catch((error) => {
   console.log('Something went wrong.', error); 
 });
```

where inside the `.then` handler, we're checking if the response is ok. If the response is ok, we're calling a method that will send the result to the next handler.

If the response is not ok, then we're rejecting the promise so it will call the `.catch` handler to print the actual error.

That’s it for today.

**Don’t forget to subscribe to get my weekly newsletter with amazing tips, tricks, and articles directly in your inbox [here](https://yogeshchavan.dev).**

[<img src="https://cdn.buymeacoffee.com/buttons/default-yellow.png" >](https://www.buymeacoffee.com/myogeshchavan97)
#11 Updating Record
Tags: mongodb
Published: 2020-11-28 04:34:09

Various mongoose methods
* char.update()
* MarioChar.update()
* MarioChar.findOneAndUpdate()

```
// Saving the data
character = new MarioChar({
    name: "Mario",
    weight: 60
})
character.save().then(function(){
    ...
})

// Updating the data
MarioChar.findOneAndUpdate({ name:"Mario"}, { name:"new_name"}).then(function(){
    MarioChar.findOne({ name:"Mario" }).then(result => {
        ...
    })
})
```
The the new changes will be injected and this will not overwrite the complete objects. This update results to the object:
`{ name: "new_name", weight: 100 }` and not just `{ name: "new_name" }`
Bolsonaro é o nosso Trump?
Published: 2020-11-28 04:30:27

# Obviamente que não

A distância entre os dois é gigantesca.

O Bolsonaro SEMPRE mamou nas tetas do Estado sendo no Exército ou como político, mas o Bolsonaro quem um agravante. Ele colocou toda a família que conseguiu na política para mamar mais e mais nas tetas do Estado.

Bolsonaro nunca esteve na iniciativa privada, já o Trump se criou nela, por maiores percalços que ele teve, o Trump NUNCA teve nenhum cargo público.

Porém os 2 têm algo em comum.

A ideologia idiota da direita? Também, porém além disso os dois utilizaram de dinheiro que não ganharam pessoalmente para alavancar suas carreiras.

O Trump utilizou o dinheiro do seu pai e de investidores, já o Bolsonaro utilizou do dinheiro do Estado, mediante seus funcionários fantasmas, passando essa tradição para seus filhos que elevaram essa condição de uma forma que ele nunca tinha feito.

Os 2 são IDIOTAS e se não fosse o dinheiro dos outros estariam no ostracismo público.

Uma pena que os 2 foram eleitos, pois sim a população é ignorante, aliás a americana é muito pior que a brasileira.

Boa parte dos Mestrados e Doutorados criados nos Estados Unidos são de imigrantes. UAU Q COISA NÃO?
Unit testing your code!
Published: 2020-11-28 04:25:15

### Introduction

This week, we embarked on how to create a testing units and workflow using Github Actions. The testing framework I choose is "Jest" because of its popularity and simplicity for using.

### How to integrate "Jest"
* Firstly, we need to install by using 
```
npm install --save-dev jest

```

In `package.json`, add the following lines:

```
{
  "scripts": {
    "test": "jest"
  }
}
```
* We can create the first test file by using this naming convention `checkFunctions.test.js`
* We can easily run the test by using:
```
npm run test
```
### What did I learn while writing my test case:

Well, since my test case is pretty long. Thus, I highly recommend you to have a look at my [test file](https://github.com/phast184/link-checker-tool/blob/master/test/urlFunctions.test.js).

* I have learned how to write a test unit that we can compare right from console.log
* I have learned to consider many options that could happen for my functions

### Add Continuous Integration

* Github Actions is a CI that is highly recommended. Therefore, I would like to introduce a bit about the way we set it up.
* Firstly, we need to create a template to the .github/workflows directory of your repository.

* This is how the YML file looks like:
```
name: Node.js CI

on: [push]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [8.x, 10.x, 12.x]

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm install
    - run: npm run build --if-present
    - run: npm test
      env:
        CI: true
```

* A CI is perfect when we want to automating all our test in a large project. However, if someone's change might break the tests, there's no way we could merge them until their changes are fixed. This way help us to save tons of resource.

### Learning from the process:
Well, this week assignment is highly educational. There are several things I could learn from the lab:

* How to set up a CI
* How to write a simple unit test
* How to set up a code coverage analysis so that I could write more test to cover the aspects that I might miss of a function.
* How to fix my functions when there are bugs while testing.
#10 Deleting Record
Tags: mongodb
Published: 2020-11-28 04:09:58

Mongoose has 3 records to delete records
* `char.remove()`
* `MarioChar.remove()` Inside the bracket we are going to pass the options
* `MarioChar.findOneAndRemove()` Inside the bracket we're going to pass the options

Use of `findOneAndRemove()`
```
MarioChar.findOneAndRemove({ name:"Mario" }).then(function(){
            MarioChar.findOne({ name:"Mario" })
        })
```
NeoPentecostais e a subversão da Bíblia
Published: 2020-11-28 04:05:24

Marcos 10:25
É mais fácil passar um camelo pelo fundo de uma agulha do que um rico entrar no Reino de Deus”.

Lucas 18:25
Certamente, é mais fácil passar um camelo pelo fundo de uma agulha do que entrar um rico no Reino de Deus”.

# Agora eu vos pergunto

ONDE NO CARALEO DA BÍBLIA DIZ QUE SE VC FICAR RICO VC ENTRARÁ NO REINO DE DEUS???

Eu sou católico, fiz primeira comunhão e crisma.

*Para anos depois ouvir que se vc doar o que tem Deus te dará em dobro!!!*

> Pelo AMOR DE DEUS ONDE ISSO TA ESCRITO?

Será que os neopentecostais não lêem a bíblia e só aceito o que esses VENDILHÕES da fé dizem?

### POR FAVOR GENTE!!!! PAREM!!!

Se você que segue a Bíblia ou Jesus ou o que for, não existe em NENHHUM MOMENTO que se fala que você deve dar tudo que tem para receber em dobro.

## ISSO EH BURRICE!!!

Nós julgamos tanto os islâmicos mas vc sabia que eles não emprestam dinheiros cobrando juros? Porque isso vai contra seus ensinamentos.

A única coisa que queria que me indicassem na Bíblia onde se vc doar TUDO para "Deus", pois só vai para os pastores, vc irá receber em DOBRO!!!

Nem o dízimo diz isso.

Evangélicos vcs seguem a quem? Jesus ou Pastor?

Se vcs seguem a Jesus VCS ESTÃO FAZENDO TUDO ERRADO!!!

Vcs viraram o rebanho de um falso profeta!!!

Se vc ler as escrituras vc entenderá que esses pastores são os vendilhões do Templo que JESUS expulsou. Vcs estão seguindo uma pessoa que Jesus teria EXPULSADO do seu meio.

Por favor eu só peço que vcs leiam a Bíblia e não se deixem levar pela fala mansa desses falsos profetas.

Sigam o que Jesus falou! Ame o próximo!!!


Só para corroborar esse texto:

Jesus e o jovem rico é um episódio da vida de Jesus que trata da vida eterna[1][2]. Ele pode ser encontrado nos três evangelhos sinópticos: Mateus 19:16-30, Marcos 10:17-31 e Lucas 18:18-30. É neste episódio que Jesus faz referência a «Quão dificilmente entrarão no reino de Deus os que têm riquezas! Pois mais fácil é passar um camelo pelo fundo de uma agulha, do que entrar um rico no reino de Deus» (Lucas 18:24-25), uma frase que se tornaria uma de suas mais famosas expressões. 

https://pt.wikipedia.org/wiki/Jesus_e_o_jovem_rico
PostgreSQL Database Instance Creation and Configuration in AWS RDS 
Tags: aws, postgres
Published: 2020-11-28 03:45:05

In this article, we will see the step by step instructions for configuring the Postgres DB instance in AWS RDS.

**Pre-requisites**
To complete this learning, you will need:
✓ An AWS Account (Free Tier)

If you don't have an account visit https://aws.amazon.com and click Sign Up.

Amazon RDS is available on several database instance types - optimized for memory, performance or I/O 
* Amazon Aurora
* PostgreSQL
* MySQL
* MariaDB
* Oracle
* SQL Server

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

**PostgreSQL on EC2**

You can manage your own DB instance by provisioning the EC2 instance and installing the Postgres Database.

**Managed PostgreSQL on RDS**

Managed RDS Service can handle the patching, backup, recovery, provisioning the resources, availability.

In this article, we focus on using the managed services AWS RDS for creating PostgreSQL Database Instance

**Working with Amazon RDS via the AWS Management Console Step by Step Instructions**

**Step 1:** Log in to AWS Management Console and search with the keyword 'RDS'. You will be redirected to the RDS Home Page
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yvqb7xdmd0lyjb4kxduv.png)


**Step 2:** Click on the `Create Database` and Select `Postgres`
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/to7uwmzj9pqyay410e8k.png)


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


**Step 3:** DB Instance Settings
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/c86jcavbkdv90c4qq6qz.png)


**Step 4:** DB Instance Size and Storage. For the Free tier, you will get 'db.t2.micro' instance.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6v39rea8llv8ahp35xdh.png)

**Step 5:** Instance Connectivity
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wu4kgztzsr4ry1dx552c.png)


**Step 6:** Additional Configuration
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x85j1est4ntjhgdxfub8.png)

**Step 7:** Backups Configuration
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8ognnjvismcsy27odfbk.png)

**Step 8:** Click On Create Database you will see the resource creation progress. It will take some time for provisioning the resources 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3vu5nydm0cstz9any0ux.png)

**Step 9:** To view Connection Details click on the `View Credential Details` Button
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4kgyw4xykvt79xweow0l.png)

**Step 10:** Connect to AWS RDS Instance from your Local and execute the DB Scripts
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yhmzg1kn0n6m3yvfkzb4.png)

**Working with the AWS Command Line Interface**
To control and automate Amazon RDS resources from the command line, use the [AWS Command Line Interface (CLI)](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)

**Summary**
You can see the detailed implementation and connecting the API to the RDS instance in below github project
{% github https://github.com/sunilkumarmedium/CleanArchitectureApp %}
#9 ObjectId
Tags: mongodb
Published: 2020-11-28 03:38:57

To retrieve data by ID from the collection: 
```
MarioChar.findOne({ _id: character._id }).then(result => {
    assert(result._id === character._id)
    done();
})
```
But the above code is not going to work as 
`result._id===character._id` is going to return `false` as 
`result._id` is of type `ObjectID` and `character._id` is of type `String`. So we've to convert both of them to String and then compare.
`result._id.toString()===character._id.toString()`
will return `true`
#8 Finding Records
Tags: mongodb
Published: 2020-11-28 03:23:16

To search we can use `find` or `findOne` method to the model.
```
MarioChar.findOne({ name: "Mario"}).then(result => {
    ...
})
```
This code, finds the first match where name==="Mario"
Our finding_test.js file is
```
const assert = require('assert');
const MarioChar = require('../models/mariochar');

describe('Some demo tests', function(){

    beforeEach(function(done){
        var character = new MarioChar({
            name: "Mario",
        })
        character.save().then(function(){
            assert(character.isNew === false)
            done();
        })
    })

    //Create tests
    it('Finding a record form the database', function(done){
        MarioChar.findOne({ name: "Mario"}).then(result => {
            assert(result.name === "Mario")
            done();
        })
    })
})
```
9 No-Code Videos You Should Watch
Tags: nocode, video, tutorial
Published: 2020-12-01 00:11:23

---
title: 9 No-Code Videos You Should Watch
published: true
date: 2020-11-28 03:18:19 UTC
tags: NoCode,Video,tutorial
canonical_url: https://maxkatz.org/2020/11/27/9-no-code-videos-you-should-watch/
---

I’m very passionate about the no-code space. I have been recording videos on how to build small applications using no-code tools and services. In particular, I like to find applications built with code and then rebuild them using no-code. Here is a [YouTube playlist](https://www.youtube.com/watch?list=PLSAWywyhniCOpvlFSfUWVNAbclc2-1Kne&v=0mqssckUDnE) that shows how to build these no-code solutions. The videos are short, all are under 15 minutes.

[![](https://dev-to-uploads.s3.amazonaws.com/i/6nbcmze7x2b2ot230qqj.png)](https://www.youtube.com/watch?list=PLSAWywyhniCOpvlFSfUWVNAbclc2-1Kne&v=0mqssckUDnE)<figcaption>Click image to watch the YouTube playlist</figcaption>


Note: when I write this the playlist has nine videos. It’s possible you will see more when you read this.
Recommend VS Code extensions to your future teammates
Tags: vscode, texteditor, extensions
Published: 2020-11-28 03:08:41

If you are using an awesome VS Code extension and you want to share it with your current team members and future ones, you can use this feature of VS Code.

# Configuring recommended extensions

- Open the command palette `CMD + Shift + p`
- Type `Configure Recommended Extensions`
- A new file called `extensions.json` will be created under `.vscode/` in the root of the project.
- Place the cursor within the recommendations array and press `CMD + i`.
- Select the required extensions from the list of installed extensions and save the file.
- Include this file in your source control tools(we use Git).

![Create VSCode extensions.json file](https://dev-to-uploads.s3.amazonaws.com/i/1n939dnihki157z5jbl0.gif)


# Installing recommended extensions

Once the configuration is done, everyone who opens your project will get a recommendation notification like this
![Install recommended extensions VSCode notification](https://dev-to-uploads.s3.amazonaws.com/i/yvs88ge27z0lf4cpza30.png)From here the extensions are just a click away.
On clicking `Install` all recommended extensions will be installed.



For any reasons, if the notification doesn't show up we can manually open up Recommended Extensions settings
- Open the command palette `CMD + Shift + p`
- Type `Show Recommended Extensions`
- All the extensions can be installed together or only required extensions can be installed

![Using command palette to open Recommended Extensions settings](https://dev-to-uploads.s3.amazonaws.com/i/gcgi8seqo66u2a978zvd.gif)

---

>`CMD + i` is one of the default VSCode shortcuts to trigger suggestions/IntelliSense.

---

>Keystrokes and mouse clicks can be made visible in VSCode by turning on the `Screencast Mode` from the command palette.

Feel free to comment your thoughts on this. Let me know if you find this useful, do share your tips and tricks for utilising VSCode to its fullest.
Why you shouldn't cascade functionality
Tags: codequality, codenewbie, php, beginners
Published: 2020-11-28 02:55:27

Don't do it! I'm serious, it will come back and bite you in the ass. :satisfied:

# So here is what I did
I was working on a microservice that should extract images that have faces in them from PDF files. I used Symfony and as such I made a few services that were responsible for their part of the job. For example, `ImageExtractionService` or `FaceDetectionService`.
I was pretty proud of the finished project, using some open source services to detect faces in pictures and choosing what program to use to extract images from PDF files, that I forgot to think ahead about code reusability and overall code quality.

# The problem

I cascaded the functionality between the services. It looked something like this:

```php
//ImageExtractionService
$this->faceDetactionService->detect()

//FaceDetectionService
function detect() {
    //some code
    $this->imageService->process()
}

//ImageService
function process() {
    //some code
    $this->cleanupService->cleanUp()
}
```
Chaining it like this you end up making unwanted connections, for example if I was only interested in what FaceDetectionService "saw" I couldn't obtain that data because it doesn't return that data instead it immediately tries to process the image.

# How did it come to bite me in the ass?

Well, few days after the feature went to production I noticed a need for a service debug option. But because my code is chained and **needs** a link to download a PDF and **needs** a link where to upload the images I just couldn't make a local debug unless I truly separated the services.

# So... Don't do it! Don't chain the functionality of separate services.

If you'd like to support me writing future posts feel free to buy me a cup of coffee.

[![](https://cdn.buymeacoffee.com/buttons/default-blue.png)](https://www.buymeacoffee.com/wSd4q6U)
ทำไมเราถึงเห็นข้อมูลแบบ []byte หลายที่ใน standard package ของ Go
Tags: go
Published: 2020-11-28 02:42:24

เราจะมักจะเห็นข้อมูลแบบ `[]byte` อยู่หลายที่ใน standard package ของ Go ไม่ว่าจะเป็น `io.Reader`, `io.Writer` interface หรือจะใน package `net/http` และใน `encoding/json`

slice ของ byte เนี่ยมันก็แค่ลำดับของตัวเลขที่มีในช่วง 0-255 หลายๆตัว ซึ่งถ้าเราพิพม์ออกมาดูเนี่ย จะไม่รู้เลยว่ามันหมายถึงอะไร ที่เป็นแบบนี้เพราะมันคือ _**raw data**_ ยังไงล่ะ

_**raw data**_ จุดที่ถูกใช้ก็คือ จุดที่เราใช้ส่งข้อมูลโดยที่ไม่สนใจรูปแบบของข้อมูล ไม่ว่าจะเป็นเรื่อง IO (Input/Output) ที่ต้องส่งต่อให้อุปกรณ์ภายนอกหรือคุยกับ OS (Operating System) หรือคุยกับ Network พวก package `net/http` ที่ต้องส่งข้อมูลผ่าน protocol HTTP และข้อมูลที่ต้องผ่านการ encode/decode ต่างๆพวก package ในกลุ่ม `encoding` ไม่ว่าจะเป็น `encoding/json`, `encoding/xml` 

พวกนี้ข้อมูลต้องถูกแปลงไป แปลงมา ระหว่าง format ต้นทาง กับ raw data (`[]byte`) เพื่อให้ปลายทางไปแปลงกลับอีกรอบได้

แต่อย่างไรก็ตามเราเองอาจจะไม่ได้จัดการ `[]byte` เองโดยตรงเท่าไหร่เพราะมี package ในการแปลงข้อมูลให้เราอยู่แล้ว อย่างมากก็อาจจะแปลงจาก string ไปเป็น `[]byte` แล้วแปลงกลับเป็น string อีกที ยกเว้นก็แต่เราต้องเขียน package เพื่อจัดการอะไรในระดับ protocol หรือ I/O ในระดับล่างๆ หรือจัดการแปลง raw data ไปมาเป็น format ที่ยังไม่เคยมีใครทำมาก่อน

<a href="https://www.buymeacoffee.com/weerasak" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
I use static by default... But should I?
Tags: csharp, codequality
Published: 2020-11-28 02:40:02

For code to be self-documenting, I like to do any sort of business rule at the lowest level. If I have a business rule that says, "When the requested delivery date is less than 30 days, put a flag so a customer service representative can approve it," I have a matching method which might be called, "AddFlagIfShortLeadTime."

When you compose your system from these small components, you find you don't need state in order to accomplish work. In our example above, AddFlagIfShortLeadTime takes in the model it might operate on and returns a model of the same type with the transformations applied. If any information from a database is needed, we can pass it into this method as well. Let the something else worry about querying the database.

One interesting thing about this is that I rarely see this sort of pattern in a C# codebase. I can see it in other languages which primarily work in a functional paradigm, but I'm not sure why I don't see it in my main language. Below are some of my reasons for doing it. I'd love to hear if anyone has thoughts on why this is or isn't a good idea.

# It's easier than DI and more DRY than multiple instantiations

There's still an argument about whether to use dependency injection. I've found that if I introduce a static class, neither side gets mad. A common argument for DI is that it's hard to instantiate classes. With static classes, you don't have to instantiate anything. An argument against DI is that it's hard to work with. With static classes, you don't have to work with DI at all.

# Unit tests are easy

Of course, I'm not advocating for making private things public, but if you happen to need to expose your static class, zero properties and no instanciation means no mocking. You can focus on what you're really trying to test - your business rules.

# It's better for your computer

I don't know a lot about this, but I do know that keeping an instanciated object takes processing power. Static classes can be called upon by the compiler at any time without instantiation, and so take up less processing power... Or something like that.

# It encourages modular thinking

Usually you shouldn't just use static classes for everything. Static classes are great for documenting business rules and terrible for reading or writing to databases. By using static classes by default, we can separate our business logic by default.

# Summary

Do you disagree with this approach? I have found it odd that I can't find many examples outside of my own code where people do this. Let me know what you think. 😀