teleren/devto huggingface dataset:
[Mastering Swoole PHP] Parte I e II - Introdução e Background
Tags: swoole, php
Published: 2021-10-14 19:59:02

Olá mundo!

Estou lendo o livro [Matering Swoole](https://www.amazon.com.br/Mastering-Swoole-PHP-performance-concurrent-ebook/dp/B0881B227S#:~:text=This%20book%20is%20for%20the,Swoole%20PHP%20system%20with%20confidence) PHP PHP do Bruce Dou por indicação do [@SwooLeoCavalcante](https://twitter.com/leocavalcante). Como é um livro em inglês, estou tendo alguma dificuldade em assimilar os conteúdos que foram apresentados ali, por esse motivo resolvi escrever com minhas palavras um resumo de cada parte.

A ideia principal dessa série de artigos não é fazer uma tradução do livro ou reescrever com detalhes o que já está escrito lá, mas mostrar os pontos abordados em cada parte através da minha ótica. Recomendo a vocês a leitura deste livro para terem suas próprias ideias e opiniões.

Leia o artigo completo no meu [blog](https://diegoborgs.com.br/blog/mastering-swoole-php-parte-i-introdu%C3%A7%C3%A3o).
[Semanal de quarentena] - Como definir um preço sólido para projetos ágeis?
Published: 2021-10-14 19:56:18

Olá seres humanos, hoje é o dia 397 desta quarentena insana e neste artigo resolvi contar pra vocês como eu faço para cobrar em projetos ágeis.

Se você não faz idéia do que é o ágil e porque trabalhar com projetos ágeis, dê uma olhada no [manifesto ágil](https://agilemanifesto.org/iso/ptbr/manifesto.html) antes de continuar.

Antes de qualquer outra coisa, gostaria de deixar bem claro que eu não sou especialista em nenhuma metodologia ágil, acredito que por mais que uma metodologia ágil ajude na organização do trabalho, o ágil esta muito mais relacionado a um estilo de vida. Para entender um pouco melhor isso recomendo que assista este [vídeo](https://www.youtube.com/watch?v=xjjX3R2WuoM) do Fábio Akita.

Veja o post completo no meu [blog](https://diegoborgs.com.br/blog/semanal-de-quarentena-como-definir-um-pre%C3%A7o-s%C3%B3lido-para-projetos-%C3%A1geis).
Python challenge_9
Tags: challenge, python, programming, beginners
Published: 2021-10-14 19:54:03

##Flatten a list  

####level of challenge 3/10


- Write a function that takes a list of lists and flattens it into a one-dimensional list.
- Name your function flatten. 
- It should take a single parameter and return a list.

- For example, calling:
- flatten([[1, 2], [3, 4]])

- Should return the list:
- [1, 2, 3, 4]

Hint:

Start by defining an empty list as the result:

result = []

Then use a nested for loop to fill up the result.

```
# My solution

def flatten(out_list):
    new_list = [] 
    for in_list in out_list:
        for item in in_list:
          new_list.append(item)
    return new_list
print(flatten([[1, 2], [3, 4], [5, 6], [7, 8]]))
```

```
# Another Solution

def flatten(outer_list):
  return [
    item
    for inner_list in outer_list
    for item in inner_list
  ]

```

Add your solution in the comment :)
[Semanal de quarentena] - 8 Conceitos fundamentais para um bom desenvolvedor
Published: 2021-10-14 19:53:59

E aí galera, tudo bem? Eu espero que sim!

Dando sequência aos meus posts semanais de quarentena para vocês, hoje resolvi seguir o conselho de alguns amigos no twitter que me pediram para falar um pouco sobre alguns conceitos de desenvolvimento, além disso, faz um tempinho que eu quero escrever alguma coisa sobre carreira. Então, eu vou fazer uma abstração e reaproveitar esse código… ops, quero dizer post para fazer uma listinha com os conceitos que eu considero fundamentais para bons desenvolvedores.

Apesar de ter feito minhas primeiras linhas de HTML em 2011, e de lá pra cá já são 9 anos em que tive a oportunidade de trabalhar em muitos projetos com desafios diferentes e em times com muita gente boa, confesso que às vezes eu não acredito que minha carreira é tão longa assim para falar como outra pessoa deve lidar com a dela. O que eu vou deixar para vocês aqui são alguns conceitos que, depois que comecei a entender, me tornaram um desenvolvedor melhor, mas deixo com vocês a responsabilidade de decidir aplicar ou não eles em suas vidas profissionais.

Leia esse post na íntegra no meu [blog](https://diegoborgs.com.br/blog/semanal-de-quarentena-conceitos-fundamentais-para-um-bom-desenvolvedor).
Utilizando o princípio First para escrever testes unitários melhores
Tags: testing, testdev, test
Published: 2021-10-14 19:51:07

Já não é novidade que sou fã da prática de TDD para desenvolvimento de softwares, acredito realmente que um bom código só é um bom código se tiver bem coberto por testes, afinal de contas, são os testes que terão a capacidade de medir a qualidade de um código.

Recentemente estive lendo o “Clean Code” do Tio Bob, um livro excelente pra quem busca uma maior sensibilidade à qualidade de um código. Neste livro existe um capítulo inteiro dedicado às boas práticas na escrita e execução de testes. Tio Bob afirma que um teste deve ser bem escrito para que assim os desenvolvedores possam evoluir tanto o teste quanto o código de maneira simples e que não deixem de praticar a escrita de testes por ser um fardo no projeto.

Leia o post completo no meu [blog](https://diegoborgs.com.br/blog/utilizando-o-princ%C3%ADpio-first-para-escrever-testes-unit%C3%A1rios-melhores).
05 coisas sobre o TDD que você pode estar pensando errado
Tags: tdd, culture, testing, testdev
Published: 2021-10-14 19:47:46

Esses dias escrevi um post sobre a importância da cultura de TDD para desenvolvedores e não desenvolvedores, para dar continuidade sobre esse tema que eu acho extremamente relevante, vamos desmistificar algumas coisas sobre TDD e a cultura de testes.

Leia o post completo em meu [site](https://diegoborgs.com.br/blog/05-coisas-sobre-o-tdd-que-voc%C3%AA-pode-estar-pensando-errado).
Strict mode in JavaScript
Tags: javascript, webdev, strictmode, beginners
Published: 2021-10-14 19:25:49

## What is strict mode?
- Strict mode was introduced in ECMAScript5 also known as ES5 in 2009.
- Adding strict mode to JavaScript code allows your code to be checked more strictly.
- Allows programmer to write more secure JavaScript code.

## Benefits of Strict Mode
- Using strict mode in JavaScript code throws visible errors in developer console which would otherwise fail silently (shown in the examples below).
- Forbids programmers to use certain syntax.
- In some cases using strict mode in code can make the code to run faster.

## How to enable strict mode in JavaScript?
- To enable strict mode write ` "use strict" ` or ` 'use strict' ` at the beginning of JavaScript code.
![Strict mode for entire code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dzr31z7z292mrv2elkbo.png)
 

- The strict mode can also be used for a function.
- To enable strict mode in function, ` "use strict" ` or ` 'use strict' ` must be the very first line in function body.
![Strict mode in function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eizx9nbglojjtsa25jlc.png)


## Common mistakes that occur in non-strict mode
### Using reserved words as variable names
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n1vd3f236atgcsdx96yk.png)
 
![Output 20](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4np27ow4229evpfdvhgw.png)

- Wait!! Isn't **_"let"_** a reserved word in the JavaScript? Therefore it mustn't be used as a variable name according to naming an identifier rules.
Here in the above code snippet JavaScript fails silently instead of throwing an error.
- But, if we use strict mode, JavaScript engine will throw an error-
![Strict mode in code snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9md3nht65fa8vvsnlvwu.png)
![Produces error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqdqx5mdg5qulqocoic5.png)


### Using variables before declaring them
![variable used before declaration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/itj5u38vhvrln5k09uaa.png) ![Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xzmq0fip1x8dtbg8g5z2.png)

- Using strict mode gives _Reference Error_.
![Variable used before declaration in strict mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/640wr270x9qp3lhl30iz.png)
![Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmu9qm3h3b4rqg1e0ujz.png)

- To know more about the strict mode, checkout the documentation by [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)

## Conclusion
- That will be all from my side. I hope, this article gave you a basic idea about the strict mode.

Keep Learning!!
Rebased
Tags: opensource
Published: 2021-10-14 18:51:40

This week's work involved refactoring code from my GAS SSG. I started by making a refactoring branch where I staged my changes before committing them. 

My first set of changes were variable name changes to make variable names more meaningful and consistent throughout my code. I changed a lot of "line" arguments to specify things like input/output, order of use, or in my header function, which was being made into a header. I committed these changes and went on to the next.

The next set involved creating a few functions for validating filetype when the SSG receives CLI arguments. I created functions to determine if a file was text, markdown, json, or a folder. I then took out any redundant logic throughout the program to call my functions instead.

Finally, I implemented a change my prof requested earlier, which was to use std::filesystem's status function to check the type of argument being passed as input. I upgraded my newly created folder checking function to check specifically for a directory from the path given, rather than just checking if it wasn't a text or markdown file. 

With all these changes tested, committed, and ready to go I entered the last stretch of squashing the commits by rebasing the main. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kjwnyl1gnrsrt5a7yzsl.PNG)
 
I had to do some Googling to refresh my non existent vim skills, but got it saved and committed without too much trouble. I amended the commit to add some more details to my commit messages and finally merged and pushed the changes. This was probably the easiest lab so far, I found everything straightforward and was able to fix up my code without breaking anything. 10/10 would refactor again. +
"Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value"
Tags: swift, nil, developers
Published: 2021-10-14 18:36:57

//View controller 

Class MyViewController : UIViewController

@IBOutlet weak var myLabel : UILabel! 
…………………………………………………………………………………………………………………
//Table view cell 
Var VC : MyViewController !

@IBAction myButton(_ sender: Any ) {
VC.myLabel.text = “ hello “ }. // I get the error here
✏️Drawing function✏️
Tags: html, canvas, javascript, draw
Published: 2021-10-14 18:35:06

# Intro

Hey Everyone! I made a drawing function on canvas, here it is!

***

# Description/Instructions

It's simple! Draw on the canvas!

***
# Outro

Thanks for reading and playing! Here are some socials.

Repl Profile: [dudeactualdev](https://replit.com/@dudeactualdev)

Github Profile: [dudeactual](https://github.com/dudeactual)

#### DEMO: [DrawFunction](https://drawfunction.dudeactualdev.repl.co/)

Github Repository: [draw]
(https://github.com/dudeactual/drawhttps://github.com/dudeactual/Number-Guessing-Game)
Become a Happy Developer
Tags: productivity, career, writing, mentalhealth
Published: 2021-10-14 18:24:47

A while back, I did an interview with [TechLeadJournal](https://techleadjournal.dev/episodes/48/), in which Henry and I discussed why communication is such an important skill to develop for engineers, as it directly influences their impact. 

In the podcast I also shared insights and tips on how to deal with sources of unhappiness, such as impostor syndrome, stress, and burnout. Using [the C4E Book](chrislaffra.com#book), any engineer can learn to become a successful, productive, and happy engineer. 

We recently scheduled a couple of workshops on the topic as well. If you are interested, check out [C4E Workshop](c4e.education) for the lineup. The events are a bit short notice, held the last week of October, so we hope you can still make it.
How to overload function in Rust (Basic case).
Tags: rust, programming
Published: 2021-10-14 17:44:44

---
title: How to overload function in Rust (Basic case).
published: true
description: 
tags: rust, programming
//cover_image: https://direct_url_to_image.jpg
---

Adapt version:

```
$ rustc --version
rustc 1.55.0 (c8dfcfe04 2021-09-06)
```

To overload functions in Rust, "generics" is your friend.

```rust
use std::net:: {
    IpAddr,
    SocketAddr,
};

use socket2:: {
    Domain,
    Protocol,
    Socket,
    Type,
};

struct SampleStruct {
    ip_address: IpAddr,
    port_number: u16,
    sample_socket: socket2::Socket,
}

trait SampleTrait<T, O> {
    fn new(address:T, port:O) -> SampleStruct;
}

impl SampleTrait<String, u16> for SampleStruct {
    fn new(address: String, port: u16) -> Self {
        let addr = address.parse::<IpAddr>()
            .unwrap_or_else( |_| { panic!("`address` MUST be an IPv4 address (dotted-decimal form) or an IPv6 address.") });

        return SampleStruct {
            ip_address: addr,
            port_number: port,
            sample_socket: Socket::new(
                if addr.is_ipv4() { Domain::IPV4 } else { Domain::IPV6 },
                Type::DGRAM,
                Some(Protocol::UDP)
            ).unwrap()
        }
    }
}

impl SampleTrait<&str, u16> for SampleStruct {
    fn new(address: &str, port: u16) -> Self {
        let addr = address.to_string().parse::<IpAddr>()
            .unwrap_or_else( |_| { panic!("`address` MUST be an IPv4 address (dotted-decimal form) or an IPv6 address.") });

        return SampleStruct {
            ip_address: addr,
            port_number: port,
            sample_socket: Socket::new(
                if addr.is_ipv4() { Domain::IPV4 } else { Domain::IPV6 },
                Type::DGRAM,
                Some(Protocol::UDP)
            ).unwrap()
        }
    }
}

impl SampleTrait<IpAddr, u16> for SampleStruct {
    fn new(address: IpAddr, port: u16) -> Self {
        return SampleStruct {
            ip_address: address,
            port_number: port,
            sample_socket: Socket::new(
                if address.is_ipv4() { Domain::IPV4 } else { Domain:: IPV6 },
                Type::DGRAM,
                Some(Protocol::UDP)
            ).unwrap()
        }
    }
}

fn main() {
    let foo = SampleStruct::new("127.0.0.1".to_string(), 12345);
    println!("IP address = {}, Port = {}", foo.ip_address.to_string(), foo.port_number);

    let hoo = SampleStruct::new("127.0.0.1", 12345);
    println!("IP address = {}, Port = {}", hoo.ip_address.to_string(), hoo.port_number);

    let priv_ip: IpAddr = "192.168.0.1".parse::<IpAddr>().unwrap();
    let bar = SampleStruct::new(priv_ip, 12345);
    println!("IP address = {}, Port = {}", bar.ip_address.to_string(), bar.port_number);
}
```

When you run the previous code, you may get the following result.

```
IP address = 127.0.0.1, Port = 12345
IP address = 127.0.0.1, Port = 12345
IP address = 192.168.0.1, Port = 12345
```

[Link to Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=539c24bd97d72d99d51fd1b587613ef5)
Learning in Public and Getting Opportunities
Tags: codenewbie, 100daysofcode, productivity, career
Published: 2021-10-14 17:33:00

Recently I came across this talk by Kunal Kushwaha and Anais Urlichs at Open Source Cafe:

{% youtube d8AJEXmOBnI %}

And I have also been personally asked this question a lot of times.
So, check out the key takeaways from this talk which have entirely worked for me as well.

## What is learning in Public?

* Creating content of any form which is accessible to other people
* Sharing our work with the community
* Instead of keeping your knowledge with yourself, you share it
* Make your thoughts accessible to other people
* Documenting your journey, as others can also get motivated
* Use hashtags like #100DaysOfCode , #100DaysOfKubernetes , #DSAwithKunal

## Why learn in Public? 

* A benefit to yourself and others
* Get feedback from the community
* People more knowledgeable than you can help you with opportunities
* Sharing our work in public is not bragging, because 
*  (1) You are doing good work, 
*  (2) People having a hard time or making career changes get motivated from our work
* Hiring someone is a risk for companies when you have proved yourself through sharing your work, that gives confidence to people who hire you
* Proof of concept available like GitHub profile
* When you share about existing work, remember that you are not only helping others but also yourself in enhancing your skills and documenting your learning journey

## How should we learn in public? 
### What are the different ways to learn in Public?

* Share your work as blog posts
* Share your learning journey on social media - Twitter tweets, LinkedIn Posts
* Share about events you attend
* Create Twitter threads about favourite talks
* Create GitHub Repositories on the topics you have learnt
* Create YouTube videos and tutorials 

## Tips for Learning in Public

* Start with what you are most comfortable with from the above techniques
* Choose the type of content you want to create
* Recreate content - It doesn’t have to be original content, just * share the knowledge you gained
* Curate content - List out the resources you are using and share them in public
* Get Creative - Try to do new things, learn from them and share that as well


### I’m Aswin Barath 
About myself => {
 Community Leader | Web Developer | Blogger | Graphic Designer
}

Thank you for reading my work.

Now it’s your turn to share the knowledge you’ve gained ;)
How to add limit on input using Vue Js
Tags: beginners, vue, javascript, webdev
Published: 2021-10-14 17:32:08

Hey Artisan, welcome back to my new post.

In today's post I am going to describe how we can limit the input (how many characters should we allow to enter) on input box using VueJs.

***Follow the given steps:***
Firstly we will define the `maxLength` in the data() of vue js, and next we will bind the maxLength to the `maxlength` attribute of input box.

Create a Component and add below code 
```javascript
<div>
    <input type="text" v-model="value" placeholder="enter your name"
    :maxlength="maxLength"> 
    <span>{{ maxLength - value.length}} / {{ maxLength }}</span>
</div>
  
<script>
export default() {
   data: {
    maxLength: 10,
    value: ''
	}
}
</scrpit>
``` 

In this way you can limit the input filed.

{% jsfiddle https://jsfiddle.net/SnehalKadwe/q97c5txu/12/ result,html,css %}

Happy Reading :unicorn: :unicorn: :lion: :heart:
Reload page after a set interval ?
Tags: discuss, javascript, challenge, webdev
Published: 2021-10-14 17:25:52

Hey Devs. I have been working on this problem since a week now and it's not even finishing. All the other parts are working except for the following situation where I want to execute a script in the browser console to reload the current page after every 5 seconds of interval.

I tried using setInterval for 5000 ms but it only works for the first time and then the javascript resets. After googling and searching on stackoverflow I improved my approach and used ` window ` object to persist the setInterval function but that didnt work too. 

Is there any way to achieve this?
Why You Should Use Typescript Over Javascript?
Tags: typescript, javascript, webdev
Published: 2021-10-14 17:16:19

## What Typescript Actually Is?

Typescript is a strongly typed programming language like Java or C and typescript compiles into javascript so that we can use it in our browser or other platforms.

## Reasons To Use Typescript Over Javascript

1. #### Type Safety
![Typescript Typecheck](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lpakahlru9nvtz1d2u1p.png)
When we do dynamic assigning in javascript it allows us to do that and also it will give us expected results. but if you are working on a large codebase you are not going to track each variable and ensure the types of each of them

2. #### Better Auto-Complete
Typescript provides a complete type system so that ide/text editors eg.vs code can give you better autocompletion on your whole project and increase your productivity.

3. ####  Conversion From Javascript To Typescript
![jsts](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b05fwgb9m89vwnii2a5i.png)
Every valid javascript is a valid typescript. so you can start by converting your file to typescript files and set the rules of typescript low and make it strict as time goes on

## Where To Start
[Tyescript Website And Doc](https://www.typescriptlang.org/)
[Freecodecamp Video For Typescript](https://www.youtube.com/watch?v=gp5H0Vw39yw)

## conclusion 
Typescript is better tool to use when you are comfortable with javascript and need more control over your codebase and want to catch silly mistake on compile-time rather than runtime.
Building web components
Published: 2021-10-10 21:45:00

**What to consider**
 
When building a web component you have to take many things into consideration before the actual development begins.  It is important to think about all the design aspects such as properties, states, its structure, how it will look, accessibility and security concerns and more.  You want to really think through the design and functionality you want in your component.  Determining these up front can also help mitigate the risk of scope creep later on.  Once done with all the design considerations you can start to actually create the web component.  It is very possible and likely that through designing, developing, and testing changes will have to be made to the original design.  

**Project Comp**
My team and I are working on developing a card similar to the ones shown below. 
![Screen Shot 2021-10-10 at 5.20.33 PM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dpy2i9zx5npcrof4g28k.png)
 
These cards are made up of 4 elements:
+ Scaffolding (the card itself)
+ Icon
+ Header/banner
+ Body 

**Expected difficulties and more manageable:**
I think that deciding how we want to make the card interactive may be difficult.  For example my team has discussed having the card change or flip when clicked on or hovered over.  We also discussed having the icon, header, and body of our card switch if the user slides the card.  I think determining exactly what we want to do without making it feel overwhelming to the user will be challenging.  In addition, these are interactions that we have not worked with prior to this project.  I also have limited experience with web components.  Trying to figure out how everything works together has been challenging.  Beginning with creating a button will definitely help with the creation of the card. The button project has allowed me to get more comfortable with css, HTML, and JS.  It also has given me practice with web components and looking at other people’s code to get a better idea of how to do something.