teleren/devto huggingface dataset:
Avoiding storage access in functions - 1
Tags: solidity, gasoptimization, bestpractice
Published: 2022-05-02 20:02:37

---series: Gas Optimization techniques---

In many cases accessing data from memory(local variables) is cheaper than accessing data from storage(state variables).

But this might not be always the case, there can be some circumstances where copying to memory can lead to some additional steps.
We will experiment this case in other post.

Let's focus on a general case now. Consider the following contracts:

```solidity
contract varReferencing_1{
    uint iterations = 10;
    uint public sum;

    function addItem() external {
        for(uint i; i < iterations; i++) { // reference from storage
            sum++; // updating storage
        }
    }

}

contract varReferencing_2{
    uint iterations = 10;
    uint public sum;

    function addItem() external {
        uint _iterations = iterations; // creating a copy in memory
        uint _sum = sum; // creating a copy in memory

        for(uint i; i < _iterations; i++) { // reference from memory
            _sum++; // updating in memory
        }
        sum = _sum; // updating in storage
    }
}
```
**varReferencing_1** and **varReferencing_2** both are doing the exact same thing. Only difference is, the `addItem()` in **varReferencing_1** is accessing directly from storage and in **varReferencing_2** it's creating copy in memory and then accessing it.

### Results:

**varReferencing_1**  `addItem()`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8h7t2kyotmevur4muesp.PNG)

**varReferencing_2**  `addItem()`

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

**Observation:**
The gas consumption is reduced while using memory access.
Fig - Your terminal, reimagined... with telemetry ( but you can disable that part ) 👾👾👾👾
Tags: cli, autocomplete, plugin
Published: 2022-05-02 19:37:52

