teleren/devto huggingface dataset:
Adventofcode 🎄: Day 7 - Hooks
Published: 2023-12-07 19:35:05

In React, a hook is a special function that allows you to use state and other React features in functional components. Hooks were introduced to enable functional components to manage state and side effects, which were previously exclusive to class components.

The most commonly used React hook is the 'useState' hook, which allows functional components to have local state.  

**'useState'**

This hook allows you to add state to functional components. It returns an array with two elements: the current state value and a function that lets you update it.

**'useEffect'**

This hook enables you to perform side effects in your functional components. It can be used for tasks such as data fetching, subscriptions, or manually changing the DOM.

These are just a couple of React hooks, there are others such as 'useContext', 'useReducer', and 'useCallback'.

I hope that this short description on React hooks has helped, in the meantime....KEEP CODING!!!
Advent of Code #7 (in Crystal)
Tags: crystal, adventofcode
Published: 2023-12-07 19:34:45

Today's problem was primarily an exercise in sorting, with a little bit of math/logic for part 2. Instead of assigning a new order for each card, I kept the numbers the same and assigned new values to the face cards (and the number 10). Then I used `Array.group_by` and some patter matching to determine the order of the type of hand.

I don't know of any language that features composition of comparisons. Comparisons are usually represented as `-1/0/1` for less than, equal, or greater, but are sometimes represented as an enum or tagged union such as `LT/EQ/GT`. I would imagine such a feature to take two comparisons and return the result of the second if the first is equal. It is surprising how often I run into this situation. Maybe when I finally get around to writing my own language, I'll add this feature.

The last thing I wanted to discuss is code readability (or whatever word you want to use for the quality of code). Functional programming is often labeled as a paradigm that leans into math (perhaps too much). While I think that is a misrepresentation, it is often true that a functional style of code lacks descriptiveness. The OOP approach of representing everything as an object has the advantage of forcing you to use descriptive names.

It is certainly possible to write FP style code that uses more intermediate variables and even objects to convey intent and meaning more clearly. But coming up with those descriptive names takes careful consideration, and can slow down the 'real' code.

Sometime, I would like to discuss this more and show examples of improved readability of FP code. But today is not that day, so here is the mess of code I came up with:
```crystal
input = File.read("input").strip

cards = input.split("\n").map do |line|
  card, bid = line.split(' ')
  bid = bid.to_i
  card = card.gsub({T: ':', J: ';', Q: '<', K: '=', A: '>'})
  {card, bid}
end

def type(a)
  cases = {
    [] of Int32 => 7,
    [1] => 7,
    [2] => 7,
    [1, 1] => 6,
    [3] => 7,
    [1, 2] => 6,
    [1, 1, 1] => 4,
    [4] => 7,
    [1, 3] => 6,
    [2, 2] => 5,
    [1, 1, 2] => 4,
    [1, 1, 1, 1] => 2,
    [5] => 7,
    [1, 4] => 6,
    [2, 3] => 5,
    [1, 1, 3] => 4,
    [1, 2, 2] => 3,
    [1, 1, 1, 2] => 2,
    [1, 1, 1, 1, 1] => 1
  }

  hand = a
    .gsub('1', "")
    .chars
    .group_by { |x| x }
    .values
    .map(&.size)
    .sort

  cases[hand]? || 1
end

def stronger_hand(a, b)
  compare_type = type(a) <=> type(b)
  compare_type == 0 ? a <=> b : compare_type
end

part1 = cards
  .sort { |(a, _), (b, _)| stronger_hand(a, b) }
  .map_with_index(1) { |(_, bid), i| bid * i }
  .sum

puts part1

part2 = cards
  .map { |card, bid| {card.gsub(';', '1'), bid} }
  .sort { |(a, _), (b, _)| stronger_hand(a, b) }
  .map_with_index(1) { |(_, bid), i| bid * i }
  .sum

puts part2
```
Datatypes in C Programming.
Tags: c, coding, programming, datatype
Published: 2023-12-07 18:33:33

