teleren/devto huggingface dataset:
Polyglot Series in Javascript, Dart, Ruby, Python,Go: Enum
Tags: javascript, dart, python, ruby
Published: 2020-05-24 04:33:16

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

Playground path: collection/enum
{% replit @achristoph/pg  %}


## Enum
Javascript does not have enum type, however Typescript does have enum type. The default value type is numeric, enum type can also be of string type.

###Typescript
```typescript
// numeric enum
enum Color {
  Red,
  Green,
  Blue,
}

// string enum
enum Answer {
  No = '1',
  Yes = '2',
}

// printing its value: 0
console.log(Color.Red);
console.log(Color.Red.valueOf());
// printing its name: 'Red'
console.log(Color[Color.Red]);

// enum is hashable
let m = new Map();
m.set(Color.Red, 1);
console.log(m.get(Color.Red));
```

###Dart
In Dart, the enum type is enum. To get its enum name, unlike Javascript, the default and toString() print its actual name instead of the value but it prints the fullname of it: 'Color.red'. Flutter framework has a method describeEnum that can extract just the 'red' value or you can come up with a regex.

```dart
  enum Color { red, green, blue }
  // Color.red is an enum type, this will print 'Color.red'
  print(Color.red);

  // Printing its name can be done with toString() as well
  print(Color.red.toString());
  
  // enum type has index property starting at 0
  print(Color.red.index);

  // enum type is hashable
  var m = Map();
  m[Color.red] = 1;
  print(m[Color.red]);
```

###Python
Enum in Python has to be imported from enum package and the values have to declared - not defaulted to numeric value.
The methods are nicely named and predictable: **name**,**value**
In addition, the enum is iterable and accessible like Dictionary as well. So, Python has the most complete feature of all other languages.

```python
from enum import Enum

#the enum values must be declared

class Color(Enum):
    red = 1
    green = 2
    blue = 3

print(Color.red)
# enum name and value are printable
print(Color.red.name)
print(Color.red.value)
# it can be enumerated
for c in Color:
    print(c)
# like Javascript, it can be accessed like Map
print(Color['red'])
print(Color(1))
```

###Ruby
Ruby does not have enum, we can use module instead, and must be capitalized, e.g: Red instead of red.

```ruby
module Color
  Red = 1
  Green = 2
  Blue = 4
end

p Color::Red
```

###Go
Like Ruby, Go does not have enum either. One way to simulate this is to make a list of constants with iota value - a sequential integer value
```go
type Color int

const (
  Red Color = iota
  Green
  Blue
)

fmt.Println(Red, Green, Blue)
var d Color = 0
// it will print Red
switch d {
case Red:
  fmt.Println("Red")
default:
  fmt.Println("Other Color")
}
```
Just the basics. 
Tags: Swift, beginners
Published: 2020-05-24 04:21:53

1. How do you assign a value?
    A- The "var" keyword is the only way to declare a variable in Swift. The most common and concise use of the "var" keyword is to declare a variable and assign a value to it. 

2. Which are the basic arithmetic operators?
    A- The basic arithmetic operations are (+)addition, (-)subtraction, (*)multiplication, and (/)division.
Play Video Using video.js and videojs-hls-quality-selector
Tags: videojs, angular, streaming, video
Published: 2020-05-24 04:16:12

---
title: Play Video Using video.js and videojs-hls-quality-selector
published: true
description: Play Video Using video.js and videojs-hls-quality-selector
tags: video.js, angular, streaming, video
---

## Introduction
How to play hls video in Angular using video.js and show quality-selectors

## Create simple angular App and use following commands to install video js components
```
npm install --save video.js
npm install --save videojs-hls-quality-selector
npm install --save videojs-contrib-quality-levels
```

video-player.component.html
```
<video
id="my-video"
class="video-js vjs-default-button vjs-big-play-centered"
  controls
  playsinline
  preload="auto"
  width="640"
  height="480"
  data-setup="{}"
>
  <source src="{{this.url}}" type="application/x-mpegURL"/>
  <p class="vjs-no-js">
    To view this video please enable JavaScript, and consider upgrading to a
    web browser that
    <a href="https://videojs.com/html5-video-support/" target="_blank"
    >supports HTML5 video</a
    >
  </p>
</video>
```

video-player.component.ts
```
import {AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild} from '@angular/core';
import videojs from 'video.js';

declare var require: any;
require('videojs-contrib-quality-levels');
require('videojs-hls-quality-selector');

@Component({
  selector: 'app-video-player',
  templateUrl: './video-player.component.html',
  styleUrls: ['./video-player.component.css']
})

export class VideoPlayerComponent implements OnInit, AfterViewInit, OnDestroy {
  
  public player: videojs.Player;
  

  
  url = 'https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8';

  constructor() {
  }

  ngOnInit(): void {
  }

  ngAfterViewInit() {
    const options = {
      'sources': [{
        'src': this.url,
        'type': 'application/x-mpegURL'
      }
      ],
      // 'poster' : this.urlPoster
    };
    this.player = videojs('my-video', options, function onPlayerReady() {
      console.log('Player ready');
      var myPlayer = this, id = myPlayer.id();
      myPlayer.hlsQualitySelector();
    });

  }

  ngOnDestroy(): void {
    if (this.player != null) {
      this.player.dispose();
    }
  }

}
```

package.json
```
{
  "name": "videojs-player",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    ...    
    "video.js": "^7.7.5",  
    "videojs-contrib-quality-levels": "^2.0.9",
    "videojs-hls-quality-selector": "^1.1.1",
    ...  
  }
}
```

Source
https://silentsudo.gitlab.io/post/angular/2020-05-04-videojs-quality-selector-hls-streaming/
Where to go from here?
Tags: beginners, career, help
Published: 2020-05-24 03:36:47

The long and short of this post is, Were you to pay for training in learning front-end development, where would you go?

I currently work in Civil Engineering and I've become tired of the engineering field in general. I've wanted to teach myself front-end development for many years but have not completed this goal. Now I'm at a point where I would like a career change and after chatting with my wife, I want to investigate paid options with structure and requirements. This can be a degree or something else. The key is, career change.

My current situation is that I work 40 hours a week so I need something that can work with that but I need the structure and accountability of a "class". I'd be learning nights and weekends essentially.

Thank you in advance for your thoughts and opinions. All are welcome.
Day 4: Finding time during transition
Published: 2020-05-24 03:21:12

Today was a pretty rough day for me. 

I had a 12 hour train ride from D.C. to Rochester to visit my sister, and I in turn had nothing to do but code today. I was able to finally complete my responsive web design certificate.

I found the responsive web design section to be the easiest yes, but there were some very key basic styling and some more advanced styling topics that were new to me and are still important to know.

I also began to study some Javascript today and go over some of the Javascript basics that I currently possess already. I am quickly coming to the aspects of the language that I still struggle in, which I am excited to learn and get better at. 

I had an immense headache today after working for over 10 hours after I had a 2 hour delay which was grueling.
código limpo + visão computacional = só felicidade
Tags: python, codequality, productivity
Published: 2020-05-24 03:12:08

Recentemente voltei a estudar visão computacional, confesso que é uma área bem fascinante e um tanto complexa. Pois bem, é muito comum em meus estudos, eu me deparar com códigos que por si só, não transmitem um significado conciso sobre o que eles realizam. *Clean code* é uma filosofia aonde você aplica técnicas para deixar o código mais descritivo sobre o que ele faz, quem nunca viu aquelas variáveis `x, y, z, ix, iy` ou aquelas funções `do_something(), apply(), convert()`. O domínio de visão computacional por si só já é complexo, se o código não for legível, fica mais difícil ainda. Ainda poderiamos falar de *object calisthenics* ou *S.O.L.I.D*; contudo, é comum fazer uso do jupyter aonde o estruturado reina, a realidade é que você não precisa forçar seu código a passar com sucesso por object calisthenics ou outras filosofias voltadas para *OOP*. Dar um bom nome as coisas e separar as responsabilidades, é um avanço mais que ideal. I know, I know, nomear não é uma tarefa simples mas podemos tentar evitar esses `x's` e esses `y's`.


### Quick tip 1

```python
f = sys.argv[1]
i = cv2.imread(f, 0)

w = i.shape[1]
h = i.shape[0]
```
Nunca abrevie, não existem motivos para abreviar, a preguiça é um caminho sem volta. Tanto você quanto quem for analisar o código, vai perder tempo tentando entender essas abreviações. 

### Quick tip 2 
```python
def draw(img):
    # code

def convert(img):
    # code
```
Tente usar um nome que esclarece o que aquela função ou class vai realizar, um `draw_circle()` por exemplo, se tiver um caso com muitas figuras a serem desenhadas, use uma *interface* com os métodos: `draw_circle()`, `draw_triangle()` e etc. A ideia é separar as responsabilidades e dar um bom nome as coisas, como você vai fazer isso, deixo ao seu critério ^^

### Quick tip 3 
```python
ix = -1
iy = -1

magnitude_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:, :, 1], dft_shift[:, :, 1]))
```
Não use números mágicos, no momento em que você está programando, você sabe o que é o `-1` ou `20`; entretanto, depois de um tempo aquilo pode não fazer mais nenhum sentido para você, muito menos para quem não escreveu o código. É comum colocar esses números em constantes com nomes descritivos sobre o que eles são. 

Isso são pequenos exercícios para você praticar no momento da codificação, comece aos poucos e tranforme em uma rotina ^^


### Extras

* Como normalmente a gente vai está utilizando python, tente seguir a [PEP 8](https://www.python.org/dev/peps/pep-0008/), isso é muito importante. Você pode utilizar algum code formatter para facilitar sua vida, como o [Jupyterlab Code Formatter](https://jupyterlab-code-formatter.readthedocs.io/en/latest/index.html)

* Leia o livro Código Limpo do Robert C. Martin, é um bom livro para ler antes de dormir ^^
JavaScript: Double Not Operator?
Tags: javascript, webdev, todayilearned
Published: 2020-05-24 02:37:59

_Article originally published on [Will’s personal blog](https://www.willharris.dev/garden/javascript-double-not-operator)_

---

Here's a little JavaScript tidbit I learned about recently.

The `!` operator is a familiar face in the JavaScript landscape, showing up when we need to negate a value.

```javascript
let thing = true
thing = !thing
thing === false // true
```

Here we take a Boolean value (`true`) and invert it to the opposite value (`false`).

This also works with non-Boolean values as well, since all values in JavaScript are either [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) or [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).

```javascript
let thing = "This string is truthy!"
thing = !thing
thing === false // true
```

Here we can see how the `!` operator casts the value from a string value (truthy) to it's opposite Boolean value `false`. The same conversion happens when we use the `!` operator on any value in JavaScript. If the value is already truthy it is cast to `false`, and vice versa.

It follows then that `!!` just performs this inversion twice.

```javascript
let thing = "This string is truthy!"
thing = !!thing
thing === true // true
```

This is really just a shorter way to cast a value to it's Boolean counterpart. If a value is already falsy, using `!!` will result in the value being cast to `false`.

We could just as well do this for the same result:

```
let thing = Boolean("This string is truthy!")
thing === true // true
```

What's the difference? As far as I can tell, there is none!

Although `!!` is more succinct, the argument could be made that it is more confusing syntactically than `Boolean(value)`.
Function curring
Tags: javascript, webdev, react, todayilearned
Published: 2020-05-24 02:28:51

This article makes more sense if you know about javascript closures. If you want to know about closures please go through this ([javascript closures](https://dev.to/mohananagavenkat/javascript-closures-pbe)) article.
##What is a curried function?
A curried function is a function that accepts multiple arguments one by one. For example, a curried function of three arguments takes the first argument and returns a function that takes the second argument and returns a function that takes the final argument and returns the final result.

*Example:*
Let's implement a function that takes three arguments and returns the sum at the final.

```js
function sum(a){
  return function(b){
    return function(c){
      return a+b+c;
    }
  }
}
console.log(sum(1)(2)(3));
```
If you are fan of es6 you can write this in single line
```js
const sum = a => b => c => a + b + c;
console.log(sum(1)(2)(3));
```
Here, the `sum(1)` is being called that assigns a as 1 and returns a function which accepts b. Then the returned function will be called with `2` as argument and that will be assigned to b and another is function will be returned.Again, the returned function will be called with `3` as it's argument and finally our end result which is the sum of `a,b,c` will be returned.

##Why currying?
Function currying is very useful in the case of function compositions. Especially in algebra we have function definitions as follow.
```
f: a -> b
g: b -> c
h: a -> c === g(f(x))
```
let's take a simple math example
```math
f(x) = x + 1
g(x) = x * 2 
Now h(x) = g(f(x)) = g(x+1) = 2 * (x+1) = 2x+2
```
In javascript we can build this composition as follow.

```js
const f = x => x + 1; // f(x)
const g = x => x * 2; // g(x)
const compose = (f,g) => x => g(f(x)) // a function that returns a composition of f and g
const h = compose(f,g); // composite function h(x)
```

I hope this adds something to your knowledge and useful ✌.

> Before software can be reusable, it first has to be usable.
     – Ralph Johnson

**I am always open to suggestions and accept mistakes. So please leave a comment whatever you feel 🤗**
OctoGrad2020
Tags: octograd2020
Published: 2020-05-24 01:55:39



## My Mini Project
I put together a lightweight boilerplate so that I didn't have to sort through the bloat found in many other boilerplates. This made the understanding of the use of every component and tool of the full-stack boilerplate much more apparent. This boilerplate makes use of node/express, babel, webpack, typescript + react, and css, along with hot-reloading via nodemon and webpack. I would highly recommend new developers to try building one up from scratch to understand how the different components work together!
Golang gRPC handler with 2 service/usecase. should use transaction? 
Tags: help, go
Published: 2020-05-24 01:14:22

Hi guys, i have backend golang. i build 1 gRPC handler that calling 2 usecase/service with 2 different repository of course. 

i confuse how to implement transaction in handler. 

let say in gRPC handler, it calling Create Order service and Create New User service. when the first service successful store data, but the second failed. 

any suggestion? or wanna discuss about it? let me know :)
Digital Candyland Card Deck
Tags: octograd2020
Published: 2020-05-24 00:08:44

![Give Kids The World logo](https://www.gktw.org/i/common/share-logo.png)

Each year, NC State University sends a group of students down to Orlando, Florida to serve for a week at the charity [Give Kids The World Village] (https://www.gktw.org/). According to their website,

> Give Kids The World Village is an 84-acre, nonprofit "storybook" resort in Central Florida. Here, children with critical illnesses and their families are treated to weeklong, cost-free vacations.

In addition to spending a week serving in person at the village, I also had the opportunity to assist with a charity fundraiser that NC State students were hosting. Children from the local community were invited to play in a life-size version of the [Candyland](https://en.wikipedia.org/wiki/Candy_Land) board game, complete with decorations and live actors. The children themselves act as the player pawn pieces.

However, if the kids are halfway across the gymnasium standing on a red square, how could they possibly draw the next card to tell them which space to progress toward next? If they had to run all the way to the start to draw a card on every turn, they could easily get tired or forget their spot on the winding pathway.

To mitigate this issue, I designed a Progressive Web Application (PWA) that ran on digital devices of all sizes and strengths. Using modern web frameworks managed by Webpack, I created an accessible and intuitive interface that all participants could find in a web browser. Once the site was loaded once, no network connection was necessary. All of the data is cached client-side so that, if signal is weak in any given part of the Candyland game, the players can still interact with the digital deck.

You can give the app a spin [here](https://neillrobson.com/candyland/), and as usual the source code is available [on GitHub](https://github.com/neillrobson/candyland)!

Among the handful of projects that I completed during my undergraduate career at NC State, this little app brings me the most joy. Although it wasn't terribly complex to design or implement, I got to witness for the first time the power of software developers to bring tangible delight to the people they love. The simple blessing of a skill that makes others happy is what motivates me every day to pursue a career in computer science!
Is Deno worth getting excited about just yet? 
Tags: discuss, node, deno
Published: 2020-05-23 23:52:05

I don't understand all the current hype around Deno. From what I understand, it's being driven by the creator of NodeJS but with everything that should've been done the first time around. Things like supporting TypeScript out of the box, and operating in a secure runtime where permissions must be explicitly invoked are nice, but I don't see them as a reason to jump across, especially when the lack of package support is considered.

Don't get me wrong, I think it's a great thing that it's being developed and I'd jump at an opportunity to use it, but I don't see how it would differentiate in usability to NodeJS.

Why should I be getting excited?
Writing a simple API with Deno
Tags: deno, api, rest, javascript
Published: 2020-05-23 22:50:50

Today we gonna write a REST API using Deno.

Deno is a simple, modern, and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust. You can look more about Deno on his [official website](https://deno.land/)

>We're not here to fight and compete between Deno and Node, we're here to learn something new.

#### Steps 
1. Install Deno.
2. Create API
3. Run the API with permissions.
4. Test our API

### 1. Install Deno

With Shell:
```sh
$ curl -fsSL https://deno.land/x/install/install.sh | sh -s v1.0.2
```
With PowerShell:
```sh
iwr https://deno.land/x/install/install.ps1 -useb -outf install.ps1; .\install.ps1 v1.0.2
```

### 2. Create API

Open a text editor, and create a file called `index.ts`. Add this to the `index.ts` file.

```typescript
// Import the oak utils for app and router. Oak works similar than Express in Node, we are using the version 4.0.0 of oak
import { Application, Router } from 'https://deno.land/x/oak@v4.0.0/mod.ts'

// Let use the host parameters, but we set default values
const PORT = 8000
const HOST = 'localhost'

// Start instances of app and router
const app = new Application()
const router = new Router()

// This API will have only an get method
router.get('/api', (context) => {
  context.response.body = 'Hello from Deno API!'
})

// We let the app use the routes define above
app.use(router.routes())
app.use(router.allowedMethods())

// Start the app in the host and the port setted
const HOST_PORT = `${HOST}:${PORT}`
console.log(`Listen on ${HOST_PORT}`)
app.listen(HOST_PORT)
```

### 3. Run the API with permissions.

Deno has a feature to explicitly ask for permission to use the computer resources, protocols, and more.

To run the API we need to set the `--allow-net` flag to use the network protocols in our app. Now, run this script in your path where the `index.ts` is.

```sh
$ deno run --allow-net ./index.ts 
```

You will see something like this:
![output deno api console](https://dev-to-uploads.s3.amazonaws.com/i/2xifj230pkuxoebbj5xj.png)

### 4. Test our API

Now we can go to our browser and test the API at `http://localhost:8000`.

You will see something like this:

![output deno api broser](https://dev-to-uploads.s3.amazonaws.com/i/xm7tx4p9oebp5vhkky92.png)

### Wrapping up

This is a simple example of how to create a simple API in Deno.

I invite you to explore new things like Deno, use your energy on learning new things, and ovoid as much as you can the comparison between Deno and other tools.

Remember that this code is just an example, take this implementation as a reference to build your own solid, secure, and scalable solutions.

If you're more curious about Deno, I recommend these resources:

[Build a Chat app with Deno](https://aralroca.com/blog/learn-deno-chat-app)
[The Deno Handbook](https://flaviocopes.com/deno/)
[Deno — How’s it Different to Node.js and Should I Learn it?](https://medium.com/swlh/deno-hows-it-different-to-node-js-and-should-i-learn-it-4309d66ff60d)



Happy coding!
Make bat, not exe
Published: 2020-05-23 22:44:25

Yesterday, I was banging my head against the internet to find a way to convert a batch file that I have written to an executable file. Why did I want to convert my batch file into an exe file? Here is the story…

At my job, I was using a CLI tool to build and deploy my app to the server. Every time I made a change to the code and wanted to deploy the latest code, I had to execute five commands to build and deploy my app.

I am not that person who gets everything right at the first shot. When I test the app after deploying, more often than not, I would find that I missed something. Again I had to execute those five commands. And again… and again… and again…

I am super lazy and me having to execute five commands again and again drove me crazy. So I decided to write a batch script where I would automate running these commands. I wrote the script and tested it. It worked just the way I wanted.

But then, I had this crazy idea, or… maybe a wish. The CLI tool that I was already using was packaged as an exe file. So when I used this CLI tool, I would say `cli arg1 arg2`. Mine was a batch file. So each time I executed the batch script, I had to say `mybatch.bat arg1 agr2`. I did not like having to type .bat when I executed the script.

So, I wanted to convert my batch script into an exe file, so that I can execute it without having to type .bat every time. I searched the internet, downloaded a few batch to exe converter tools. I even tried the IExpress tool that comes bundled with Windows which supposedly does the batch to exe conversion.

Either the downloaded tool was blocked by my company’s security software or they simply did not work for me. Frustrated, I gave up. I decided to live with having to type .bat in my command. After a few minutes, the *Eureka* moment happened.

Out of carelessness, my hands typed `mybatch arg1 arg2` and the command started running! I blinked in excitement. So, I did not have to type .bat to execute a batch file?

Well, that day I learnt that in order to execute a .bat file Windows, you did not have to type .bat with the filename.