teleren/devto huggingface dataset:
Threads e Processos
Published: 2023-12-20 15:21:17

Um **processo** é a representação de um programa, que fica isolada em uma memória da CPU. Um processo pode fazer a comunicação com outro processo, ter a etapa de I/O.

Uma **thread** é um "mini processo" que concorre de forma independente na cpu, porém que usa a mesma memória que o processo principal.

![Representação de um processo e thread. Uma thread faz parte de um processo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbxn1sojimcqqm0je6k4.png)

Ou seja, um processo pode ter 1 ou N threads que dividirão trabalhos para realizar tarefas simultaneamente, porém threads estão sucetíveis a race condition.

Também há concorrência entre processos, por isso que existe o Scheduler, onde um processo utiliza a CPU e quando esperar o I/O, um outro processo pode vir e utilizar a CPU.

Mas o Scheduler nem sempre espera o processo finalizar a tarefa, e pode acabar interrompendo o processo após um tempo que ele mesmo especula e adiciona esse processo a uma lista de espera junto com outros processos.

Pode existir um processo ou multi processos, uma thread ou multi threads, por isso é importante analisar o contexto de cada situação e a situação dos cores de uma CPU.


![Exemplificação de um processo e multi processos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fr0gbhs28zvccri7llst.png)


![Exemplificação de um thread e multi threading](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oon974l8md1b9ykdbhc3.png)
Running out of space on a developer's machine
Tags: tip, productivity, cleanup
Published: 2023-12-20 15:21:00

As developers, we often find our hard drives mysteriously filling up, slowing down our workflow. 
First reflex is often to remove the waste and for developers, that includes downloaded packages that linger until we return our unused projects.
Let's explore a simple, yet powerful command-line I came across to reclaim hat precious disk space, making room for more coding and less clutter.

So I started with a 250 GB SD full

![256GB full SD card](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6nw4qfem42oyr741mdfc.png)

## The commands we will need

### Disk space

Command to get the disk space (I used an SD card smaller than my project folder until full).

```sh
 diskutil info -all
```

You can also use

### Remove a child folder from a directory

Looking for a command to recursively remove child node_module folder, I found the following command at https://stackoverflow.com/a/70549487/4819888 (it seems to have equivalents for Windows and Linux too)

```sh
find . -name '<folder to remove>' -type d -prune -print -exec rm -rf '{}' \;
```

## Cleaning up node_modules folders

```sh
find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;
```

After running this command and clearing 22 node_module folders, it went down to 76GB

![70% reduction disk space removing node_module folders](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oibbwgys8zhdplar3zff.png)


## Cleaning up bin folders


```sh
find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;
```

After running this command and clearing down 490 bin folders, I had a further 20 GB of additional free space.

![space left after removing node_module folders and bin folders](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lco0bkm730dazfj7ds3n.png)


I was thinking next we could tackle python packages but I could not find consistent naming convention though "pip" was what brought back most results. Also more on dangling docker images [here](https://docs.docker.com/engine/reference/commandline/system_prune/). Anyway...

## Conclusion

So here we are with a reduction of 78.43% of the space my projects took in no time.
What other folders shall we look to remove? Have you noticed similar savings? 
What other tips might you have to share?
Creating a margin between elements without adding in the last one.
Tags: css, react, codenewbie, html
Published: 2023-12-20 15:10:34

Hello guys! 

Just sharing a simple tip about adding some margin or padding between components. 
CSS has so many ways to do it, but this one is simple and smooth. 

So, as you see the last padding in this image example seems to be with more padding than the above ones.

How to solve it? Basically, we should avoid adding the last padding because there are no more posts below. 

```
.post + .post {
    margin-top: 1rem;
}
```
The + sign will make the CSS attributes be add just if you have a "post" class before :) 

Post example:
```
    <article className="post">
      Any text here
    </article>
  );
```

NOTE: Rem is equivalent to 16px. But is a nice pattern to help people who change interfaces on their pc or mobile. It will be rendered in the size that they define :)
Ripple has obtained a license to operate in Ireland.
Tags: blockchain, news
Published: 2023-12-20 15:05:41

