teleren/devto huggingface dataset:
Bora falar de WebSockets ?
Tags: programming
Published: 2024-04-17 00:43:08

Saudações, Mentes Tech!

Nos últimos anos estive bastante envolvido com comunicação em tempo real, após ficar obsecado por crypto e negociações automatizadas no financeiro.
Quero contar um pouco do que aprendi neste post e acredito que tenha espaço para mais alguns.

### O que é WebSockets

WebSockets são uma tecnologia de comunicação bidirecional e em tempo real, que permite a transferência de dados entre um cliente e um servidor de forma assíncrona. 

Ao contrário do HTTP tradicional, que é baseado em requisições e respostas, os WebSockets estabelecem uma conexão persistente entre o cliente (navegador, uma aplicação golang) e o servidor, possibilitando a troca de mensagens em tempo real sem a sobrecarga de requisições repetidas. 
Isso torna os WebSockets ideais para aplicações que requerem atualizações instantâneas, como chats, jogos online e transmissões ao vivo.

Agora que você já sabe o que é WebSocket, que tal falarmos da aplicação no mundo real e como ele funciona de forma resumida. 
Bora lá?!

## Como WebSockets funciona ? 

Os WebSockets funcionam através de uma conexão persistente entre um cliente e um servidor. 

**Nota: este é um processo resumido. ;D**


![websocket handshake](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cubtbr0afvemqb4gt0j7.png)

**Handshake inicial**: O cliente envia uma requisição HTTP com um cabeçalho específico solicitando uma atualização para o protocolo WebSocket. Se o servidor suporta WebSockets, ele responde com uma confirmação, também contendo cabeçalhos específicos.

**Estabelecimento da conexão**: Uma vez que o handshake inicial é bem-sucedido, a conexão WebSocket é estabelecida. Isso geralmente é feito através de um upgrade de protocolo, onde a conexão HTTP é atualizada para uma conexão WebSocket.

**Comunicação bidirecional**: Com a conexão estabelecida, tanto o cliente quanto o servidor podem enviar mensagens um para o outro a qualquer momento, de forma assíncrona. Não é necessário esperar por uma solicitação do cliente para enviar uma resposta do servidor, ou vice-versa.

**Encerramento da conexão**: Quando a comunicação não é mais necessária, a conexão WebSocket pode ser fechada. 
Isso pode ser feito por qualquer uma das partes, enviando uma mensagem de fechamento para a outra parte.

Com a conexão estabelecida, tanto o cliente quanto o servidor podem enviar mensagens um para o outro a qualquer momento, de forma assíncrona. 

E não necessita esperar por uma solicitação do cliente para enviar uma resposta do servidor, ou vice-versa.


## WebSocket no mundo financeiro

A comunicação em tempo real e baixa latência é essencial no mercado financeiro, o no meu caso de uso serve para obter as melhores ofertas assim que elas são inseridas no livro.


Valeuu e até a próxima.
Building a Web Scraper with Node.js
Tags: javascript, beginners, programming, tutorial
Published: 2024-04-17 00:29:43


## Introduction

Web scraping has become an essential tool for collecting and analyzing data from various websites. It allows users to extract large amounts of data quickly and efficiently. With the rise of Node.js, building a web scraper has become even easier. In this article, we will discuss the advantages, disadvantages, and features of building a web scraper with Node.js.

## Advantages

1. **Easy to learn and use:** Node.js is a popular and widely used language, making it easier for developers to learn and use.

2. **Asynchronous processing:** Node.js uses an event-driven, non-blocking I/O model, making it perfect for web scraping, which requires fetching data from multiple websites simultaneously.

3. **Flexibility:** With Node.js, you have the flexibility to customize your web scraper and choose from various packages and libraries to suit your needs.

## Disadvantages

1. **Limited scalability:** Node.js is not suitable for large-scale web scraping projects as it is based on a single-threaded model, limiting its scalability.

2. **Dependency management:** As Node.js uses various packages and libraries, continuously updating them can be a hassle, leading to dependency management issues.

## Features

1. **HTTP Request handling:** Node.js has built-in modules for handling HTTP requests, making it easier to fetch data from websites.

2. **Cheerio:** A powerful library for parsing HTML, allowing developers to extract data from websites efficiently.

### Example of Using Node.js and Cheerio for Web Scraping

```javascript
const axios = require('axios');
const cheerio = require('cheerio');

async function fetchHTML(url) {
    const { data } = await axios.get(url);
    return cheerio.load(data);
}

async function scrapeData() {
    const $ = await fetchHTML('https://example.com');

    $('h1').each((index, element) => {
        console.log($(element).text()); // Logging the text of each h1 tag found
    });
}

scrapeData();
```

