teleren/devto huggingface dataset:
New golang package to reduce code duplication in APIs
Tags: go, package, productivity
Published: 2021-05-01 08:56:58

Hi Golang developers!

I just released a new package that will help you develop APIs in go. 

Look at this code :

```go
func (a *API) handleChangePassword(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID := vars["userID"]

	requestBody, err := ioutil.ReadAll(r.Body)
	if err != nil {
		errorResponse(w, http.StatusInternalServerError, "", err) // <-- your custom error logic that you write for 
		                                                          //      each project
		return
	}

	var requestData ChangePasswordRequest
	if err := json.Unmarshal(requestBody, &requestData); err != nil {
		errorResponse(w, http.StatusInternalServerError, "", err)
		return
	}

	if err = requestData.IsValid(); err != nil {
		errorResponse(w, http.StatusBadRequest, err.Error(), err)
		return
	}

	if err = a.app().ChangePassword(userID, requestData.OldPassword, requestData.NewPassword); err != nil {
		errorResponse(w, http.StatusBadRequest, err.Error(), err)
		return
	}

	jsonStringResponse(w, http.StatusOK, "{}") // <-- your custom code that your are write for each project
}
```

This is often the code I see on Go projects. There is nothing wrong with writing this because it is very efficient and declarative.

But sometimes we would still like to focus a little more on what matters: business logic.

The version with KCD of this code now:

```go
type ChangePasswordRequest struct {
	UserID string `path:"userID"`
	// ...
}

func (c *ChangePasswordRequest) Validate() error {
	// ...
}

func (a *API) handleChangePassword(request *ChangePasswordRequest) error {
	if err = a.app().ChangePassword(request.UserID, request.OldPassword, request.NewPassword); err != nil {
		return errors.Wrap(err, "unable to change password").WithKind(errors.KindInvalidArgument)
	}

	return nil
}
```

As you can see the code is more concise and has less boilerplate, it is not more efficient because kcd uses reflection to achieve this simplicity.

If you want to play with this new toy this is the link of the package https://github.com/alexisvisco/kcd
Cloning JavaScript objects using graph theory
Tags: javascript, graphs, cloning, computerscience
Published: 2021-05-01 08:55:10

---
title: Cloning JavaScript objects using graph theory
published: true
description: Let's learn something about graph theory to properly clone JavaScript objects, both with and without circular references.
tags: javascript, graphs, cloning, computerscience
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/0mp3tenvhxthb91ankuo.jpg
---

## Introduction

The JavaScript slang allows us to clone objects in more than one way. We can perform a shallow clone using `Object.assign` or the spread syntax and a deep clone thanks to the `JSON.parse(JSON.stringify())` trick.
Unfortunately, the last solution suffers from a problem: `JSON.stringify` cannot work on an object that has circular references, erroring out in such a case.

In this episode we'll learn a bit of graph theory to then use this knowledge to build a simple, but efficient, deep cloner.

&nbsp;

[Link to the full article](https://andreasimonecosta.dev/posts/cloning-javascript-objects-with-graph-theory/) 😄
Firebase API Key Security Issue – for Custom Sign Up/Login
Tags: firebase, javascript, html, security
Published: 2021-05-01 08:47:46

Hello! Hope you're having a good day.

I was working on a project where I am making a user input form with HTML, JavaScript but when I inspect using Google Chrome, the front-end codes are showing up. All of my firebase Realtime Database API, Key, everything is there, visible.

I was wondering, if I make a login/sign up page using firebase and JavaScript, someone will be able to steal this database API and create their own HTML form, submit information and then they come back to my site and directly login with what they have, right?

Is there possibly any way (without React.js .env method) to prevent users from stealing my firebase API codes?
How to convert an integer into String?
Published: 2021-05-01 08:28:36

IN order to convert an integer into a string

we are supposed to use an object of the input/output class.

-----> Stringstream  ---> (String stream)
-----> iStringstream --> (input string stream)
------> oStringstream ---> (output string stream)


The above functions are defined in the header files.

"stream".


Steps to convert an integer into a string.

step 1: include header files #:include<sstream>".
step 2:  Take a Integral data.
Step 3:  Declare the output string stream.
Step 4: Sending the integer as a stream the output string stream.
Step 5: Finally declare a string variable where you want to store the new string.

code :
#include <iostream>
#include<sstream>
using namespace std;
int main()
{


int n = 2344;
//declare output string stream
ostringstream strq;

//sending integer as a stream into a string stream

strq<<n;

//declare string variable

string s = strq.str();
// output the string 

cout<<"output the converted string is"<<s<<endl;


return 0;

}


Thank you:)
How to use particles.js
Tags: javascript
Published: 2021-05-01 07:48:34