[Fig](https://fig.io/) is pretty cool. It is GUI autocomplete for your terminal. Simple, effective. It also has a bunch of other extensible stuff going on but I am not covering it here.

Also, as user _chickenimprint_ made clear in a [comment on ycombinator](https://news.ycombinator.com/item?id=31222277)...

>  piece of proprietary software that collects data on basically everything on your machine and is unavailable on Linux? Nice!

Welp, if you install it and pay attention, you can click a link and find out exactly what kind of telemetry it is using. Truth be told it doesn't appear to be much, but for you paranoid types you can just use this command

`fig settings telemetry.disabled true`

I just installed it and it does seem to be a useful little app.

And yes, I disabled the telemetry.
Get Started with Face Detection with Python
Tags: python, programming, beginners, womenintech
Published: 2022-05-02 19:35:57

NOTE: Used a pre-trained model
Face detection in photos can be performed using the classical feature-based cascade classifier using the OpenCV library (cv2).

**Used packages**

```PYTHON
import cv2
import time
import os
```
OpenCV provides the `CascadeClassifier` class that creates a cascade classifier for face detection. The constructor can take a filename as an argument that specifies the XML file for a pre-trained model.

Download a pre-trained model ([file here](https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml)) for frontal face detection from the OpenCV GitHub project - to be placed in your working directory. 

**Setup the image directory**
```PYTHON
# function to get images from folder 
def get_images(dir_name):
    list_images = os.listdir(dir_name)
    all_images =list()

    for entry in list_images:
        full_path =os.path.join(dir_name, entry)
        if os.path.isdir(full_path):
            all_images.all_images + get_images(full_path)
        else: all_images.append(full_path)
    return all_images
```
Load the model that will perform face detection on photographs by calling the `detectMultiScale()` function.

```PYTHON
# Face Detection

def  main():
    dir_name = 'images' # directory for images
    list_images = get_images(dir_name)

    for i in range(20): #20 images
        image_path = list_images[i]

        print(image_path)
        
        # load the pre-trained model
        case_path = "haarcascade_frontalface_default.xml" # define the model used for recognition detection
        faceCascade= cv2.CascadeClassifier(case_path)
        image=cv2.imread(image_path)
        gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # make the picture to gray from color

        # face detection 
        faces = faceCascade.detectMultiScale(gray,
                                            scaleFactor = 1.1,
                                            minNeighbors=5,
                                            minSize = (30, 30))

        for (x, y, w, h) in faces: # draw rectangles on the faces when detected
            cv2.rectangle(image, (x,y), (x + w, y+h), (0, 255, 0), 2)
            
        #Load the detected faces
        cv2.imshow("Face Found", image)
        cv2.waitKey(5)
        time.sleep(5)
        cv2.destroyAllWindows()

if __name__ == '__main__':
    main()
```
Running the model loads the images and configures the cascade classifier; faces are detected, and each bounding box gets printed.

The model only works for faces directly at the camera (in front).


![Face detection 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dti9k27s4qz0h9bbekge.png)

![Face detection 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ylc4xnu1f7vai1ip2kro.png)
Can you help a student with a questionnaire?
Published: 2022-05-02 18:42:48

I'm an MSc student studying computer Science with Cyber Security at Wrexham Glyndwr University. As part of my research, I have a short questionnaire for any software developers willing to help me out. The questionnaire can be found here:  https://forms.office.com/Pages/ResponsePage.aspx?id=DQSIkWdsW0yxEjajBLZtrQAAAAAAAAAAAAN__ipZAO5UNDExNVRWTTdJQjczRFc0NjgxUkJES0pPSy4u . 

Thanks very much for your help!
Michael.
Lunes de música... ¿Qué estás escuchando? 🎵
Tags: spanish, music, discuss, monday
Published: 2022-05-02 17:55:10

> **"Hasta cierto punto, la música ya no es mía, es tuya."**
_Phil Collins_

La música es parte importante de la vida de la mayoría de las personas y una vida no basta para poder escuchar todas las canciones que quisiéramos o conocer a todos los artistas, solistas o bandas.

Últimamente mis gustos musicales han sido muy estáticos y siento que necesito abrir mis horizontes y poder conocer nueva música interesante. 

Este post será la primera entrega de una serie semanal que lanzaré todos los lunes para que como comunidad podamos compartir y por qué no conocer nuevas melodías. 🎶

Puedes compartir tus sugerencias usando los *liquid tags* de Dev.to, por ejemplo:

* Para compartir un video desde youtube:
```js
{% youtube dQw4w9WgXcQ %} // dQw4w9WgXcQ es el id del video
```

* Para compartir una canción desde spotify:
```js
{% spotify https://open.spotify.com/track/7GBwTrOpTtsLdJN3Dc0U1C?si=ea737b51f47043b6 %} 
```

Mi sugerencia para esta semana es de un grupo de rock boliviano llamado **Llegas** y la canción **Escenografía**

{% spotify https://open.spotify.com/track/0ee0Ow3VRGrUNsx4DtKRiL?si=44054d7400f34b80 %} 

De hecho si estas en Bolivia puedes ver la información de conciertos en la gira 2022 del Grillo.

{% twitter 1513964921628897283 %}
 


---

Este post no sería posible sin mi amigo @michaeltharrington y su post:

{% link https://dev.to/michaeltharrington/music-monday-what-are-you-listening-to-4g1o %}

Los respectivos créditos a él por ser tan buena onda. 

Y dime, ¿qué estás escuchando ahora? Te leo en los comentarios.
Postman API
Tags: postman, api, postmanapi101
Published: 2022-05-02 17:37:13




**Hey there👋**,


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

_APIs (Application Programming Interfaces) allow applications to interact and_ 
_communicate with each other by using a set of definitions and protocols. 
The software has become more complex, and collaborative over the year. 
The developer no longer needs to create every service from scratch.
APIs allow developers to access data from a service (like Google or Twitter) without 
any knowledge of how the codebase has been implemented.
Example: Google map, Weather reports on your phone, Laptop, and other gadgets.
There is everything like the Cat API, Open Weather Map, Genius, Discord, Youtube to MP3, etc.

_
**POSTMAN**

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


A_ postman is a good tool for testing APIs, by sending to the web server and getting 
back the response. Postman is a scalable API testing tool that quickly integrates into 
CI/CD pipeline. It started in 2012 as a side project by Abhinav Asthana to simplify 
API testing and development. It is a collaborative API development platform that 
simplifies creating, using, and testing APIs with a UI. 
It has become easier to work with URLs using postman instead of doing 
tedious task by command line.
This is being used as a mainstream tool in top software testing companies due to its 
tremendous benefits, some of them are listed below: -
▫ Postman allows you to move and share test cases from one system to 
another system and environment. This makes it extremely easy to use and 
manage test cases.
▫ Easy to create test suits.
▫ It can be easily integrated by different tools like Jenkins.
▫ It allows you to store data from previous test cases into a global variable.
▫ All the data can make available anytime as its entities can be saved to the 
cloud_

**Postman API Testing** 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/21dtv6wpfh1k7wt0moeo.png)
_Postman API testing bunch of software that tests how the 
APIs were developed and analyzes whether the APIs 
correctly fulfill their purpose to ensure the application`s 
functionality, reliability, security, and performance are not
compromise. Moreover, API testing mainly entails testing SOAP web
services or REST APIs, using JSON or XML message payloads, which are sent through HTTPS and HTTP.
Though other tools like assertible are also in the picture, 
Postman remains the top choice for API testing in many 
software services companies.
_
REST API Snippets
Tags: rest, api, restful
Published: 2022-05-02 17:33:24

Seguindo com a proposta de trazer um conteúdo mais rápido e prático de RESt API's, hoje vamos falar um pouco sobre o uso de **PUT** e **PATCH**, mas vou fazer um resumo sobre cada verbo HTTP.

## GET

Esse é o que a maior parte das pessoas conhece, uma tradução ipsis literis do verbo te ajuda a entender que deve ser usado para obter algum recurso do servidor. Se você abrir o debug do chrome em qualquer página que estiver navegando vai ver centenas de chamadas GET obtendo informações/artefatos/assets usando o método GET. O mais importante aqui é que esse verbo **NÃO** deve alterar nenhum estado no servidor de origem.

## POST

Diria que esse é o segundo mais usado, mas tem a função de criar um recurso no servidor. Pensando em um CRUD, esse é o cara responsável pelo **CREATE**. Por ser a porta de entrada do recurso em questão, devemos trabalhar muito com as validações para tornar esse recurso usável dentro da nossa aplicação. É aqui que você implementa coisas como:

* Validar CPF
* Garantir que o formato da Data esteja correto

## DELETE

Acho que esse é o mais fácil de entender. Seu objetivo é o que você imagina, deletar (ou marcar como removido) um recurso específico. Inclusive a própria [RFC](https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5) diz que é algo semelhante ao comando rm do linux, expressa uma operação de exclusão no mapeamento de URI do servidor de origem.

## PUT

Esse verbo na sua essência existe para solicitar uma alteração a um recurso em um servidor, e aqui que boa parte das pessoas se perdem uma vez que ele se propõe a alterar **TODO** o recurso em questão (passando todos os atributos de fato). 

Ex:

### Estado antes da requisição

```
{
  "nome": "Elon Musk",
  "idade": 50,
  "dataAniversario": "1971-06-28"
}
```

### Estado após chamada (alterando, nome e idade mas sendo necessário fornecer aniversário também)
`PUT /clientes/1`

```
{
  "nome": "Elon Musk 1",
  "idade": 51,
  "dataAniversario": "1971-06-28"
 }
```

## PATCH

Aqui o verbo também indica uma alteração no estado daquele recurso, mas o escopo é menor. Esse método deve ser usado como forma de atualizar 1 (ou mais atributos) garantindo a consistência da entidade como um todo.

Ex:
### Estado antes da requisição

```
{
  "nome": "Elon Musk",
  "idade": 50,
  "dataAniversario": "1971-06-28"
}
```

### Estado após chamada (alterando, nome apenas)

```
PATCH /clientes/1

{
  "nome": "Elon Musk da Silva"
}
```

```
{
  "nome": "Elon Musk da Silva",
  "idade": 50,
  "dataAniversario": "1971-06-28"
}
```


Existem questões mais técnicas acerca dos dois verbos, e acho que o importante lembrar (para não esquecer mais), é saber que por definição o **PUT** é [idempotente](https://developer.mozilla.org/pt-BR/docs/Glossary/Idempotent) enquanto o **PATCH** não.

Tem algo sobre RESt API`s que gostaria de saber mais?? Deixa ai nos comentários!!!
ERC-20 CLI Faucet
Tags: blockchain, go, solidity, programming
Published: 2022-05-02 17:13:40

## Summary

Hi everyone, I wanted to share this project I've been working on for any constructive criticism and reviews to help sharpen my knowledge with Blockchain technology and general Software Engineering. I appreciate all forms of advice and looking forward to what this community thinks about it, thank you.


## Github Repository
 - https://github.com/kimanikelly/cli-faucet

## Built With

- Golang - I used this programming language for 100% of the CLI functionality.

- https://github.com/urfave/cli - A Golang package used to structure the CLI.

- https://github.com/kimanikelly/cli-faucet/actions) - Implemented the Go Continuous Integration with Github Actions to verify the application will build on every push to the main branch.

- https://kimanikelly-contractapi.herokuapp.com/tokenContract - I built this API to allow any programming language to perform an HTTP GET request and return the Address, ABI, and Bytecode of `Token.sol` as a response. For this project I chose Golang to create the Token.sol contract instance.

## Features
- Connect your Ethereum wallet to the application by supplying your private key and Infura Rinkeby provider url inside of a `.env` file.

- Execute a command to view the amount of `TEST TOKENS` the connected wallet will receive.

- Execute a command to view the amount of `TEST TOKENS` the `Token.sol`smart contract has in its balance.

- Execute a command to view the `TEST TOKEN` balance of a wallet.

- Execute a command to view the `Rinkeby ETH` balance of a wallet.

- Execute a command to receive the `FundAmount` from `Token.sol`. The `FundAmount` will be deposited into the connected wallet.

## Future Features

- Integrate the MySQL Database to record every transaction
- Containerize the application through Docker for an easier installation process
- More unit tests
Day 21 of 100 Days of Code: Thinking and Coding Responsively for the Web Part 1
Tags: html, webdev
Published: 2022-05-02 17:05:00

Today I learnt about coding responsively for the web. Responsive Web Design is about using HTML and CSS to automatically resize, hide, shrink, or enlarge, a website, to make it look good on all devices (desktops, tablets, phones and other devices that could come up in the future). This included the view port, width, font-size, margins, padding, media queries, images and a basic introduction to flexbox.
Why Is OSS Good For The World?
Published: 2022-05-02 16:53:43

The headline - is that even a question? 😲It is not - we just wanted to catch your attention! 
Now that you are already here, stay with me till the end; it will be short, I promise.


Tech is evolving so fast that it is almost impossible to keep up with it. You build a project with a particular tech, and within a month, there is something new, and you get busy implementing that. This way, will we ever finish the project? Single-handedly? Well, that’s a big question! But, we have open source to the rescue.

**World-class technology** - There are so many examples of side-projects making it big (as big as a company), which have been possible because of open source. Software is a major part of our life now and would not have been so if open source never existed.  

**Hands-on with tech** - With open source, there is so much transparency with the code that it becomes easier for one to understand the architecture and better understand how the software works.

**Innovation at its peak** - With developers from across the world contributing, so many new ideas and perspectives are brought to the table.

**More secure** - According to [research](https://www.sas.com/content/dam/SAS/en_gb/doc/analystreport/open-source-vs-proprietary.pdf), open-source software is more secure, thanks to all the contributors and maintainers continuously working on bugs found by users. The feedback process in open source is very fast, which otherwise takes weeks in closed development environments.

**Community support** - What needs to be highlighted is the community's support in any open-source project. They are not only contributors, but also users who test, use, and provide feedback to the project. This has resulted in building world-class software and has also led to people landing good opportunities. 

**Free to use** - This makes it easier for individuals and small companies to get hold of the recent technology without spending a ton of money.

And the list goes on. It is fair to say that the world of technology has become a little better with open source. With everything going well, there comes a time in the life of a maintainer when it becomes difficult for them to go ahead with the project. With so much love and support, there is a constant pressure to get better, use the most recent updates, make the project faster, more scalable, give a better experience to the community. Still, all of these come with a burning hole in the pocket and is a reason why funding becomes so important. Just as easy as it may sound, receiving funding is a task in itself.

At Appwrite, we have come up with an initiative for the OSS community. Our aim is to help support maintainers and invest in technology and people. If this is something that excites you, stay tuned till May the 4th for more announcements from us! Here’s to the spirit of open source: let it never get dull!

Join the launch at 9 am PT 👇
{% embed https://twitter.com/appwrite/status/1520376271544463367?s=20&t=2LjSSDgdjpRQP57wB0iRkw %}
What I learned This Week. Week 10.
Tags: datascience, python, weeklyretro
Published: 2022-05-02 16:50:37

This week went a little differently than the past. I helped my girlfriends parents move from Florida to Tennessee. So instead of having a paragraph for each day, I will be doing some bullet points as a summary of what I did that day. 

### Monday
* Worked on SQL practice problems.
* Practiced Spanish on Duolingo.
* Read article on new machine learning technologies.

### Tuesday
* Applied for jobs.
* Reached out to a few people via Linkedin.
* Did a little SQL and Spanish.

### Wednesday
* Reflected on quality of resume and personal profiles.
* Learned new SQL concept and completed practice problems. 
* Practiced Spanish.
* Applied for jobs and conversated with a few recruiters.

### Thursday
* Drove about 10 hours down to Tennessee to help unload moving truck.
* Did some practice problems and my Spanish lessons.
* Slept on very uncomfortable pullout. 

### Friday
* Unloaded moving truck.
* Helped organize kitchen and living room boxes.
* Finally relaxed with good food.

### Saturday
* Drove another 10 hours home.

This week felt slow at first but came and beat my ass up before I knew it. I was happy I set myself up for success by not pushing myself. Although I didn't get near as much done as would normally. I kept up with the basics of my responsibilities to continue my good habits. I hope you enjoyed the quick read about my week and I hope to see you back here next week.
Changelog #0015 — 🐑 Duplicating collections and more
Tags: devtools, httpie, api, testing
Published: 2022-05-02 16:49:02

---
title: Changelog #0015 — 🐑 Duplicating collections and more
published: true
description: Duplicating collections, UI improvements, and bug fixes.
cover_image: https://httpie.io/Images/Share/blog-changelog-0015.png
canonical_url: https://httpie.io/blog/changelog-0015
---

Last week we [announced Spaces](https://httpie.io/blog/changelog-0014), a new way to organize your requests and collections. Since then, our main focus has been on the upcoming integration of HTTPie for Web & Desktop with our cloud sync backend. At the same time, we’ve also shipped a few goodies.

Check out what's new 👇


## HTTPie for Web & Desktop

### 🐑 Duplicating collections

It’s been possible to duplicate requests for a while. Now you can also duplicate whole collections for even faster reuse.

![Duplicate_Collections](https://httpie.io/_next/image?url=%2FBlog%2Fchangelog-0015%2FDuplicate_Collections-EDWERZ2D.png&w=3840&q=95)


### ✨ Other improvements

- We’ve moved the “Preview & export…” panel toggle up next to the request form tabs based on our users’ feedback. More accessible and easy.
- Look at our new settings icon! You can access your settings through the account menu.

### 🪲 Bug fixes
- The header name autocomplete dropdown doesn’t hide the name field anymore.
- The `…` menu in the message panel that allows you to copy the messages was misaligned when activated. It’s fixed now.
- The icon inside the collection tab was too small. Now it has the correct size.
- The settings tab’s checkmarks could sometimes overlap the library in some outstanding layouts. Fixed.
- The new font improvements uncovered an extra backtick we had on the preview type selector. A tiny bug that is now gone.

## HTTPie for Terminal

We’ve been putting the finishing touches on a new 3.2.0 release that we plan to release next week. See [last week’s changelog](https://httpie.io/blog/changelog-0014) for an [overview of the upcoming features](https://httpie.io/blog/changelog-0014#httpie-for-terminal).

## Happy testing, and see you next week!

But in the meantime…

- 💁🏻‍♀️ If you’re not on the private beta yet, you can [join the waitlist here](https://httpie.io/beta).
- 👉 You can also follow [@httpie](https://twitter.com/httpie) and join our [Discord community](https://httpie.io/discord).
- 👩‍💻 We’re looking for new colleagues in [engineering and design roles](https://httpie.io/jobs).

---

Originally published on [HTTPie blog](https://httpie.io/blog/changelog-0015).