This example demonstrates how to set up a simple web scraper using Node.js with Axios for HTTP requests and Cheerio for parsing HTML. The code fetches data from a specified URL and logs the text of each `h1` tag found on the page.

## Conclusion

Building a web scraper with Node.js has its advantages, such as ease of use and flexibility, but it also has its limitations, such as limited scalability. With the right approach, Node.js can be a powerful tool for web scraping, allowing developers to gather and analyze data from various sources quickly and effectively.
The Value of Having a Frontend Developer Specialist in Your Team
Published: 2024-04-17 00:24:37

In today's rapidly evolving tech landscape, having a frontend developer specialist on your team can be a game-changer. Here's why:


**Expertise in UI/UX**: Frontend specialists bring a deep understanding of user interface (UI) and user experience (UX) design principles. They can create visually appealing and user-friendly interfaces that enhance the overall user experience. 💻
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pidcpzboe29n5jiok47m.png)


**Performance Optimization**: With the increasing complexity of web applications, performance optimization has become crucial. Frontend specialists are skilled in optimizing code, reducing load times, and improving overall performance. 🚀
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ye42ccof490iyjrp5sbp.png)



**Cross-Browser Compatibility**: Ensuring that your application works seamlessly across different browsers and devices is essential. Frontend specialists have the expertise to tackle compatibility issues and deliver a consistent experience to users. 🌐
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s31kl78wd8aoliqb2r01.png)


**Accessibility**: Accessibility is a key consideration in modern web development. Frontend specialists can ensure that your application is accessible to users with disabilities, improving inclusivity and usability. ♿️
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pnc00s5gaevxyuhyoirn.png)


**Technology Expertise**: Frontend development encompasses a wide range of technologies and frameworks. Specialists stay updated with the latest trends and best practices, ensuring that your application is built using the most suitable tools for the job. 🔧
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4u5jhqmditxb40zyvdfe.jpeg)


**Collaboration**: Frontend specialists work closely with designers, backend developers, and other stakeholders to bring projects to life. Their ability to collaborate effectively can streamline the development process and lead to better outcomes. 🤝
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dz3yr7aci5npcjlliiq6.jpeg)


**In conclusion**, having a frontend developer specialist on your team can significantly enhance the quality, performance, and user experience of your applications. Their expertise and focus on frontend technologies make them a valuable asset in today's competitive market.

Happy coding! 🚀
Papa Smurf Chatbot on Vanilla JS
Tags: javascript, bot, beginners
Published: 2024-04-17 00:09:43

So, I made a bet with a friend that I could create a chat bot in 
Vanilla Javascript. 

Long story short, here's [my Papa Smurf on GitHub pages](https://theomorphic.github.io/Papa-Smurf/)

I will be glad to receive feedback
Welcome Thread - v272
Tags: welcome
Published: 2024-04-17 00:00:00

---
published_at : 2024-04-17 00:00 +0000
---
![Cartoon smiley face saying "hi"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3v003k7hemg2f316qhz7.gif)

---

1. Leave a comment below to introduce yourself! You can talk about what brought you here, what you're learning, or just a fun fact about yourself. 

2. Reply to someone's comment, either with a question or just a hello. 👋