What is particles.js?
As is evident from the name, it is a JavaScript library that can help you create particle systems. Moreover, it is lightweight, easy to use, and gives you a lot of control.

⭐ Create a folder :

1. Inside the folder create an index.html file.

2. Inside this HTML file create a div with the id of particles-js.

 ![div](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jw30upky69uoxo94s88v.png)

3. Search partilces.js on your web browser.
   (https://vincentgarreau.com/particles.js/).

4. Visit the official GitHub repo of the particles.js
   (https://github.com/VincentGarreau/particles.js).

5. Download these files from the repo or clone the repo.
👉 paricles.js
👉 app.js
👉 particles.json

6. Create a CSS file styles.css

7. Add this CSS :

![css](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zfgpk7euquvuyp8o515.png)
 
8. Link these style sheets and scripts into index.html
   (The sequence of the script files should be the same).
👉 style.css
👉 particles.js
👉 app.js
![links](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u82sa68xhz8v8bvd1emh.png)
9. Run index file (open index file on the browser).

10. If still not working properly then watch this 
video: https://youtu.be/cUzihD4JBQU

Thank you 💖
How to convert Character into integer and vice-versa?
Tags: cpp
Published: 2021-05-01 08:13:35


ASCII code link: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
//convert an integer into a character

int p = 54;
char x = (char)p;


//Convert character into an integer 

char p ='a';
int x = (int) p;

#include<iostream>
using namespace std;

int main()
{
// integer to character conversion
int p = 43;
char x ;
x = (char)p;
cout<<x<<endl;
}

//the output of the following code would be '+'

#include<iostream>
using namespace std;

int main()
{
// integer to character conversion
char x = 56;
int p ;
p = (int)x;
cout<<p<<endl;
}

//the output of the following code would be 56
Why Use Pointers in C?
Tags: c
Published: 2021-05-01 08:05:02

Here, I will outline the importance of pointers and why we should use them when building programs in C.

*What is a Pointer?*
<ul>
    <li> A pointer is a special variable where the value if a memory address. </li>
</ul>

<hr/>

*Reasons to Use Pointers*
<ol>
    <li>Accessing data by only variables is very limiting and expensive. With pointers, you can access any location and perform arithmetic operations with pointers.</li>

    <li> Pointers make it easy to use arrays and strings.</li>

    <li> Pointers allow you to refer to the same memory space from multiple locations. This means that you can update memory in one location and you will see the change everywhere else it is being used in the program.</li>

    <li> Saves space by being able to share components in your data structures. </li>

    <li> Pointers allow functions to modify data passed to them as variables.</li>

    <li> Pointers allow us to get multiple values from a function. </li>

    <li> Dynamic memory can be allocated according to the program use. We can save memory from static declarations. </li>


    <li>Pointers allow us to develop complex data structures like queues, linked lists and stacks. </li>

    <li> Pointers provide direct memory access. This makes our program run very fast and efficient! </li>
</ol>

<hr/>
Python Automate the task of creating a file and run it from any directory.
Published: 2021-05-01 07:21:47

If you are a Coder? We have to create a file with a basic syntax on regular basis.

In the last blog as I told you, I am learning some Competitive programming I have to create a new python file every time I learning and solving a new algorithm.

Also, each file has a main() function which I have to write every time, and also I have to update my readme.md file as I push it on GitHub and keep track of problems I solve.

So I created a simple template file using python which I can run from any directory. I just have to type "template" in cmd > enter new filename > enter the text I have to append to the readme.md file > and Enter.
It's that simple!

### Code of my template.py file.
```
#imports
import os
from datetime import date, datetime
today = date.today()
now = datetime.now()
d1 = today.strftime("%B %d, %Y")
current_time = now.strftime("%H:%M:%S")

#file creation locations and file name input
Newfilename = input("Enter filename:")
readmefileinput = input("Enter readme input:")
Newfilelocation = Newfilename
ReadmeFileLocation = "readme.md"

#open file to read, write or append 
f = open(Newfilelocation, "a")
g = open(ReadmeFileLocation, "a")


#Declaration of the lines to write
comments = "#Date: " + d1 + '   ' + "Time: " + current_time + "\n" 
imports = "from sys import stdin, stdout\nimport collections\nimport time\n\n\n\n"
line1 = "def main():\n\n\n\n"
line2 = "if __name__ == '__main__:'\n "
line3 = "	main()"


#Writelines in the file created
f.writelines ([comments, imports, line1, line2, line3])
g.write("\n" + readmefileinput)
f.close()
g.close()

```
To make Python scripts runnable from any location under Windows:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ts8qz03oudyc3io2hau.PNG)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gmenkp46dm0nup9y9zpm.PNG)