A data type is a classification that specifies which type of value a variable can hold.
`int age;`
In the above initialisation code the datatype is int. The variable age can only store integer value. 
The datatype also tells the compiler to allocate specific bits of memory according to the datatype used in the variable.
In the code above the variable with int value can store 4 bytes of data.

## Important datatypes in C

- int       (4 bytes) | %d for printing  
- double    (8 bytes) | %lf for printing  
- float     (4 bytes) | %f for printing  
- char      (1 bytes) | %c for printing 
- bool      (1 bytes) | %d for printing

The above list shows the main 4 datatypes in C along with its size and format specifier.

**int**
The int data type is used to declare integer variables.The int type is commonly used to represent whole numbers (integers) without any decimal places.
`int num1 = 42;`

**char**
The char data type in C is used to represent individual characters. It is typically used to store single characters, such as letters, digits, and special symbols.
`char myChar = 'A';`
We must use only single quot for char.
Characters are internally stored as integers. Each character corresponds to a numerical value according to the ASCII. For example, in ASCII, the character 'A' is represented by the integer value 65, 'B' by 66, and so on.
```
#include <stdio.h>      
int main() {
  
  char character = 'z'; 

  printf("%c", character);
  printf(" %d", character);
  
  return 0;
}
```

**float and double**
float and double is used to store decimal and exponential values. Only difference between float and double is its size.
`float myFloat = 3.14159;`
`double myDouble = 3.14159265359;`
```
#include <stdio.h>      
int main() {

  double number = 12.45;
  printf("%lf", number);
  
  return 0;
}
```
In the above code the output is `12.450000`. The float and double will have 6 digits after the decimal points that is the reason for the additional zeros in the above output.
If we want to avoid those values and we need only 2 digits after decimal points use `.2` after `%`.
```
#include <stdio.h>      
int main() {
  double number = 12.45;
  float number1 = 10.9f; //f is to indicate its a float value 
                           rather than a double value.
  printf("%.2lf", number);
  
  printf("\n%.1f", number1);
  
  return 0;
}
```

**bool**
C provides a built-in data type called bool to represent Boolean values. This allows you to store and manipulate logical states directly, enhancing code readability and type safety.
Holds two possible values: true and false.
Represented internally as 1 for true and 0 for false.
```
bool isLoggedIn = true; // Initialize to true
bool isDone = false; // Initialize to false
```
🚀 Elevate your text game with HTML! Need to raise text?
Tags: html, css, webdev, javascript
Published: 2023-12-07 19:14:24

Ever wondered how to add a superscript or subscript in HTML as we did while solving maths in high school? 

We are used to add the superscript or subscript in google docs or microsoft word using which looked like this.
![Superscript and Subscript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3eg4deg4m6w26w197d25.png)

### How to achieve superscript and subscript in HTML?

In HTML we can achieve the same using the tags **<sup>** for **superscript** and **<sub>** for **subscript**

```html
<p>Example of superscript: (a + b)<sup>2</sup></p>
<p>Example of subscript: F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub></p>
```
**Output**
<p>Example of superscript: (a + b)<sup>2</sup></p>
<p>Example of subscript: F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub></p>
🤔 Python Quiz: `with` or without?
Tags: python, beginners, programming, tutorial
Published: 2023-12-07 19:12:02

