teleren/devto huggingface dataset:
Sync and Async for dummies or cooking chefs
Tags: javascript, programming, algorithms, motivation
Published: 2022-01-09 19:57:11

Hello devs and not devs!

I always guess there is not thing that is so difficult and impossible to learn, but all things it is necessary one important thing: dedication and what the best way for your learning. 

Daily analogies is a way that the majority people could learn. So, what we will learn here are _sync (synchronous)_ and _async (asynchronous)_ concepts with: CAKE!

![A beautiful and delicious cake](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hdhwnf0cpi9rf7agdarg.png)
 
How can we make a cake with many layers?

**1 - Do one layer, after the next, and so on, 
2 - Clearly you can't do the second without do the first before, right?**

Therefore, I need to wait one layer to do the next, got it? Yes? So, you already know the concepts above. When you need to wait something finish first to go to another action, so we are talking about _async/await_, on the contrary would be the _sync_.

For each layer of our cake we need to wait one before, but at the final when we are doing the roof cake, it can be done with _sync_ because we don't have a new action.

Let's detail in Javascript and cook our _**doLayer()**_, _**doSweet()**_ and _**finishRoofCake()**_ functions:

```
const doLayer = () => {
	console.log("do layer");
}

const doSweet = () => {
	console.log("layer for sweet");
}

const finishRoofCake = () => {
	console.log("delicious roof");
}
```

And now we can cook our _**doCake()**_ function

```
const doCake = async () => {
  await doLayer();
  await doSweet();
  await doLayer();
  await doSweet();
  finishRoofCake();
}
```

You can take all this functions and write in one file cake.js and call _**doCake()**_ at the end and the returns will be:

```
//cake.js

const doLayer = () => {
	console.log("do layer");
}

const doSweet = () => {
	console.log("layer for sweet");
}

const finishRoofCake = () => {
	console.log("delicious roof");
}

const doCake = async () => {
  await doLayer();
  await doSweet();
  await doLayer();
  await doSweet();
  finishRoofCake();
}

cake();

/* output

"do layer"
"layer for sweet"
"do layer"
"layer for sweet"
"delicious roof"
*/
```

You like to cook? Ops, to program? A simple concept help us to grow up rapidly. Learn what the best way to work for your learning and fire!

**Contacts**
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca
Diff Array Algorithm: JavaScript
Published: 2022-01-09 19:12:10

This algorithm problem asks to compare two arrays, and return a new array containing the difference of the two arrays. Here is how to solve the problem:

Step 1. Setting up the answer: 

```
function difArray(array1, array2) {
  
}

difArray([1, 2, 3, 5], [1, 2, 3, 4, 5])
```


Here, we have two arrays. We want to compare them, and return a new array that would contain the difference. In this case, it would be the number 4. 


Step 2. Loop through both arrays and push unique values to empty array. 

```
const union = []

    for (let i = 0; i < array1.length; i++) {
        if (!union.includes(array1[i])) {
            union.push(array1[i])
        }
    }
    for (let i = 0; i < array2.length; i++) {
        if (!union.includes(array2[i])) {
            union.push(array2[i]);
        }
    }
}
```


Step 3. Loop through union array and compare the elements, adding the different elements to a new array 

```
function difArray(array1, array2) {

    const union = []

    for (let i = 0; i < array1.length; i++) {
        if (!union.includes(array1[i])) {
            union.push(array1[i])
        }
    }
    for (let i = 0; i < array2.length; i++) {
        if (!union.includes(array2[i])) {
            union.push(array2[i]);
        }
    }

    const difference = []
    for (let i = 0; i < union.length; i++){
        const current = union[i]; 
        if (array1.includes(current) && !array2.includes(current)){
            difference.push(current)
        } else if (array2.includes(current) && !array1.includes(current)){
            difference.push(current)
        }
    }
    return difference 
}
```



And you're done!
Blog Card fun #1
Tags: codepen
Published: 2022-01-09 18:37:20

<p>That just some fun in material design.
Inspired by the really talented : Magnigenie ! 
<a href="https://dribbble.com/shots/2442471-Material-Blog-Card" target="_blank">https://dribbble.com/shots/2442471-Material-Blog-Card</a></p>