To call python script directly from the command prompt, e.g., to invoke the script “template.py” simply typing:
```
 > template
```
instead of needing to type: 
```
> python path\to\template.py 
```

Steps to add template.py to Environment Variables:
Go to your python directory. E.g. Mine is "C:\Python39\Scripts"
Copy template.py file into this directory
It's more likely you already have a Python script folder in your Environment Variable but if not
Add the path to this script directory in Windows "PATH" system variable:

You should be able to run any of your python template files from any directory now.
Bot COVID
Tags: twiliohackathon
Published: 2021-05-01 07:02:54

[Comment]: # (All of this is placeholder text. Use this format or any other format of your choosing to best describe your project.)

[Reminder]: # (Make sure you've submitted the Twilio CodeExchange agreement: https://ahoy.twilio.com/code-exchange-community)

[Important]: # (By making a submission, you agree to the competition's terms: https://www.twilio.com/legal/twilio-dev-hackathon-terms)


## What I built
#### Category Submission: COVID-19 Communications
This is whatsapp bot that I made with the help of Flask and Twilio's messaging API. It gives information about the current COVID status in all over the world. One can narrow down the search by providing particular place name or date. It also gives a list of verified oxygen cylinder resources and hospitals or clinics with avialable COVID bed based on the geographic location. The main purpose of this app is to help people for accessing the verified data so that they can resolve their issues.

## Demo Link
https://drive.google.com/file/d/1dCRTkWjuqv7rcsWqzVUjP76WBRP7p7Ho/view?usp=sharing
 

## Link to Code
https://github.com/HOTSONHONET/CovidWhatsapp

## How I built it 
The app uses Twilio's messaging API to create a WhatsApp bot. The bot runs in the backend which is made by Flask, and it is responsible for collecting all the messaging queries and giving appropriate responses. Also, the backend invokes multiple web crawlers that extract data from verified resources

## Tech Stack
- Flask
- BeautifulSoup
- Twilio
- Python
- Selinium


# Sample Images

<table>
  <tr>
    <td>Test Case I</td>
     <td>Test Case II</td>
  </tr>
  <tr>
    <td><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8gkug4bxf48s9at7szcf.jpeg" width=500 height=200></td>
    <td><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5pgttnvbka3ypcifppl.jpeg" width=500 height=200></td>
  </tr>
  <tr>
    <td>Test Case III</td>
     <td>Test Case IV</td>
  </tr>
  <tr>
    <td><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9c0zullo4601irmsxsww.jpeg" width=500 height=200></td>
    <td><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t99l2nmuefe1otgucffi.jpeg" width=500 height=200></td>
  </tr>
</tr>
  <tr>
    <td>Test Case V</td>
     <td>Test Case VI</td>
  </tr>
<tr>
    <td><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xhis8eniebvmdf81mllp.jpeg" width=500 height=200></td>
    <td><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t99l2nmuefe1otgucffi.jpeg" width=500 height=200></td>
  </tr>
 </table>
Coding is a wild ride.
Tags: webdev
Published: 2021-05-01 06:57:45

Back in 2015 I really started down the rabbit hole of coding. Like many I started with HTML, CSS, and JavaScript. I had enrolled in Udacity's Front End Web Development Nanodegree program. Using Udacity and Free Code Camp, I quickly gained some skills needed to make responsive websites and some games using HTML Canvas and JavaScript. It was all fine and well until I could no longer afford Udacity, and eventually fell out of programming. Fast forward a few years and here I am trying again. There is just something so alluring about programming that makes it difficult to stay away. I sincerely hope that this time I can see the program to the very end, and I plan to share the steps of my journey here.
20210503
Tags: node
Published: 2021-05-01 06:17:58