Thanks to the license from the Irish regulator, Ripple will be able to conduct transactions on behalf of another individual or legal entity moving digital assets. The company is allowed to provide cryptocurrency exchange services for fiat or between different cryptocurrencies, as well as engage in asset custody.

The registration will expand Ripple's business in Europe following the implementation of the European Union's cryptocurrency regulation law (MiCA). To comply with the requirements, Ripple will need to obtain additional licenses.

In February of last year, Ripple opened an office in Dublin, which became its first office in the European Union. The company's leadership stated that Ireland provides a favorable environment for development. In 2018, the Central Bank of Ireland launched the Innovation Hub, allowing fintech companies to interact more easily with regulators.

Stuart Alderoty, Chief Legal Officer of Ripple Labs, noted that obtaining the approval of the Irish central bank amid regulatory uncertainty in the United States signals a successful end to the year for the company.

In October, Ripple obtained a license to operate with digital assets from the Monetary Authority of Singapore (MAS). Earlier, Ripple's CEO, Brad Garlinghouse, referred to the United States as a dangerous place for crypto companies.
Beginner's TypeScript #3
Tags: programming, typescript, tutorial, beginners
Published: 2023-12-20 15:00:00

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

⭐ **Set Properties as Optional** ⭐

Consider this **getName** function:

```ts
export const getName = (params: { first: string; last: string }) => {
  if (params.last) {
    return `${params.first} ${params.last}`;
  }
  return params.first;
}
```

We can see that we do not need to pass in a last name for the function to work.

However, TypeScript does not know that yet.

We have an error:

```bash
Argument of type '{ first: string; }' is not assignable to parameter of type '{ first: string; last: string; }'.
Property 'last' is missing in type '{ first: string; }' but required in type '{ first: string; last: string; }'.
```

We will figure out how to type the object so that **last** is **optional**.

👉 **Solution:**

This is a one-character solution.

Adding a ? before the colon tells TypeScript that the property is not required in order for the function to work.

With this update, we do not have to pass in a last if we don't want to:

```ts
export const getName = (params: { first: string; last?: string }) => {
  // ...
}
```

Tooling in VS Code is smart enough to recognize if a key is optional. This can be seen in the autocomplete, where you will be reminded that **last** should be either a **string** or **undefined**.

```ts
type Params = { first: string; last: string | undefined }
```

👉 Summary:

If you want to set a property as optional, use the❓.

---

