teleren/devto huggingface dataset:
Working with the Basics
Tags: webdev, beginners, programming
Published: 2023-02-19 05:30:55

What I have come to realized as I work with the [repo](https://github.com/DevelopingSpace/starchart) is my lack of understanding of what I'm even doing.
I write code base on the research I've done, but it seems that I don't try to understand them, and just look at the code and implement it based on what I need. I realized that this type of thinking is flawed and can never work.


### Copy and Paste ###

I've always researched my issue, and go directly into the code, and just copy and paste what they have, only changing a bit to fit the code that I am writing. The code works perfectly, but I learn nothing from it. New developers tend to simply just copy whatever they see, and forget about its functionality later on, but I find that mindset destructive. 

I have a peer that I am working on with a project, and during one of our weekly meetup, they were stuck on a piece of code. I told them to show me the problem, and I realized immediately what they were doing wrong (they were using map for a non-array object). I told them to check the console, and it literally shows them what the error was, but it never came across their mind. I wouldn't have had any problems with it, but it's a repetitive issue I had working with them.

### I'm New ###

When the information you need is given to you directly. You never even bothered asking yourself how it works, you go straight to the answer. I noticed that junior developers such as myself, don't bother understanding what they are doing. We tell ourselves that "I'll learn about this later on" or that "It's not important". We mask our lack of knowledge with our experience. We tell ourselves that we are new, but never tried to take a stride to get better.

Of course, not everyone will have such a thorough understanding of their job. Regardless of your experience, you are bound to not know something, and the beauty of programming is that you are constantly learning-- there is never an end in sight.

### Conclusion ###

This week has been an eye opener for me. It made me realize that I should try to understand the code I'm writing, even when I think I know it already. Never forget the basics, and continue working to gain experience. There is no developer who knows everything, only those who strive to learn.
Data-* attributes instead of if-else statement for styling component states
Published: 2023-02-19 05:14:56

## First thing first
Hello fellow devs, I am Duong, a Fullstack developer. Yesterday (at the time I wrote this), I discovered a new way to style Component states with CSS, thus I want to share it with everybody. Let's go.

## Problem
Suppose we have a button with a loading state, usually, we will style it as below:

```js
// Button.js
const Button = ({children, loading}) => {
   // other code...
   // If you use classNames it would be like this:
   // className={cx('other class go here', {['loading']: loading})}
   return <button className={`other class go here ${loading ? 'loading' : ''}`}>{children}</button>
}
```

```css
/* button.css */
.loading {
    ...CSS properties
}
```

But I have found a new way for this with the data-* attributes. Before diving into the code, we need to know what data-* attributes is.

According to MDN docs:
>The data-* global attributes form a class of attributes called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM representation by scripts.

So we could create a custom attribute with it and leverage these attributes for our CSS selector.

```js
// Button.js
const Button = ({children, loading}) => {
   // other code...
   return <button className={`other class go here`} data-loading={loading}>{children}</button>
}
```

```css
/* button.css */
button[data-loading="true"] {
   // CSS properties...
}
```

With this approach, we won't need an `if-else` statement or classNames library at all. Moreover, it is easier for us to test the button state because we can use the selector `button[data-loading="true"]` to select the dom element.

In the code example above, I use React, but since this is a native feature of HTML so we can use it for every frontend framework out there. I will leave a [stackblizt sandbox](https://stackblitz.com/edit/vitejs-vite-bu26eu?file=src/components/Button.vue) here so you could play with it

{% embed https://stackblitz.com/edit/vitejs-vite-bu26eu?embed=1&file=src/components/Button.vue %} 

Now you've known another way to style your component. Hope this is useful for you

## References:
1. [W3schools documentation about data-* attributes](https://www.w3schools.com/tags/att_data-.asp)
2. [MDZ documentation about data-* attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*)
What is AWS?
Tags: aws, cloud
Published: 2023-02-19 03:55:31

AWS is a leading cloud service provider. But before understanding AWS lets first understand what is cloud. So cloud is just computers situated at some other location which we can access remotely according to our needs and we pay rent to those cloud service providers, few top cloud service providers are AWS(Amazon web services), GCP(Google cloud platforms) and Mircosoft Azure and many more.

Now first thought strikes into our mind is why to rent these computers, why big tech companies rent those computers? why don't they just buy computer on their own so that they don't have to spend any money in renting it, well its not that straight forward. These companies don't always know how much machines do they require or may be don't want to manage those machines on thier own or may be they want to keep their machines secure may be at hardware level and at software level. 

![Aws Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pkjsyeey2pb16upqnpmq.png)
So here comes into picture AWS with a tons of services, security, reliability. AWS provides on-demand machines means you pay only for what you use no requirement of preplanning just ask AWS for more machines when you need it and with in seconds you will be having those. These are so much reliable that even big companies like netflix, airbnb, dropbox, ESPN, twitch etc. 
AWS have services like EC2 for cloud computing, S3 for object storage, Auto Scalling, AWS Lambda provides serverless means you don't have worry anything about servers, IAM for managing permissions with built in policies. Since AWS is building services for a huge number of companies so obviously it will far better than building infrastrucure on own by a small or mid size company.
Thank You,
Keshavcodex
StackExchange.Redis: Principais interfaces
Tags: dotnet, redis, braziliandevs, programming
Published: 2023-02-19 03:37:07

## Introdução

As interfaces do `StackExchange.Redis` são abstrações que definem o comportamento de objetos responsáveis por se comunicar com o Redis.

## Interfaces

- **`IConnectionMultiplexer`** define o comportamento de um objeto que gerencia a conexão com o servidor Redis.
- **`IDatabase`** define o comportamento de um objeto que representa um banco de dados Redis e fornece métodos para executar comandos em um determinado banco de dados.
- **`IServer`** define o comportamento de um objeto que representa um servidor Redis e fornece métodos para executar comandos no servidor, como informações de monitoramento ou gerenciamento.
- **`ISubscriber`** define o comportamento de um objeto que pode se inscrever em canais pub/sub do Redis para receber mensagens.
- **`ITransaction`** define o comportamento de um objeto que representa uma transação do Redis.

## Conclusão

Suas interfaces principais, `IConnectionMultiplexer`, `IDatabase`, `IServer`, `ISubscriber` e `ITransaction`, permitem aos desenvolvedores se comunicarem com o Redis de maneira simplificada e organizada. Um exemplo de utilização seria a criação de uma conexão com o Redis usando o `IConnectionMultiplexer` e então obtendo uma referência para um `IDatabase`, onde se pode utilizar comandos de armazenamento e recuperação de dados.
How to Create Wordle Game in HTML, CSS and Javascript ?
Tags: javascript, beginners, wordle, programming
Published: 2023-02-19 03:30:30

Wordle is a popular word-guessing game where players have to guess a five-letter word with a limited number of attempts. The game has become an online sensation with people spending hours trying to guess the word. If you are looking to create a Wordle game of your own, this article will guide you through the process using HTML, CSS, and JavaScript. Demo here [Play Wordle game](https://wordlex.org/play-wordle-game/)


The first step is to create the HTML structure for the game. Create a div that will hold the game and add an input field for the user to enter their guess. Also, add a button to submit the guess and a list element to display the guesses made by the user.

```
<div class="wordle-game">
  <h1>Wordle Game</h1>
  <p>Guess a 5-letter word:</p>
  <input type="text" id="guess" placeholder="Enter guess here">
  <button id="submit-btn">Submit</button>
  <ul id="guess-list"></ul>
</div>
```
Next, style the HTML elements using CSS. You can choose any style you want, but here is an example:

```
.wordle-game {
  text-align: center;
  margin: 20px auto;
  width: 50%;
  background-color: #f7f7f7;
  padding: 20px;
  border-radius: 10px;
}

h1 {
  font-size: 40px;
}

p {
  font-size: 25px;
}

input[type="text"] {
  padding: 10px;
  font-size: 20px;
  border: none;
  border-bottom: 2px solid #ccc;
  margin-bottom: 20px;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-bottom: 10px;
}

button:hover {
  background-color: #3e8e41;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  font-size: 20px;
}

li {
  margin-bottom: 10px;
}

```
Finally, add JavaScript code to make the game functional. The first step is to generate a random five-letter word that the user has to guess.

```
const words = ["apple", "banana", "cherry", "grape", "kiwi", "lemon", "melon", "orange", "peach", "pear", "plum", "strawberry"];

let word = words[Math.floor(Math.random() * words.length)];
console.log(word);
```
Next, add an event listener to the button that will trigger when the user clicks on it. Inside the event listener, check if the guess is correct or not, and add the guess to the list.

```
const submitBtn = document.getElementById("submit-btn");
const guessInput = document.getElementById("guess");
const guessList = document.getElementById("guess-list");

let attempts = 0;

submitBtn.addEventListener("click", function() {
  const guess = guessInput.value.toLowerCase();
  let result = "";
  attempts++;

  if (guess.length !== 5) {
    result = "Please enter a 5-letter word";
  } else if (guess === word) {
    result = "You win!";
    submitBtn.disabled = true;
  } else {
    const letters = word.split("");
    for (let i = 0; i < letters.length; i++) {
      if (guess.includes(letters[i])) {
        result += "O";
      } else
```
Building Your Own Personal Assistant With ChatGPT
Tags: chatgpt, python, alexa, anime
Published: 2023-02-19 03:28:28

If you've ever used Siri, Alexa, or Google Assistant, you know how powerful and convenient having a personal assistant can be. What if you could build your own personal assistant, tailored to your specific needs? Thanks to the power of OpenAI's ChatGPT language model and the open-source community, you can!

In this post, we'll explore a GitHub project called "ChatGPT-chan," which provides a collection of tools to help you build your own personal assistant. Let's dive in!

## What is ChatGPT-chan?

ChatGPT-chan is an open-source project that provides tools for building conversational interfaces, automating tasks, and more. It leverages the power of OpenAI's ChatGPT language model to understand natural language inputs and provide intelligent responses.

The project consists of three main components: 
- Emotion Classifier: A machine learning model that can detect the emotion in a given text input. 
- Stable Diffusion Model: A machine learning model that generates realistic images based on text prompts. 
- ChatGPT Wrapper: A Python library that provides a simple API for integrating the above models and creating conversational interfaces.

The project also includes a demo that showcases the power of the ChatGPT wrapper. Check out the demo video [here](https://odysee.com/@rushi:2/chatgptchandemo2:4) 

[github: chatgpt-chan](https://github.com/rushic24/chatgpt-chan) 


## How to Set Up ChatGPT-chan

To get ChatGPT-chan up and running, you'll find comprehensive guidance in the project's GitHub repository. Here’s a simplified setup process:

1. Install the Emotion Classifier and Stable Diffusion Model either on a server or locally.
2. Clone the ChatGPT-chan repository and install all necessary dependencies.
3. Modify the configuration file to connect to the Emotion Classifier and Stable Diffusion Model servers.
4. Launch the ChatGPT Wrapper.

This streamlined overview should help you initiate the setup quickly, with detailed steps available in the GitHub readme.

## Why Build Your Own Personal Assistant?

Building your own personal assistant can be a fun and rewarding project, but it also has practical applications. For example, you could use it to automate tasks in your daily life, such as setting reminders or sending messages. You could also integrate it into your own projects to provide a natural language interface for your users.

Another benefit of building your own personal assistant is that you have full control over the data it collects and how it's used. With commercial personal assistants, you may not know what data is being collected and how it's being used.

## Conclusion

If you're interested in building your own personal assistant, ChatGPT-chan is a great place to start. It provides powerful tools for understanding natural language inputs and generating intelligent responses, all using open-source software.

While the setup process can be a bit involved, the end result is a powerful tool that you can use to automate tasks and provide natural language interfaces for your projects. Give it a try and see what you can build!
Visão geral do ecossistema de clientes Redis no .NET
Tags: redis, dotnet, braziliandevs, programming
Published: 2023-02-19 03:08:39

## Introdução

O ecossistema de clientes para Redis é diverso. Com exceção do cliente `hiredis`, o ecossistema de clientes foi inicialmente construído a maior parte pela comunidade. 

## Níveis de abstrações

Existem diferentes níveis de abstração que os clientes do Redis podem ter:

1. **Clientes do Protocolo Mínimo**: Esses clientes basicamente lidam com a conexão, encapsulam o protocolo RESP (o protocolo de rede para Redis) e pouco mais. Eles são bastante minimalistas e destinados a fornecer o máximo de controle ao usuário.
2. **Clientes do Nível Geral de Comando**: Os clientes que expõem diretamente a interface de comando Redis e fornecem alguma análise para as estruturas de resultado vindas dele. Estes têm mais ou menos uma correspondência de 1:1 entre os comandos no Redis e os comandos no cliente.
3. **Clientes Abstratos de Nível Mais Alto**: Esses clientes são destinados a fornecer uma interface amigável ao usuário e fornecer alguma abstração significativa acima da interface de comando Redis e dos paradigmas aos quais os usuários estão acostumados.
4. **Integrações de Framework**: Esses clientes são escritos para interagir diretamente com um framework específico, muitas vezes implementam alguma funcionalidade muito particular de uma maneira nativa do framework.

Existem uma infinidade de clientes de cada uma dessas categorias em toda a comunidade .NET. O que teve o impacto mais significativo, no entanto, é sem dúvida o `StackExchange.Redis`.

## Introdução ao `StackExchange.Redis`

 `StackExchange.Redis` foi escrito por **Marc Gravell** em colaboração com **Nick Craver** como parte do seu trabalho na **StackExchange**. **Marc** havia escrito um cliente mais antigo chamado `BookSleeve` que apresentava alguns problemas fundamentais que ele procurou resolver no `StackExchange.Redis`. A biblioteca fica em algum lugar entre os clientes de segundo e terceiro níveis.

## Impactos do `StackExchange.Redis`

A comunidade Redis .NET foi amplamente moldada por esse projeto. Outras bibliotecas de terceiro e quarto níveis têm essa biblioteca como dependência. Consequentemente, é importante que mergulhemos em alguns dos fundamentos da biblioteca para ver como ela funciona, seus benefícios e algumas de suas limitações.

## Conclusão

Em resumo, a diversidade e a riqueza do ecossistema de clientes do Redis oferecem aos usuários uma ampla variedade de opções para escolher, e o `StackExchange.Redis` é um exemplo importante dessa variedade.
Open Question: How Can AI Help Instead of Hurt?
Tags: ai, chatgpt, future, prediction
Published: 2023-02-19 02:37:40

The [ChatGPT](https://chat.openai.com/chat) public phenomenon has given us a glimpse of what is to come.

Making dark predictions is easy. Too many people do that -- on almost any topic.

**_Predicting how a disruptive technology can lead to a better future for the general population is not as easy._**

**Question:** What steps would need to fall in place for mankind, all ages and skill levels, to have a better working and living future 20 years from now instead of a darker one as AI technologies take over more functions that today are owned by living-breathing-creative human beings?
Manipulando Sorted Sets no Redis
Tags: programming, redis, tutorial, braziliandevs
Published: 2023-02-19 01:14:35

## Introdução

O Sorted Set é uma estrutura de dados do Redis que é similar a um conjunto, mas que tem um valor associado a cada elemento, chamado de "pontuação". Os elementos são armazenados em ordem de pontuação, o que permite a realização de operações de classificação e ordenação.

## Comandos

Os comandos mais relevantes para a manipulação de Sorted Sets são:

1. `ZADD`: adiciona um ou mais elementos com suas pontuações ao Sorted Set.

```bash
ZADD myset 1 "one"
ZADD myset 2 "two"
ZADD myset 3 "three" 4 "four"
```

1. `ZRANGE`: retorna um intervalo de elementos do Sorted Set de acordo com suas pontuações.

```bash
ZRANGE myset 0 -1
```

Este comando retorna todos os elementos do Sorted Set, ordenados de acordo com suas pontuações.

1. `ZINCRBY`: incrementa a pontuação de um elemento existente no Sorted Set.

```bash
ZINCRBY myset 2 "two"
```

Este comando incrementa a pontuação do elemento "two" em 2.

1. `ZRANK`: retorna a posição de um elemento no Sorted Set, ordenado por pontuação.

```bash
ZRANK myset "two"
```

Este comando retorna a posição do elemento "two" no Sorted Set.

1. `ZSCORE`: retorna a pontuação de um elemento no Sorted Set.

```bash
ZSCORE myset "two"
```

Este comando retorna a pontuação do elemento "two" no Sorted Set. 

1. `ZREVRANGE`: retorna um intervalo de elementos do Sorted Set em ordem reversa.

```bash
ZREVRANGE myset 0 -1
```

Este comando retorna todos os elementos do Sorted Set em ordem reversa. 

1. `ZCOUNT`: retorna a quantidade de elementos no Sorted Set com pontuações dentro de um intervalo especificado.

```bash
ZCOUNT myset 2 4
```

Este comando retorna a quantidade de elementos no Sorted Set com pontuações entre 2 e 4.

## Utilização no dia a dia

1. **Classificação de jogadores em jogos**: os pontos ou pontuações de jogadores podem ser armazenados como a pontuação de cada jogador em um Sorted Set. Isso permite que os jogadores sejam classificados de acordo com sua pontuação e que a lista dos melhores jogadores seja facilmente exibida.
2. **Gerenciamento de feeds**: itens em um feed, como mensagens de redes sociais ou notícias, podem ser armazenados em um Sorted Set, onde a pontuação é a hora em que o item foi postado. Isso permite que o feed seja ordenado pela hora em que cada item foi postado.
3. **Sistemas de votação**: cada voto pode ser armazenado como um elemento no Sorted Set, onde a pontuação é a quantidade de votos que esse elemento recebeu. Isso permite que os elementos sejam classificados por popularidade ou ordem de votação.
4. **Geolocalização**: as coordenadas geográficas de pontos de interesse podem ser armazenadas como a pontuação em um Sorted Set, permitindo que os pontos de interesse sejam classificados de acordo com a proximidade a um local específico.

## Conclusão

- Sorted Sets são uma coleção ordenada de valores únicos.
- Cada membro tem uma pontuação (`score`) associado.
- Pode ser acessado ordenado de maneira ascendente ou descendente.
EF Core string conversions
Tags: webdev, csharp, dotnetcore, tutorial
Published: 2023-02-19 01:12:24

EF Core provides methods to transform one type into another. Most common use is with enumerations ([see using Enum with EF Core](https://dev.to/karenpayneoregon/using-enum-with-ef-core-20go)) while many other transformations are possible. 

In this article a string property `Password` is encrypted when saving to a database table and decrypted when reading from the database table.

Microsoft [simple starter code sample](https://github.com/dotnet/EntityFramework.Docs/blob/main/samples/core/Modeling/ValueConversions/EncryptPropertyValues.cs) for `HasConversion` which in this case takes a string and reverses the string and stores in the table then read back reverses the value back to what was entered.

**Original conversion**

Which allows a developer to work from a simple example to implement their own logic while in this project a NuGet package is used as per below.

```csharp
modelBuilder.Entity<User>().Property(e => e.Password).HasConversion(
    v => new string(v.Reverse().ToArray()),
    v => new string(v.Reverse().ToArray()));
```

**Current conversion**

The conversion here is done with NuGet package [Inferno](https://www.nuget.org/packages/Inferno/) crypto [library](https://securitydriven.net/inferno/), Once configured as shown below the conversion is seamless.


![OnModelCreating code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1owrch6x812nliihgbxw.png)


## inferno crypt library

While many developers are aware enough not to roll their own crypto, they either pick the wrong approach, screw up the implementation, or both. Many of these libraries focus on providing as many crypto primitives as possible, which is a [huge disservice](https://spar.isi.jhu.edu/~mgreen/CryptoAPIs.pdf).

I highly recommend taking time to read the [docs](https://securitydriven.net/inferno/).


> **Note**
> Before running this project the database must be created with the script under the folder **Scripts**

## Source code

Clone the following [GitHub repository](https://github.com/karenpayneoregon/ef-core-string-has-conversion)

## See also

Microsoft: [Pre-defined conversions](https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations#pre-defined-conversions)

## Summary

What has been presented is not true encryption but a lesson in using transformations with EF Core.