vue3相对于vue2的一个优化：diff算法的变动
vue2对所有的元素进行diff
vue3只对会发生的动态变化的元素进行diff
vue3对会发生动态变化的元素增加一个标记。只有含有这个标记的元素才会进行diff.
Bellow is the flag which will be attached:
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/03rgqr6ejkhd923k88yd.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2w27f58xgnyp68kng8r7.png)
 
 
```javascript
// output: 8
console.log(1<<3)
// Vue.createApp(App).mount("#app")
const { createApp } = Vue;
createApp(App).mount("#app");
typeof vm.selected // => 'object'
```

```html
加载指定的vue版本依赖：
<script src="https://unpkg.com/vue@3.0.2"></script>
```
[Question] Where do I find a list of posts I marked on dev.to?
Tags: question
Published: 2021-05-01 06:16:22

---
title: [Question] Where do I find a list of posts I marked on dev.to?
published: true
description: 
tags: question
//cover_image: https://direct_url_to_image.jpg
---

As the title says. No help in the FAQs on this.
Small Utility for Productivity
Tags: utility, productivity
Published: 2021-05-01 04:14:58

When you switch on your system/laptop/PC you need to open certain websites and directories on your system.

I usually open following websites 
1. https://canva.com
2. http://google.com
3. https://stackoverflow.com/
4. https://dev.to/

and my programming directory in my laptop.
C:\Hemant\CodeBase\

I have created a batch file which opens this when I click it. This saves me a bit of my time and gets me ready to be productive in a second.

*You can add your path and website for your utility.*

### Process to create the batch file.
1. Create a Utility.txt file
2. Add following text in the file.
```javascript
explorer.exe https://canva.com
explorer.exe http://google.com
explorer.exe https://stackoverflow.com/
explorer.exe https://dev.to/
explorer.exe C:\Hemant\CodeBase\
```
3. Rename the file to Utility.bat

That's it!!! your own utility bat file is ready. 

N.B. : If you need to make any changes in the file right click the file and open it in notepad or any other text editor of your choice.

My website : https://www.productkhareed.com/small-utility-for-productivity/

Let me know how you use this for your productivity. Keep Liking , keep sharing :-)
Flask app with postgreSQL
Tags: python, sql
Published: 2021-05-01 03:44:26

Hi! In my video I'm showing you a Flask app that I have connected with PostgreSQL. We are also using pgadmin4, Psycopg2 (a database adapter) and SQLAlchemy. Have a nice day! :)

{% youtube XZ_gAWdGzZk%}

➤Code:
https://github.com/Lumary2/Python/tree/master/Python_HTML_flask

➤Timestamps:
0:00 Introduction
0:16 Which libraries we use
1:37 Tutorial overview
2:10 Flask app
8:33 Create table, post and get data
12:12 Solve error "connection refused"
Postgres conf file (path Manjaro): /var/lib/postgres/data/postgres.conf
ArchWiki: https://wiki.archlinux.org/index.php/PostgreSQL
Error Budget
Tags: sre, devops, sla, slo
Published: 2021-05-01 02:48:11

---
title: Error Budget
published: true
description: Veja o que é e como calcular o Error Budget
tags: #SRE, #DevOps, #SLA, #SLO
cover_image: https://cdn-images-1.medium.com/max/800/0*gAU-UJ72hoyXH9I0
---
# Error Budget

## O que seria error budget?

Orçamentos de erro (error Budget), no contexto de Site Reliability Engineering (SRE), ou "Engenharia de Confiabilidade de Sites", são uma estrutura para gerenciar riscos e trazer equilíbrio entre o desenvolvimento e os SREs. 

Em particular, eles são usados basicamente para medir quanto risco estamos dispostos a tolerar em um serviço.

Contanto que o tempo de atividade / disponibilidade medido esteja acima do SLA / SLO, haverá um erro de orçamento restante. 

Conseqüentemente, novos recursos e lançamentos podem ser colocados em produção.

> Um orçamento de erro é a quantidade de erros que seu serviço pode acumular ao longo de um determinado período de tempo antes que seus usuários comecem a ficar insatisfeitos.

Mas para que error budget funciona bem, precisamos nos atentar a alguns pontos:

* Termos SLOs que todas as partes interessadas na organização aprovaram como adequados para o produto.
* Uma vez que você esgote seu orçamento de erro (ou chegue perto de esgotá-lo), você deve fazer algo para restaurar a estabilidade do seu sistema.
* As pessoas responsáveis ​​por garantir que o serviço atenda ao seu SLO concordaram que é possível atender a este SLO em circunstâncias normais.
* A organização se comprometeu a usar o orçamento de erros para a tomada de decisões e priorização. Esse compromisso é formalizado em uma política de orçamento de erro.
* Que exista um processo em vigor para refinar o SLO. (Como melhorar o SLO?)

