teleren/devto huggingface dataset:
Pass a value to the generator using next() method in JavaScript
Tags: javascript
Published: 2020-08-13 00:00:00

---
  title: Pass a value to the generator using next() method in JavaScript
  published: true
  tags: JavaScript
  date: Thu Aug 13 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/pass-value-yield-next-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-4acd9ed6bbbddddd5fcb1a455161eac8.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/pass-value-yield-next-javascript)
  
The yield keyword in the generator function is commonly used to return a value from the generator function.

But what if I told you it can do more than that!

It can also accept a value to a generator function.

Let's understand this,

let's make a generator function that asks a question first and then takes a value and then yields a value based on that.

```javascript
// Multiply by 2 Generator function
function* MultiplyBy2() {
  const number = yield "Which number would you like to be multiplied by 2 with?";

  yield number * 2;
}

// initializing genrator function
const multiplyBy2 = MultiplyBy2();

// First the question is returned from generator function
// We can show the returned or yielded value using the
// next() method and then using the value property
console.log(multiplyBy2.next().value); // the question is shown
```

- Here we have a generator function which first gives a question `Which number would you like to be multiplied by 2 with?` to the user.

- After initializing the generator function, then we are showing the first yield value which is the question to the user using the `next()` method and access the value using the `value` property.

- **Now to pass a value to the generator function we need to pass that value as an argument to the `next()` method like this**.

```javascript
// Multiply by 2 Generator function
function* MultiplyBy2() {
  const number = yield "Which number would you like to be multiplied by 2 with?";

  yield number * 2;
}

// initialising generator function
const multiplyBy2 = MultiplyBy2();

// First the question is returned from generator function
// We can show the returned or yielded value using the
// next() method and then using the value property
console.log(multiplyBy2.next().value); // the question is shown

// passing 4 as a value to the generator function
// as an argument to the next() method
// after that, the passed value is multiplied by 2
// and then the next yield value is
// returned from the generator function
console.log(multiplyBy2.next(4).value);
```

- **Now the passed value will be stored inside the `number` variable inside the generator function, and the next value of the yield is returned from the generator function (The value which is multiplied by 2)**

- 2 things have happened here, first we have passed 4 as a value to the `next()` method and the next `yield` value is returned from the generator function.

### Feel free to share if you found this useful 😃.

---
Best Free UI/UX Design Tools/Resources 2020
Tags: design, ux, tools
Published: 2020-09-01 10:56:02

---
title: Best Free UI/UX Design Tools/Resources 2020
published: true
date: 2020-08-13 00:00:00 UTC
tags: Design,UX,Tools
canonical_url: https://www.loginradius.com/engineering/blog/best-ui-ux-design-tools-2020/
---

