teleren/devto huggingface dataset:
Design of Hashing Algorithms in Solidity
Tags: solidity, ethereum, web3, blockchain
Published: 2023-03-10 17:03:59

>The choice of hashing algorithm depends on the specific use case and security requirements

At the heart of hashing is a mathematical function that operates on two fixed-size blocks of data to create a hash code. This hash function forms part of the hashing algorithm. The size of each data block varies depending on the algorithm. Typically, the block sizes are from 128 bits to 512 bits. 

The following illustration demonstrates the hash function:

![Hash Function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eet80van0j2l6bl3f6a9.jpg)

The hashing algorithm, which is similar to a block cipher, consists of rounds of the hash function described above. For each round, a fixed-size input is required, which is often a combination of the most recent message block and the output from the previous round. This operation is repeated as many times as necessary to hash the entire message, up to the maximum number of rounds allowed. 

The following graphic depicts a schematic representation of the hashing algorithm:

![Hash Representation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ombonb967qug4qfw0ec7.jpg)

As a result, the hash value of the first message block is used as an input for the second hash operation, the output of which influences the result of the third operation, and so forth. This phenomenon is referred to as the avalanche effect of hashing. When two messages differ by even a single bit of data, the avalanche effect results in significantly different hash values for the two messages.

Understand the difference between a hash function and an algorithm in the proper manner. The hash function generates a hash code by performing operations on two blocks of binary data of defined length. In computing, a hash algorithm is a procedure for employing the hash function that specifies how the message will be divided up and how the results from previous message blocks will be linked together.

Solidity includes many cryptographic functions that can be used to protect data. The methods listed below are essential.

- keccak256(bytes memory) returns (bytes32) - It computes the Keccak-256 hash of the given input.

- ripemd160(bytes memory) returns (bytes20) - This function is used to compute the ripemd160 hash of the input compute using RIPEMD-160 algorithm.

- sha256(bytes memory) returns (bytes32) - Computes the SHA-256 hash of the input using the sha256(bytes memory) returns (bytes32) function

- ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address) - This function recovers the address associated with the public key from the elliptic curve signature or returns zero if there is an error. The following parameters of the function correspond to the ECDSA values of the signature: r represents the first 32 bytes of the signature; s represents the second 32 bytes of the signature; and v represents the final 1 byte of the signature. This method returns an address in the form of a string.

For more content, follow me at - https://linktr.ee/shlokkumar2303
Token Bucket
Tags: programming, security, kotlin, java
Published: 2023-03-10 17:02:53

## O que é token bucket?
Token bucket é um algoritmo para controlar a quantidade de transmissões de modo que não ultrapasse uma determinada capacidade. 

No contexto de aplicações esse algoritmo ajuda a limitar a carga que a aplicação vai receber, evitando qualquer tipo de abuso de requisições.

## Como ele funciona?
A quantidade máxima de tokens que podemos usar é determina pelo seu bucket. Um bucket é como se fosse um balde cheio de fichas (tokens). Cada requisição pode consumir uma ou mais fichas, dependendo da regra de controle do fluxo. Todo bucket possui uma taxa de reposição de tokens, ou seja, a cada "x" tempo, ou quando algo acontece, o token é devolvido ao bucket permitindo assim novas requisições.

Para entender melhor vamos usar o Pix do banco central como exemplo. Veja a tabela a seguir como o bacen descreveu suas regras de token bucket:

![Limitação de requisições PIX](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k4t5gacgufmj8vy8dvl4.png)

A regra para criar uma chave pix possui limitações. O bucket tem tamanho de 36k de tokens. Isso significa que é possivel fazer uso de 36k de requests para criar chaves pix. Se algum dia acontecer uma rajada de requisições o máximo possivel será de 36k e a partir dai o bucket ficará vazio, forçando a aguardar até que a taxa de reposição aconteça. Neste caso a cada minuto serão repostos 1200 tokens. Esse limite é compartilhado nas funcionalidades de criar e deletar chaves.

Alem disso é possivel realizar combinações da taxa de reposição com regras de negocio de sua aplicação. Por exemplo o banco central consome mais de um token quando uma chave pix é lida e não é utilizada em seguida em algum pagamento. Isso evita abuso do consumo desse recurso pois se isso acontece o bucket fica vazio rapidamente e não é mais possivel utilizar esse recurso.

Da pra imanigar muitas formas diferentes de evitar sobrecarga e abuso da API que esta sendo protegida por este método.

## Legal, como implemento isso na minha aplicação?

