teleren/devto huggingface dataset:
Interfaces e Polimorfismo
Tags: java, polimorfismo, poo, braziliandevs
Published: 2023-09-18 16:20:08

## Interfaces em Java:
O que é uma Interface?
Uma interface em Java é como um contrato que define um conjunto de métodos que uma classe deve implementar. É uma estrutura que define o que uma classe deve fazer, mas não como ela deve fazer. As interfaces são usadas para alcançar a abstração e a reutilização de código.

**Exemplo**:
Suponha que você esteja criando um sistema de formas geométricas e deseja garantir que todas as formas tenham um método calcularArea(). Você pode criar uma interface chamada Forma para definir esse contrato:


![Image i 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onx4ldoigepy3yjkl135.png)

Agora, qualquer classe que queira representar uma forma geométrica deve implementar essa interface e fornecer uma implementação para o método calcularArea().

![Image i 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ninm49e9lub716p1vkmd.png)

## Polimorfismo em Java:
O que é Polimorfismo?
Polimorfismo em Java permite que objetos de diferentes classes sejam tratados de maneira uniforme, desde que compartilhem um contrato comum, como uma interface. Isso significa que você pode chamar métodos em um objeto sem saber exatamente qual classe o objeto pertence.

**Exemplo**:
Vamos usar o exemplo anterior com a interface Forma. Agora, podemos criar uma matriz de objetos de diferentes formas e calcular suas áreas sem se preocupar com as classes específicas:


![Image i 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mqen5yoqpavrscczve4j.png)

_Não esqueça de deixar seu like_ ❤️

Neste exemplo, Circulo e Retangulo são classes diferentes que implementam a interface Forma. O polimorfismo permite que tratemos todos os objetos como objetos Forma, independentemente de suas classes específicas.

Isso é uma simplificação, mas espero que ajude a entender os conceitos básicos de Interfaces e Polimorfismo em Java. Eles são fundamentais para criar código flexível e reutilizável em muitos projetos Java.