As a designer, often wondered which new tools and utilities, other designers are using? So here is a list of all the tools and utilities famous around the world in designers.

   
[Read On](https://www.loginradius.com/engineering/blog/best-ui-ux-design-tools-2020/)
What's a function you've used/wrote that brought you joy?
Tags: programming, discuss
Published: 2020-08-12 23:59:22

---
title: What's a function you've used/wrote that brought you joy?
published: true
description: I like using the print_r() in php because it usually means I'm about to solve a problem.
tags: #programming #discuss
//cover_image: https://direct_url_to_image.jpg
---
*Variance Analogy
Tags: concept, functional, scala
Published: 2020-08-12 23:53:21

[functional]: https://www.freecodecamp.org/news/an-introduction-to-the-basic-principles-of-functional-programming-a2c2a15c84[/
[kodumaro]: https://kodumaro.cacilhas.info/2020/08/variance.html
[scala]: https://www.scala-lang.org/

Post from [Kodumaro][kodumaro].

![German Shepherd dog](https://dev-to-uploads.s3.amazonaws.com/i/gixzq6jh212cja4to8qh.png)

The other day, talking to some coworkers, I realised developers unacquainted to [functional programming][functional] find hard to understand type covariance and contravariance abstractions.

So I thought about an analogy to make it easier.

### Type contravariance

Let’s define two classes that represent something easy to get in mind: dogs. Shepherds are dogs, so (in [Scala][scala]):

```scala
class Dog

class Shepherd extends Dog
```

We have a job for a dog trainer. Think about a Shepherd pack needing to be trained.

The job title is “Shepherd trainer”, but a dog trainer – someone who know how to train every kind of dog – is competent for the job:

```scala
class Trainer[-A]

val trainerJob: Trainer[Shepher] = new Trainer[Dog]
```

That’s okay! But a Shepherd trainer couldn’t take a general dog trainer job, ’cause he has no experience with training other kinds of dog.

This is **contravariance**:

```scala
// If:
implicitly[Shepherd <:< Dog]
// Then:
implicitly[Trainer[Dog] <:< Trainer[Shepherd]]
```

⦅`<:<` means “is subclass of,” or: every `Shepherd` is a `Dog` too, so every `Trainer[Dog]` is a `Trainer[Shepherd]` too.⦆

In Scala we use `-` to represent contravariance.

### Type covariance

Now imagine that we need to hire a dog producer. We’re not interested in what kind of dog he’ll supply, any kind is great.

So a Shepherd producer could apply for the service, ’cause Shepherd dogs are so good as any other.

```scala
class Producer[+A]

val producerContract: Producer[Dog] = new Producer[Shepherd]
```

It’s called **covariance**:

```scala
// If
implicitly[Shepherd <:< Dog]
// Then
implicitly[Producer[Shepherd] <:< Producer[Dog]]
```

⦅Yet every `Producer[Shepherd]` is a `Producer[Dog]` too – he produces only dogs.⦆

In Scala we use `+` to represent covariance.
Flutter share plugin
Tags: dart
Published: 2020-08-12 23:25:42

Um plugin do Flutter para compartilhar conteúdo do seu aplicativo Flutter por meio do diálogo de compartilhamento da plataforma.

Quebra a intenção de ACTION_SEND no Android e UIActivityViewController no iOS.

### Uso
Para usar esse plug-in, adicione share como uma dependência no seu arquivo pubspec.yaml .

### Instalação
1. Depende disso
Adicione isso ao arquivo pubspec.yaml do seu pacote:
```
dependencies:
  share: ^0.6.2+1
```
2. Instale
Você pode instalar pacotes a partir da linha de comando:

com Flutter:

```
$ flutter pub get
```
Como alternativa, seu editor pode suportar flutter pub get. Verifique os documentos do seu editor para saber mais.

3. Importe
Agora, no seu código Dart, você pode usar:
```
import 'package:share/share.dart';
```
Exemplo
Importar a biblioteca via
```
import 'package:share/share.dart';
```
Em seguida, invoque o sharemétodo estático em qualquer lugar do seu código Dart
```
Share.share('check out my website https://example.com');
```
Fonte: https://pub.dev/packages/share
Flutter Target of URI doesn’t exist: ‘package:http/http.dart’
Tags: dart
Published: 2020-08-12 23:23:07

O erro Target of URI doesn’t exist: ‘package:http/http.dart’ acontece pois na mais recente versão do Flutter, o pacote Http não é mais incluído por padrão.

Para que você consiga incluir o pacote Http ao seu projeto, adicione o plugin do Http no seu pubspec.yaml da seguinte maneira:
```
dependencies:   
  flutter:
    sdk: flutter
 
  cupertino_icons: ^0.1.2
  http: ^0.12.0+2            # copie apenas esta linha e cole nas suas dependências
```
Logo após clique no botão flutter packages get e pronto!

### Aviso
1) Deixe esta nova linha alinhada com a linha do cupertino_icons, dando 2 espaços do lado esquerdo.

2) Utilize sempre a versão mais recente deste plugin, que você pode encontrar aqui: https://pub.dartlang.org/packages/http#-installing-tab-

Fonte: https://www.udemy.com/curso-completo-flutter-app-android-ios/
Ciclo de Vida Ionic
Published: 2020-08-12 23:20:30

(Este post foi publicado em 09/2018, estou apenas movendo do meu site pessoal para o dev.to)

Antes de falar sobre o ciclo de vida ionic, vale lembrar que o Ionic Framework é um kit de ferramentas de interface do usuário de código aberto para a criação de aplicativos móveis e de desktop de alto desempenho e de alta qualidade, usando tecnologias da Web (HTML, CSS e JavaScript).