{% codepen https://codepen.io/IMarty/pen/zrdYGe %}
Kickstart Your Journey as a Go Engineer in 4 Easy Steps
Tags: go, programming, career
Published: 2022-01-09 18:35:33

A structured approach to learning goes a long way in maximizing your output as a developer. Why struggle with theory when you can code immediately?

As an entrant, look for small wins every day - the key is to get instant gratification by writing production-grade Go.

## #1 Win at the Syntax Game
A developer communicates through code; the first obvious step is to learn the syntax - a language's grammar.

Learning syntax can be slow - one has to remember many minute details. But thanks to [gobyexample](https://gobyexample.com/), this has been made simple.

Run the code snippets in [Go's Playground](https://play.golang.org/). Tweak the code and implement various use-cases.

**Another excellent news:** Go offers limited in-built data structures, so the learning curve is shallow.

## #2 Read Code to Write Code
Read code to incorporate different design patterns.

> **Read code with an eye for design but a vision to improve it.**

Review code - read other reviewers' comments, ask questions, seek clarity. This is a proven method to grasp the language better.

## #3 Master Best Practices
Want to master a coding language? Learn its best practices.

One language's guidelines don't apply to another. Even as a proficient [Gopher](https://go.dev/blog/gopher), you'll find yourself revisiting [Effective Go](https://go.dev/doc/effective_go).

Conquering best practices goes a long way in writing maintainable code that can be tested quickly and refactored fewer times.

> **Communicating with your code will be easier if your code has a structure that most engineers know.**

## #4 Make Your First Contribution!
Make your first contribution while learning the syntax.

Create an HTTP service. Next, are you able to write a CLI service in Go?

Shadow other developers. Pick a low-hanging fruit - fixing a bug in a codebase, enhancing an API or writing a new script. Find a proficient colleague who can review your work.

There are tons of [open-source projects in Go](https://github.com/topics/go); contribute to these fantastic projects.

I hope you master Go by following these quick tips.
May the force be with you!
Tiny Softbox — Simple light box & color panel
Tags: showdev, macos, ios, swift
Published: 2022-01-09 18:30:53

---
title: Tiny Softbox — Simple light box & color panel
published: true
description: A simple app with many use cases, from lighting up your face during video calls to helping you set the perfect light for your photography.
tags: showdev, macos, ios, swift
canonical_url: https://alexandersandberg.com/tiny-softbox-announcement/
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/idkiwxrohsfmmlsoer9j.png
---

Not too long ago I made the decision to switch careers from cross-platform mobile development (React Native) to native iOS development (Swift). I will talk about why in a future post (if I ever get around to writing it).

As I love learning new stuff by building things, one of the things I did to learn Swift and SwiftUI was to build an app.

After [joining Practice](https://alexandersandberg.com/joining-practice/) at the end of 2021, where my colleagues are mostly located in North America, I now have most of my video calls for work when it's dark outside. Due to bad lighting in my office, I made [a quick web app](https://twitter.com/alexandberg/status/1467576459178950656?s=20) to fix this.

I realized this would make for a perfect first app built in Swift, and a few days later of tinkering with SwiftUI (which I absolutely love, btw), [**Tiny Softbox**](https://alexandersandberg.com/tiny-softbox/) was born.

![App Store screenshot of Tiny Softbox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/idkiwxrohsfmmlsoer9j.png)

It's a very simple app, but it works very well for its purpose. And other than helping with lighting during video calls, the app can also be used for a bunch of other use cases, from photography to reading.

![App Store screenshot of Tiny Softbox, showing off different use cases for the app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xcp33h12jj6zpzne7gea.png)

After experimenting with free apps before ([Tiny Weather](https://tinyweather.app)), I decided to make Tiny Softbox a paid app—mostly due to my curiosity for learning about the differences between publishing free vs. paid apps. I priced it at $2/€2, which I thought was a reasonable price considering that you get it for both macOS and iOS with a single purchase.

It's currently available for Mac, iPhone, and iPad, but I'm considering making an Apple TV app as well.

For the launch of Tiny Softbox, I [tweeted](https://twitter.com/alexandberg/status/1472877106963140608?s=20) about it and launched it on [Product Hunt](https://www.producthunt.com/posts/tiny-softbox) the day after that. The engagement was not amazing, but the feedback I got was very positive, and from the App Store impressions and sales it seems to be off to a great start.

I love building tiny (but useful) apps like this and hope to find time to build many more. I have a long list of ideas. 🙂

👉 [**Tiny Softbox**](https://alexandersandberg.com/tiny-softbox/)

---

*This post was originally published on my website at [alexandersandberg.com](https://alexandersandberg.com/tiny-softbox-announcement/).*
Python #1 : variáveis e operadores.
Tags: python, beginners, programming, codenewbie
Published: 2022-01-09 18:17:22

_Esse post faz parte dos meus cadernos **pessoais** de estudos. Todas as anotações são baseadas nas aulas da Mentorama - Cientista de Dados do zero e organizadas sob o meu ponto de vista. M2A1A2_. 

---

### Fundamentos básicos de Python

#### 1. Variáveis  

Definição: Espaço em memória que representa algum valor. 
O operador de atribuição usado é o `=`

Exemplo:

`Nome = "Sarah" 
Idade = 26 
Altura = 1.75
e_letras = True `

#### Tipos de variáveis

String = "Sarah" (sempre entre aspas)
Int = 28 (número inteiro)
Float = 1.68 (número decimal)
Boolean = e_letras (True ou False)

##### Verificar a gravação da variável: 

`print(nome)
print(altura)`
 
ou 

`nome, altura`


##### Combinar texto com a variável na hora do print 

`print("O valor da variável nome é:", nome)`

##### Para saber o tipo da variável 

`type(nome)
type(idade) `

##### Para converter os tipos 

**Ex: trocar a variável 'idade' que é um int, para float.**

1. nome do tipo(variável)

`float(idade)`

mas ainda não vou atribuído o tipo 

2. atribuir a variável novamente com outro tipo 

`idade = float(idade)`

agora sim converteu!

3. pedir o tipo pra confirmar 

`type(idade)`


**Ex: trocar o boolean para float **

`float(e_letras)
e_letras = float(e_letras`

true = 1, false = 0 

##### Sobrescrever o valor de uma variável 

Pode-se trocar o valor e o tipo. 

1. atribuir outro valor, normalmente 

`idade = 27`

OU  

`idade = "vinte e seis"`

Obs.: Ficar atenta a mudança de variáveis no meio do processamento do código. 

---


#### 2. Operadores 

Definição: Combina elementos básicos da linguagem para formar expressões complexos. 

#####Tipos de operadores


Aritméticos: cálculos matemáticos
Relacionais: ordem e comparação
Lógicos: expressões lógicas
Atribuição: atribui valor ao objeto


Exemplo:

Definindo variáveis para exercício:

`a = 2
b = 5
d = 'para'
e = 'lelepípedo'`

##### Aritméticos 

**Adição numérica**
`print(a + b)`

**Adição strings**
`print (d)
print (e)
print (d+e)`

Ou seja: o operador `+`pra variáveis numéricas, ele vai somar e dar o resultado; para variáveis de texto, ele concatena as palavras. 

**Subtração **
`print (a-b)`

**divisão **
`print (a/b)`

**resto da divisão **
`print (a)
print (b)
print (a%b) #resto`

##### Relacionais 

`==` Testa a igualdade entre as variáveis 

`print (a==b)`

Obs.: lembrar que Python é case sensitive. 

`>=` Compara

> = maior 
< = menor 
>= maior ou igual 
<= menor ou igual 

##### Lógicos 

`and` = VV
`or` = VF
`not` = FF 

##### Atribuição

`=`  coloca valor 
`+=` adiciona um valor à variável existente 
`-=` subtrai um valor à variável existente 
`*=` multiplica o valor da variável existente
New Things Added - Laravel 8.78 Released
Tags: laravel, php, programming, beginners
Published: 2022-01-09 18:12:33

Let's get started quickly I found new things in Laravel 8.78 Released I wanted to share with you.
- For example, if you uncheck a form checkbox input it is not sent to the server. You might have to write something like the following
```php
if ($request->missing('boolean_setting')) {
    $request->merge(['boolean_setting' => 0]);
}
```
Now you can define values that are merged with the request if missing
```php
$request->mergeIfMissing(['boolean_setting' => 0]);
$request->boolean_setting;
```
- the ability to define custom validation rules that will run as part of default password rules using the rules() method
The rules() method accepts a single rule, an array of rules, or a closure for a closure validation rule
```php
Password::defaults(function () {
    return Password::min(8)
        ->symbols()
        ->mixedCase()
        ->uncompromised()
        ->rules(new ZxcvbnRule());
});
```
- add schedule:clear-mutex command https://github.com/laravel/framework/pull/40135
```php
php artisan schedule:clear-cache
```
- Add method to add multiple lines as once https://github.com/laravel/framework/pull/40147
https://github.com/laravel/framework/pull/40147/files
- Sort collections by key when first element of sort ope
ration is string (even if callable) 
https://github.com/laravel/framework/pull/40212
```php
$collection = collect([
    ['name' => 'Taylor Otwell', 'sort' => 34],
    ['name' => 'Abigail Otwell', 'sort' => 30],
    ['name' => 'Taylor Otwell', 'sort' => 36],
    ['name' => 'Abigail Otwell', 'sort' => 32],
]);

$sorted = $collection->sortBy([
    ['name', 'asc'],
    ['sort', 'desc'],
]);
```
- Assert Batch Count assertBatchCount() method to the Bus facade, which asserts how many batches have been dispatched
```php
Bus::assertBatchCount(3);
```
- HTML String Method toHtmlString() method to Str and Stringable
```php
// Before
new HtmlString(Str::of($content)->markdown());
 
// After
Str::of($content)
    ->markdown()
    ->html();
```
- Lazy Loading Eloquent Results
```php
$flights = Flight::where('de', true)->lazy(100);
$flights->each->archive();
$flights = Flight::where('de', true)->lazyByIdDesc(100);
```
- Adding Full-text Indexes
```php
$table->string('name')->fulltext();
```
- Hiding Columns in "select *" Statements
```php
$table->string('password')->invisible();
```
- New allowIf() & denyIf() Gate Methods
- Retrieve Request Input as Carbon Instances
```php
$request->date('when', 'Y-m-d', 'Africa/Cairo');
```


Sources :- https://www.youtube.com/watch?v=OdxVhb_kfvE
Sources :- https://laravel-news.com/laravel-8-78-0
Sources :- https://www.youtube.com/watch?v=0tDGI2IPv5Q
I hope you have fun.
Discuss: Would you have one style sheet for all or make a style sheet for each page when making a basic website? 
Tags: discuss, css, html, webdev
Published: 2022-01-09 17:38:37

So I saw this question on Twitter by @zocodes 

When making a basic website with many pages, would you have one style.css sheet for all or make a style sheet for each page? 


What do you guys think?

One style sheet for each page or different style sheets for different pages?
How to toggle dark mode
Tags: html, css, javascript, tutorial
Published: 2022-01-09 17:31:34

Hi all. In this post, I'll show you how to create a toggle button to switch between dark and light mode.

## HTML

```html
<!DOCTYPE html>
<html lang="en" data-theme ="light">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, 
initial-scale=1.0">

    <link rel="stylesheet" href="styles.css">
    <script src="script.js" defer></script>

    <title>toggleDark</title>
</head>
<body>
    
    <div class="toggle-container">
        <input type="checkbox" id="toggle" name="toggle">
        <label for="toggle"></label>
    </div>

    <h1>Long Live Rock 'n Roll</h1>
    <p>Rock and Roll ain't noise pollution!
Rock and Roll will never die!
I like that old time Rock and Roll!</p>

</body>
</html>
```

## CSS

```javascript
*{
    box-sizing: border-box;
}

body{
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;

    min-height: 100vh;
    flex-direction: column;
    padding: 5rem;
    transition: background 0.4s linear, color 0.4s linear;
    font-size: 2rem;
}

body.dark{
    background: #201e1e;
    color: white;
}

label{
    user-select: none;
    cursor: pointer;
    background-color: #201e1e;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: inline-block;
    transition: background 0.4s linear;
}

body.dark label{
    background-color: #ffff;
}

.toggle-container{
    position: fixed;
    top: 10px;
    right:10px
}

input{
    visibility: hidden;
}
```
## Javascript
```javascript
const toggle = document.getElementById("toggle")

toggle.addEventListener('change', (e)=>{
document.body.classList.toggle('dark',e.target.checked)

}) 

```

## Final Result
{% codepen https://codepen.io/Yisemiramis/pen/yLzxypB %}

---
I hope you find this tutorial useful. See you on the next article.
Here's the [Source Code](https://github.com/yigitsr/toggleDark) on GitHub
Here's the [YouTube Video](https://www.youtube.com/watch?v=XyDIUOV0SIA) where I code it from scratch.
Check it out on [CodePen] (https://codepen.io/Yisemiramis/full/yLzxypB)

---
**Follow me on**

- [GitHub](https://github.com/yigitsr)

- [CodePen](https://codepen.io/yigitsr)

- [Twitter](https://twitter.com/ziggywoxx)

- [Twitch](https://www.twitch.tv/lemmy_ace)

- [Instagram](https://www.instagram.com/ziggywoxx/)
Excluding certain file paths from in React Router
Tags: react, javascript, webdev, beginners
Published: 2022-01-09 17:30:43

Hi guys.
In this post I will explain how to exclude certain file names or paths from react router.
For example, we want to redirect user to homepage if he types
any path except for some pages.

```Javascript
<Route
  render={({ location }) =>
    //This array includes pages on which user will
    // not be redirected
    ["/", "/register", "/dashboard", "/login"].includes(
      location.pathname
    ) ? null : (
      <Redirect to="/" />
    )
  }
/>
```

If the pathname does not contain register, dashboard or login, it
will redirect to the homepage (/).

---

So that's about it.
If you have any questions, don't hesitate to ask
Check out my recent Hubpages tutorial:
>[Javascript Modal gallery](https://discover.hubpages.com/technology/javascript_gallery)
thanks :)
5 HTML Input types you are missing!
Tags: html, webdev, javascript, css
Published: 2022-01-09 17:23:25

Input tags in HTML are a way of getting an input from the user. The commonly used input types are text, password, email, number etc. 
But there's more to it. Here are 5 input types that every Web Developer must know!

1. input type ="**color**":
You can now have a color picker in your webpage. How cool is that?? Just set type property as color in input tag. You can also pass a initial color value in value attribute.
![HTML Input type = color](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1w3gusbn30nplp20ipu5.png)

2. input type ="**search**":
Now this type is similar to regular text type but with a small difference. The input box automatically adds a cross icon after you start typing to clear the input field. This is very handy input type when you want to add a search box field.
![HTML Input type = search](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z7714iz92o0zhy8r5548.png)

3. input type="**tel**":
Use this type when you want the user to fill a phone number. When accessed through a touch device (phone/tablet) the input type opens up a numerical keyboard.
![HTML Input type = tel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gw8hvqc4i64tz4re10fe.png)

4. input type="**datetime-local**": 
This input type allows user to select Time, Date, Month and Year.
![HTML Input type = date and time](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ipdg7tteo17p5wltjgb.png)

5. input type="**range**":
This is another alternative for numerical inputs. This allows user to input a numerical value with a slider control. Use min-max attributes to provide a valid range.
![HTML Input type = range](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t3bdux12nin96cwo3nlt.png)

Make sure you try them in your next project! Good luck!
Daily Habits of an Effective Software Tester QA
Tags: testing, selenium, tutorial, discuss
Published: 2022-01-09 17:22:22

In this video, We are going to cover the Daily Habits of an Effective Software Tester QA.

I am going to share step by - step tips to become a better QA or Software Tester.

{% youtube XxPfxKha1H8%}


✅  We are covering
1. Plan your Day with QA Daily Planner download https://sdet.live/week-planner.
2. Keep learning
3. Share what you know
4. Fewer meetings, more work
5. Don't bite more than you can chew.

✅ If you are serious, I invite you to Our community course
http://sdet.live/print

✅ Resources for Selenium Training with Custom Framework.
🔥🔥https://sdet.live/30dayselenium
🔥🔥https://sdet.live/2WlO



🔥🔥 IMPORTANT LINKs 🔥🔥

✅ API Testing –
https://www.learnapitesting.com

✅ Cypress Tutorial with LIVE Projects –
http://cypresstutorial.com

🟢 30 Days of Automation Testing
https://go.scrolltest.com/automation
simple restapi in go with post request
Published: 2022-01-09 09:56:26

```
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type album struct {
	ID     string  `json:"id"`
	Title  string  `json:"title"`
	Artist string  `json:"artist"`
	Price  float64 `json:"price"`
}

func postAlbums(c *gin.Context) { // postAlbums adds an album from JSON received in the request body.
	var newAlbum album

	// Call BindJSON to bind the received JSON to
	// newAlbum.
	if err := c.BindJSON(&newAlbum); err != nil {
		return
	}

	// Add the new album to the slice.
	albums = append(albums, newAlbum)
	c.IndentedJSON(http.StatusCreated, newAlbum)
}

func main() {
	// new_list := []string{}
	// fmt.Printf("%T\n", albums)
	// fmt.Printf("%T\n", new_list)
	router := gin.Default() //Default returns an Engine instance with the Logger and Recovery middleware already attached.
	router.GET("/albums", getAlbums)
	router.POST("/albums", postAlbums)
	router.Run("localhost:8000")
}

var albums = []album{
	{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
	{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
	{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

func getAlbums(c *gin.Context) { //gin.Context is the most important part of Gin.
	//It carries request details, validates and serializes JSON, and more.
	//(Despite the similar name, this is different from Go’s built-in context package.)
	c.IndentedJSON(http.StatusOK, albums) //Call Context.IndentedJSON to serialize the struct into JSON and add it to the response.
}

```