[Follow me to learn 🐍 Python in 5-minute a day](https://dev.to/vladignatyev) fun quizzes!

The `with` statement in Python is a powerful feature for managing the lifetime of resources, ensuring they are properly acquired and released, thus promoting cleaner and more reliable code. It's primarily used in scenarios where a pair of related operations need to be executed, such as opening and closing a file, or acquiring and releasing a lock.

## Quiz

## Sample 1
```python
file = open('example.txt', 'r')
content = file.read()
print(content)
```

## Sample 2
```python
# Using 'with' statement for file operations
with open('example.txt', 'r') as file:
    content = file.read()
print(content)
```

Post your answer in the comments – is it 0 for the first sample or 1 for the second! As usual, the correct answer will be explained in the comments.
Upload repository to GitHub with Git.
Tags: git
Published: 2023-12-07 19:02:47

Hello World!
Today i teach you how to upload your file to GitHub by using git.

1.`git clone _repository-link_`download GitHub repository to device.
after cloning repository you can add some files on this file.

2.`git status`You can see aded files.

3.`git add _filename_ or (.)`for add new files.

4.`git commit -m "anything"`
5.And finally `git push` you upload your repository with your new files.
Padroneggiare il successo su YouTube: svelare suggerimenti utili e strategie di crescita
Published: 2023-12-07 19:01:09

[TuttoYouTube ](https://tuttoyoutube.it/)è il tuo sportello unico per tutte le esigenze di YouTube! Forniamo le notizie, gli approfondimenti e i consigli di cui hai bisogno per sopravvivere nel mondo in continua evoluzione dei video online, che tu sia un creatore di contenuti esperto o che tu abbia appena iniziato.

Mantieni la tua conoscenza sulle notizie più recenti di YouTube

Esamina le tendenze più recenti, gli aggiornamenti degli algoritmi e le modifiche alla piattaforma che potrebbero avere un'influenza sul tuo canale.
Per mantenere la tua strategia sui contenuti in carreggiata, leggi la nostra panoramica approfondita della situazione attuale di YouTube.
Strategie di crescita esplosiva: libera il potenziale del tuo canale

Scopri strategie collaudate nel tempo per espandere i tuoi iscritti, le tue visualizzazioni e la tua partecipazione.
Scopri come gli innovatori di successo affrontano le sfide e le trasformano in opportunità di crescita.
Realizzare video coinvolgenti: guida alla creazione di contenuti

Utilizza il potere della narrazione e il coinvolgimento degli spettatori nei tuoi video.
Esamina nuove idee per miniature, titoli e descrizioni accattivanti.
Trasformare la passione in profitto: padroneggiare la [monetizzazione](https://set.page/tuttoyt/)

Per aumentare i tuoi guadagni, esplora le sfumature delle funzionalità di monetizzazione di YouTube.
Cerca nuovi flussi di entrate e collaborazioni adatte al tuo marchio.
Practical Storage Savings for Backend Developers
Tags: backend, webdev, laravel, database
Published: 2023-12-07 18:56:15

As a backend developer, your role in efficiently managing storage is crucial to avoid unnecessary costs for your clients. Here are key strategies to implement in various scenarios:

**File Storage:**
- Resize and compress images, especially when you don't need to display them in HD resolutions.
- When users update their profile pictures, ensure the removal of the old ones.
- Regularly clear old log files, such as Laravel errors stored in the "laravel.log" file, to prevent excessive storage usage.

**Relational Databases:**
- Prioritize database normalization to organize data into separate tables based on logical relationships and reducing redundancy.
- Choose appropriate data types for columns to minimize storage requirements.
- Implementing indexes on frequently queried columns improves query performance but comes with storage overhead, So balancing the number and size of indexes optimizes performance and storage.

**Summary:**
Optimize storage management by implementing strategies such as resizing and compressing files, removing outdated content, and optimizing database design through normalization, appropriate data types, and indexing. Balancing performance and storage considerations is crucial for backend developers to minimize costs and ensure efficient resource utilization.
NodeJS Backend tools - Node Version Manager (NVM)
Tags: javascript, tools, node
Published: 2023-12-07 18:49:36

Here is a very basic page on NVM.  If you don't know what NVM is and you use nodeJS, you should know!

# NVM
Node version manager is very powerful allowing you to easily install and switch back and forth between different node versions.

Install nvm per instructions.
https://github.com/nvm-sh/nvm

(I used their curl command to download script and run)
```
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
```

Node install with nvm:
- node -v. # is v20.10.0 at this point.
- nvm install 16   #installs node v16 and switches to it.
- node -v   # now equals v16.20.2.

To switch:
- nvm use 20   # (may need to install 20 with nvm for it to be able to use it)
top developing tools
Tags: webdev, beginners
Published: 2023-11-30 19:07:54

I read about the top web development tools being used right now and what you'll need in the future i also learnt what some of these tools do ill give a short list now 

1. IP stack this is a device the allows you to keep track of the people who are visiting you're website simple by getting an IP address 
built within these are 5 different modules that do different objectives 
location, currency, time, security and connection 

2. Vs code this is and open source editing software that makes editing code simpler and easier to handle one of the major changes with this is debugging with Vs code you can get rid of them easier 

3. Git hub has been around for many years and is still one the most recommended social sharing platforms on the market allows you to code with friends avoid confusion and minus the delays 

there were other tools like docker, sifler and Microsoft visual studios with more information I recommend check it out when you have time  
 
 https://webdesignledger.com/best-development-tools-2020/
AWS Bedrock Claude 2.1 - Return only JSON
Tags: aws, bedrock, claude
Published: 2023-12-07 18:49:36

Working with the AWS Bedrock API is an exhilarating experience! I came across an interesting business case where I needed to develop an AI MVP. The MVP generates JSON data based on a prompt and utilizes the [anthropic.claude-v2:1](https://docs.anthropic.com/claude/docs) model in [AWS Bedrock](https://aws.amazon.com/bedrock).

I encountered an issue where the response I received was not pure JSON. It contained additional characters that I couldn't remove like:

```txt
" format: {\"one\":\"Supplier\",\"many\":\"Time\"}"
```

Seeking help from the AWS Community, I was able to find a solution to this problem. In this post, I will share the solution with you.

## The Problem

```txt
Human: $YOUR_PROMPT . Answer in JSON formatAssistant:{,
```

This technique is known as "Put words in Claude’s mouth". It involves providing a prompt to Claude and letting it generate the rest of the response on its own. While there may be alternative approaches to solving this issue, I am currently happy with this solution.

## Thanks

I would like to express my gratitude to the AWS Community for their invaluable assistance in helping me resolve this issue.

A special thanks goes to [Corvus Lee](https://www.linkedin.com/in/corvus/) for providing the advice that ultimately solved the problem.

I would also like to thank [Ken Collins](https://www.linkedin.com/in/metaskills/) for bringing the [Claude 2 docs sheet](https://docs.google.com/presentation/d/1tjvAebcEyR8la3EmVwvjC7PHR8gfSrcsGKfTPAaManw) to my attention.

Once again, thank you all for your support and contributions.

## Conclusion

Working with AWS Bedrock AI is incredibly enjoyable. The field is constantly evolving, and there is always something new to learn. In this post, I demonstrated how to obtain a pure JSON response from AWS Bedrock Claude 2.1. As AI technology continues to advance rapidly, you may not encounter this issue in the future. However, if you are working with Claude 2.1 or newer, be sure to refer to the [documentation](https://docs.anthropic.com/claude/docs) for more information.

I hope you found this post helpful, and I look forward to sharing more with you in the future.

I love to work on Open Source projects. A lot of my stuff you can already use on <https://github.com/mmuller88> . If you like my work there and my blog posts, please consider supporting me on the:

[![Buy me a Ko-Fi](https://storage.ko-fi.com/cdn/useruploads/png_d554a01f-60f0-4969-94d1-7b69f3e28c2fcover.jpg?v=69a332f2-b808-4369-8ba3-dae0d1100dd4)](https://ko-fi.com/T6T1BR59W)

OR

[![Buy me a Ko-Fi](https://theastrologypodcast.com/wp-content/uploads/2015/06/become-my-patron-05.jpg)](https://www.patreon.com/bePatron?u=29010217)

And don't forget to visit my site

[![martinmueller.dev](https://martinmueller.dev/static/84caa5292a6d0c37c48ae280d04b5fa6/a7715/joint.jpg)](https://martinmueller.dev/resume)
O que é Análise de Requisitos?
Tags: softwareengineering, webdev, beginners, programming
Published: 2023-12-07 18:40:00

A análise de requisitos de software é uma etapa crucial no ciclo de vida do desenvolvimento de software, responsável por identificar, entender e documentar as necessidades e expectativas dos usuários e demais partes interessadas. Essa fase é essencial para garantir que o software a ser desenvolvido atenda às demandas específicas do cliente e do projeto.

Durante a análise de requisitos, os engenheiros de software trabalham em estreita colaboração com os stakeholders para coletar informações detalhadas sobre funcionalidades desejadas, restrições, comportamentos esperados do sistema e outros aspectos relevantes. Essa interação visa criar uma compreensão compartilhada entre a equipe de desenvolvimento e os clientes, evitando mal-entendidos que poderiam surgir mais tarde no processo.

Os requisitos podem ser classificados em diferentes categorias, incluindo requisitos funcionais, que descrevem as funcionalidades específicas que o software deve executar, e requisitos não funcionais, que abrangem características como desempenho, segurança e usabilidade. A documentação cuidadosa dos requisitos serve como uma base sólida para o design, implementação e teste do software.

Metodologias ágeis, como o Scrum, enfatizam a importância da flexibilidade na análise de requisitos, permitindo ajustes contínuos ao longo do desenvolvimento conforme novos insights surgem. Ferramentas de modelagem, entrevistas com stakeholders e prototipagem são comumente utilizadas para aprimorar a precisão e a compreensão dos requisitos.

Uma análise de requisitos eficaz contribui significativamente para o sucesso do projeto, minimizando riscos, melhorando a comunicação entre as partes envolvidas e fornecendo uma base sólida para o desenvolvimento de software que atenda às expectativas do cliente.
PL/SQL Tutorial
Published: 2023-12-07 18:26:46


**Tutorial: Introdução ao PL/SQL com exemplos práticos**

1) Criação de uma Procedure Simples
Vamos começar criando uma procedure simples que recebe um número como parâmetro e retorna o dobro desse número.
sql

CREATE OR REPLACE PROCEDURE CalcularDobro(
    numero IN NUMBER,
    resultado OUT NUMBER
)
AS
BEGIN
    resultado := numero * 2;
END;
Explicação:

CREATE OR REPLACE PROCEDURE: Cria uma nova procedure ou substitui uma existente.
numero IN NUMBER: Parâmetro de entrada.
resultado OUT NUMBER: Parâmetro de saída.
BEGIN ... END: Bloco onde a lógica é executada.


2) Uso da Procedure Criada
Agora, vamos chamar a procedure que criamos no exemplo anterior.

sql

DECLARE
    num NUMBER := 5;
    resultado_dobro NUMBER;
BEGIN
    CalcularDobro(num, resultado_dobro);
    DBMS_OUTPUT.PUT_LINE('O dobro de ' || num || ' é ' || resultado_dobro);
END;
Explicação:

DECLARE ... BEGIN ... END: Bloco anônimo PL/SQL para execução do código.
DBMS_OUTPUT.PUT_LINE: Imprime na saída do console.


3) Implementando uma Função
Vamos criar uma função que recebe um nome como parâmetro e retorna uma saudação personalizada.

sql

CREATE OR REPLACE FUNCTION GerarSaudacao(
    nome IN VARCHAR2
) RETURN VARCHAR2
AS
    saudacao VARCHAR2(100);
BEGIN
    saudacao := 'Olá, ' || nome || '! Seja bem-vindo(a)!';
    RETURN saudacao;
END;


4) Uso da Função Criada
Chamando a função para gerar uma saudação para um determinado nome.

sql

DECLARE
    nome_usuario VARCHAR2(50) := 'Ana';
    saudacao_usuario VARCHAR2(100);
BEGIN
    saudacao_usuario := GerarSaudacao(nome_usuario);
    DBMS_OUTPUT.PUT_LINE(saudacao_usuario);
END;



5) Utilizando Triggers para Validar Dados
Criaremos um trigger que valida a idade de um usuário ao inserir dados na tabela.

sql

CREATE OR REPLACE TRIGGER ValidarIdade
BEFORE INSERT ON Usuarios
FOR EACH ROW
BEGIN
    IF :NEW.idade < 18 THEN
        RAISE_APPLICATION_ERROR(-20001, 'É necessário ter mais de 18 anos.');
    END IF;
END;
Explicação:

BEFORE INSERT ON Usuarios: O trigger é acionado antes de uma inserção na tabela "Usuarios".
:NEW: Referência aos dados que serão inseridos.
Conclusão
O PL/SQL oferece recursos poderosos para manipular dados e lógica de negócios no Oracle. Esses exemplos são apenas um ponto de partida para explorar suas capacidades.
Experimente esses códigos em um ambiente Oracle para entender melhor o funcionamento e explore mais recursos conforme necessário para suas necessidades específicas.

Para visualizar os resultados ou executar esses exemplos, utilize uma ferramenta de acesso ao banco de dados Oracle, como o SQL Developer, e certifique-se de ter permissões adequadas para criar objetos no banco de dados.

Exemplo de PL/SQL

Este tutorial abrange apenas conceitos básicos. Você pode expandir seu conhecimento explorando outros recursos, como tratamento de exceções, manipulação avançada de cursores, e otimização de consultas. Experimente diferentes cenários e casos de uso para aproveitar ao máximo o potencial do PL/SQL em suas aplicações e rotinas de trabalho.

Espero que este tutorial forneça um bom ponto de partida para entender e começar a trabalhar com PL/SQL.
How to migrate Google Photos to Proton Drive Photos
Tags: proton, migrate, scripting, googlephotos
Published: 2023-12-07 18:19:42

Proton Drive just released their photo syncing feature on Android. I've been patiently waiting for this since Drive came out.

In this post I'm going to explain a an easy way to migrate your data from Google Photos to Proton Drive.

This will get outdated quickly as I'm sure they will integrate a better migration service, but until then this should work.

First step is to go to [takeout.google.com](https://takeout.google.com) and download all of your Photos data.

You will eventually receive an email with a link to download all your photos.

Once downloaded, you can unzip all your pictures with this command:

```sh
UNZIP_DISABLE_ZIPBOMB_DETECTION=TRUE unzip <takeout-filename.zip>
```

Now you have a nested set of directories with many pictures in them. I recommend deleting all directories that don't have a name like `Photos from 2010` as the rest are from albums which are likely duplicated in the `Photos from XXXX` files.

Now you will be left with all your photos as well as some json metadata files, which contain some info about when the photos were taken.

You could now, upload all the photos to Proton Drive via the web interface. Unfortunately, the photos will all be in the wrong order as they are sorted by the file creation date (which will be today) instead of the date the photo was taken. Also some files could have missing timestamp data.

Thankfully, there is a really cool tool called [google-photos-takeout-helper](https://pypi.org/project/google-photos-takeout-helper/). So you can go ahead and install that, and then run this command to sort all the timestamps:


```sh
google-photos-takeout-helper -i Takeout -o FixedTakeout
```

This will copy all the files to FixedTakeout with the correct metadata.


Now that this is done, we can finally upload the folder to the Proton Drive Photos service, and they should hopefully be in chronological order.
 
At the time of writing this post however, there is an annoying bug with the photo upload feature on the web interface which causes many failures.

So a better option, would be to copy all these files to your Android device, and select the new folder to be backed up to Photos, in the Drive settings page.