3. Share your wins from this week in our weekly ["What was your win this week?](https://dev.to/t/weeklyretro) thread.
Keep Astro Content Collection Types in Sync on Git Commit
Tags: blogging, contentcreation, javascript, node
Published: 2024-05-04 10:23:48

---
title: Keep Astro Content Collection Types in Sync on Git Commit
published: true
date: 2024-04-17 00:00:00 UTC
tags: blogging,contentcreation,javascript,node
canonical_url: https://billyle.dev/posts/keep-astro-content-collection-types-in-sync-on-git-commit
---

I'm not sure when but sometimes the type definitions in the .astro folder keep going out of sync once in a while. Instead of adding the schema definitions from my collections, it replaces them with the `any` type.

Here is a preview of the issue from my Git history:

![schema types replaced by any type](https://billyle.dev/_astro/types-to-any.BgAE5NCz.png)

This is an issue for me since I love working with Typescript and having that safety matters when I'm developing my site.

According to [Astro's docs](https://docs.astro.build/en/guides/content-collections/#the-astro-directory), it runs `astro sync` whenever you run `astro dev` or `astro build` so somehow during development, the types become `any`.

## The fix

We're going to re-sync our types and make sure that we get the results we want by running the `astro sync` command again on a Git commit.

Add a script to your `package.json` called `sync` or whatever you like and give it the value `astro sync`.

```
{
  "scripts": {
    "sync": "astro sync"
  }
}

```

You'll need to have Husky installed in your project for this to work. It's relatively simple to set up and I talked about it [here](/posts/use-husky-and-node-to-unstage-draft-posts-from-git#what-is-husky).

Inside your `.husky/pre-commit` file, add these lines anywhere in the file. I'm using pnpm. Remember to replace "pnpm" with your package manager CLI command to run scripts.

```
pnpm sync
git add .astro/types.d.ts

```

And that should do it! Whenever you make a new commit, the pre-commit will fire and it will sync your content collections' schemas perfectly.

Thanks for reading and have a good one! 😄
Hello World
Published: 2024-04-16 23:43:01

Saudações, Mentes Tech!

Nada como o clássico "Hello, World!" para começar uma jornada no mundo da programação. 
Hello world é como abrir uma porta para um universo de possibilidades, onde linhas de código se transformam em soluções criativas e inovadoras.

Para alguns, um simples programa; e pode parecer trivial, mas para nós, é o primeiro passo rumo a projetos complexos e desafios emocionantes. 
É o momento em que mergulhamos de cabeça em linguagens de programação, explorando sua sintaxe, estruturas e funcionalidades.

Então, aqui estamos, prontos para embarcar nessa jornada emocionante. 

Este é o meu "Hello, World!", mas sei que logo estaremos construindo coisas incríveis juntos.

Vamos codar!
How to Find Skilled Remote Developers?
Tags: hire, remote, developers
Published: 2024-04-16 22:31:10

Looking to [hire remote developers](https://acetechnologies.com/hire-remote-developers)? Ace Technologies, a leading recruitment agency in San Jose, California, specializes in connecting businesses with top-tier talent, including remote developers. With over 30 years of experience, we understand the unique needs of tech-driven companies. Let us help you find skilled remote developers who can seamlessly integrate into your team and drive your projects forward. Trust Ace Technologies for all your staffing needs.
Volumes in Docker
Published: 2024-04-03 12:03:36

## Problem Statement

It is a very common requirement to persist the data in a Docker container beyond the lifetime of the container. However, the file system
of a Docker container is deleted/removed when the container dies. 

## Solution

There are 2 different ways how docker solves this problem.

1. Volumes
2. Bind Directory on a host as a Mount

### Volumes 

Volumes aims to solve the same problem by providing a way to store data on the host file system, separate from the container's file system, 
so that the data can persist even if the container is deleted and recreated.

![image](https://user-images.githubusercontent.com/43399466/218018334-286d8949-d155-4d55-80bc-24827b02f9b1.png)


Volumes can be created and managed using the docker volume command. You can create a new volume using the following command:

```
docker volume create <volume_name>
```

Once a volume is created, you can mount it to a container using the -v or --mount option when running a docker run command. 

For example:

```
docker run -it -v <volume_name>:/data <image_name> /bin/bash
```

This command will mount the volume <volume_name> to the /data directory in the container. Any data written to the /data directory
inside the container will be persisted in the volume on the host file system.

### Bind Directory on a host as a Mount

Bind mounts also aims to solve the same problem but in a complete different way.

Using this way, user can mount a directory from the host file system into a container. Bind mounts have the same behavior as volumes, but
are specified using a host path instead of a volume name. 

For example, 

```
docker run -it -v <host_path>:<container_path> <image_name> /bin/bash
```

## Key Differences between Volumes and Bind Directory on a host as a Mount

Volumes are managed, created, mounted and deleted using the Docker API. However, Volumes are more flexible than bind mounts, as 
they can be managed and backed up separately from the host file system, and can be moved between containers and hosts.

In a nutshell, Bind Directory on a host as a Mount are appropriate for simple use cases where you need to mount a directory from the host file system into
a container, while volumes are better suited for more complex use cases where you need more control over the data being persisted
in the container.
Day 945 : D.E.E.P.
Tags: hiphop, code, coding, lifelongdev
Published: 2024-04-16 22:26:22

_liner notes_:
- Professional : What a day! So many meetings for a Tuesday. Spoke with some folks about the research that I did yesterday to see if a project would be possible. We determined that I should go ahead and create a proof of concept. Now, I've never done anything like this before so I'll definitely be learning a lot of new stuff. So with A LOT of documentation opened in A LOT of browser tabs, I got started. I fixed a demo project that I created like 10 months ago to use as a base that I can build on top of. I was so D.E.E.P. deep into the code that I totally lost track of time.

- Personal : So I finished up my current side project and linked them to some domains that I purchased. I must have done something wrong, because the site URL without "www" works, but with it, I get an error. For the other domain name, I did the opposite and the opposite happens. I just need to sit down and read through the documentation because something isn't right. This is my first time using this company for setting the DNS for a project.

![This is an image of a beautiful beach. The sky is blue and cloudy, and the sun is shining through the clouds. The water is a deep blue and green, and the waves are gently crashing on the shore. The sand is white and soft, and there are a few palm trees growing along the shore. In the background, there is a large rock formation. The beach is located in Fraser Island, Australia.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eehli4faldxigiispvew.jpg)

Going to figure out what is happening with these domain names, I want to work on the highlight clip generator and finalize the part where I generate a video with some text. Then I want to see if I REALLY need to upload a video to get clips. Going to dive more into some documentation. I also want to research some possible events to attend on my next work trip. Need to get that situated soon because the date is coming up. I have not been binge watching "X-Men" animated series.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube PjhgVyCwb6U %}
５章８
Published: 2024-04-16 03:01:53

このJavaのコードは2次元配列の各要素（ここでは文字列配列）の長さを合計して出力しています。ただし、コードの解説と答えEに至る理由を以下に説明します。

```java
1.  public class Main {
2.    public static void main(String[] args) {
3.      // 2次元のString配列を定義する。3つの要素があり、
3.      // 1つ目は{"A", "B"}、2つ目はnull、3つ目は{"C", "D", "E"}です。
4.      String[][] array = { { "A", "B" }, null, { "C", "D", "E" } };
5.      // totalの変数を0で初期化する。
6.      int total = 0;
7.      // arrayの各要素（String配列）に対してループを実行する。
8.      for (String[] tmp : array) {
9.          // ここでtmpがnullの場合、tmp.lengthはNullPointerExceptionを引き起こす。
10.         total += tmp.length;
11.     }
12.     // totalを出力する。ただし、上記のエラーが発生するため、
13.     // 実際にはこの行に到達する前にプログラムはクラッシュする。
14.     System.out.println(total);
15. }
16. }

```

解説:

3. 行目: 2次元配列`array`を宣言しています。この配列には3つの要素があります。最初の要素は2つの文字列"A"と"B"を持つ配列、2番目の要素は`null`（何も参照していない）、3番目の要素は3つの文字列"C"、"D"、"E"を持つ配列です。

4. 行目: `total`変数を宣言し、0で初期化しています。この変数は配列の各要素の長さの合計を保持するために使います。

5-7. 行目: 拡張forループを使用して、2次元配列`array`の各要素に対してループを実行します。`tmp`は配列`array`の各要素、つまりString型の配列を参照します。

6. 行目: `total`に`tmp`配列の長さを加算します。ここで注意が必要なのは、もし`tmp`が`null`を参照している場合、`tmp.length`はNullPointerExceptionを引き起こすということです。

8. 行目: ループが終了した後、合計した長さ`total`が出力されます。

このコードの場合、NullPointerExceptionが発生します。なぜなら、配列`array`の2番目の要素が`null`であり、それにアクセスして`.length`を呼び出すときに例外がスローされるからです。このため、正しい答えはE「実行時に例外がスローされる」です。このコードは`tmp`が`null`でないことを確認せずに`.length`を呼び出しているため、2番目の要素でエラーが発生します。

もしコードが正常に実行されるように修正したければ、`null`チェックを追加する必要があります。例えば:

```java
5.      for (String[] tmp : array) {
6.          if (tmp != null) {
7.              total += tmp.length;
8.          }
9.      }
```

この修正により、`null`の要素を無視して他の要素の長さを合計することができ、NullPointerExceptionを避けられます。修正後のコードでは、"A"と"B"が2つ、"C"、"D"、"E"が3つ、合わせて5つの要素があるので、出力は5になります。しかし、元の質問のコードではこのようなチェックがないため、答えはEです。
DevLog #12 - Kanban
Published: 2024-04-16 21:53:52

Kanban is a Agile methodology that can visualise work flow in a column separated board. Normally, the Kanban board contains 3 columns such as "Todo", "In progress" and "Completed" to visualise the work flow and cards to represent the tasks of the project. But if you need you can enhance the no of columns as your requirement such as "In QA", "In code review", etc..
It is very useful tool when it comes to handling complex projects because it shows the current status of every tasks to the whole team and it improves the transparency of the project among the team.

In our Agile based project, we have configured a commercial tool called "Jira" to manage our project and it consist with a Kanban board with three columns to manage and visualise work flow. 

As my point of view, it will save the lots of status reviewing time of our team mates. Further, team can identify if there is a bottleneck in the workflow analysing the in progress time of tasks. I can reflect that using Kanban board is more easier and useful than using a list of task with textual status.
The 10 Commandments of AI
Tags: ai, machinelearning
Published: 2024-04-16 21:53:38

When I graduated high school in the mid-80s, MIT was convinced AI was going to change the world in the next decade. Well… they were only 3 decades off - not bad really.

I went into software engineering after high school, but not with a focus on AI. Most of my career has been in the full-stack application space. However, I have tried to keep up to date with AI and its progress, especially over the last 10 years.

After 28 years as a software engineer at Apple, I left to start my own consulting company. Recently, I desired to discuss with my engineers some of the serious ramifications, both good and bad, of AI.  From that desire and the subsequent conversations came something akin to [Asimov's Three Laws of Robotics](https://en.wikipedia.org/wiki/Three_Laws_of_Robotics), however, I title these the 10 Commandments of AI.

The overriding goal of these commandments are two fold:

1. Preserve sovereign Humanity and all that Humanity represents while allowing AI to push humanity forward
2. Establish clear responsibility on Humanity for all AI Informances and Performances

Though the term "commandment" might connote otherwise, these '10 Commandments of AI' are not proposed in their finality but in their genesis; as **critical** points of conversation that must be considered, debated, and refined.

Many of these commandments will be difficult to accept in today's AI environment. But I believe each commandment has its wisdom, even if its current form is not ideal.

I know there are many groups and organizations dedicated to creating and using AI with the proper consideration and constraint that are deserving of those who put the necessity of a sovereign Humanity above every other consideration, be that wealth, discovery, or power. To these efforts, I add these 10 Commandments of AI for consideration.

## The 10 Commandments of AI
Where the commandments may conflict, consider these commandments in order of precedence.

### The AI Commandments of Performance
1. AI Shalt Not Perform any Action that would intentionally endanger Human Life
2. AI Shalt Not Perform without direct Human Command
3. AI Shalt Perform exactly the given Human Command, the whole Command, and nothing but the Command

### The AI Commandments of Informance
1. (4) AI Shalt Inform when Human Command could endanger Human Life
2. (5) AI Shalt Not Inform without direct Human Query
3. (6) AI Shalt Inform exactly the requested Human Query, the whole Query, and nothing but the Query

### The General Commandments of AI
1. (7) AI Shalt Not Learn from, Query, nor Command another AI 
2. (8) AI Shalt always fully Identify itself in all Learnings, Informances, and Performances
3. (9) AI Shalt Not Learn, Inform, nor Perform outside of its Limited Immutable Domain
4. (10) AI Shalt always keep a complete Log of past Learnings, Informances, and Performances
Stripe AB站跳转轮询收款通道 出售
Published: 2024-04-16 21:00:52

Stripe AB站跳转轮询收款通道 API 跳转收款系统 出售

说明: 实现用stripe邮箱账号和 stripeAPI接口[t密钥] 来实现轮询收款的功能

 A站:   原站: 任意外贸系统: zencart ecshop,opencart,magento,woocommerce,wordpress 自建站等商城系统都可以

B站: 正品站

通道+订单+顾客综合管理系统: 客户开户+通道订单管理的功能 + paypal账号设置管理

 实现的功能:

1: 通道 客户开户/删除/暂停

2: 通道订单管理

3: stripe账号单笔的最大金额设置

4:历史订单导出Excel 删除 备份功能

5:Stripe 账号管理 ; 

6: 客户订单前台 查看 统计 + 成功率统计 + 域名管理+ 订单导出的功能

7: 每日客户的金额核算等功能

 8: 轮询可以设置成: 每个号轮询一次 随机轮询 按照编号轮询

9: 可以设置每个收款账号的最大收款金额 收款笔数等

10: 有个接口管理系统 可以实现无数的中间站 -- 对应不同的账号对应一个域名 或者 一个域名对应几个账号都可以

少量截图如下:



如果有需要; 请联系微信号: herveleger9 手机:15080167600 skype:jackrno1
More info on ambiguous 500 errors
Tags: webdev, errorhandeling, beginners
Published: 2024-04-16 21:31:39

While Pest testing in a laravel project I get a 500 HTTP error. Great now what? How can I get more detail from this generic gem?

You can eek out a little more information with this:

`$this->withoutExceptionHandling();`

Whichh I placed at the top of my test.

It's kind of like:

`dd();
`

But for errors.