teleren/devto huggingface dataset:
NestJS: stop handling errors like this!
Tags: node, typescript, javascript, nestjs
Published: 2022-03-30 15:20:42

I see people making this mistake all the time.

Let's say you've got an API server written in NestJS, and you need an endpoint for fetching a single product by its ID. So, in your `product.service.ts` you would typically write:

```typescript
async findOne(id: number) {
  try {
    return await this.productRepository.findOneOrFail(id);
  } catch (err) {
    throw new NotFoundException();
  }
}
```

_(I'm using TypeORM here, but the same principle can be applied to other libraries as well.)_

So what we've got here? You attempt to query a product by its ID, and if there is no product with this ID, you just throw the 404. And in your `product.controller.ts` you simply write:

```typescript
@Get(':id')
findOne(@Param('id') id: string) {
  return this.productService.findOne(+id);
}
```

And everything indeed works fine.

## So what's the problem with this?

The thing is that the above code would work well for REST APIs. But what if tomorrow you will need to fetch that product via GraphQL or WebSockets? The `NotFoundException()` and its fellow HTTP-related exceptions will not be suitable for that any more. You will definitely need different error handling.

Therefore, by throwing HTTP-related errors (exceptions) from services **you simply make your code less reusable**.

## What to do instead?

As we have implicitly mentioned above, the HTTP-related exceptions are suited only for REST APIs. But so are _controllers_!

You see, NestJS controllers are used only during REST API development, while services can have wider use. This makes controllers the perfect place for throwing HTTP-related exceptions.

Thus, in the simplest scenario, your `product.service.ts` code (fragment) would look just like this:

```typescript
findOne(id: number) {
  return this.productRepository.findOneOrFail(id);
}
```

And in the `product.controller.ts` you now handle the "not found" error:

```typescript
@Get(':id')
async findOne(@Param('id') id: string) {
  try {
    return await this.productService.findOne(+id);
  } catch (err) {
    throw new NotFoundException();
  }
}
```

Of course, if you need more sophisticated error handling, you can define custom error classes to throw from services and handle in controllers (for REST) or resolvers (for GraphQL).

## Conclusion

**Don't throw HTTP-related exceptions from services, throw them from controllers!**

Have you been making this mistake before reading this article? Comment down below!

And, of course, leave your reaction to this article, share it with your friends via social media and follow me on this platform!

Don't stop coding,
don't stop growing,
**stand with Ukraine!** 🇺🇦
Connecting bSQL to Tableau!
Tags: database, datascience, analytics, programming
Published: 2022-03-30 15:17:49

One of the advantages of the [bSQL](https://bsql.org/) language is that it's both immutable relational. Other ledger database technologies are modifications on document storage. While they may be "SQL compliant" to some degree, these implementations are non-native and lack complex query features and optimization. 

SQL-based technologies, such as Tableau, use SQL to query data. There is immense value in using live database connections. I'll be going over how to connect a bSQL instance to Tableau.

**Pre-requisites:**
- [Tableau Desktop](https://www.tableau.com/products/trial/desktop) > 2020.4
- A bSQL instance (instructions [here](https://dev.to/cassidymountjoy/how-to-create-a-database-and-blockchain-in-bsql-hbi))

## Download the JDB Driver
The bSQL JDBC driver can be found on the Maven Central Repository [here](https://search.maven.org/search?q=g:com.blockpointdb). You will need to download the latest version as a `.jar` file.

## Download the `.taco` custom connector
In order to connect your `bSQL` instance to Tableau you need the `bsql_jdbc` connector. This connector allows for live communication between your bSQL instance and Tableau Desktop. It can be downloaded from the bSQL [documentation](https://bsql.org/docs/connecting/bsql-taco).

## Configuring Tableau Desktop
Tableau desktop can be configured to use custom connectors.
- Copy the connector you downloaded into your `My Tableau Repository/Connectors` directory.
- Place the .jar file in the folder for your operating system. 
    - Windows: C:\Program Files\Tableau\Drivers
    - Mac: ~/Library/Tableau/Drivers
    - Linux: /opt/tableau/tableau_driver/jdbc

## Ready to connect
Now when you start Tableau Desktop there should be an option for bSQL: `bsql_jdbc`. If the option doesn't show up, double check the file path in which you placed the connector.

![bSQL tableau connector](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eemwcfi0hx4kpo60gfb0.png)

After choosing the connector, this should open the connection dialogue. From here you can specify the bSQL instance you wish to connect to.

![bSQL connection dialogue](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ws97c8tg64qp8u1x6s26.png)

## Continuations
- In the `run initial SQL` pane you can add bSQL specific features such as setting the state of the database you want to work by using [SET TRANSACTION QUERY TIME](https://dev.to/cassidymountjoy/hindsight-20-20-querying-any-point-in-time-2noi)
- Using the `New Custom SQL` we can generate views on lifetime attributes of tables. For instance, creating.
Terraform State Nightmare
Tags: terraform, devops, migration, hugops
Published: 2022-03-30 15:13:04

If you've used terraform, you know how important the `tfstate` file is. In case you're taking it lightly do not(I'm serious)

Today my colleague and I were working on creating an S3 backend, but due to a `Resource Error` which was probably not caused by the state file we tried to do a `terraform init` but accidentally did a `terraform init -reconfigure`, instead of a `terraform init -migrate-state`(Mistakes happen, we're humans). Luckily the state file was backed up. Now I want to also document the steps taken here and what failed.

> Disclaimer: I'm new to terraform, the following is my personal experience.

- We tried to upload the state file to S3 and tried to do `terraform init -migrate-state`(Spoiler Alert: It didn't work). Terraform just closed its eyes and was like I don't see the resources.
- We tried switching back to local backend, but the statefile there too didn't work, we even replaced `.terraform/terraform.tfstate`
- When we did a `terraform apply -state=backed.tfstate` it did recognize our resources, so we knew there was hope.
- Apparently `terraform init` doesn't have a `-state` option...
- Somewhere along the line we started getting the error

```
Terraform 0.11.1 does not support state version 4, please update
```

The solution? Hidden in a [Stackoverflow](https://stackoverflow.com/questions/59603458/terraform-0-11-1-does-not-support-state-version-4) answer.
```
Terraform does not support state version 4 is a common issue.

There is only one fix to this

Take the local state file and push it to some remote backend and then delete the .terraform directory and run the init command with the backend.
It should work
```
Frustration had hit the roof, we'd been at this for almost an hour or more(Time goes very fast when you're debugging)

![5 Stages of Debugging](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p2qbz9r2kp0njiikrdnz.png)

I think I was at the anger stage. Everything we tried just gave us no results and terraform was acting as if it couldn't see the state file.

Then we had the terraform state file so we did a
`terraform state push backup.tfstate` and lo-and-behold, we got some random `lineage` error. 

Modified the `lineage` parameter in the tfstate file to match the file which terraform created in the s3 bucket. And that was it. Terraform agreed that the file was up to its standards and it got all the resources intact.

### Takeaways from this.
- Always enable object versioning in your S3 Bucket or object storage.
- Always backup your state files.
- Always try all sort of combinations when it comes to terraform, there is a workaround hidden almost somewhere.

Thanks for reading, hopefully the Terraform spirit is never angry on you.
Make Reservation | Laravel Restaurant Reservation Website
Tags: beginners, tutorial, laravel, vue
Published: 2022-03-30 15:12:35

{% embed https://youtu.be/Q20Um5Uxt7s %}
Hello, friends in this video we are going to make reservation for the Laravel restaurant reservation website.
Restaurant reservation website.

Support me: 
https://www.patreon.com/Laraveller
https://paypal.me/TonyXhepa

Follow me:
Twitter: https://twitter.com/Laravellercom
Facebook Page: https://www.facebook.com/1laravellercom
Instagram: https://www.instagram.com/laravellercom/
Github: https://github.com/laraveller
Website: https://laraveller.com/

Setup VS CODE for Laravel: https://youtu.be/EliywWn4IK4
Setup Mac for development: https://youtu.be/yxuR5myrVi4

Playlists:
Laravel Restaurant Reservation: https://bit.ly/3Jc5IcG
Spatie Laravel Permission: https://bit.ly/3pOsOhN
Laravel Testing For Beginners: https://bit.ly/3t1gNq4
Laravel Roles and Permissions: https://bit.ly/3gOhM7d
LARAVEL INERTIA MOVIE APP: https://bit.ly/3FVMp4Q
Laravel Livewire Movie App: https://bit.ly/3s8D6v1
Laravel Classified Website - https://bit.ly/3nsFRnb
Livewire Employees - https://bit.ly/2ZtIpZY
Laravel Employees Management - https://bit.ly/3Gglt14
Laravel admin panel - https://bit.ly/3CcX75M
Paracetamol.js💊| #87: Explica este código JavaScript
Tags: javascript, beginners, webdev, spanish
Published: 2022-03-30 15:08:18

## **Explica este código JavaScript**

```js
const nombres = ["Ana", "Sofia", "Carmen", ...["Cris"]];
const [, , , miNombre] = nombres;
console.log(miNombre["length"]);
```

A. `SyntaxError`
B. `6`
C. `5`
D. `4`

Respuesta en el primer comentario.

---
ESP32 有些變數名稱不能用--兼談 C++ 的連結性 (linkage)
Tags: esp32, cpp, arduino, linkage
Published: 2022-03-30 15:04:47

今天使用 ESP32 時遇到一個莫名其妙的雷, 先來看看以下這個程式：

```cpp
int times = 32;

void setup() {
  Serial.begin(115200);
  Serial.print("\ntimes = ");
  Serial.println(times);
}

void loop() {}
```

你覺得執行後會輸出什麼呢？

其實會輸出什麼要看你使用哪一個版本的 [ESP32 Arduino Core](https://github.com/espressif/arduino-esp32), 如果是使用 2.0.0 之前的版本, 輸出結果就是如同大家想的一樣：

```
times = 32
```

可是如果你是使用 2.0.0 之後的版本 (至少到我今天使用的 2.0.2), 你會看到如下的輸出：

```
times = 620773686
```

這是什麼奇怪的妖術？直覺地想顯然我列印的變數 times 不是我程式裡宣告的 times, 但為什麼呢？

## 尋找 times 變數

還好有開放原始碼, 經過在 ESP32 Arduino Core 的 [github](https://github.com/espressif/arduino-esp32) 上搜尋, 發現有一個連結器 (linker) 使用的 [esp32.rom.syscalls.ld](https://github.com/espressif/arduino-esp32/blob/371f382db7dd36c470bb2669b222adf0a497600d/tools/sdk/esp32/ld/esp32.rom.syscalls.ld) 檔, 裡面有這樣的一段：

```
close = 0x40001778;
open = 0x4000178c;
read = 0x400017dc;
sbrk = 0x400017f4;
times = 0x40001808;
write = 0x4000181c;
```

所以應該是連結時把 times 重新定位到 0x40001808 這個位址了, 所以才會讀到奇怪的數值。為了驗證這一點, 只要印出 times 的位址來比對就知道了：

```cpp
int times = 32;

char buf[20];

void setup() {
  Serial.begin(115200);
  Serial.print("\n&times = ");
  sprintf(buf, "%p", &times);
  Serial.println(buf);
}

void loop() {}
```

輸出結果如下：

```
&times = 0x40001808
```

果然沒錯, 我在程式裡宣告的 times 變數被連結器重新定位了。但是為什麼會發生這樣的事呢？

## C++ 的連結性 (linkage)

C++ 對於每一個符號都有訂定它的[**連結性 (linkage)**](https://en.cppreference.com/w/cpp/language/storage_duration#Linkage), 在檔案中定義的全域變數如果沒有指定, 就會具備[**外部連結性 (external linkage)**](https://en.cppreference.com/w/cpp/language/storage_duration#external_linkage), 意思就是其他檔案內的程式也可以使用這個變數。因此, 像是我一開始舉的例子：

```cpp
int times = 32;
```

這個 times 就具備外部連結性, 它跟以下使用 [`extern`](https://en.cppreference.com/w/cpp/keyword/extern) 明確指定外部連結性是一樣的：

```cpp
extern int times = 32;
```

具有外部連結性的變數因為要能夠給其他檔案中的程式使用, 所以必須出現在符號表中, 才能依據其位址將其他檔案中用到此變數的地方重新定位到正確的位址。但是我們剛剛看到的 esp32.rom.syscalls.ld 檔的內容, 卻[定義了同名的符號](https://ftp.gnu.org/old-gnu/Manuals/ld-2.9.1/html_mono/ld.html#SEC13), 強制將 times 定位到指定的位址, 造成讀取變數內容時跑到不對的地方取值, 當然就讀到錯誤的值了。

## 使用 static 指定內部連結性 (internal linkage) 避免問題

要避免本文提到的問題, 最簡單的方法就是使用 [`static`](https://en.cppreference.com/w/cpp/keyword/static) 明確指定[**內部連結性(internal linkage)**](https://en.cppreference.com/w/cpp/language/storage_duration#internal_linkage), 這樣就不會讓變數可以讓其他程式檔使用, 也就不會出現在符號表中, 自然就不會被  esp32.rom.syscalls.ld 檔的作用影響。修改後的程式如下：

```cpp
static int times = 32;

void setup() {
  Serial.begin(115200);
  Serial.print("\ntimes = ");
  Serial.println(times);
}

void loop() {}
```

輸出的結果就是正確的 32 了：

```
times = 32
```

## 小結

對於在程式中宣告的全域變數, 如果沒有要給外部使用, 那麼最好養成使用 `static` 指定為內部連結性的好習慣, 不然難保哪一天會像我一樣採到雷, 花個一下午就為了找問題, 實在得不償失。
How to stop being controlled by your DC motor: reverse the roles! Part 1
Tags: robotics, tutorial, motor, luos
Published: 2022-03-30 15:02:05

Reverse the roles, take control of your DC motor!
⏩ https://www.luos.io/blog/how-to-stop-being-controlled-by-your-dc-motor-reverse-the-roles
Our game master Simon#2786 (on our Luos Discord) will develop in several articles the basics of DC motors in robotics, #edge, and #embeddedsystems and precisely how to control them.

Discover some concepts like direction control or motor rotation, and if you need, ask your question in a comment or on our Discord!
Something Different uncommented and commented
Published: 2022-03-30 14:59:00

slight change
this should fail
Short blog.

```python
def python():
  pass

```

**This is bold text**

_This is italic text_

`This is inline code`

[This is a link](www.google.com)

# Heading 1

##### Heading 5

- Bullet points

1. Number points

![Alternate text ](/media/useless-images/all-markdown-types.png "Image title")

code folding

<details>
<summary>I could use some help...</summary>
<p>

```python
def helloworld():
  print("hello")
```

</p>
</details>
 
new blog 
modified, removed, added
Sathyabama Institute of Science and Technology
Tags: education, admission, india
Published: 2022-03-30 14:54:44

Sathyabama Institute of Science and Technology (SIST), formerly Sathyabama University, is a private deemed to be university, situated at Chennai, Tamil Nadu, India. It was founded in 1987 as Sathyabama Engineering College by the late Jeppiaar and received its deemed to be university status in 2001.

Sathyabama Institute of Science and Technology has been accredited by the National Assessment and Accreditation Council (NAAC) with 'A' Grade.[4]

SATHYABAMA has received ISO 9001:2008 certification.[5]

The University is accredited by the governing body, National Buildings Organisation (NBO), Computer science engineering department latestly got the privilege of being accredited by NBO.

Sathyabama offers visits to companies. Some of the activities like Industrial Visit, Inplant Training, Advisory Bureau for Higher Studies, Entrepreneur Development Cell, Guest Lectures, Foreign Language Classes and Sports.
Something Different
Published: 2022-03-30 14:50:57

slight change
this should fail
Short blog.

```python
def python():
  pass

```

**This is bold text**

_This is italic text_

`This is inline code`

[This is a link](www.google.com)

# Heading 1

##### Heading 5

- Bullet points

1. Number points

![Alternate text ](/media/useless-images/all-markdown-types.png "Image title")

code folding

<details>
<summary>I could use some help...</summary>
<p>

```python
def helloworld():
  print("hello")
```

</p>
</details>
 
new blog 
modified, removed, added
Selenium WebDriver With JavaScript Tutorial | Generate Mocha Report With Mochawesome | Part VI
Published: 2022-03-30 14:47:36

Learn how to generate Mocha reports using Mochawesome, a popular and easy-to-use Mocha reporter for Selenium test automation. [Start FREE Testing](https://accounts.lambdatest.com/register?utm_source=devto&utm_medium=organic&utm_campaign=mar30_sb&utm_term=sb&utm_content=tutorial_video)

This video is the next part of the Selenium WebDriver JavaScript Tutorial series for beginners, wherein Ryan Howard (@ryantestsstuff) has explained how to add reports into the existing Selenium WebDriver test project with JavaScript.

By the end of this video, you will learn 🎫 -:

◼ What is Mochawesome report?
◼ Is Cypress based on mocha?
◼ How do I set up Mochawesome?
◼ How do I create a mocha report?
◼ How to customize a Mochawesome report?
◼ How do I use Mochawesome-merge?

This tutorial covers a step-wise advanced approach where beginners can learn the fundamentals and prerequisites for creating custom reports with the Mocha framework, adding Mochawesome into existing Selenium test projects, and more.
He likes me!
Tags: funny, chatbot, gpt3
Published: 2022-03-30 14:36:42

This is what my bot said:

Me: Never gonna give you up!
Bot:  What you need hos
Me: Never gonna let you dooooown!
Bot:  be alone

Awwwww. He likes me! (this is generated by a real GPT-3 chatbot made by me)

You can check him out at https://discord.st/gpt-bot!
And you can vote at https://discord.st/server/gpt-bot/!
omniauth-twitter2 gem - How to authenticate twitter account by OAuth 2.0 on your Rails app?
Tags: rails, ruby, omniauth, twitter
Published: 2022-03-30 14:27:26

---
title: "omniauth-twitter2 gem - How to authenticate twitter account by OAuth 2.0 on your Rails app?"
published: true
description: 
tags:
 - Rails
 - Ruby
 - OmniAuth
 - Twitter
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/755m0bbx0ncypl9ecepp.png
---

## tl;dr
I made this gem.

{% embed https://github.com/unasuke/omniauth-twitter2 %}

This gem is one of the OmniAuth strategies for Twitter, using OAuth 2.0 for the authentication protocol.

## We have omniauth-twitter gem. Why this gem?

Yes, the omniauth-twitter gem is a well-maintained, widely-used gem.

<https://github.com/arunagw/omniauth-twitter>

But, omniauth-twitter uses OAuth 1.0a.

## Twitter OAuth 2.0 GA from 2021-12-15
When 2021-12-15, Twitter announced OAuth 2.0 General Availability.

{% embed https://twitter.com/TwitterDev/status/1470834775019515907 %}

And we can use "new fine-grained permission scopes" at the release.

We could choose those three kinds of scopes in the older permission scope. That's too rough.

- Read
- Read and Write
- Read and write and Direct message

![OAuth 1.0a permission scopes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rgifpkpvuoz520pjzfdb.png)

But now, We can choose **enough permissions** from the list on OAuth 2.0 (through Twitter API V2)

<https://developer.twitter.com/en/docs/authentication/oauth-2-0/authorization-code>

`tweet.read`, `tweet.write`, `tweet.moderate.write`, `users.read`, `follows.read`, `follows.write`, `offline.access`, `space.read`, `mute.read`, `mute.write`, `like.read`, `like.write`, `list.read`, `list.write`, `block.read`, `block.write`

## OK, how to use twitter with OAuth 2.0 with my rails app?

I created a gem, "omniauth-twitter2". 

<https://github.com/unasuke/omniauth-twitter2>

This is one of the omniauth strategies, so it's easy to integrate your rails app if you use omniauth (or devise?)

("2" means OAuth 2.0, not means successor of "omniauth-twitter" gem. because the gem still working everywhare!)

And I have created a sample application that uses omniauth and omniauth-twitter2.

- URL: <https://twitter-login-app.onrender.com/>
- Source code: <https://github.com/unasuke/twitter-login-app>

This app only signs in with twitter, but it's enough to show how to implement "sign in with Twitter".

## Attention
If you want to use OAuth 2.0 API in your twitter app, you should move your app to under "Project". You can't use OAuth 2.0 in your app if the app is still a "Standalone app".

![twitter developer portal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ro4p0uaev4dm3l83o265.png) 

...And I'm not a specialist in the authentication. Please give me a pull request or issue if you found a bug.

-------

I'm glad if you star the GitHub repository or share the post, if you want!

:memo: Original post: <https://blog.unasuke.com/2022/how-to-authenticate-twitter-account-by-oauth-2/>
How A Clear Strategy Guides Your Blitzscaling Practice
Published: 2022-03-30 14:25:27

Colonel John Boyd was one of the best fighter pilots on the planet who risked his life every time he jumped into the cockpit. But thanks to his OODA loop strategy, high-velocity chases, death-defying rolls, and last-gasp pivots were no longer uncomfortable. 
Almost 70 years after the Korean War ended, his aerial battle strategy is one of the most popular business decision-making frameworks in the world, used by many fast-growing companies to guide their blitzscaling tactics. 
So, what does the military philosophy of a 1950s dogfighter have to do with the needs of fast-scaling startups today? 
Let’s consider the four stages of the OODA loop:
Observe:  Decision-makers must study their environment, identify changes at the micro or macro level, and determine whether a response is required. 
Orient: With their observations at hand, decision-makers must position themselves to protect against threats or take advantage of opportunities. 
Decide: Decision-makers must confirm if they are going to respond to the changing environment. While quick decision-making is encouraged, you should avoid acting out of any sense of obligation. Sometimes, the best course of action is to do nothing.
Act: Once decision-makers have made up their minds, they should act quickly.
Blitzscaling businesses can apply the tenets of the OODA loop to assess their current environment quickly, prepare for likely scenarios, make quick decisions and take action. 
This strategy is an iterative process that encourages rapid decision-making and consistent optimization, as decision-makers will return to the observation stage to assess the results before repeating the process. 


Final Thoughts
Whether it’s boxing, wrestling,  or blitzscaling, real growth only happens when you consistently put yourself in uncomfortable situations. It’s only through practice that you can develop the situational awareness you need to adapt to changes. 
When you're trying to move through the levels rapidly, things may seem chaotic without any clear or coherent plan. Whether 3 hours doing situps and punching things or it's grueling rounds at the gym, or endless dark mornings trudging through the snow with a bicycle heavy laden with newspapers, you can easily lose sight of your goals.  
Taking a proactive approach to practice and applying Boyd's strategy of an iterative loop will give you some direction. You can continually observe your ever-evolving environment, aggressively solve problems, and make changes on the fly. In short, you must embrace the chaos, harness your most elite inner just like a fighter pilot.
I love to talk about fighting and blitzscaling. If anyone is interested, please do reach out. My work email is thomas@armory.io, my calendly is https://calendly.com/thomas-mcgonagle and my cellphone is 339-203-3816. You can call anytime.