teleren/devto huggingface dataset:
Linting for your git commit messages
Tags: git, github, devops
Published: 2020-11-14 20:08:58

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

[Gitlint](https://jorisroovers.com/gitlint/) is a git commit message linter written in python: it checks your commit messages for style.

# Features

* Commit message hook
* Easily integrated
* Sane defaults
* Easily configurable
* Community contributed rules
* User-defined rules
* Full unicode support
* Production-ready

# Installation

pip

```bash
#### Pip is recommended to install the latest version
pip install gitlint
```

macOS

```bash
brew install gitlint
sudo port install gitlint  # alternative
```

Ubuntu

```bash
apt-get install gitlint
```

Docker

```bash
docker run --ulimit nofile=1024 -v $(pwd):/repo jorisroovers/gitlint
```

# Usage

```bash
# Check the last commit message
gitlint
# Alternatively, pipe a commit message to gitlint:
cat examples/commit-message-1 | gitlint
# or
git log -1 --pretty=%B | gitlint
# Or read the commit-msg from a file, like so:
gitlint --msg-filename examples/commit-message-2
# Lint all commits in your repo
gitlint --commits HEAD

# To install a gitlint as a commit-msg git hook:
gitlint install-hook
```
How to simplify nested async subscriptions in Angular template
Tags: angular, codenewbie, javascript, typescript
Published: 2020-11-14 20:04:38

One way to subscribe to observable in Angular is *async* pipe into the HTML template. It is easy but when you have several subscription use ng-container with *ngIf is a common solution, like : 
```html
<ng-container *ngIf="userAuth$ | async as user">
    <span column-1 class="licence-name">
        {{user.role}}
    </span>
    <ng-container *ngIf="domains$ | async as domains">
      <ul *ngFor="let domain in domains">
        <li>{{domain}}</li>
    </ng-container>
<ng-container *ngIf="ads$ | async as ads">
       <div *ngFor="let ad in ads">
           {{ad.name}}
       <div>
</ng-container>
<ng-container 
</ng-container>
```
## use Object :)

The ng-contanier generate too noise into the DOM, but we can simplify using object into a single *ngIf and grouping each subscription into it object like:

```html
<ng-container *ngIf="{
    user: userAuth$ | async,
    domains: domains$ | async
} as state ">
    <span column-1 class="licence-name">
        {{state.user.role}}
    </span>
      <ul *ngFor="let domain in state.domains">
        <li>{{domain}}</li>
      </ul>
</ng-container>
```

Hopefully, that will give you a bit to help you avoid nested *ngIf for observable subscription. 

If you enjoyed this post, share it.

Photo by <a href="https://unsplash.com/@barkiple?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">John Barkiple</a> on <a href="https://unsplash.com/s/photos/cables?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Exercism Teams - The support I needed
Tags: javascript, exercism, frontend
Published: 2020-11-14 19:48:03

---
title: Exercism Teams - The support I needed
published: true
description: How exercism and a supportive community have giving me an opportunity to shake my imposter syndrome.
tags: javascript, exercism, frontend,
//cover_image: https://direct_url_to_image.jpg
---

My imposter syndrome took another hit this week, in a good way! 

I "joined" [exercism](https://exercism.io/) back in May 2016. But I did not submit a JavaScript kata till July 2018 (yes, it took me over two years to get the guts to submit). I did have a productive day back on July 13, 2018 when I submitted five katas. Then my confidence took a nosedive, nothing until this November (2020). I would love to say that work or family life got busy but I just think it was imposter syndrome lurking again.

## Where I started

Time for a little background, I have been doing web coding for 15 years. I have mastered HTML, CSS, Drupal, and WordPress to build sites. What has been missing is a command of JavaScript. I have done freeCodeCamp, tutorials on Udemy, workshops, conferences, etc. I've got a strong foundation of the JS basics but stumbled on breaking a problem down into little pieces and programming them all together.

## What helped

Nicole Archambault's [Problem Solving](https://www.lavieencode.net/courses/ncpss/) course gave me some concrete ways to break down a programming problem into smaller pieces and using natural language for better understanding. Code comments here I come!

My compatriot, Mike Rogers, at [Virtual Coffee](https://virtualcoffee.io) started a VC team on Exercism. He started a channel on our Slack and offered to answer any questions and to pair-program if needed. Thanks, Mike!

And this week it all fell into place and clicked! Now I'm back at doing exercism katas! Just this week, I have submitted three individual JavaScript track katas, three extra individual katas, and three team katas. 

Wow, typing this all up feels so monumental. Thank you everyone!

### Shout Outs

* @antoniosaric on exercism, a great mentor who provides great refactoring ideas that help me take my code up to the next level.

* Nicole Archambault (@lavie_encode).

* [Virtual Coffee](https://virtualcoffee.io) for prompting me to write about my coding journey.
Async code: return vs return await
Tags: javascript, webdev
Published: 2020-11-14 19:31:47

This one will be short and sweet.
Can you tell what is wrong with this piece of code?
```js
async function getAllUsers() {
  try {
    return fetchAllUsers(); // returns promise
  }
  catch (e) {
    return new Error('never gonna happen')
  }
}
```

So what is wrong with the first example? Well you see if the `fetchAllUsers` function rejects, the `catch` block inside the `getAllUsers()` will never run.
The return result of `getAllUsers()` is a promise that is not yet resolved. And if that promise rejects, it will never run the `catch` block of `getAllUsers()`, basically it will `reject/throw` one level up.

```js
const users = await getAllUsers()
//it will throw here
```

What you really want is:

```js
async function getAllUsers() {
  try {
    return await fetchAllUsers(); // returns promise
  }
  catch (e) {
    return new Error('oops')
  }
}
```
Have you noticed the `return await`? This way the `try` block will return a **resolved** promise from the `fetchAllUsers()`
but if that promise rejects, the `catch` block will run, and handle the rejection.

```js
const users = await getAllUsers()
// users will have a value from try or catch block return statemen
```
It is a subtle but important difference, and can easily be missed.
The hidden Django anti-pattern preventing your prod rollback
Tags: django, codequality, python, webdev
Published: 2020-11-14 19:26:31

Picture the scene: it's 11pm and production is down. Stress. You're about to roll back to the last good release. All you need is to reverse the database migrations and then deploy and...wait what?

```sh
$ python manage.py migrate hounds 0002
Operations to perform:
  Target specific migration: 0002_auto, from hounds
Running migrations:
  Rendering model states... DONE
  Unapplying hounds.0003_auto...Traceback (most recent call last):
django.db.migrations.exceptions.IrreversibleError: Operation <RunPython > in hounds.0003_auto is not reversible
```

## Migrations forwards and back

Django data migrations are two parters: forwards and backwards, but the cause of this failed migration is...for reasons...the develop only added the `forwards` handler:

```py
# 0003_auto.py
def forwards(apps, schema_editor): 
    ...

class Migration(migrations.Migration):
    dependencies = [("cases", "0009_auto_20200320_1210")]
    operations = [migrations.RunPython(forwards)]
```

Django requires forwards, but backwards is technically optional. While the above is valid, below is infinitely better:

```py
# 0003_auto.py
def forwards(apps, schema_editor): 
    ...

def backwards(apps, schema_editor):
    ...

class Migration(migrations.Migration):
    dependencies = [("cases", "0009_auto_20200320_1210")]
    operations = [migrations.RunPython(forwards, backwards)]
```

So `backwards` is _technically_ optional in the same way that wearing a parachute while skydiving is optional: given enough time you will eventually hit the ground. Hard. Indeed, if you want the option of rolling back your production website then no, `backwards` is not optional. Omitting `backwards` means you only have the option of [rolling forwards](https://www.xmatters.com/blog/devops/after-a-deployment-error-should-you-fix-forward-or-roll-back/), which is a bit more daunting compared with safely rolling back to a release we _know_ works.

The fix is a super simple too: just specifying `migrations.RunPython.noop` can be enough. As the name implies, Django will [do nothing](https://en.wikipedia.org/wiki/NOP_(code)) for the reverse, simply skip over the data migration, without throwing `IrreversibleError`:
```py
# 0003_auto.py
class Migration(migrations.Migration):
    dependencies = [("cases", "0009_auto_20200320_1210")]
    operations = [migrations.RunPython(forwards, migrations.RunPython.noop)]
```

So in practice, follow this advice:

![I'm a GitHub code review bot, and I automatically suggest this fix](https://dev-to-uploads.s3.amazonaws.com/i/yb64fspuytx5pwxf9h2z.png)


### Does your codebase have a IrreversibleError waiting to happen?

Over time it's easy for tech debt to slip into your codebase. You might have a irreversible migration in your codebase. I can check that for you at [django.doctor](https://django.doctor), or can [review your GitHub PRs](https://github.com/marketplace/django-doctor/):

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

Or try out [Django refactor challenges](https://django.doctor/challenge).
PHP - Create a simple session wrapper class
Tags: php, laravel, codequality, opensource
Published: 2020-11-14 19:25:36

*PHP version required 7.3*

#Manage your session without use directly $_Session global variable

Let's create the interface.

```php
<?php

namespace DevCoder;

interface SessionInterface
{
    /**
     * @param string $key
     * @return mixed
     */
    public function get(string $key);

    /**
     * @param string $key
     * @param mixed $value
     * @return SessionInterface
     */
    public function set(string $key, $value): self;

    public function remove(string $key): void;

    public function clear(): void;

    public function has(string $key): bool;
}
```
Let's create the class that will manage session.

```php
<?php

namespace DevCoder;

class SessionManager implements SessionInterface
{

    public function __construct(?string $cacheExpire = null, ?string $cacheLimiter = null)
    {
        if (session_status() === PHP_SESSION_NONE) {

            if ($cacheLimiter !== null) {
                session_cache_limiter($cacheLimiter);
            }

            if ($cacheExpire !== null) {
                session_cache_expire($cacheExpire);
            }

            session_start();
        }
    }

    /**
     * @param string $key
     * @return mixed
     */
    public function get(string $key)
    {
        if ($this->has($key)) {
            return $_SESSION[$key];
        }

        return null;
    }

    /**
     * @param string $key
     * @param mixed $value
     * @return SessionManager
     */
    public function set(string $key, $value): SessionInterface
    {
        $_SESSION[$key] = $value;
        return $this;
    }

    public function remove(string $key): void
    {
        if ($this->has($key)) {
            unset($_SESSION[$key]);
        }
    }

    public function clear(): void
    {
        session_unset();
    }

    public function has(string $key): bool
    {
        return array_key_exists($key, $_SESSION);
    }

}
```
**How to use ?**
```php
$session = new \DevCoder\SessionManager();
$session->set('token', 'hash');

var_dump($session->get('token'));
// hash
$session->remove('token');
var_dump($session->get('token'));
// NULL
```

```php
$session = new \DevCoder\SessionManager();
$session->set('date', new \DateTime());
var_dump($session->get('date'));
// class DateTime#2 (3) {
//  public $date =>
//  string(26) "2020-11-14 22:17:39.128909"
//  public $timezone_type =>
//  int(3)
//  public $timezone =>
//  string(13) "Europe/Berlin"
}

$session->clear();
var_dump($session->get('date'));
// NULL
```

Simple and easy!
[https://github.com/devcoder-xyz/php-session-manager](https://github.com/devcoder-xyz/php-session-manager)
Understanding Django HttpResponse
Tags: python, django
Published: 2020-11-14 19:22:53

HttpResponse() is a class that returns an HTTP response.
in this tutorial, we'll understand how to use HttpResponse with simple examples.

#1. HttpResponse
As we said, HttpResponse() returns an HTTP response, so in this first example, we'll write a simple view that returns some HTML contents.

###views.py
In our views.py file, we need to add this view function.

```python
from django.http import HttpResponse

def http_response(request):
    return HttpResponse('<h1>Hello HttpResponse</h1>')    
```
###urls.py
Now, let's add a path for the view.

```python
path('http-response/', http_response), 
```

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

#2. HttpResponse with form

In this second example, we'll write a view that we'll use HttpResponse as a form response.

Let's, see the example.

###Views.py
In our views, we need to this following view function.

```python
def http_response_form(request):
    if request.method == "POST":
        username = request.POST.get('username')
        if username:
            return HttpResponse(f'<h1>hello {username}</h1>')
        else:
            return HttpResponse('<h1>please, enter your username</h1>')

    return render(request, "HttpResponse.html")
 ```       


So, after submitting the form, if the username's input is not empty, the browser we'll return hello with the username, else the browser we'll return please, enter your username.

###urls.py
Adding a path for ou view.

```python
path('http-response-form', http_response_form, name="httpresponse")
```
###HttpResponse.html
```html
<!DOCTYPE html>
<html>
<head>
    <title>Test httpResponse with form</title>
</head>
<body style="padding-top: 20px">


    <form method="POST" action="{% url 'httpresponse' %}">
        {% csrf_token %}
        <input type="text" name="username">
        <input type="submit" name="submit">
    </form>

</body>
</html>
```
Now let's test the function.


Submitting "mark" username


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


Submitting an empty username.

Result:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jdo7ikb8kscelrnspkl0.png)
[How to Use Django HttpResponse](https://pytutorial.com/django-httpresponse)

Happy coding!
If you need emacs on macOS Catalina or Big Sur
Tags: emacs, macos, catalina, bigsur
Published: 2020-11-14 19:16:00

Occasionally, we may still need emacs for small editing, but on Catalina or Big Sur, emacs is not available.  There are some options: one is to use `nano` or `vi` instead. Another is to install `emacs` using Homebrew.  The third option which can be simple is just to use `mg`.  It is [MicroGnuEmacs](https://en.wikipedia.org/wiki/Mg_(editor)) and when you use it, you can use the familiar keystrokes as in emacs.  

Note it is **already pre-installed on Catalina and Big Sur**. There is no need to install it.

If you are used to typing `e` for `emacs` and using `emacs` for `git`, simply change the zsh alias in `~/.zshrc` to

    alias e='mg'

and config `git`:

    git config --global core.editor mg
How to configure github actions for a python package
Tags: programming, ci, python, opensource
Published: 2020-11-15 09:08:32

---
title: How to configure github actions for a python package
published: true
date: 2020-11-14 19:00:00 UTC
tags: programming,CI,python,opensource
canonical_url: https://www.argpar.se/posts/programming/configure-github-actions-for-python-package
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/etd3uixa0ib8i2dolmfb.jpg
---

This is what a build action for running a test matrix in github actions looks like in python. The yaml file is saved in `.github/workflows/<your_name>.yml`.

```yaml
name: Running unittests

on:
  push:
    branches: [master]
  pull_request:
    branches: [master]

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: [3.6, 3.7, 3.8]
        django: ["2.2", "3.0", "3.1"]

    steps:
    - uses: actions/checkout@v2
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v2
      with:
        python-version: ${{ matrix.python-version }}
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements-tests.txt
        if [-f requirements.txt]; then pip install -r requirements.txt; fi
    - name: Linting
      run: flake8
    - name: Run unittests
      env:
        TOX_ENV: py${{ matrix.python-version}}-django${{ matrix.django }}
      run: |
        tox -e $TOX_ENV

```

In the matrix we define the python versions and in this case also the django versions. `django` in this case will be set as an environment variable.

Further down I've set a TOX env to set exactly how I expect the tox environment variable to be set. So that is what I'm relying `tox` to use in the end.

The python package [tox-gh-actions](https://github.com/ymyzk/tox-gh-actions) may help mapping the python versions with the tox versions. In this case I chose to do it directly with github actions to keep things simpler. One less dependency, one less worry so to speak.

For the full documentation of all the things you can do with github actions there is the [official documentation](https://docs.github.com/en/free-pro-team@latest/actions).
How can I get the definition file (goToTypeDefinition)
Tags: vscode
Published: 2020-11-14 18:56:12

I am writing a C++ extension. I would add an include instruction to the current file (which uses the type).
It is like an import instruction in JS.
How can I get the file path of the file where the type is defined?
Is there a way to get the file of goToTypeDefinition or goToDefinition?
Use `stopImmediatePropogation` to prevent invoking of other listeners for the same event
Tags: javascript
Published: 2020-11-14 18:54:42

I recently added an event listener to a DOM element. The element had another event listener for the same `click` event. Two questions came to my mind:

1. What is the order in which two event listeners attached to the same event target are called?
2. What if I want to prevent the second, or subsequent, event listener(s) from being called?

Let me share with you what I've learned.

First, I learned that, according to the DOM Level 3 specification, the order in which multiple event listeners attached to the same event target is determine by the order in which the event listeners were added. So, first-added-first-called if you will.

Second, I learned about the `stopImmediatePropagation()` method. I have used the `stopPropagation()` method in the past to prevent the propagation of the event during either the capture or bubble phases to the event target's ancestors. However, if the event target has multiple event listeners the `stopPropagation()` method will not prevent the other event listeners on the event target from being invoked.

This is where I learned that `stopImmediatePropagation()` method set's the stop immediate propagation flag, which instructs the JavaScript VM to no longer invoke event listeners on the event target as well as propagation of the event for the capture and bubble phases.

Let's look at an example of successfully using the `stopImmediatePropagation()` method:

```typescript
const el = document.getElementById('btn');
el.addEventListener('click', event => {
  console.log('first was called');
  event.stopImmediatePropagation();
});
el.addEventListener('click', event => {
  console.error('second was called'); // 👍 second event listener is not invoked
});
```

Check out [more of my lookouts on lookout.dev where I learn in public](https://lookout.dev).

I'm the Principal Architect at [LoveLoveApp, an angular and react consulting company](https://liveloveapp.com). If you need help with your Angular, React, or Node.js project, then hire the best for your project! Give us a shout and we'd love to learn about your project and how we can help.
Architecture Thoughts?
Tags: architecture, rails, github
Published: 2020-11-14 18:40:08

Hi everyone!

I would like to get your input on something. Basically, my client has a live version of their platform that consists of 3 apps (Frontend, Backend and API) that have separate Github repos. There is an urgent requirement to build a V2 of the service that will be using completely different data sources to process.

Because of urgency and to reduce the risk they proposed the following:

- Keep V1 as is
- Clone V1 into V2 and change the data sources and deploy it on separate AWS instances.

They want to Fork the repos to avoid risk, but eventually, want to merge V2 and V1 (so they want to remain eventually with just 3 repos as it is now, but every app would be able to accommodate both old/new data).

If we fork these we end up maintaining 6 repos and I can see a huge pain when trying to merge them back together eventually. Plus the code collaboration would become more complicated.

I am inclined to instead of forking create a v2 branch on each of repos.

The advantages that I see:

- easier to maintain
- increased visibility
- easier to merge in the end

Disadvantages:
- probably one big PR in the end on each of the apps
- merging v2 branch with the master on each of the repos has to happen simultaneously on all 3 apps (although feature flags could be used)

Note: All 3 apps are pretty complicated with big codebases and they work tightly together. 

What are your thoughts?
What is PyTorch `.detach()` method?
Published: 2020-11-14 18:37:14

What is PyTorch `.detach()` method?

PyTorch's detach method works on the tensor class. 

`tensor.detach()` creates a tensor that shares storage with tensor that does not require gradient. `tensor.clone()` creates a copy of tensor that imitates the original tensor's `requires_grad` field.

You should use `detach()` when attempting to remove a tensor from a computation graph, and clone as a way to copy the tensor while still keeping the copy as a part of the computation graph it came from.

Let's see that in an example here

```python
X = torch.ones((28, 28), dtype=torch.float32, requires_grad=True)
y = X**2
z = X**2

result = (y+z).sum()

torchviz.make_dot(result).render('Attached', format='png')
```

![1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1603379723625/NmP78Zuam.png)

And now one with the detach.
```python
X = torch.ones((28, 28), dtype=torch.float32, requires_grad=True)
y = X**2
z = X.detach()**2

result = (y+z).sum()

torchviz.make_dot(result).render('Attached', format='png')
```

![Screen Shot 2020-10-22 at 8.48.43 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1603379927351/ZsGdLEa2U.png)

As you can see now that the branch of computation with `x**2` is no longer tracked. This is reflected in the gradient of the result which no longer records the contribution of this branch