(A política de orçamento de erro também deve ser documentada)

## Como calcular error budget?

Se definirmos nosso objetivo (SLO) como sendo 99% de eventos validos com sucessos, teremos 0,1% de margem para erros, ou seja, se nossa api recebe 1000000 requisições, com um SLO de disponibilidade de 99% teremos um orçamento de 1.000 erros durante esse período.

[Faça suas simulações aqui](http://fabriciogoncalves.com/sre/error-budget-calculator/).

## Exemplificando

Imaginem o seguinte cenário:
Temos uma API que *prometemos* para o cliente que essa funcionalidade não retornará em mais de *200ms* (SLA)

Internamente, *acordamos* que seria possível mantermos essa API retornando em menos de *100ms* (SLO)

Porém, em alguns casos, inevitavelmente nossa a API vai demorar mais de 100ms, ai, neste momento, começamos a queimar nosso error budget (linha laranja).

![alt text](https://cdn-images-1.medium.com/max/800/1*QzCQofI2szoOPICR4BhlLg.png "SLA-SLI-SLO-Error-budget")


## Queimando error budget

Esse tópico ficará para o próximo post….

## Lei também

[Example Error Budget Policy](https://sre.google/workbook/error-budget-policy/#:~:text=An%20error%20budget%20is%201,1,000%20errors%20over%20that%20period.)
[What is an error budget - and why does it matter?](https://www.atlassian.com/incident-management/kpis/error-budget)
Deploying an Elixir app
Tags: elixir, deployment
Published: 2021-05-01 02:16:10

I'm amazed by all the ways we can deploy an Elixir app. It's a little overwhelming (see: analysis paralysis). But it's a good problem to have. Especially now that Elixir has native support for deployment. Here are some notes that I wrote up while learning about deploying an Elixir app. Note, I didn't dive into *where* you should put your app. Just the deployment methods:

- **With Mix**. You host the source code on the production server and you run a mix command to start the app, e.g. `mix run --no-halt` (with the corresponding flags).
- **Using Elixir Releases**. This is a built in feature since Elixir 1.9. There's a command, `mix release` that will compile your elixir code and packages it into an artifact. This artifact will then be uploaded to a production server. 
- **Using [Distillery](https://github.com/bitwalker/distillery)**. Distillery is a library that is used to produce an Erlang/OTP release. It works with Elixir 1.6+, presumably solving release problems before 1.9 was released.

There are various features of each of these ways to release as well. When we deploy with Mix, we can run mix commands, e.g. `mix phx.server`. But there are some trade-offs. The source code is visible to anyone with access to the production server. And we don't have access to the Remote Observer. 

Alternatively, to start our app with Elixir releases we can use a command similar to this: `_build/prod/rel/my_app/bin/my_app start`. With Elixir releases (and Distillery) we have access to the Remote Observer and our source code is hidden. Because we're compiling our app it also results in smaller slug sizes which means faster startup times [^1]. However, we don't have access to Mix. Since Elixir 1.11, we have access to `runtime.exs` which is executed after the code is compiled. In a Phoenix app, this means renaming `config/prod.secret.exs` to `config/runtime.exs` and replacing `use Mix.config` with `import Config`. 

Finally, a feature that Distillery has that Elixir releases doesn't is hot upgrades. With hot upgrades we can release a new version of our app without bringing the old app down. There is a lot of overlap between Distillery and Elixir releases. Distillery brings its own configuration so you shouldn't mix deployment methods. Choose one or the other. One reason you'd use Distillery over Elixir releases is if you need to deploy an Elixir app pre 1.9. 

**Further reading**
- [Gigalixir: Mix vs Distillery vs Elixir Releases](https://gigalixir.readthedocs.io/en/latest/modify-app/index.html)
- [Elixir v1.11 released introduces runtime.exs](https://elixir-lang.org/blog/2020/10/06/elixir-v1-11-0-released/)
- [Elixir 1.9 release vs Distillery discussion](https://elixirforum.com/t/elixir-1-9-release-vs-distillery/23454)

[^1]: https://gigalixir.readthedocs.io/en/latest/modify-app/index.html