teleren/devto huggingface dataset:
NodeJs Singleton Injector
Tags: node, typescript
Published: 2019-06-21 22:13:19

---
title: NodeJs Singleton Injector
published: true
description: 
tags: NodeJs, Typescript
---

I am going to talk about one of my most used patterns.

When given the task to write an API using NodeJs and Express I like to implement the following pattern, which I tend to call Singleton Injector (yes I like to make up names) that allows me to manage singletons easily. 

This pattern is ofcourse the singleton pattern with a small mixture of (but not quite) the dependency injection pattern.

My application entry point looks as follows

```javascript
(async () => {
    await addAndInitDepedencies();
    // express stuff. configure and start server
})();

async function addAndInitDepedencies() {
    injector.addService(MySql, DatabaseConnection.MySql);
    const mysql = injector.getService<MySql>(MySql);
    mysql.init();

    // other singletons that follow the same pattern
}
```

So when I need to use for example the mysql connection pool, I can simply do

```javascript
 this.mysql = Injector.getInstance().getService<MySql>(MySql);
 this.mysql.executeQuery(sql, []);
```

and this infamous Singleton Injector is just the following really simple class

```javascript
export class Injector {
    private static instance: Injector;
    private _di: any = {};

    private constructor() { }

    public static getInstance() {
        if (!Injector.instance) {
            Injector.instance = new Injector();
        }
        return Injector.instance;
    }

    public addService(dependency, args) {
        if (this.serviceExists(dependency.name)) { return; }
        const construction = new dependency.prototype.constructor(args);
        this._di[dependency.name] = construction;
    }

    public getInjector() {
        return this._di;
    }

    public getService<T>(dependency): T {
        if (!this.serviceExists(dependency.name)) { return {} as T; }
        const di: any = this._di as T;
        return this._di[dependency.name];
    }

    private serviceExists(name: string) {
        return this._di[name] ? true : false;
    }
}

```

basically you provide the `class` you wish to use as well as any arguments that might need, it calls its `constructor` and returns back the initialized object. And you can get any singleton back anytime by using the `class` as a `type` and `parameter`.

Nothing fancy, just small stuff that makes your life easier.

To be completely honest, until two years ago, I only used Node to write command line tools (so much better than bash), as my background was mainly in c# and c++. It's been an interested trip.
Building Serverless or Debug APK for React Native apps
Tags: reactnative, android, node, npm
Published: 2019-06-21 22:07:08

