teleren/devto huggingface dataset:
Why are we still using Laravel helpers?
Tags: laravel, architecture, php
Published: 2024-04-15 05:04:23

If you look at the [list](https://laravel.com/docs/11.x/helpers), you will see functions like `app`, `config`, `response`, and so on.
Maybe you are thinking why won't you use these functions? They are a part of the framework.

If you look at the code for the helpers most of the time they are syntactic sugar for calling facade classes.

Look at this controller;

```php

class HomePageController {
   public function __invoke() {
     if(!auth()->hasUser()) {
       return redirect()->route('login');
     }

     $user = auth()->user();
     $timezone = config('app.timezone');
     $api = resolve('HelpSpot\API');
     // do something with the variables
     return view('homepage');
   }
}
```
If you written this controller with facades, you get;

```php
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;

class HomePageController {
    public function __invoke(Auth $auth, Redirect  $redirect, Config $config, App $app, View $view) {
        if(!$auth::hasUser()) {
            return $redirect::route('login');
        }

        $user = $auth::user();
        $timezone = $config::get('app.timezone');
        $api = $app::get('HelpSpot\API');
        // do something with the variables
        return $view::make('homepage');
    }
}
```
 As you can see using facades is not a lot more code. I disregard the imports because they are handled by your IDE. 

Adding the facade classes as parameters of a function has multiple benefits over using the helper functions.

- You know exactly which facade you are using. Did you know the resolve function is using the App facade? The resolve function is syntactic sugar for the app function if you look at the code.

- Your functions are easier to mock. So instead of needing end to end tests, you can use unit tests.

- When you see the dependencies, you are going to be warned faster that the function is doing a lot of things. And you can figure out a way to prevent this.

I was thinking why are the helpers still in the framework. And the only idea I had is, because it is a remnant of the time intellisense wasn't as good as it is now. The helpers are easier to remember for the people that write code without intellisense.

Now you just type a few letters and you get a list of classes you can to use. Your IDE imports the class to make the parameter types shorter. And you type a double colon or an arrow and you get a list of methods you can use.

So instead of using your brain to memorize helpers, let you code editor do that work for you. And you concentrate on the things you are building.
Postgres on Debian in WSL
Tags: postgres, wsl, debian
Published: 2024-04-15 04:16:48

This article covers the basics of installing and running Postgres on Debian running in [Windows subsystem for Linux](https://learn.microsoft.com/windows/wsl/about) (WSL).

WSL makes for a great development environment if you're running Windows and want to use Linux locally. You could of course install Postgres directly on Windows but you may have various reasons for wanting a more authentic Linux environment.

## Which Linux distro?
You can choose from many Linux distributions to run on WSL (run _wsl -l -o_ to see a list or import any distro using a TAR file). I like to use **Debian** as it's a popular, stable, general purpose distro with good support. You can install Debian to WSL directly from the [Microsoft Store](https://apps.microsoft.com/detail/9msvkqc78pk6?hl=en-US&gl=US), and use [Windows Terminal](https://learn.microsoft.com/windows/wsl/setup/environment#set-up-windows-terminal) to log on to it.

## Install Postgres
Once you're connected to the Debian command line, make sure you're up to date with the latest patches:

```
sudo apt update
sudo apt upgrade
sudo apt autoremove # to free up space if needed
```

Then install with:

```
sudo apt install postgresql postgresql-contrib
```

See [Install PostgreSQL](https://learn.microsoft.com/windows/wsl/tutorials/wsl-database#install-postgresql) in the WSL docs for more details.

Set a password for the postgres user with _sudo passwd postgres_ and then start the service:

```
sudo passwd postgres
sudo service postgresql start
sudo systemctl enable postgresql # to start service automatically
```

You can then enter the PostgreSQL shell with:

```
sudo -u postgresql psql
```

..and from there run SQL commands, e.g. create PostgreSQL users with _CREATE USER_

Or run SQL commands directly, e.g.

```
sudo -i -u postgres psql < create_db.sql
sudo -i -u postgre psql -d mydb < create_schema.sql
# list databases
sudo -i postgres psql --list
```

## Connecting with pgAdmin
You can install [pgAdmin](https://www.pgadmin.org/) on Windows and connect the GUI Admin/developer tool directly to your Postgres server running in WSL.

In pgAdmin, create a new server with the name of your choice, Host name/address: 127.0.0.1 and a valid PostgreSQL user/password.

![A screen shot of a pgAdmin new server definition panel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ztthuzw4l7j5acqx390q.png)


![A screen shot of pgAdmin server view](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ha0cvbdustsmrdoutgv2.png)
Once I've done my local development it's very straightforward to export a database from WSL to a Postgres cloud service or other production destination.
🍕English Tutor: Speak and get instant feedback about your vocabulary
Tags: cloudflarechallenge, devchallenge, ai
Published: 2024-04-15 03:50:16

*This is a submission for the [Cloudflare AI Challenge](https://dev.to/devteam/join-us-for-the-cloudflare-ai-challenge-3000-in-prizes-5f99).*

## What I Built

I built an app that you can SPEAK directly in the browser and get instant feedback about your vocabulary by talking with "english tutor"

This app can easily become a micro saas, where you ask about the language the customer wants to learn and get paid by use.


## Demo

Link to [video demo 🚀](https://www.youtube.com/watch?v=es9RQaPi7jA)

Link to [live demo 🤙🏻](https://englishtutor.pages.dev/)

## My Code

Here is my code: https://github.com/IgorHalfeld/englishtutor

## Journey

I live in Brazil and here a lot of people don't practice speaking so I built this app to use AI to help them enhance english skills.

AI Models used:
 - `@cf/openai/whisper`
 - `@cf/qwen/qwen1.5-0.5b-chat`

## Feedbacks to Cloudflare

This is my first time using CF Worker and I know how important it is to get feedback from customers, so here is mine:

- Workers DX are not good
The best way I found to make this work great was by using Honojs

- 1MB to deploy a frontend is not enough
I faced this trouble when deploying Nuxt app, so I made a [workaround versioning static generated files](https://github.com/IgorHalfeld/englishtutor/tree/main/.output)
_As you can see by the source code above, it's a really simple app to get this message about the size_

- Whisper could have a parameter to pass the language
If I could define the language I'm speaking this would not happen
![error screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uh5dtvw935h6rnutfgu4.png)

- Generic errors from wrangler commands when using AI Workers
Errors like "Unknown internal error" happened multiple times
How to Connect BH1750 with Arduino: Measure Ambient Light
Published: 2024-04-15 03:37:07

{% embed https://www.youtube.com/watch?v=Z4abxVif80A %}

In this tutorial video, you'll learn how to physically connect the BH1750 light sensor to your Arduino board and use Arduino code to retrieve luminance values from the sensor in lux units. This knowledge is incredibly useful for various applications, from smart lighting systems to environmental monitoring setups. By following the steps carefully, you'll understand both the hardware setup and the code integration process, allowing you to incorporate the BH1750 sensor seamlessly into your projects. Before reading the remainder, be sure to subscribe and support the channel if you have not!

**Subscribe:**
[Youtube](https://www.youtube.com/@mmshilleh)

**Support:**
https://www.buymeacoffee.com/mmshilleh

## Step 1-) Physical Setup

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/atfgduwwnlni0k8807a5.png)

For this tutorial, we'll be using an Arduino Nano, but feel free to use any Arduino model you prefer. Just ensure that you map the same four connections for I2C. Keep in mind that different Arduino models may have different pin arrangements, so match all connections appropriately according to your specific board's layout. Additionally, verify that the pinout matches your BH1750 sensor to ensure seamless integration.

## Step 2-) Code Arduino IDE

Go to Arduino IDE and download the BH1750 library by Christopher Laws. You can download it from the Library Manager.

Next you can open an example file in File > Examples > BH1750 > BH1750test. If you did everything properly you can run this example which incrementally reads lux values from the sensor. Shine a light at your BH1750 and see how it reacts, the lux values should increase accordingly, pretty neat. This code is the building block of projects you can create with this sensor. I hope you got it to work

## Conclusion

If you found this BH1750 tutorial helpful, consider subscribing to the channel. Your support enables us to create more simple and useful videos for the community.
Fix code . command not working | Visual Studio Code
Tags: vscode, javascript
Published: 2024-04-15 02:50:40

# How to Reinstall Visual Studio Code on macOS Using Command Palette

Visual Studio Code is a popular code editor among developers for its versatility and extensive features. However, sometimes you might encounter issues with the `code` command not working in the terminal, especially after an update or if you've had a problematic installation. In this guide, we'll walk through the steps to reinstall Visual Studio Code on macOS using the Command Palette.

## Step 1: Remove Previous Installation (if needed)

If you're experiencing issues with the `code` command, it might be due to a previous installation. Let's start by removing the existing `code` binary.

Open your terminal and run:

```bash
sudo rm /usr/local/bin/code
```

This command removes the `code` binary from the `/usr/local/bin` directory.

## Step 2: Reinstall Visual Studio Code

Now, open Visual Studio Code. Since the `code` command is missing, you won't be able to launch it from the terminal directly. Instead, we'll use the Command Palette within Visual Studio Code to set it up.

## Step 3: Use Command Palette to Install 'code' Command

1. **Open Visual Studio Code**.
2. Press `Ctrl + Shift + P` (or `Cmd + Shift + P` on macOS) to open the Command Palette.
3. Type `Shell Command: Install 'code' command in PATH` and select it when it appears in the list.

   ![Command Palette](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5tg8qjbpjuqverz1fv23.png)

4. Follow the instructions in the popup that appears. This will automatically set up the `code` command for you.

## Step 4: Verify Installation

After completing these steps, you should be able to use `code .` in the terminal to open Visual Studio Code in the current directory. This method is very handy for setting up the `code` command without manually editing configuration files.

### Additional Note for Users with Multiple Terminals

If you have more than one terminal installed (e.g., zsh, bash), you'll need to repeat the steps (Step 3 -> Point 3) above for each terminal you use. This ensures that the `code` command is available in all your terminal sessions.

### Summary

In this guide, we've covered how to reinstall Visual Studio Code on macOS using the Command Palette. If you're encountering issues with the `code` command not working in the terminal, following these steps should help resolve the issue.

If you have any questions or encounter any difficulties during the process, feel free to ask in the comments below!
Arduino IDE 1.8.19 ESP32 編譯當掉
Tags: esp32, arduino
Published: 2024-04-15 03:26:37

最近使用 Arduino IDE 1.8.19 版本開發 ESP32 專案遇到奇怪的問題, 只要開啟**顯示詳細輸出**, 編譯就會當掉無法結束：

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cjt8jmv227l57ua7u2fl.png)

目前還不知道原因是什麼？但是只要關閉顯示詳細輸出, 就可以正常運作。

## ESP32 開發板套件降版本

如果你在額外的開發板管理員網址輸入的是：

```
https://espressif.github.io/arduino-esp32/package_esp32_index.json
```

就不會顯示舊版本的 ESP32 套件, 若是需要降版到較舊的版本, 可以改使用以下的開發板管理員網址：

```
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
```
Developer’s Guide : Modular, Flexible, Scalable Prod ready RAG
Tags: machinelearning, llm, rag, systemdesign
Published: 2024-04-15 03:19:52

Hands-On with Cognita : modular, open source RAG application for prod, built w/ scalability in mind.

[Full Article](https://medium.com/@learn-simplified/developers-guide-modular-flexible-scalable-prod-ready-rag-d5ee5a6dcf85)

This comprehensive guide provides a hands-on approach to building and deploying Retrieval Augmented Generation (RAG) systems using Cognita, a modular and open-source framework designed with scalability in mind. The article walks you through the process of setting up Cognita, ingesting your knowledge base, and leveraging its core features to develop production-ready RAG applications.

🔹 Seamless Setup: Step-by-step instructions guide you through cloning the Cognita repository, creating a virtual environment, installing dependencies, and configuring the necessary files.

🔹 Knowledge Base Ingestion: Learn how to ingest and process your knowledge base, including chunking documents, generating embeddings, and indexing into a vector database.

🔹 Modular Architecture: Cognita promotes separation of concerns by decoupling the data ingestion process from the query service, enabling independent scaling and efficient updates.

🔹 Scalable Deployment: Explore how Cognita facilitates scalable deployments by integrating with cloud infrastructure, allowing independent scaling of components based on resource requirements.

🔹 Production-Ready: Discover the key challenges addressed by Cognita when transitioning a RAG system from a development environment to production, such as chunking and embedding large datasets, building scalable query services, deploying language models and embedding models as separate services, and setting up robust vector databases.

🔹 Hands-On Example: Follow along with a practical example that demonstrates ingesting a credit card knowledge base, configuring the RAG system, and testing the question-answering capabilities using cURL requests.

Whether you're a seasoned developer or new to RAG systems, this article equips you with the knowledge and tools to build modular, flexible, and scalable production-ready RAG applications using the Cognita framework.
３章２０
Published: 2024-04-15 03:17:30

もちろんです。以下は、Javaのコードスニペットにコメントを追加したものです。各`case`文の動作を解説しています。

```java
public class Main {
    public static void main(String[] args) {
        final int NUM = 0; // 'NUM'は定数として0に設定されている。
        int num = 10; // 'num'は変数として10に設定されている。

        switch (num) { // 'num'の値が10であることに基づいて、以下の'case'文が評価される。

        // 以下のケースでは型の不一致があるためコンパイルエラーになる。
        // 'num'はint型であるため、文字列リテラルとマッチすることはできない。
        case "10": // コンパイルエラー: 'case'ラベルは'int'型のリテラルか定数式である必要がある。 "10"はString型（文字列型）
            System.out.println("A");
            break;

        // 以下のケースでは変数が使用されており、Javaではコンパイルエラーとなる。
        // 'case'ラベルには定数値が必要であり、変数を使うことはできない。
        case num : // コンパイルエラー: 'case'ラベルとして変数は許されていない。
            System.out.println("B");
            break;

        // このケースは正しく機能する。'2 * 5'はコンパイル時に評価される定数式であり、
        // 'num'の値と一致するため、このケースが実行される。
        case 2 * 5 : // 実行されるケース: 'num'の値10と一致。
            System.out.println("C"); // この行が出力される。
            break;

        // 以下のケースでは定数が使われているが、'num'の値とは一致しない。
        // 'NUM'は0であり、'num'の値は10なので、一致しない。
        case NUM : // 実行されないケース: 'NUM'は0であり、'num'の値10とは一致しない。
            System.out.println("D");
            break;
        }
    }
}
```
上記のコメントはコードの各部分がどのように機能するか（または機能しないか）を説明しており、特に6行目と8行目のコンパイルエラーに注目しています。`case "10":`は型の不一致でコンパイルエラーが生じ、「`case num:`」は`switch`文内で変数が`case`ラベルとして許されていないため、こちらもコンパイルエラーが生じます。
Plugin: Análise de Vulnerabilidade
Tags: ide, plugin, relato, intellij
Published: 2024-04-15 03:17:03

## Package Checker - IntelliJ Idea Community

Ao atualizar a minha IDE (Integrate Development Environment), percebi então uns warnings diferentes conforme a imagem abaixo:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i5fgmatyh8ccft7d26bq.png)

Isso foi muito util porque pude esperar os desafios que esse projeto construído alguns anos atrás poderia trazer de surpresas.

Deixei o meu relato, mas o que é esse plugin que está disponível na versão 2024.1 (Community Edition) da IDE da [JetBrains](https://www.jetbrains.com/) e o que ele faz?

O plugin busca vulnerabilidades nas dependências (Pacotes) do projeto na IDE, e as analisa destacando quais dependências estão vulneráveis no editor, sugerindo correções, por qual dependência deveria trocar, e traz funcionalidades como:
 
- Ignorar a vulnerabilidade (Not Cool); 
- Reportar falsos positivos; 

A base de vulnerabilidades é alimentada pela empresa [Checkmarx](https://checkmarx.com/). 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mr1scllvj08c28pcpg7n.png)

No meu caso sou desenvolvedor Java, além de analisar projetos Gradle e Maven também funciona com NPM, PyPI, e NuGet.

Para mim é mais uma ferramenta voltada para o [desenvolvimento seguro](https://dev.to/teuscode/introducao-ao-desenvolvimento-seguro-1nml), antes essas informações estariam em uma [esteira de desenvolvimento](https://dev.to/m3corp/ci-cd-e-as-esteiras-ome) ou em ferramentas [SAST](https://dev.to/pavini/analise-sast-com-veracode-uma-abordagem-detalhada-15jg) como Veracode Greenlight, agora está gratuita ao nosso alcance antes mesmo da primeira entrega.

Se você gostou do artigo, comente se você já utilizou ou utiliza algum plugin de "Análise de Vulnerabilidade".

---

Para quem deseja aprofundar mais no plugin, abaixo o link da fonte oficial:
[https://www.jetbrains.com/help/idea/package-analysis.html](https://www.jetbrains.com/help/idea/package-analysis.html)
mount: /mount/path: wrong fs type, bad option, bad superblock on /dev/sda3, missing codepage or helper program, or other error.
Tags: ubuntu, mount, path, errors
Published: 2024-04-15 03:04:34

I changed from Windows Desktop to Ubuntu almost a year ago due to blue screen errors that damaged my productivity. Prior Linux environment experience was on deployment servers, cloud containers and WSL. My other 3 partitions on the hard disk are still NTFS after installing the Ubuntu desktop. I document the issues I face and how I overcome them.

## Background

Upon upgrading from Ubuntu 23.01 to Ubuntu 23.10, I encountered a strange error when the Ubuntu desktop GUI file explorer Icon was active and I rushed to check my three partitions. The error read "wrong fs type, bad option, bad superblock on /dev/sda3, missing codepage or helper program, or other error". You can imagine how terrified I was!


## Problem

![mount: /mount/path: wrong fs type, bad option, bad superblock on /dev/sda3, missing codepage or helper program, or other error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2x7roajiun3ginsea1s.png)

Research 
Listing all the block devices showed two device partitions with no mount path with the following command:

```sh
lsblk
```

![Listing all the block devices](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zkktbhzlic29iughmw97.png)
navigating to the media folder to check the available directories, the two media paths were missing

```zsh
kesa@KESA-DESKTOP:/$ cd media/
kesa@KESA-DESKTOP:/media$ ls
kesa
kesa@KESA-DESKTOP:/media$ cd kesa/
kesa@KESA-DESKTOP:/media/kesa$ ls
XYZ
```

## Solution

Manually mount the device or partition. Create mount paths with the label of the partition that can be found using `lsblk -f`

![list block devices towith -f flag to see device labels](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jc0essktos9r5uaq7wwa.png)

In my case:
```sh
kesa@KESA-DESKTOP:/media/kesa$ sudo mkdir WORKSPACE
```
mount the device partition using the mount command to the newly created mount path
```sh
kesa@KESA-DESKTOP:/media/kesa$ sudo mount /dev/sda3 /media/kesa/WORKSPACE
```

![mount device command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2z8o98psfxmmpsam7nmk.png)
```sh
kesa@KESA-DESKTOP:/media/kesa$ sudo mount /dev/sda1 /media/kesa/New\ Volume
```

change the device name and path in your scenario. Ensure you use the root user when you encounter permission issues. Check final block devices with the list block command.


![manual mount successful](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v9lv0x8cj8vr739sjv2h.png)

### Using disks application


![disks application option](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jq5px6ynrlfxf3augo5p.png)


![turn off user sessions defaults](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jpawe2kcmabgxqdj3eo3.png)

Turn User Session Defaults Off and click OK
Implementing Microfrontends
Tags: webdev, javascript, beginners, programming
Published: 2024-04-15 02:59:40

## Introduction

Microfrontends is a relatively new approach to web development that involves breaking down a complex frontend application into smaller, independent and self-contained parts. Each of these parts or microfrontends can be built and deployed independently, allowing for a more modular and flexible architecture. In this article, we will discuss the advantages, disadvantages, and features of implementing microfrontends.

## Advantages

One of the major advantages of microfrontends is the ability to scale and maintain large and complex frontend applications more efficiently. Each microfrontend can be developed and tested separately, leading to faster development and deployment cycles. This enables teams to work independently on different parts of the application, improving overall productivity and reducing development time. The use of microfrontends also minimizes the impact of changes to one component, making it easier to maintain and update the entire application.

## Disadvantages

Despite its advantages, microfrontends also have some drawbacks. One of the main challenges is managing the communication between different microfrontends, as it can be challenging to maintain a consistent user experience across the application. Furthermore, implementing microfrontends can increase the complexity of the project and require a high level of expertise from the development team.

## Features

Some key features of microfrontends include the use of frameworks like React, Vue, or Angular, which allow for the creation of modular and reusable components. It also enables the integration of microfrontends with different backend technologies, allowing for a more flexible and diverse tech stack. Additionally, the use of microfrontends makes it possible to adopt a microservices architecture, which provides better scalability and resilience.

### Example of Microfrontend Architecture

```javascript
// A basic example of a microfrontend using React
function App() {
  return (
    <div>
      <h1>Welcome to the Microfrontend</h1>
      <p>This is a standalone microfrontend component.</p>
    </div>
  );
}

export default App;
```

This simple example demonstrates how a React component can be structured as a microfrontend, focusing on specific functionality within a larger application.

## Conclusion

Implementing microfrontends offers several benefits, including improved scalability, flexibility, and productivity. However, it also comes with its challenges, requiring careful consideration and planning before implementation. With the right approach and a thorough understanding of its features and limitations, microfrontends can be a powerful tool in building modern and maintainable frontend applications.