I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- **Medium:** https://medium.com/@nhannguyendevjs/
- **Dev**: https://dev.to/nhannguyendevjs/
- **Hashnode**: [https://nhannguyen.hashnode.dev](https://nhannguyen.hashnode.dev/)/
- **Linkedin:** https://www.linkedin.com/in/nhannguyendevjs/
- **X (formerly Twitter)**: https://twitter.com/nhannguyendevjs/
Solution for Failed to execute 'postMessage' on 'DOMWindow' on Next.js
Tags: javascript, react, nextjs
Published: 2023-12-20 14:54:53

When I open the Chrome console, I saw the error "Failed to execute 'postMessage' on 'DOMWindow': The target origin provided"

i use react with nextjs and Plyr for embeding youtube
the solution is to delay nextjs auth session refresh rate in `SessionProvider `
 

```jsx
<SessionProvider session={session} refetchInterval={5*60*60}>
```
Spring Boot 3 – package javax.persistence does not exist
Tags: springboot, java
Published: 2023-12-20 14:57:53

When migrating from Spring Boot 2 to Spring Boot 3, one might face this error: 
```
The import javax.persistence cannot be resolvedJava(268435846)
```
This is due to this [Transition from Java EE to Jakarta EE](https://blogs.oracle.com/javamagazine/post/transition-from-java-ee-to-jakarta-ee)

Spring Boot 2.x using Java EE APIs javax.*
```java
java: package javax.persistence does not exist

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;  
```

To fix this, we can just update all javax to jakarta.

Spring Boot 3 using Jakarta EE APIs jakarta.*
```java
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; 
```
Thanks!
Protocolos base da internet: HTTP
Published: 2023-12-20 14:57:21

## HyperText Transfer Protocol

O HTTP é um protocolo de transferência de hipertexto que fica na camada de aplicação, e é a base da internet quando se refere a carregamento de recursos de hipertexto, iamagens, vídeos, o que compõe uma página web.

Uma forma de se comunicar usando esse protocolo é a base do request-response, onde:

O navegador **sempre** inicia a comunicação (enviando uma requisição)

![Exemplo de padrão request. Método, path, protocol/header/body](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mrfnvdd2yul8n7nedfq7.png)

Ao enviar uma requisição para o back-end, o client tem que garantir que está enviando o método, o path, header e body correto. Lembrando que um GET não deveria ter conteúdo no body.

Obs: Um IP pode ter diversos websites, então, por trás do DNS, todos os websites estão apontado para o mesmo IP, mas no header tem o campo "host" e é através dele que a aplicação entende de onde/para onde é.

Ao longo do tempo houveram evoluções do HTTP. A primeira versão é a 1.0, após isso vieram a 1.1 (a mais conhecida), 2.0 e 3.0.

O HTTP 3.0 é um HTTP que não opera pelo TCP, mas sim através do UDP, tendo como premissa uma maior rapidez em comparação as outras versões e sendo uma forma de evitar o bloqueio que acontece com o TCP ao fazer o multiplexing e acaba tendo alguma perda de pacote na transmissão (pelo fato do TCP ler em sequência, e se um pacote for perdido, precisar fazer a retransmissão).

Além do HTTP 3.0, o HTTP 2.0 também tem o suporte de fazer o multiplexing (no caso do HTTP 2.0, é feito com o TCP), é mais rápido e traz uma maior segurança por padrão ao invés da versão 1.1.

Além disso, o HTTP é um protocolo que não tem estado então não existe um armazenamento das informações que foram trocadas "por conta própria", o armazenamento deve ser feito usando outras estratégias, como, por exemplo, cookies.


![Exemplo de padrão response. Protocolo, status code, code text, headers/body](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xz03v3btlv9d2l8wkrvi.png)

Na versão 1.1, ao receber o response, existe a transcrição do status code. Ex: 200 OK, 404 NOT FOUND

Tanto o request quanto o response têm headers onde é possível colocar um cabeçalho genérico, que não tem relação aos dados em si transmitidos, quanto cabeçalhos específicos para request/response.
Popular Word to PDF APIs ?
Published: 2023-12-20 14:55:03

Hey Devs,

Do you know any popular APIs that can efficiently convert [Word documents to PDFs](https://apyhub.com/blog/convert-docx-to-pdf-using-api)?

Some parameters should be considered: 

1. **High Reliability:** Minimal downtime and consistent performance.
2. **Quality of Conversion**: The PDF output should closely match the original Word document in terms of formatting and layout.
3. **Ease of Use:** Simple integration with clear documentation.
4. **Security:** Ensuring data privacy and security during the conversion process.


Let me know in the comments below
How to Create a Template in Django
Tags: django
Published: 2023-12-20 14:44:54

In Django, you can create views and templates as you like. Here's a simple guide.

## How to Create a Template

### 1. Add a path to `urls.py`
Add the following section to `urlpatterns` in `urls.py`:
```python
from .views import MyClass  # Add this

urlpatterns = [
    path('XXXurl/', MyClass.as_view(),  # Add this
]
```

### 2. Create a file for the view
As shown below, create a view file, import `TemplateView`, and specify `hello.html` as the template (to be created later).
```python
from django.views.generic import TemplateView  # Add this

class MyClass(TemplateView):  # Add this
    template_name = 'hello.html'  # Add this
```

### 3. Create the template file
First, create a `templates` directory at the project's root, and within it, create a file named `hello.html`.
```zsh
cd /your/project/path
mkdir templates
touch templates/hello.html
```

```html
Hello World!
```

### 4. Modify `setting.py`
By default, the template file directory is not registered, so modify the file as follows:
```python
TEMPLATES = [
    'DIRS' = [BASE_DIR / 'templates'],  # Modify
```

### Verification
Run the following, and the content of `hello.html` should be displayed in the browser.
```zsh
python3 manage.py runserver
```
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3522867/323adf1d-e0b6-3187-bf8c-a68ff401a1c0.png)



## How to Handle `TemplateDoesNotExist` Error
An error you'll likely encounter when working with templates.
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3522867/02801e62-0d27-eec3-ca84-60817bdb6e89.png)

Since it says "Template does not exist," check the following:

- Is the content of `DIRS` in `settings.py`'s `TEMPLATES` correct?
- Does the file name for the view match the template name registered in `views.py`?
- Does the class name defined in `views.py` match the class name imported in `urls.py`?

That's it.
Introducing the Simplified Color Palette Generator!
Tags: ai
Published: 2023-12-20 14:35:59

Are you tired of spending hours trying to find the perfect color combination for your next project? Look no further! The Simplified [Color Palette Generator](https://simplified.com/color-palette-generator/) is here to make your life easier. Whether you're a designer, artist, or simply someone who loves playing with colors, this tool is perfect for you.

With just a few clicks, our Color Palette Generator will provide you with a stunning array of harmonious colors that will take your project to the next level. Gone are the days of guesswork and frustration as you try to find colors that complement each other. Our intelligent algorithm analyzes your input and generates a curated selection of colors that work seamlessly together.

Here's how it works:

Input your base color: Start by selecting your desired base color. You can either enter a specific color code or use our intuitive color picker to choose from millions of shades. Don't worry if you're unsure about the exact color you want; our tool provides suggestions based on your input.

Choose your color scheme: Once you've selected your base color, it's time to choose your color scheme. Our Color Palette Generator offers various options, including complementary, analogous, triadic, and tetradic color schemes. Experiment with different schemes to find the one that best suits your project's needs.

Explore your color palette: Sit back and let the magic happen! Within seconds, our Color Palette Generator will generate a beautiful palette of colors that complement your base color and chosen scheme. Each color is carefully selected to ensure balance and visual appeal. You can easily preview and adjust the colors to find the perfect combination.

Save and export: Once you've found your ideal color palette, you can save it for future reference. Our tool allows you to download the palette as a file or copy the color codes directly to your clipboard. This way, you can easily share your palette with colleagues, clients, or use it in your favorite design software.

The Simplified [Color Palette](https://simplified.com/color-palette-generator/) Generator is your go-to tool for creating visually stunning projects. Whether you're designing a website, creating artwork, or planning a marketing campaign, our generator will save you time and effort, allowing you to focus on what you do best - bringing your creative vision to life.

So why wait? Visit our website now and experience the power of the Simplified Color Palette Generator. Get ready to unlock a world of endless color possibilities!
HOW TO RECOVER YOUR CRYPTO INVESTMENTS FROM SCAMMERS- ADWARE RECOVERY SPECIALIST
Published: 2023-12-20 14:35:52

When faced with losing their cryptocurrency, some individuals may attempt to recover their funds using do-it-yourself (DIY) methods. While commendable, these DIY approaches often fall short in the face of sophisticated cybercriminals. Crypto thieves are constantly evolving in their techniques, making it challenging for individuals without specialized knowledge to recover stolen assets successfully. DIY recovery methods may prove futile and result in further damage or loss of funds. In such cases, seeking professional assistance becomes a wise choice. A lifeline is provided by Adware Recovery Specialist to people who have been the victims of cryptocurrency theft. Their staff of professionals is well-versed in the strategies used by cybercriminals and focuses on recovering stolen cryptocurrency. You can take advantage of their experience, knowledge, and state-of-the-art tools by putting your case in the hands of pros. Adware Recovery Specialist offers specialized methods that increase the likelihood of recovering stolen money since it knows the particular difficulties associated with recovering crypto theft. Getting professional help ensures a more successful and efficient recuperation process than taking on an uncertain and maybe ineffective do-it-yourself project. Crypto criminals use a variety of techniques to take advantage of unwary people and companies by stealing digital assets. Attacks using phishing techniques are still common, in which fraudsters pretend to be trustworthy organizations to deceive victims into disclosing their passwords or private keys. Additional methods include breaking into digital wallets, taking advantage of security holes in Bitcoin exchanges, or infecting users' devices with malware to access their devices without authorization. Knowing these strategies is crucial if one wants to increase their defenses against becoming a victim of cryptocurrency theft. With a strong focus on professionalism and client satisfaction, Email: Adwarerecoveryspecialist@ auctioneer .net aims to bring peace of mind to those who have fallen victim to crypto theft for more information.

webpage: www.adwarerecoveryspecialist.expert

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gb45eol7yatafx75a2lh.jpg)
LPIC-1: Tópico 101 - Arquitetura de Sistemas
Published: 2023-12-20 14:25:01

A partir de hoje estou começando uma série sobre o que venho estudando sobre o LPIC-1 a fim de me preparar para o exame. Com isso, a intenção desta série - além de me preparar - é conseguir identificar o que compreendi e o que ainda falta eu compreender.

## O que é o LPIC?
O LPIC (Linux Professional Institute Certification) é um exame para certificação linux que valida habilidades dos candidatos com manutenção em sistemas linux.
Existem 2 exames, o LPIC-1 e o LPIC-2, ambos abordam diferentes contextos de sistemas linux e o material para estudá-los é fornecido pelo próprio instituto.

### LPIC-1
Para estar apto ao LPIC-1 precisa compreendar alguns temas no qual o próprio material são abordados, que são:

- **Arquitetura de sistema:** Entender sobre o Kernell linux, como o software se comunica com o hardware, onde ficam seus diretórios e arquivos além de saber identificar possíveis problemas durante execução e ter noções para realizar manutenção de alguma falha.

---

- **Instalação Linux e Gerenciamento de Pacotes:** Saber como se faz instalação do linux e de suas distribuições e gerenciar os pacotes que mantém o sistema operacional.
 

---


- **GNU e Comandos Unix:** O GNU é acrônimo recursivo (GNU's Not Unix) que seria um sistema operacional do tipo Unix open source. Os comandos Unix são programas - utilitários - que rodam através de linhas de comando via terminal - prompt de comando - e realizam instruções como criar pastas, navegar entre elas dentre outras muitas. Esses comandos são muito importantes para utilizar sistemas linux.
 

---

- **Dispositivos, Arquivos de Sistemas Linux, Hierarquia Padrão dos Arquivos de Sistema:** Criar partições e arquivos do sistema e realizar manutenções de integridade dos arquivos do sistema. Montar e desmontar (mount and unmounting) partições do sistema, gerenciar permissões e proprietários de arquivos e diretórios, conhecer os links simbólicos sabendo como mudá-los e criá-los. Encontrar arquivos do sistema e colocá-los nos lugares corretos.
 

Além dos temas abordados, é possível realizar exercícios prévios antes de realizar o exame, além disso, enquanto estuda é possível realizar testes para fixar compreensão.

## Dicas
Existem alguns comandos que são perigosos de se executar na máquina local, pois fazem tarefas de desabilitar e habilitar módulos importantes do Kernell, podendo ser danosos. Caso - assim como eu - tenha curiosidade e queira executá-los, usar uma máquina virtual como o VirtualBox ou correlatos.

## E o LPIC-2?
Não cheguei a ler o resumo sobre este material e como meu objetivo primário é o LPIC-1, vou deixar pra uma próximo.
Mas é possível conferir [aqui](https://www.lpi.org/our-certifications/lpic-2-overview/).

_Gostou do conteúdo?
Tem alguma dúvida sugestão ou correção?
Vou ficar feliz em saber!_


## Referências

- https://www.lpi.org/our-certifications/lpic-1-overview/

- https://pt.wikipedia.org/wiki/GNU
Web Host Most - The Ultimate Shared Web Hosting For PeopleWeb Host Most - The Ultimate Shared Web Hosting For People
Published: 2023-12-20 14:23:38

Looking for a secure and reliable #webhosting ? 🤔
It's time to meet the new hero! 🤺

[**Web Host Most**](www.webhostmost.com) - The Ultimate #webhostingprovider For People. 🤩
More than just another web hosting, it's a professional tool for #webdevelopers

Optimized #wordpresshosting with secure web servers, intuitive web control panel, and unlimited performance.

We also offer a 125Mb #freewebhosting plan along with a free subdomain. 🤪
No need to have a domain to start using your hosting plan.

Get complete control over your website and its infrastructure.

Perfectly fits for enthusiasts, professionals, and the beginners.