_Agora vocês já está pronto para aprender sobre listas_
[Clique aqui para aprender](https://dev.to/antoniorws/listas-em-java-uma-introducao-simples-e-pratica-2e79)🚀

Repositório com a trilha de java: https://github.com/antoniorws/basic-java

Linkedin: https://www.linkedin.com/in/antonio-rodrigo-wanderley-serra/
GitHub: https://github.com/antoniorws
The Future is Prompt Engineering: How to Speak AI's Language
Tags: ai, promptengineering, llm, chatgpt
Published: 2023-09-18 16:17:45

Artificial intelligence (AI) is advancing at a breakneck pace. The pace of AI research doubles every month as new models like Stable Diffusion and Claude push boundaries. With over 100 million ChatGPT users, it's clear that AI is going mainstream.
But simply using these tools isn't enough. To really unlock AI's potential, you need to learn prompt engineering.

### What is Prompt Engineering?

A prompt is the instructions you give an AI system to get it to generate content. For example, "Write 10 product names for shoes that fit any foot size." That's a basic prompt that will work, but the results may be inconsistent.
Prompt engineering involves crafting prompts to get more reliable, useful results from AI systems. It's about speaking AI's language clearly to coax the best content from the model.
With principles like templates and formulas, prompt engineers can get AI systems to consistently return content in a desired format. This makes it easy to integrate AI into workflows and scale creative output.

### Why Learn Prompt Engineering?

As AI rapidly improves, prompt engineering skills will remain relevant. The principles apply across models and versions. Even as AI gets better at interpreting prompts, effectively communicating ideas will be critical.
Prompt engineering is becoming a must-have skill like Excel. It will be baked into everything we do, from generating content to automating tasks. Especially for technical founders, understanding prompt engineering will be key to leveraging AI.


### Prompt Engineering in Practice

With prompt engineering, you can:

- Get more useful, consistent results from AI systems
- Unlock advanced techniques like style mixing in generative art
- Scale creative output by automating content generation
- Avoid common AI issues like hand hallucinations in images

Prompt engineering is part art, part science. It involves carefully crafting prompts while also creatively coaxing AI systems to get the desired output.

### The Future of Prompt Engineering
As models continue to improve, the need to "hack" prompts with specific tricks will decrease. But effectively communicating ideas will remain critical.

Prompt engineering will evolve from tricky prompt hacks to an interdisciplinary skill combining communication, design, and management skills. It will be less about "engineering" and more about understanding humans and AI.

The future is prompt engineering. To leverage AI and generate content at scale, users should start learning prompt engineering principles now. With some practice, you'll be ready to integrate prompt engineering into your workflows as new AI capabilities emerge.
Esto nunca para
Tags: writing, javascript, spanish
Published: 2023-09-18 16:17:41

Esto nunca para. Como muchos ya lo saben estudio varias cosas a la par, y pues varias de ellas tienen conceptos relacionados por lo cual si ya tuviste contacto que ese tema en un lenguaje de programación diferente al que actualmente estas pues no se te va hacer muy complicado entender el concepto.

De estos días estoy revisando como hacer sitios con ReactJS, primero y principal es porque siempre me había dado curiosidad de como es que funcionaba. El camino para llegar a este punto no ha sido sencillo y mucho menos un paseo por el parque, me dedique a aprender bien JavaScript, porque si lo había utilizado a través de JQuery pero la verdad es que no tenia muy claro algunos conceptos que ahora si ya los domino como por ejemplo, el uso de variables, como funciona el motor V8 de Chrome, promesas, deconstrucciones, Programación Orientada a Objetos (POO), métodos de arreglos, npm, Postman, etc.

No solo ha sido ver los cursos y hacer las practicas sino también hacer proyectos de mi trabajo en ese lenguaje para enfrentarme a retos que yo sé, que van a ir saliendo a lo largo de los mismos.

Y heme aquí con mas experiencia y teniendo un entendimiento más profundo del funcionamiento de JavaScript y porque es uno de los lenguajes de programación mas ocupados del mundo. En este momento siento que tanto desarrollar el front end como el backend en JavaScript es la cúspide de lo que se puede hacer en cuanto a desarrollo significa. Al punto que quiero llegar es que no te limites y no dejes de saciar tu curiosidad, no porque tu entorno laborar no le estén poniendo atención a ciertos puntos o tecnologías no significa que las debas dejar de lado por el simple hecho de que tu tribu no esta apuntando hacía esa dirección. Si alguien en algún momento quiere aprender conmigo las puertas están abiertas.

Ahora entiendo que la comunidad es un lugar en donde te puedes apoyar con otras personas que tiene un mayor conocimiento que tú y les gusta compartir lo que saben. Acá en Twitter hay muchos de esos y creo que me incluyo en ese grupo que comparte y difunde sus experiencias para que le sirven a alguien mas en su camino de formación profesional.

-U.
What is a Binary Number?
Tags: whatis, binary
Published: 2023-09-18 16:16:59

---
image:
title: What is a Binary Number?
description: "A binary number is a number expressed in the base-2 numeral system, which uses only two digits: 0 and 1. This is in contrast to the decimal (base-10) numeral system that we use in everyday life, which uses ten digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9."
tags:
  - whatis
  - binary
author: ilihub
series: Number System
---

A binary number is a number expressed in the `base-2` numeral system, which uses only two digits: 0 and 1. This is in contrast to the [decimal][Decimal Number] (`base-10`) numeral system that we use in everyday life, which uses ten digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.

In the binary system, each digit represents a power of 2, starting with {% katex inline %}2^0{% endkatex %} (which is equal to 1) and increasing by a factor of 2 for each successive digit. For example, the binary number 1011 represents:

{% katex %}
1 \times 2^3 + 0 \times 2^2 + 1 \times 2^1 + 1 \times 2^0 = 8 + 0 + 2 + 1 = 11
{% endkatex %}

Binary numbers are commonly used in computer science and digital electronics because they can be easily represented using electronic switches that are either on or off (i.e., 1 or 0). This makes them ideal for representing digital data, such as the instructions that a computer executes or the pixels in a digital image.

In addition to binary, there are other numeral systems that use different bases, such as [octal][Octal Number] (`base-8`) and [hexadecimal][Hexadecimal Number] (`base-16`). These systems are also commonly used in computer science and digital electronics because they can be easily converted to and from binary.

## Examples

The following table shows the decimal, binary representations of the numbers 0 through 15:

| Decimal | Binary |
| ------- | ------ |
| 0       | 0000   |
| 1       | 0001   |
| 2       | 0010   |
| 3       | 0011   |
| 4       | 0100   |
| 5       | 0101   |
| 6       | 0110   |
| 7       | 0111   |
| 8       | 1000   |
| 9       | 1001   |
| 10      | 1010   |
| 11      | 1011   |
| 12      | 1100   |
| 13      | 1101   |
| 14      | 1110   |
| 15      | 1111   |

---

## References

- [Binary Number Wikipedia](https://en.wikipedia.org/wiki/Binary_number)
- [Decimal Number][Decimal Number]
- [Hexadecimal Number][Hexadecimal Number]
- [Octal Number][Octal Number]

---

[Decimal Number]: https://ilihub.tech/blog/what-is/decimal-number "What is a Decimal Number?"
[Hexadecimal Number]: https://ilihub.tech/blog/what-is/hexadecimal-number "What is a Hexadecimal Number?"
[Octal Number]: https://ilihub.tech/blog/what-is/octal-number "What is an Octal Number?"
Listas em Java: Uma Introdução Simples e Prática
Tags: java, listas, arraylist, braziliandevs
Published: 2023-09-18 16:11:17

As listas são uma das estruturas de dados mais fundamentais em Java. Elas permitem armazenar coleções de elementos em uma única variável. Isso é útil quando você precisa lidar com vários valores relacionados. Imagine uma lista como uma sequência ordenada de elementos, onde cada elemento pode ser acessado por sua posição na lista.

**Exemplo 1: Criando uma Lista em Java**

Para começar, você precisa importar a classe java.util.List. Vamos criar uma lista de números inteiros:

_Não esqueça de deixar seu like_ ❤️

![Image list 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vor5u2df3742dzxfaaqx.png)

Neste exemplo, criamos uma lista chamada numeros que contém três números inteiros. Usamos o método add para adicionar elementos à lista e o método get para acessar elementos com base em suas posições. O método size retorna o tamanho da lista.

**Exemplo 2: Percorrendo uma Lista em Java**

Uma das operações mais comuns é percorrer os elementos de uma lista. Vamos ver como fazer isso usando um loop for-each:


![Image list 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1timitxr3rlqpbjjalu.png)

Neste exemplo, criamos uma lista de frutas e usamos um loop for-each para percorrer a lista e imprimir cada elemento.

**Exemplo 3: Removendo Elementos de uma Lista**

Você pode remover elementos de uma lista usando o método remove:


![Image list 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c9xhjdae7acr2fpxss9y.png)

Neste exemplo, removemos o elemento com valor 10 da lista.

Esses são conceitos básicos para começar a trabalhar com listas em Java. Elas são incrivelmente versáteis e úteis para lidar com coleções de dados em programas Java.

Repositório com a trilha de java: https://github.com/antoniorws/basic-java

Linkedin: https://www.linkedin.com/in/antonio-rodrigo-wanderley-serra/
GitHub: https://github.com/antoniorws
Methods to Quantify the Number of Test Cases in Software Testing
Published: 2023-09-18 16:09:13

Understanding the number of test cases needed for adequate testing coverage is crucial for effective software testing. This article outlines various methods to quantify the number of test cases needed for different scenarios.

## Table of Contents

1. [Exhaustive Testing](#exhaustive-testing)
2. [Boundary Value Analysis](#boundary-value-analysis)
3. [Equivalence Class Partitioning](#equivalence-class-partitioning)
4. [Combinatorial Testing](#combinatorial-testing)
5. [State Transition Testing](#state-transition-testing)
6. [Rule of Product](#rule-of-product)
7. [Conclusion](#conclusion)

## Exhaustive Testing

Exhaustive testing involves testing all possible inputs, outputs, and combinations. While theoretically ideal, it's often impractical due to time and resources.

```plaintext
Number of Test Cases = Total number of possible inputs/outputs/combinations
```

## Boundary Value Analysis

Boundary Value Analysis (BVA) focuses on testing at the boundaries between partitions.

```plaintext
Number of Test Cases = Number of Boundary Values
```

## Equivalence Class Partitioning

This technique involves identifying and testing one condition from each partition of equivalent inputs.

```plaintext
Number of Test Cases = Number of Partitions
```

## Combinatorial Testing

Involves testing all possible combinations of variables.

```plaintext
Number of Test Cases = Product of number of options for each variable
```

Example:

```plaintext
4 (dropdown options) x 2 (boolean options) = 8
```

## State Transition Testing

This technique involves testing from one state to another. The number of test cases depends on the number of possible states and transitions.

```plaintext
Number of Test Cases = Number of Transitions
```

## Rule of Product

The Rule of Product can be applied to quantify test cases where multiple variables are involved.

```plaintext
Number of Test Cases = n1 * n2 * n3 * ... * nn
```

Where \( n1, n2, n3, \ldots, nn \) are the number of variations for each variable involved.

Example for a system with 10 selectable options:

```plaintext
2^10 = 1024
```

## Conclusion

These methods provide various ways to quantify the number of test cases needed for different testing requirements. Choose the most suitable method based on your project's specific needs.
Redis Queues in Golang
Tags: go
Published: 2023-09-18 16:08:09

If you come from a framework like Laravel, you will be quite familiar with dispatching jobs onto a queue and then consuming that job via a queue worker.

Usually in Golang, we tend to just use goroutines that can run jobs in the background without needing Redis or some external service, and this works fine for a fair amount of use cases however there'll come a time when you need to distribute work across multiple servers and need some kind of retry mechanism.

This is just a basic example of how you would go about setting up a Redis queue in Golang, it's not meant to be a complete solution but should give you a good idea of how to go about building your own job queue system.

Firstly you'll need to pull in a Redis Go driver:

``` 
github.com/go-redis/redis
```

To set up a Redis client:

```golang
client := redis.NewClient(&redis.Options{
		Addr:     "127.0.0.1:6379",
		Password: "",
		DB:       0,
	})
```


Next, to add data to a queue:

```golang
err = client.LPush("queuename", "some data").Err()
if err != nil {
  log.Fatal(err)
} 
```


Finally, to read the data from your queue:

```golang
item, err := client.LPop("queuename").Result()
```
Laravel routes: apiResource vs resource
Tags: php, laravel, performance
Published: 2023-09-18 16:07:33

Laravel routes application: using apiResource and resource. These methods help you create routes for a resource controller, following the RESTful conventions.

**apiResource Function:**
```
Route::apiResource('users', 'PostController');
GET           /users                      index   users.index
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

```



**resource Function**
```
Route::resource('users', 'PostController');
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy
```

**In summary**

When using apiResource in Laravel, the routes are typically associated with the api middleware group by default. The api middleware group often excludes unnecessary middleware that is typically used for web requests, which can result in slightly **faster performance** compared to using the web middleware group.

The api middleware group usually includes middleware like throttle (for rate limiting) and auth:api (for API authentication). These are tailored for API routes, focusing on efficient handling of API requests.

On the other hand, the web middleware group includes middleware that are more suited for traditional web application routes, which might not be necessary or optimal for API routes.

So, if you're building an API and want to optimize for **speed and efficiency**, using apiResource with the api middleware group is a good choice. It ensures that the routes are handled with middleware optimized for API requests
12 Must-Have VS Code Extensions for Frontend Developers
Tags: vscode, frontend, webdev, productivity
Published: 2023-09-18 16:06:45

Visual Studio Code is a popular code editor among developers for its versatility and extensibility. If you're a frontend developer looking to supercharge your productivity, these 12 VS Code extensions are essential additions to your toolkit. They'll help you write cleaner code, catch errors early, and streamline your development workflow.


**Auto Close Tag - [Link](https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-close-tag)**
Automatically generates closing tags as you type, ensuring well-formed HTML.

**Auto Rename Tag - [Link](https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-rename-tag)**
Renames the opening or closing HTML/XML tag when you rename one, maintaining consistency in your markup.

**Console Ninja - [Link](https://marketplace.visualstudio.com/items?itemName=WallabyJs.console-ninja)**
Enhances your debugging experience by providing real-time logs instead of checking your browser console.

**Error Lens - [Link](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens)**
Highlights and annotates errors and warnings directly in your code, making them impossible to miss.

**ESLint - [Link](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)**
Integrates ESLint to help you maintain consistent code quality and style. Your project needs to have an ESlint file e.g. .eslintrc.json, for it to work. 

**GitLens - [Link](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens)**
Supercharges your Git workflow by providing in-depth insights into your code's history and authors.

**JavaScript and TypeScript Nightly - [Link](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-typescript-next)**
Offers VS Code's built-in JavaScript and TypeScript support. 

**Lorem Ipsum - [Link](https://marketplace.visualstudio.com/items?itemName=Tyriar.lorem-ipsum)**
Quickly generate placeholder text with this Lorem Ipsum generator.

**NPM Intellisense - [Link](https://marketplace.visualstudio.com/items?itemName=christian-kohler.npm-intellisense)**
Autocompletes npm modules in your import statements, saving you time searching for package names.

**Path Intellisense - [Link](https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense)**
Autocompletes file paths as you type, preventing typos and reducing errors.

**Prettier - Code Formatter - [Link](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)**
Automatically formats your code to conform to a consistent style, improving code readability.

**Tailwind CSS IntelliSense - [Link](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss)**
Enhances your Tailwind CSS development by providing autocompletion for classes.

Feel free to share your own favorite VS Code extensions or offer any corrections in the comments below.
react-live-island, Dynamic Island for React
Tags: react, apple, ui, ux
Published: 2023-09-18 16:06:36

**Product Hunt**: https://www.producthunt.com/posts/react-live-island

**GitHub**: https://github.com/nanxiaobei/react-live-island

---

```jsx
import LiveIsland from 'react-live-island';

const Demo = () => {
  return (
    <LiveIsland>
      {(isSmall) => (isSmall ? 'small' : 'large')}
    </LiveIsland>
  );
};
```

---

I searched the entire internet but couldn’t find a suitable ⚛️ React Dynamic Island 🏝 component, so I decided to create one myself.

It is a very simple component that doesn’t introduce any external libraries. Simply importing it can add a dynamic island at the top of the page.

Considering that both the `dynamic-island` and `react-dynamic-island` NPM packages have been preempted, I named it `react-live-island` 🎉.

I hope you will like it, It is really very simple, directly importing and then you can see a dynamic island! ✌️ while also providing rich customization props.

---

Introducing `react-live-island` by 🐤 Kee (https://kee.so)
Laravel 4Ways to Select specific columns
Published: 2023-09-18 15:57:57

select specific columns from a database table using various methods provided by the Eloquent ORM (Object-Relational Mapping). Here are four common ways to select specific columns on a model:



```
$users = User::select('id', 'name')->get();
// or
$users = User::select(['id', 'name'])->get();
// or
$users = User::find(3,['id', 'name']);
// or
$users = User::get(['id', 'name']);
```
Download video from TikTok
Published: 2023-09-18 15:51:46

Hello everyone!
If you need to download videos from TikTok without problems and quickly, then I can advise you a cool site [https://savetiktok.org](https://savetiktok.org) This great service was recommended to me by my friend. Now you do not need to install additional applications and programs to save your favorite video, the whole process happens in seconds. You just need to copy the link from the browser bar of the Tik Tok service and paste it into a special form on our site, then select the desired quality and after a couple of seconds to save the file to your phone or computer.