## Diagrama do ciclo de vida:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mjslgl5cfccghpizbiun.png)
## Em resumo, estes são os eventos do ciclo de vida ionic:
* ionViewDidLoad: Disparado somente quando uma visão é armazenada na memória. Este evento NÃO é disparado ao entrar em uma exibição que já está em cache. É um bom lugar para tarefas relacionadas ao init.
* ionViewWillEnter: É acionado ao entrar em uma página antes de se tornar a ativa. Use-o para tarefas que você deseja fazer toda vez que entrar na visualização (definindo ouvintes de eventos, atualizando uma tabela, etc.).
* ionViewDidEnter: Disparado ao entrar em uma página, depois que ela se torna a página ativa. Bastante semelhante ao anterior.
* ionViewWillLeave: Despedido quando você sai de uma página, antes de deixar de ser a ativa. Use-o para coisas que você precisa executar toda vez que estiver saindo de uma página (desative os ouvintes de eventos, etc.).
* ionViewDidLeave: Despedido quando você sai de uma página, depois que ela deixa de ser a ativa. Semelhante ao anterior.
* ionViewWillUnload: Disparado quando uma exibição será completamente removida (depois de deixar uma exibição não armazenada em cache).

## Nav guards
Como faixa bônus, há dois outros métodos poderosos relacionados a esses eventos: nav guards. Esses métodos são focados no controle de acesso à exibição (com fins de autenticação).

* ionViewCanEnter: Disparado antes de entrar em uma visão, permite que você controle se a visão pode ser acessada ou não (retornando verdadeiro ou falso).
* ionViewCanLeave: Despedido antes de deixar uma visão, permite controlar se a visão pode ser deixada ou não.
É importante destacar que os Guardas de Navegação(Nav guards) são executados antes de qualquer outro método de evento de ciclo de vida.

Para mais informações consulte o site oficial do Ionic.
useReducer ReactJS gotcha
Tags: jstrivia, react, usereducer, javascript
Published: 2020-08-12 23:00:50

Question: Is there a difference between these two `useReducer`s in the following codesandbox?

https://codesandbox.io/s/frosty-dubinsky-no5rf?file=/src/App.js

```jsx
import React, { useReducer } from "react";

export default function App() {
  const [state1, dispatch1] = useReducer(reducer1, 0);
  const [state2, dispatch2] = useReducer(reducer2, 0);

  return (
    <div className="App">
      <div>1: {`${state1}`}</div>
      <div>2: {`${state2}`}</div>
      <button
        onClick={() => {
          dispatch1(1);
          dispatch2(state2 + 1);
        }}
      >
        Click
      </button>
    </div>
  );
}

function reducer1(state, action) {
  return state + action;
}

function reducer2(state, action) {
  return action;
}
```

Answer: yes. By using the state that is automatically passed in, `reducer1` is safe to be called multiple times because it always gets the most up-to-date state.

`reducer2` is not safe to call multiple times because it looks at stale state when it’s called subsequent times. Here's an example of where it breaks:

https://codesandbox.io/s/bitter-currying-bsx6g?file=/src/App.js

```jsx
//answer: run this code
import React, { useReducer } from "react";

export default function App() {
  const [state1, dispatch1] = useReducer(reducer1, 0);
  const [state2, dispatch2] = useReducer(reducer2, 0);

  return (
    <div className="App">
      <div>1: {`${state1}`}</div>
      <div>2: {`${state2}`}</div>
      <button
        onClick={() => {
          dispatch1(1);
          dispatch1(1);
          dispatch2(state2 + 1);
          dispatch2(state2 + 1);
        }}
      >
        Click
      </button>
    </div>
  );
}

function reducer1(state, action) {
  return state + action;
}

function reducer2(state, action) {
  return action;
}
```
The Cloud Skills Show Episode 1: Learning Fundamentals
Tags: livestream, azure, devrel, learning
Published: 2020-08-12 22:44:18

The Cloud Skills Show is a new weekly livestream, brought to you by the folks at Microsoft Developer UK. Each week, we'll feature guests from the UK and around the world to talk about the cloud skills that Developers and IT Professionals can use to develop their career (or to start a career in tech).

We'll also take a look at the latest cool technologies from the Microsoft Cloud, and meet technical communities to hear about the skills they think are most relevant in 2020 and beyond. 

###In Episode 1...
... we start with the basics and explaining some of the resources that are available to technical folks looking to learn with Microsoft. We introduce you to our Documentation, our Microsoft Learn Platform and our Certifications. We also talk about our new programme for Students and some of the pathways for specific roles. 

Episode 1 is hosted by Adam Jackson and Anna Fear, with our special guests *Salman Chishti* and *Ed Baker*. Adam and Anna work at Microsoft in the Developer Relations team, where they support technical communities in the UK. 