É possivel implementar o algoritmo token bucket do zero. Mas isso pode dar trabalho e desprender muito esforço. Uma boa opção é utilizar a biblioteca bucket4j.

O bucket4j possui a implementação do token bucket e pode ajudar muito nesse sentido.

## Referências
- https://en.wikipedia.org/wiki/Token_bucket
- https://github.com/bacen/pix-dict-api/releases/tag/1.8.0
- https://github.com/bucket4j/bucket4j
- https://bucket4j.com/8.2.0/toc.html#quick-start-examples
Tips for using LinkedIn effectively
Tags: job, linkedin, internships, github
Published: 2023-03-10 17:01:36

Using LinkedIn for professional growth can help you to build your personal brand, establish new connections, and find new job opportunities. 

**Here are some tips for using LinkedIn effectively:**

1- **Create a Complete Profile** : Your LinkedIn profile should be complete, up-to-date, and highlight your skills, education, and work experience. Make sure to include a professional headshot and a well-written summary that showcases your accomplishments and aspirations.

2- **Connect with Other Professionals** : Connect with other professionals in your industry by sending connection requests to colleagues, former classmates, and others you have worked with. You can also join LinkedIn Groups related to your industry or interests.

3- **Engage with Content** : LinkedIn is a great platform to stay up-to-date with industry news and trends. Engage with posts by liking, commenting, and sharing them. You can also publish your own content, such as articles or blog posts, to showcase your expertise.

4- **Use LinkedIn Learning** : LinkedIn Learning offers a variety of courses and tutorials on various topics related to professional growth. Take advantage of this resource to develop new skills or enhance your existing ones.

5- **Explore Job Opportunities** : LinkedIn also serves as a job board where you can search for new job opportunities or even get headhunted by recruiters. Make sure your profile is up-to-date and reflects your current career aspirations.

By following these tips, you can effectively use LinkedIn for professional growth and build your personal brand in the process.

Let me know for any help related to [LinkedIn](https://www.linkedin.com/in/avinash-singh-071b79175/) profile , resume , [GitHub](https://github.com/avinash201199) and [portfolio](https://avinash201199.github.io/Avinash-Singh/).
Como fazer uma requisição de API no React?
Tags: beginners, react
Published: 2023-03-10 16:52:59

No desenvolvimento de aplicações web modernas, a comunicação com APIs é um aspecto fundamental. O React, uma biblioteca JavaScript para construir interfaces de usuário, oferece suporte para realizar requisições de APIs de forma simples e eficiente. Neste artigo, exploraremos como fazer requisições de API no React, utilizando a biblioteca Axios como exemplo.

**Requisições utilizando Axios -**

O Axios é uma grande ferramenta de requisição de dados em uma API,o fazendo de maneira fácil e intuitiva. Com eles, conseguimos utilizar os métodos HTTP, incluindo GET, POST, PUT e DELETE. Mas para poder fazer uso do Axios, é necessário o instalar.


**Instalando o Axios -**

Precisamos abrir nosso terminal e usar o seguinte comando(pode ser instalado via npm e yarn):

```
npm install axios

//ou 

yarn add axios
```

**Testando uma requisição com Axios -**

```
import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });
```
Neste exemplo, utilizamos o método get do Axios para realizar a requisição para a URL especificada. Em seguida, utilizamos o método then para lidar com a resposta da API, que será retornada no parâmetro response. Por fim, utilizamos o método catch para lidar com possíveis erros que possam ocorrer durante a requisição.

**Aplicando Hooks na requisição de API no React-**

Nós também podemos usar um raciocínio de Hooks quando estivermos escrevendo nossa consulta de API no React. Para fazer requisições, podemos utilizar o `useState` para armazenar o resultado da requisição e o `useEffect` para carregar a requisição do componente. Veja o exemplo mais abaixo:

```
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        setPosts(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  return (
    <div>
      {posts.map(post => (
        <div key={post.id}>
          <h3>{post.title}</h3>
          <p>{post.body}</p>
        </div>
      ))}
    </div>
  );
}

export default App;
```
Neste exemplo que acabamos de ver, utilizamos o `useState` para inicializar a variável posts como um array vazio. Em seguida, utilizamos o `useEffect` para realizar a requisição para a API assim que o componente é montado. Utilizamos o segundo parâmetro do `useEffect` (um array vazio) para garantir que a requisição seja disparada apenas uma vez, quando o componente é montado.


Com base nisso, vimos como realizar requisições de API no React utilizando a biblioteca Axios. Vimos também como utilizar Hooks para disparar alguma chamada de API, e como o processo é simples de se fazer.
Steps to adopt micro frontends architecture for your frontend application in Angular
Tags: angular, microfrontends, webdev, javascript
Published: 2023-03-10 16:07:01

If you have an Angular project with a mono repo that is shared among various teams, you should consider changing the monolithic architecture of your application to micro-frontends using module federation.

1 Create an nx-worspace using:
```
npx create-nx-workspace@latest <project name>
```
_• Select angular and scss_

2 Change the directory to the project folder using:
```
cd <project name>
```

3 Open Visual Studio code using:
```
code .
```

4 Create separate containers using:
```
nx generate @nrwl/angular:app <container name>
```

5 Compile and run all containers using:
```
nx run <container name>:serve:development - port <port>
```
_Note: You can also use ng instead of nx_

6 Use the following command to create new components:
```
nx generate @nrwl/angular:component <component name> - project <project name>
```

7 Set up module federation in all containers:
```
npm i @angular-architects/module-federation
```

8 Run the following command to add webconfig file to all the containers:
```
ng g @angular-architects/module-federation:init
```
_• Select container and assign port_

9 Expose the component you want to use in other containers in webpack.config.js:
```
exposes: {
    './Module': './apps/<container-name>/src/app/remote-entry/remote-entry.module.ts',
     },
```

10 Use the exposed module in the routing of app.module.ts of the shell container:
```
RouterModule.forRoot(
     [
       {
           path: '<container-name>',
           loadChildren: () =>
           loadRemoteModule({
           remoteEntry: 'http://localhost:<port>/remoteEntry.js',
           type: 'module',
           exposedModule: './Module',
           }).then((m) => m.RemoteEntryModule),
        }
       ],
       { initialNavigation: 'enabledBlocking' }
      )
    ],
```

11 In order to create a shared service in a shared folder, use:
```
ng g @nrwl/angular:lib shared/test-service
```

12 Install ngx-mfe (version 3.0.2):
```
npm i ngx-mfe
```

13 Create index.ts file and import:
```
export * from './lib/shared-test-service.module';
export * from './lib/test-service.service';
```

14 Add the path to tsconfig.base.json:
```
"paths": {
          "@micro-frontends/shared/test-service": ["libs/shared/test-service/src/index.ts"]
         }
```

15 Add the shared service to the webpack.config.js file of the container you want to use the service in:
```
sharedMappings.register(sharedMappings.register(
         path.join(__dirname, '../../tsconfig.base.json'),
         path.join(__dirname,'../../tsconfig.base.json'),
         [/* mapped paths to share */]);
         ['@micro-frontends/shared/shared/test-service']);]);
```

16 In order to use the service, import it into the component:
```
import{{ TestService }} from '@micro-frontends/shared/test-service'
```
_Note: Please change micro-frontends to the name of your project and test-service to the name of your service in the above commands._

Happy Coding!
Start experience in c++
Published: 2023-03-10 15:59:45

Hello
I'm Mariarty.
This is my c++ blog. this post
will be short, but I promise, during my training I will share my knowledge with you.
The first lesson was devoted to the correct writing of codes in c++. we also learned how to enter variables in the console, also enter a value through the console using CIN>>. that's it. see you in the next post.
Procesar una transacción remota (XML) mediante un procedimiento almacenado
Tags: xml, oracle, java, backend
Published: 2023-03-10 15:50:29

Para enviar información (transaccional) hacia una base de datos centralizada, prodríamos emplear un servicio web: recibe los datos y los persiste de forma autónoma, segura y confiable. Pero como alternativa, es invocar un procedimiento almacenado remoto. 

Consideremos la limitante que no podemos enviar la información en formato JSON. La versión del motor no lo soporta: Oracle 11g. La solución será emplear el formato XML. 

No pasemos por alto los riesgos de enviar la información no cifrada (el sistema está en una red privada o no), el tamaño de los datos y el costo de procesamiento del servidor.

---

Este ejemplo nuestra cómo generar el formato XML en el cliente. Se etiqueta los bean's con la anotación  @XmlRootElement. 

{% embed https://gist.github.com/edgargs/2e31a20bb39635932fca931ca8f295bc %}

El procedimiento para interpretar el xml y grabar las tablas correspondientes. La solución es válida para todas las base de datos relacionales (como Postgres y Sql Server), aunque el código varía entre ellas.

{% embed https://gist.github.com/edgargs/3aac9caf278ef79f55b09f225cd8963c %}

---

## Documentación

https://github.com/edgargs/Ejemplo-2016-01.git
http://howtodoinjava.com/jaxb/jaxb-exmaple-marshalling-and-unmarshalling-list-or-set-of-objects/ 
http://viralpatel.net/blogs/oracle-xmltable-tutorial/
Code Search and Navigation with livegrep
Tags: codesearch, livegrep
Published: 2023-03-10 15:48:45

---
title: Code Search and Navigation with livegrep
published: true
description: Code Search and Navigation
tags: codesearch, livegrep
---
## Using Code Search : Livegrep

After trying out bunch of indexing (tag) tools production/command-line, one that index git repo, uses ngram, has web frontend, includes docker setup. It is code search that just works!

(Original Github) [https://github.com/livegrep/livegrep]

This are instructions to run source indexer
- Go to Source Directory
- Clone repo and output index file with idx suffx current directory, mouted as data on container

```
docker run -v ${PWD}:/data ghcr.io/livegrep/livegrep/indexer /livegrep/bin/livegrep-github-reindex -repo doxygen/doxygen -http -dir /data
```

- Create Network
```
docker network create livegrep
```

- Create backend process load it with idx file and accept RPC call at grpc
```
docker run -d --rm -v ${PWD}:/data --network livegrep --name livegrep-backend ghcr.io/livegrep/livegrep/base /livegrep/bin/codesearch -load_index /data/livegrep.idx -grpc 0.0.0.0:9999
```

- Connect web app and backend process and publish web application
```
docker run -d --rm --network livegrep --publish 8910:8910 ghcr.io/livegrep/livegrep/base /livegrep/bin/livegrep -docroot /livegrep/web -listen 0.0.0.0:8910 --connect livegrep-backend:9999
```

* Using It
  1. Connect to "0.0.0.0:8910" of web application
  2. Search for Code literal

* Best Parts
  1. LIVE GREPPING! Grep Works as you type. faster than egrep,grep
  2. Click on Search, it takes you to github file with anchor! :D

HTH!
Local Kubernetes with DNS
Tags: kubernetes, linux, dns, network
Published: 2023-03-10 15:45:27

A simple and short experience report from my daily Kubernetes playground.

I've got a local cluster running. Plain Kubernetes on virutal Nodes with KVM. That's my little lab where I can break things and repair them. That's the way I learn in tandem with all the abundance of documenation (which is old, as soon as you read it).

So, having services and exposing them as NodePort or LoadBalancer is nice, but you either have to type in the IP of the cluster, put some static values in your `hosts` file or provide a header when running `curl` against a service.

But, the little Kubernetes project [external-dns](https://github.com/kubernetes-sigs/external-dns) allows you to make your cluster create DNS entries in cloud providers and even local DNS.

In my case, I have the great tool [pi-hole](https://pi-hole.net/) running on a dedicated little Raspberry-Pi, which also serves as my primary DNS.

Now, whenever I expose an service and/or create an Ingress resource, specified DNS names will be [relayed to pi-hole](https://github.com/kubernetes-sigs/external-dns/blob/master/docs/tutorials/pihole.md). No need to hack in numbers or manipulate static files, anymore.

I love it! ;-)
Finally, I figure out how to do shift + ins on HP laptop
Published: 2023-03-10 15:34:19

---
title: Finally, I figure out how to do shift + ins on HP laptop
published: true
description: 
tags: 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-03-10 15:24 +0000
---
HP ELITEBOOK laptop combines F10 and insert keys together. It will kill you if you just want to do a shift + ins for pasting something in terminals. Fn + F10, Win + F10, shift + Win + F10, … , none of those work.

Finally, I figure out how to do a shift + ins. Just

**right shift** + **Fn** + **E**

Note that left shift is combined with fn lock, so you must use right shift.

As for ctrl + ins, just use **ctrl** + **Fn** + **E**, both ctrl keys work.
C++ Izoh
Published: 2023-03-10 15:33:22

Assalomu alaykum hurmatli dasturchi bugun C++ dasturlash tilida izoh qoldirish haqida gaplashib olamiz! Boshlashdan oldin biz nima uchun Izoh dan foydalanishimiz kerak ekanligini bilib olishimiz zarur hisoblanadi! Shuni esda saqlab qoling! Izoh lar ochiq va Yopiq turga bo'linadi!

C++ dasturlash tilida **//** belgidan so'ng izoh yoziladi. Bu belgi faqat bir qatorli izoh uchun amal qiladi. Bir nechta qator uchun qo'llashingiz mumkin. Buning uchun **//** ni har qatorda qo'llashingiz zarur bo'ladi.

```
**//** Bu Izoh uchun yozil
```
**//** Ikkinchi qator izoh uchun yozildi.
cout << "Hello World! mirjalol";
C++ dasturlash tilida operator oxirida ham izoh sifatida yozib ketsak bo'ladi.

```
cout << "Hello World! mirjalol";
```
 **//** Bu izoh (Chiqarish operatori)
C++ dasturlash tilida ko'p qatorli izoh.
Ko'p qatorli sharhlar bilan boshlanadi **/***va tugaydi ***/**.

Yozilgan kod o'rtasida /*bo'lgan barcha matn yoki operatorlar ***/**  e'tiborsiz qoldirladi.

```
**/*** Bu izoh uchun yozilgan bo'lib
bir nechta qator uchun amal qiladi
muallif MasterSherkulov** */**
cout << "Hello World! mirjalol";
```
Ochiq Izoh - Bu foydalanuvchiga ko'rinib turadigan izohlar sirasiga kiradi. Masalan! Tizimga kirish vaqtida sizning login parolingiz to'g'ri yoki notug'ri ekanligini bildiruvchi xabarni misol keltirishimiz mumkin!
Yopiq Izoh - Bu dasturchilar o'rtasida qayta tushuntirish uchun hojat qolmasligi uchun dastur qismiga sharx sifatifa qoldiriladigan izohlar hisoblanadi!
C++ dasturlash tilida Misol keltiramiz!
**//** Bu izoh uchun yozilgan
**//** 

Izoh C++dasturlash tilini kodini tushuntirish uchun qo'llash mumkin!
Kodni o'qilishi uchun sharxlardan foydalanish mumkin.
Jamoa bo'lib ishlagan vaqtda kodingizni qayta jamoaningizga tushuntirish zarur emas! chunki izoh qoldirib bir yo'la yozgan kodingizni tushuntirish imkoniyatiga ega bo'lasiz!
Odatda, biz **//**qisqa ya'ni bir qatorli sharh uchun va **/* */** bir yoki bir nechta qatorli sharhlar uchun foydalanamiz .
What was your win this week?
Tags: discuss, weeklyretro
Published: 2023-03-10 15:28:58

Howdy! 🤠

Hope everybody had a wonderful week and that y'all all enjoy your weekends. 😀

Looking back on this past week, what was something you were proud of accomplishing?

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Fixing a tricky bug
- Celebrating a birthday 🎂

---

![A child excitedly blowing out candles on their birthday cake](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kk4wsxuo3jkgh8a4m27g.gif)
Powershell Delete files by Size & Notify Telegram Log
Tags: script, powershell, telegram, log
Published: 2023-03-10 15:28:16

_This script remove files more than X size and notify log by Telegram._

###Powershell script:

- set variables.
- run on Powershell.

> can be used with task scheduler to keep specific folders clean

```

# First, we specify the details of the Telegram account and the chat ID

$botToken = Get-Content -Path  Env:\botToken
$chatId =   Get-Content -Path  Env:\chatId 

# Then, we define the path of the directory that we want to check, Size,Log Directory
$directory = "YOUR_PATH" 
$sizeFile = 2GB #100MB
$directoryLOG = YOUR_PATH


# We get a list of files in the directory that are greater than size specify
$filesBig = Get-ChildItem $directory -Recurse | Where-Object { $_.Length -cge $sizeFile } | Select-Object Name,";",Directory,@{n='GB';e={"{0:N2}" -F ($_.length/ 1GB)}} 

# If there are no files that meet the criteria, we end the execution of the script
if ($filesBig.Count -eq 0) {
    Write-Host "No files larger than $($sizeFile/1GB)GB."
    return
}

# If there are files that find the criteria, we generate the message that will be sent by Telegram
$message = "$(Get-Date -Format "yyyyMMdd_HH:mm:ss") ;" 

foreach ($files in $filesBig) {
    
    
    $message += "$($files.Name) ;$($files.GB)GB; $($files.Directory) ;files more than $($sizeFile/1GB)GB `n"
    # Save LOG
    Add-Content -Path $directoryLOG $message
    # Remove items
    Get-ChildItem $directory -Recurse | Where-Object { $_.Length -cge $sizeFile } | Remove-Item -Force 
}

# Send the message via Telegram
$message = [System.Web.HttpUtility]::UrlEncode($message)
$uri = "https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatId&text=$message"
Invoke-WebRequest -Uri $ur
```


Thanks for read!

- [redhcp page](https://redhcp.me/)
- [redhcp github](https://github.com/redhcp)