![Photo by [Artem Sapegin](https://unsplash.com/photos/ZMraoOybTLQ?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/search/photos/react-native?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)](https://cdn-images-1.medium.com/max/800/1*wyxuq21keffc5b0d_lMkUw.jpeg)
Photo by [Artem Sapegin](https://unsplash.com/photos/ZMraoOybTLQ?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/search/photos/react-native?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)


So I have been working on React Native for a long time, now and no one actually asked me this till I actually asked myself, “So every time, I have to create a signed APK to test it on another device?”. And as usual, I started googling but came up with a lot of results but none of them actually worked for all the apps that I created or worked with. Eventually, I came up with a solution to build a complete, working serverless APK that runs without the `npm` packager.

Basically, the process is very easy. Open a terminal/command prompt inside the root directory of your project and run the following commands:

1\.  Start the node packaging bundler:

```bash
npm start
```

2\. When the terminal shows: “Loading dependency graphs….”, open a new terminal in the same directory and now run the following to create a new directory inside the app to store the assets:

```bash
mkdir -p android/app/src/main/assets
```

3\. Use react-native’s bundle to bundle the assets in the directory created above:

```bash
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
```

4\. Curl the .js files created to the index.android.bundle:

```bash
curl "http://localhost:8081/index.bundle?platform=android" -o "android/app/src/main/assets/index.android.bundle"
```

5\. Change to _/android_ directory and run _gradlew_ to build the APK:

```bash
cd android && ./gradlew clean assembleDebug
```

Well, that’s it. Easy, peasy! After everything is done and it shows “Build successful”, your APK will be present in the folder

```bash
<project>/android/app/build/outputs/apk/debug
```

If you have some suggestions, comment below or give a clap!
Fix audio errors in Ubuntu 18.04 with alsamixer
Tags: ubuntu, linux, audio, alsamixer
Published: 2019-06-21 21:43:01

Recently I installed Ubuntu 18.04 on my laptop having an SSD and an internal HDD. Soon after fixing a lot of issues, I encountered through this one and thought maybe a lot of people are going through this. So,why not write about it?

![Sound panel in Ubuntu 18.04](https://thepracticaldev.s3.amazonaws.com/i/ngrqy7f6orzk8hgo4r93.png)

Sometimes it happens that all the audio controls and volume are full and you stilll don't hear any volume coming out of those speakers. I researched a lot and found out that there maybe a problem with the mixer control. And here is what I found out. I ran `alsamixer` in terminal and checked if all the volumes are full or not.

![Alsamixer](https://thepracticaldev.s3.amazonaws.com/i/d7zjho3ux37iriic17i2.png)

The 'Headphone' volume was mute even though the 'Master' one was full. And this small thing was the issue. The fix? Simple use arrow keys (left/right) to highlight the headphones tab (it turns red as master is in the above photo). Then use arrow keys(up/down) to increase/decrease the volume. Exit the interface by tapping the Esc key.

You can also use the terminal commands to adjust the volume:

```bash
amixer set Headphone 50%

amixer set Master 80%
```

![Command Line Editing](https://thepracticaldev.s3.amazonaws.com/i/f5pjfsmcmsueg5iizcce.png)


This finally helped me figure out the issue with the audio. If this does not work, let's just discuss what might be happening!
When is NavigationCancel triggered?
Tags: angular
Published: 2019-06-21 21:19:03

This post was originally published on [my blog](https://dzhavat.github.io/2019/06/08/when-is-navigation-cancel-triggered.html).

---

Over the past couple of days, I was working on an Angular component that depended on a stream of [router events](https://angular.io/api/router/RouterEvent). There are quite a few of them but I was particulary looking at `NavigationCancel`. A question that came up was “When is this event triggered?”

The [documentation](https://angular.io/api/router/NavigationCancel) didn’t really answer my question. Here’s what it currently says:

> Represents an event triggered when a navigation is canceled.

While this was somewhat helpful, I was hoping for more details. In this short post I’d like to share my findings for cases in which `NavigationCancel` is triggered.

### When a route guard returns `false`

This is probably the most obvious one. If you have a [route guard](https://angular.io/guide/router#milestone-5-route-guards) that returns `false` during navigation, you’ll get a `NavigationCancel` event. It doesn’t matter if the return value is `false`, a `Promise` that resolves to `false` or an `Observable` that emits `false`. The end result will be the same.

```ts
canActivate() {
  // Case 1
  return false;

  // Case 2
  return Promise.resolve(false);

  // Case 3
  return new Observable<boolean>(observer => {
    observer.next(false);
    observer.complete();
  });
}
```

[StackBlitz example](https://stackblitz.com/edit/angular-zysw4m)

### On redirect initiated by a route guard

There are a couple of cases here. As of v7.1, a `CanActivate` guard can also return an [`UrlTree`](https://angular.io/api/router/UrlTree) object. In that case, the current navigation **will be canceled** and a new navigation will start based off the returned `UrlTree`.

```ts
canActivate() {
  // Case 1
  // Manually start a new navigation and cancel the current one by returning `false`
  this.router.navigateByUrl('/hello-new');
  return false;

  // Case 2
  // The router will automatically cancel the current navigation and start a new one 
  return this.router.parseUrl('/hello-new');
}
```

[StackBlitz example](https://stackblitz.com/edit/angular-7a4pty)

That’s it. These are the cases where `NavigationCancel` will be triggered. Do you know more? Let me know on [Twitter](https://twitter.com/dzhavatushev).
Creating a new Flask project with pipenv
Tags: python, flask, pipenv, python3
Published: 2019-06-21 21:13:06

---
title: Creating a new Flask project with pipenv
published: true
description: Creating a new Flask project with pipenv
tags: python, flask, pipenv, python3
---

- Create the pipenv environment

```
$ mkdir project
$ cd project
$ pipenv install
```

-----

- Install Flask

```
$ pipenv install flask
```

-----

- Structure folders/files:

```
mkdir app
touch app/__init__.py
touch app/routes.py
touch microblog.py
```

-----

- In `app/__init__.py`:

```
from flask import Flask

app = Flask(__name__)

from app import routes
```

-----

- In `app/routes.py`:

```
from app import app

@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!"
```

-----

- In `microblog.py`:

```
from app import app
```

-----

- Change into the pipenv:

```
$ pipenv shell
```

-----

- Set the `FLASK_APP` variable:

```
$ export FLASK_APP=microblog.py
```

-----

- Run the app:

```
$ flask run
```

-----

Now, whenever you need to extend your Flask app to import some new libraries or framework or whatever, just install it using pipenv.

-----

This whole process inspired me to write a bash script that does all this automatically for you. Why make things harder than they need to be?

Grab [autoflask.sh](https://github.com/mikedesu/autoflask.sh) and give it a spin on your system to quickly get a barebones Hello World project in Flask started today!

-----

# [If you need a Computer Science tutor, code reviewer, or just someone to pair program with, hit me up](https://codementor.io/mikebell66)
Privacy problems or reading comprehension issues?
Tags: privacy, questions, software, thoughts
Published: 2019-06-21 18:40:19

---
title: Privacy problems or reading comprehension issues?
published: true
description: What is your take on the Privacy concern explosion that is this technological era?
tags: Privacy, Questions, Software, thoughts
---

I constantly get articles about “Google watching us” and “How to delete your account...” for something more private across my various feeds...

I’ve always felt that people simply do not read and look to blame a company for not being ‘clear’ or just straight up not knowing what the company actually sells.

In Google’s case, I have been locked in for years; always been aware that they are an advertising company at heart and use the data it learns from me to sell products I may like, as well as personalizing everything I do across their platform. It’s a win-win in my eyes.

As a developer and/or business owner, how do you feel about the privacy concerns that arise from users of software (especially free software) that aren’t aware of how or why data is collected?

Do you feel a form of schooling would be beneficial to teach others that it’s a program that’s analyzing their personal data and not an actual individual from the company?
The World Of Product Managers(PM)
Tags: productmanagers, pms, techcompany, programmers
Published: 2019-06-21 21:01:28

Product Managers basically manage a product through its lifetime.PM's do different things depending on the type of company but I'm going to talk about PM's in a tech-related company.

So, basically I was in a tech company recently and I heard the word Product Managers and I was like..... what's that. I reached out to one of the PM's to ask what it was all about and what they actually do especially in a tech-related company.

![](https://thepracticaldev.s3.amazonaws.com/i/f0plda1t6hndyjchsfjg.jpg)

A PM in a tech-related company works like this: For example, company A approaches with a banking app idea. Product Managers look into the requirement and flow they come up with users stories, do more research on banking apps and look at best ideas, they analyze the user stories and ideas from other sources, then join these ideas together and create a full feature list.
Next, are the app flow and design process, architecture diagram and sketches(wireframes). At this point a proposal is set and sent to company A, pitch the idea and get feedback on their requirement.
After a successful delivery and company A is okay with the requirement, PM's develop mock-ups and prototype then straight to the coding phase this where the developers/programmers come into place. Product Managers still write tickets(issues), plan spirits, remove blockers for the developers and also decide which features are built first.

Product Managers are in various capacities like :
- Managing all stakeholders of the product(client, developer, QA, sales team and finance, etc)
- Detailed requirement gathering and business analysis
- Ideas generation and problem-solving
- Removing blockers for stakeholders involved
- Planning and deciding the life cycle of the product
- Testing the product( if there is no software Quality Assurance)

   And a lot of other silent activities. Product Managers are more than this but this majorly the core things of what's done

In tech, PM's are of various types:
- Design-Oriented Product Managers
- Data-Oriented Product Managers
- Developer-Oriented Product Managers

The day-to-day work of a PM is time-consuming between brainstorming new features, doing customer interviews, working with various internal/external stakeholders trying to create a go-to-market plan.

If you find that the features your team is building aren't successful for some reasons you should probably hire a dedicated PM.
A good PM decides what a company needs to build next and also creates a desired outcome and more company's product closer to its vision 

Cheers
Share Your Feedback: What Would You Expect for a VS Code DevOps Experience?
Tags: discuss, devops, vscode
Published: 2019-06-21 20:10:05

---
title: Share Your Feedback: What Would You Expect for a VS Code DevOps Experience?
published: true
description:  A great chance to share your feedback on what a VS Code DevOps experience could be
tags: discuss, devops, vscode
cover_image: https://thepracticaldev.s3.amazonaws.com/i/se788lebj90sclytvx8l.jpeg
---

Would you like to share your feedback on what would make a great DevOps experience in VS Code? 


We want your feedback on how we can build a great DevOps experience in VS Code - if you have a few minutes to talk to our team, please reply here with how we can contact you and I'll connect you via email.
I had no blog, but I wanted to scream
Tags: meta
Published: 2019-06-21 19:33:20

Hello, Dev Community!

As eagerly expected by approximately one person, now I have a [blog](https://manoel.tech)!

I will be posting about developer musings and the daily life and troubles of a common tech guy, and eventually some more technical piece. And [dev.to](https://dev.to) will be my main cross-posting and discussion station!

Hope to be back soon with my thoughts and reflections about this crazy but incredibly interesting developer life that we live.

PS: If you got the reference from the title, you earned 10 points. In whatever game you choose.
Javascript weird stuffs with number conversion
Tags: javascript, wtf
Published: 2019-06-21 19:32:29

---
title: Javascript weird stuffs with number conversion
published: true
description: Javascript weird stuffs with number conversion
tags: javascript,js,wtf
---

~~Think twice~~ Think thrice then write JavaScript

```js
    // When converting something to integer
    // the thriller begins :p


    +""          // 0
    +"5"         // 5
    +"5.00"      // 5
    +"5.00r"     // NaN


    Number("")         // 0
    Number("5")        // 5
    Number("5.00")     // 5
    Number("5.00r")    // NaN
    Number("str")   // NaN


    parseInt("")       // NaN
    parseInt("5")      // 5
    parseInt("5.00")   // 5
    parseInt("5.00r")  // 5
    parseInt("str0")   // NaN

    Number.parseInt("")         // NaN
    Number.parseInt("5")        // 5
    Number.parseInt("5.00")     // 5
    Number.parseInt("5.00r")    // 5
    Number.parseInt("str5")   // NaN



    +2.345                   //2.345
    Number(2.345)            //2.345
    parseInt(2.345)          //2
    Number.parseInt(2.345)   //2

    +(-1)                 //-1
    Number(-1)            //-1
    parseInt(-1)          //-1
    Number.parseInt(-1)   //-1


    +(-0)                  //-0
    Number(-0)             //-0
    parseInt(-0)           //0
    Number.parseInt(-0)    //0



    +NaN         //NaN
    +undefined   //NaN
    +null        //0
    +true        //1
    +false       //0

    Number(NaN)          //NaN
    Number(undefined)    //NaN
    Number(null)         //0
    Number(true)         //1
    Number(false)        //0

    parseInt(NaN)         //NaN
    parseInt(undefined)   //NaN
    parseInt(null)        //NaN
    parseInt(true)        //NaN
    parseInt(false)       //NaN

    Number.parseInt(NaN)        //NaN
    Number.parseInt(undefined)  //NaN
    Number.parseInt(null)       //NaN
    Number.parseInt(true)       //NaN
    Number.parseInt(false)      //NaN



    +[]                   //0
    Number([])            //0
    parseInt([])          //NaN
    Number.parseInt([])   //NaN

    +['somevalue'])                    //NaN
    Number(['somevalue']))             //NaN
    parseInt(['somevalue']))           //NaN
    Number.parseInt(['somevalue']))    //NaN


    +{}                   //NaN
    Number({})            //NaN
    parseInt({})          //NaN
    Number.parseInt({})   //NaN

    +{value:'somevalue'}                   //NaN
    Number({value:'somevalue'})            //NaN
    parseInt({value:'somevalue'})          //NaN
    Number.parseInt({value:'somevalue'})   //NaN
```
Am I too green to contribute to open-source? 
Tags: beginners, javascript, html, css
Published: 2019-06-21 19:13:13

I am really interested in contributing to the open source community, particularly with Mozilla. A little about me: 
I am a CS student with about 1.5 years from graduating.  Mozilla is my "dream job", but I am merely a beginner in the front end scene. I'd like to get ahead early but I have hesitations. Firstly, I only learned HTML and CSS this year, and I feel like I am just now starting to understand how to use both technologies. I am also new to JavaScript, most of my knowledge of it comes from freecodecamp's curriculum and a few very basic projects I have done in my own time. I seem to pick it up fairly quickly.My learning pace is a little slower than I would like, but it's largely due to balancing school life and personal projects. 
I attend meetups, I read just about any book on programming I can afford to get my hands on, occasionally solve code challenges on Leetcode (which I find boring but it's how you land a job), but even with all this, I feel like I am just not "there yet". Any thoughts or pointers would help!
Open Collective Interview with Brooke
Tags: opencollective, interview, witchcraft, elixir
Published: 2019-10-02 23:38:06

---
title: Open Collective Interview with Brooke
published: true
tags: Open Collective,Interview,Witchcraft, Elixir
canonical_url: https://blog.fission.codes/open-collective-brooke-interview-witchcraft/
cover_image: https://s3.fission.codes/2019/06/brooke-talking.jpeg
---

Alanna Irving from the Open Collective team [interviewed m on Witchcraft: the magic of math, functional programming, and community](https://medium.com/open-collective/witchcraft-the-magic-of-math-functional-programming-and-community-b45bc7213ff8).

Did you know she started in music composition?

> Programming absolutely scratches the same part of my brain as music composition. Instead of writing instructions for an instrumentalist, you’re writing it for a computer, but the parallels are very clear. All but one person in my composition cohort (who became a professor of music) are now programmers, because it was a crash course in that way of thinking.

It's a great overview of Brooke's background, her love of functional programming and math, and the Witchcraft library for Elixir:

{% github witchcrafters/witchcraft %}

You can follow Brooke here on DevTO as @expede:

{% user expede %}

_Edit: Is third person weird when you're talking about yourself???_
Quick access to the most relevant folder
Tags: bash, git, productivity
Published: 2019-06-21 19:06:50

If anyone else is a terminal fan like I am, I think you might like this. Being part of [azure-sdk-for-js](https://github.com/Azure/azure-sdk-for-js) has presented me with a new set of challenges, one of them being to navigate deep in folders to get where proposed changes are located. To aid in this, I made this little bash script that changes directory to the parent folder common to all the changes in the current branch. I'm enjoying it so far! Let me know if you like it or if you have any feedback <3

**About the name:** `csd` is fine to me since I'm using this a lot, just like one would use `cd`. You might prefer to use a different name for clarity.

```bash
# csd: "changes' directory", as in the directory of the changes.
# Changes the directory to the common parent to all the changes in current branch.
# Specially useful to switch to the folder relevant to the changes that a specific branch or Pull Request makes in a large project.
# By default acts based on the current changes to the current branch, but another target can be specified by passing a single argument.
# Example: csd master # changes to the common parent relative to the master branch.
# Source of the regexp: https://stackoverflow.com/a/17475354
function csd() {
 common_prefix=$(git diff $1 --name-only | sed -e 'N;s/^\(.*\).*\n\1.*$/\1\n\1/;D') 
 common_parent=${common_prefix%/*}
 cd $(git rev-parse --show-toplevel)/$common_parent
}
```