###Watch the Show###
{% youtube DYkZmQou5g4 %}

***

###Meet the guests###

![Salman Chishti](https://dev-to-uploads.s3.amazonaws.com/i/36c2ukcv5csl8udsmxnr.jpeg)

>Salman has recently joined Microsoft as a Cloud Solution Architect Intern. He’ll be with Microsoft for the next year, but is best known as being a leading voice in the Microsoft Learn Student Ambassadors programme, formerly known as Microsoft Student Partner. Salman tells us more about being a Student Ambassador, and what it involves. He also looks at some of the resources for students who are beginning their technical journey. 

![Ed Baker](https://dev-to-uploads.s3.amazonaws.com/i/nn4ueir0q31db365xzqe.jpeg)

>Ed is a Microsoft MVP (*Most Valuable Professional*) and a Regional Lead for the Microsoft Certified Trainer programme. He’s also a consultant on hybrid and on-premise cloud environments, and previously worked at Microsoft as a Technical Evangelist (alongside the hosts Adam and Anna!). 



***

####Every week we'll bring you a show with a specific theme. 

| Date        | Topic           | Host  |Guests|
| ------------- |:-------------:| -----:| -----:|
| 13th August      |Learning Fundamentals|Adam Jackson & Anna Fear|Salman Chishti & Ed Baker|
| 20th August      |Languages & Frameworks|Rory Preddy|*Announced Soon*|
| 27th August |A learner's guide to AI|Amy Boyd|*Announced Soon*|

>*More shows coming soon*

***

Each show will be completely live, streamed to you from the UK, and you can join us live at these times, wherever you are in the world:



![UK Bit Raccoon Graphic](https://dev-to-uploads.s3.amazonaws.com/i/sca1hlxti49o9ffu4qrn.png)

See you online!

— the Microsoft Developer UK Team
C# internal parameters
Tags: csharp, todayisearched
Published: 2020-08-12 22:38:09

So, let's consider a class, with a public method, that calls private methods:
```
//Parameter method

public class Doer
{
   public bool somethingDoer(int x)
   {
      doSomething(x);
      doAnotherThing(x);
      doYetAnotherThing(x);
      doSomethingElse(x);
      return true;
   }
   private void doSomething (int y)
   {
      //does something
   }
   private void doAnotherThing(int z)
   {
      //does another thing
   }
   private void doYetAnotherThing(int u)
   {
      //does Yet another thing
   }
   private void doSomethingElse(int p)
   {
      //does something else
   }
}
```

Is it better to have the x variable as a parameter passed, or a class variable assigned when calling when calling the method? Example:

```
//Class Variable Method

public bool somethingDoer(int x)
{
   _internalInt = x;
   doSomething();
   doAnotherThing();
   doYetAnotherThing();
   doSomethingElse();
   return true;
}
private void doSomething ()
{
   //does something with _internalInt
}
etc...
```

When  you call `Doer.somethingDoer(5);', you'll get the same result, I'm just wondering from the perspective of design/testing, which is a better way to go? Parameter, or Class Variable?
What was wrong with class components?
Tags: react, hook
Published: 2020-08-12 22:36:29

There is something beautiful and pure about the notion of a stateless component that takes some props and returns a React element. It is a pure function and as such, side effect free.

export const Heading: React.FC<HeadingProps> = ({ level, className, tabIndex, children, ...rest }) => {
  const Tag = `h${level}` as Taggable;

  return (
    <Tag className={cs(className)} {...rest} tabIndex={tabIndex}>
      {children}
    </Tag>
  );
};

Unfortunately, the lack of side effects makes these stateless components a bit limited, and in the end, something somewhere must manipulate state. In React, this generally meant that side effects are added to stateful class components. These class components, often called container components, execute the side effects and pass props down to these pure stateless component functions.

There are several well-documented problems with the class-based lifecycle events. One of the biggest complaints is that you often have to repeat logic in componentDidMount and componentDidUpdate.

async componentDidMount() {
  const response = await get(`/users`);
  this.setState({ users: response.data });
};

async componentDidUpdate(prevProps) {
  if (prevProps.resource !== this.props.resource) {
    const response = await get(`/users`);
    this.setState({ users: response.data });
  }
};
If you have used React for any length of time, you will have encountered this problem.

With Hooks, this side effect code can be handled in one place using the effect Hook.

const UsersContainer: React.FC = () => {
  const [ users, setUsers ] = useState([]);
  const [ showDetails, setShowDetails ] = useState(false);

 const fetchUsers = async () => {
   const response = await get('/users');
   setUsers(response.data);
 };

 useEffect( () => {
    fetchUsers(users)
  }, [ users ]
 );

 // etc.
The useEffect Hook is a considerable improvement, but this is a big step away from the pure stateless functions we previously had. Which brings me to my first frustration.
How to setup a Twilio Hello SMS
Published: 2020-08-12 22:21:37

Go to Functions:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/iqqt719lbsewyu1uqk17.png)

Create a SMS function:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e0ckfbm5vf41uzdwimek.png)

```
exports.handler = function(context, event, callback) {
    context.getTwilioClient().messages.create({
      to: '+1253xxxxxxx',         
      from: '+1256906xxxx',       //twilio number
      body: 'New Student Recieved'
    }).then(msg => {
      callback(null, msg.sid);
    }).catch(err => callback(err));
  }
```

Now just visit your */sms API to send the SMS!
Day 194: Care Packages
Tags: hiphop, code, coding, lifelongdev
Published: 2020-08-12 22:02:48

_liner notes_:
- Professional : Sat in on a couple of talk prep sessions. Had a virtual hangout with some team members. One is from Canada and it was interesting to hear how their country handled the Covid-19 thing. So different from the US. Other than that, I was working on my sample application using the Web Component to make a phone call. I got that to work. I created another Web Component to be a contacts list. After making a phone call, a dialog box pops up asking if you would like to save the number. If you do want to, you must enter in a name and then you can save the contact. That goes into the Web Component and gets saved to the local storage of the browser. I got it so that if you click a contact in the list, it will fill in the keypad's display so you can just hit the call button to make the call. No need to enter in the number. Everything works, but I'm having an issue with loading the Web Components. I'm using Material Design Web Components for styling and it looks like a library is being added twice and that causing an error and not loading one of the Web Components. I saw some similar issues posted not even a couple of days ago. The Material Design Web Components is listed as experimental. haha I'll figure something out

- Personal : Last night, I got the radio show recording edited and sent to the station. I went through some tracks for this week's broadcast. I worked on the canvas of my side project and got the text and images where I wanted. Problem is that I can not switch between the scenes. One scene only shows the image and not the text. Weird. I was able to get it to switch previously, but it was a different way. Instead of showing and hiding parts of the canvas, I actually changed the text and re-positioned it on the canvas. I'll figure it out.

![Coast of Jacksonville, Florida](https://dev-to-uploads.s3.amazonaws.com/i/mbnsq5feztd7eo5ig80n.png)

Really want to figure out that canvas issue I'm running into. I've been learning way more that I thought I would about the Canvas element. haha. Maybe go through some more tracks for this week's radio show and continue packing. Also got some more care packages in for the van.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube CenEoFNwFVE %}
Most Active GitHub User - Profile README
Tags: github, pipedream, javascript
Published: 2020-08-12 21:47:11

**This pipedream workflow lets you display your GitHub most active user rank in your profile readme.**

> Just like mine [github.com/kerolloz](github.com/kerolloz)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q6cy5wwb6j7c8qvd1mcx.png)

# How?

First, go to [commits.top](https://commits.top/) and find your country. Find yourself in the list of the top contributors for your country. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yau3bgwuqykk8j6tlfsu.png)

1. If you haven't yet, create a public repository with the same name as your GitHub username and make sure you have a README.md file. 
1. [Copy this workflow](https://pipedream.com/@kerolloz/most-active-user-p_ZJCVmz/edit?copy=true) to your pipedream account.
1. In the code, change to your username and your country.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2wvlfedxp4187yswlwl7.png)
1. You can also change the badge text and color
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tov983xmmrwluh3erxqo.png)
1. Deploy the workflow
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ql827njdwlw8711rja8j.png)
1. Copy the trigger URL of your pipedream workflow and paste it in the following format to your GitHub profile README
```markdown
![Most Active GitHub User Rank](https://<YOUR-ENDPOINT>.m.pipedream.net)
```
The following badge should appear on your profile README [![Most Active GitHub User in Egypt Rank](https://en2bnd5v3totrva.m.pipedream.net)](github.com/kerolloz)

Enjoy :tada: