teleren/devto huggingface dataset:
Mar. 13, 2020: What did you learn this week?
Tags: weeklylearn, discuss, weeklyretro
Published: 2020-03-13 07:02:19

Happy Pi Day one day early awesome community members!

It's that time of the week again. So wonderful devs, what did you learn this week? It could be programming tips, career advice etc.

![A comic sloth riding a flying book saying "Knowledge is powah!"](https://media.giphy.com/media/XZasQbAd9RGzy2rGhZ/giphy.gif)

Feel free to comment with what you learnt and/or reference your TIL post to give it some more exposure.

{%tag todayilearned %}

And remember, if something you learnt was a big win for you, then you know where to drop it as well.👇👇🏻👇🏼👇🏽👇🏾👇🏿

{% link https://dev.to/jess/what-was-your-win-this-week-2j5b %}

![A show host dancing a winning dance in their seat](https://media.giphy.com/media/l3q2Z6S6n38zjPswo/giphy.gif)
NodeJS/ReactJS: Change HOST AND Port Number
Tags: react, node, javascript
Published: 2020-03-13 06:50:57

 By default, a ReactJS/ NodeJS app runs on port 3000. An Express.js app also runs on the same port 3000. If you were to run the two apps simultaneously, there would be conflicts. You need to change the port of one of them.

In ReactJS, the easiest way to alter the port number is by setting an environment variable named PORT to the desired number via the terminal. As an example, here we change the port number to 5000. 

In Linux and Mac terminals, it would be

   $export PORT=5000
   $export HOST=IP ADDRESS


In Windows, the command is slightly different

   $env:PORT=5000
   $env:HOST=IP ADDRESS

Next if you run

   npm start

your local server will run on port 5000.
reactjs localhost port 5000

Modifying package.json

If your app is created via npx create-react-app, you will find the scripts property in your package.json file.

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}

It has the start key and its value needs to be prepended with PORT=N, where N is the assigned port number. If you wish to run your React app on port number 2000, modify your package.json file as follows:

"scripts": {
  "start": "HOST=IP ADDRESS PORT=2000 react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}

Now if you run npm start, the app will start on port 2000.

http://localhost:2000

Setting via .env

Port number can also be set as an environment variable. Create an .env file in the root directory of your project, i.e., in the same directory where the files .gitignore, package.json and README.md are located.

Environment variables declared in the .env file are consumed in ReactJS as any local variable. An environment variable is defined on process.env. If you define an environment variable named IMG_PATH, it will be available in your component as process.env.IMG_PATH.

If you need the app to run on some port, assign an environment variable named PORT to the desired port number. Here, the port is assigned to the number 4000.

PORT=4000
HOST=IP ADDRESS

reactjs env port number

Save the .env file and do

npm start

The app will run on port 4000 and New HOST.
Install Redis Cache Server on CentOS 7/6
Tags: centos, linux, redis
Published: 2020-03-13 06:41:54

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries.

Redis is an in-memory data structure store, used as a database server, cache, and message broker. It also provides a PHP module for communication between PHP script with the Redis server. Redis is written in C programming language.

This tutorial will help you with the installation of the Redis server along with PHP Redis PHP extensions on a CentOS 7/6 server.

Redis packages are not available under default yum repositories. You need to enable EPEL yum repository on your server first. Execute below command to enable:

### CentOS/RHEL 7 
    yum install epel-release

### CentOS/RHEL 6 
    rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

Install Redis Server

Now, You can use the yum package manager to install the Redis server on a VPS. Execute command to install Redis on your systems:

   yum install redis

After successfully installation start Redis service and enable auto-start on system reboot.

### CentOS/RHEL 7 
   systemctl enable redis
   systemctl start redis

### CentOS/RHEL 6 
  chkconfig redis on
  service redis restart

Centos 6 :

   chkconfig redis on

Centos 7 :
 
   systemctl enable redis

Install Redis PHP extension

We assume you already have PHP installed on your system.

cd /root
git clone https://github.com/phpredis/phpredis.git
cd phpredis
make clean
/opt/alt/phpVV/usr/bin/phpize 
./configure --with-php-config=/opt/alt/php70/usr/bin/php-config
make
make install

Replace red higlighted config with :

For php selector version :
php 5.6

/opt/alt/php56/usr/bin/phpize
./configure --with-php-config=/opt/alt/php56/usr/bin/php-config

php 7.0

/opt/alt/php70/usr/bin/phpize
./configure --with-php-config=/opt/alt/php70/usr/bin/php-config

php 7.1

/opt/alt/php71/usr/bin/phpize
./configure --with-php-config=/opt/alt/php71/usr/bin/php-config

php 7.2

/opt/alt/php72/usr/bin/phpize
./configure --with-php-config=/opt/alt/php72/usr/bin/php-config

Add this line to php.ini navigate to php selector >> Edit php.ini

(under the php version you installed redis php )

extension=redis.so

**if you’re using custom php.ini add this line to it also

 Test Connection to Redis Server

Use redis-cli tool to verify the connection between the Redis server and redis-cli.

redis-cli

127.0.0.1:6379> ping
PONG
127.0.0.1:6379>
Creating a simple PHP service in Docker
Tags: docker, php
Published: 2020-03-13 06:30:47

First of all, I assume that you have docker installed. There are plenty of tutorial for that. 

This is a tutorial to quickly create an image that serve a simple php service. 

# Folder structure
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1x9snoe4z00vc9nw8jq0.jpg)

The public folder is where I host index.php, which echo a h1. Nothing fancy here.

vhost.conf file contains the configuration for apache2 webserver that runs inside the container. You can put it anywhere, its location really doesn't matter. I put it there to copy it to the image easily.

The Dockerfile, which contains the instructions to build the image, which we will look into next.

# The Dockerfile instructions

```
FROM php:7.1.8-apache

COPY . /srv/app

COPY ./vhost.conf /etc/apache2/sites-available/000-default.conf

RUN chown -R www-data:www-data /srv/app \
    && a2enmod rewrite

```
This is a very simple image so there aren't many instructions. 
First, the FROM line tell docker to pull an already-made image called php:7.1.8-apache. 

This is probably an image with apache2 and php installed. 

The image I'm building inherits all the packages and software installed on the FROM image

Next, we COPY the current folder(.) to a location in the image which has the path /srv/app.

As you can see, the index.php in the container (when it is running) is /srv/app/public/html

The next COPY line copy the vhost configuration file for apache2. If you have worked with apache web server before, you'll know that by default, its settings for sites are stored at /etc/apach2/sites-available.

Finally, we RUN the command that grants rights for www-data (of the container) to the folder /srv/app (on the container) and enable mod rewrite (also, on the container).

# Build the image
Finally, in the same folder, run the following command to build the image
```
docker build -t simple-php .
```
Replace simple-php with any other name you like

You should get the message saying that image was built successfully.

# Run the image

```
docker run --rm -p 8080:80 simple-php
```

Finally, the above command run the image we have just create. 
Let's try viewing the service on the browser:

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

Congratulations! You have just built and run a docker image.
SQL Cursor via Context Manager
Tags: python
Published: 2020-03-13 06:16:50

## Automatically closing database connection with Context Manager

_Photo by [Taylor Vick](https://unsplash.com/@tvick?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/@tvick?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)_

If you don't know what a Context Manager is I recommend you to read about them. Dan Bader wrote a good article. But since you are here, why not read [my post](https://c-v-ya.github.io/blog/2019/11/04/why-context-manager-is-useful.html)?

Now, it's nothing special to write a cursor. You need a driver and credentials to connect to the database. In this example I'll use MySQL driver. My credentials are stored in `settings.py` (not in plain text but environment variables) as a dictionary.

First, we need to provide a driver and credentials to our cursor:

```python
import mysql.connector as connector

from settings import DATABASE

class Cursor:
    def __init__(self,
                 host=DATABASE.get('HOST'),
                 user=DATABASE.get('USER'),
                 password=DATABASE.get('PASSWORD'),
                 db_name=DATABASE.get('NAME'),
                 driver=connector,
        ):
        self.driver = driver
        self.connection = self.driver.connect(
                          host=host,
                          user=user,
                          password=password,
                          database=db_name
        )
        self.cursor = self.connection.cursor()
```

Now we need to provide methods of a Context Manager to our class:

```python
class Cursor:
    def __init__(...)
    def __enter__(self):
        return self.cursor
    def __exit__(self, ext_type, exc_value, traceback):
        self.cursor.close()
        if isinstance(exc_value, Exception):
            self.connection.rollback()
        else:
            self.connection.commit()
        self.connection.close()
```

And finally, we need to return something from the database, when it is needed:

```python
class Cursor:
    def __init__(...)
    def __iter__(self):
        for item in self.cursor:
            yield item
    def __enter__(...)
    def __exit__(...)
```

Done. Usage is a simple `with Cursor() as cursor:`

I've never bothered to simplify it via `@contextmanager` decorator because this implementation works perfectly fine for me. And I'm not sure if we can apply that decorator to a class.

I'd like to use ORM because it makes things so much easier and faster. But sometimes ORM is an overkill and you need to interact with DB manually.

Hope you find this helpful if you ever need to write a custom Cursor.
Why Context Manager is useful
Tags: python
Published: 2020-03-13 06:12:31

## How not to think about consequences when acquiring resources

_Photo by [Efe Yağız Soysal](https://unsplash.com/@efeyagizs?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/@efeyagizs?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)_

Imagine this: you automated some actions on a webpage via Selenium
and it works fine. But there are times when it might crash.
You don't want to `if` every single step that can go wrong.

Very graceful solution would be a Context Manager. You've already
used it when opened files. That `with open` is the Context Manager.
It tries to acquire a resource and closes it if something goes wrong,
releasing the given resource.

Let's get back to our example with Selenium. When it crashes browser
window doesn't close, leaving it hang until you close it. Would it be
awesome if that window would close if the program crashed?

There are couple ways to implement Context Manager in Python.
First is the class definition:

```python
from settings import web_driver

class ContextDriver:
    def __init__(self):
        self.driver = web_driver
        
    def __enter__(self):
        return self.driver
        
    def __exit__(self):
        self.driver.close()
```

The driver in the settings is a simple Firefox selenium web driver:

```python
from selenium import webdriver

web_driver = webdriver.Firefox()
```

And that's it! Now you can write `with ContextDriver() as driver`
and use that `driver` to perform automation. So if anything goes wrong
it will close the browser window.

Now, writing a class for such an easy task is redundant, in my opinion.
Luckily, in Python we have a useful decorator:

```python
from contextlib import contextmanager
from settings import web_driver

@contextmanager
def ContextDriver():
    try:
        yield web_driver
    finally:
        web_driver.close()
```

Neat, isn't it? In fact, I first wrote this Context Manager via decorator
when encountered this problem at work. And spent quiet some time rewriting
it as a class for this article. This doesn't mean you should know only
how to do it with decorator, even though it's much easier. There are times
when you will need a class and in one of the later articles I'll show that.

And there is one more way to define a Context Manager. Just import closing
and use `with closing(driver) as…` This works with everything that has
a `close()` method. But I'm not a big fan of this.

So now you know why and how to use a Context Manager! But just knowing
is not enough. Try it in your next project. Or even in your current one!
That way you will be confident that you can implement this wherever
it's suitable. Also, this is one of the topics technical interviewers
like to ask about.
Avoid multiple ElIf situation
Tags: python
Published: 2020-03-13 06:05:42

## Reducing code smelling with a help from first class citizens

_Photo by [Mae Mu](https://unsplash.com/@picoftasty?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/pancakes?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)_

Recently I've encountered a situation where `elif's` stacked on top of each other like pancakes. For example, we are parsing different file formats. Our parsers are ready and we just need a higher level interface.

```python
if file_format == 'xml':
    parse_xml(file_name)
elif file_format == 'csv':
    parse_csv(file_name)
elif file_format == 'json':
    parse_json(file_name)
else:
    parse_txt(file_name)
```

At first there were just `if` and `else`. Then things started to add up and I realized that multiple `elif's` was just a smelling piece of code.

To deal with that we can leverage a python concept that functions are first class citizens. Meaning we can return them or use them as a dictionary values. So we need to map our file formats with corresponding parsing functions:

```python
parsers = {
 'xml': parse_xml,
 'csv': parse_csv,
 'json': parse_json,
}
```

Notice that I did not include our default txt parser. It's like we rewrote 
`if` and `elif's` of our previous code. Now we need a function to return a parser for a given file format:

```python
def get_parser(file_format):
    return parsers.get(file_format, parse_txt)
```

This will return a parser function from our `parsers` dictionary for a given file format. Or, if `file_format` is not a key of that dictionary, default `parse_txt`. As an analogy before, it's like we rewrote the last `else` statement.

To use that we need to call `get_parser` function and we can also immediately execute it:

```python
get_parser('csv')(file_name)
```

But if you want to be more transparent, you can expand this to multiple lines:

```python
parser = get_parser('csv')
parser(file_name)
```

I think this code looks better than at the beginning of the article, although might not be obvious for everyone, so don't forget to place some comments :)

And I want to believe that it works a little faster because we're just getting a value from a dictionary instead of checking every single `if` case.
Getting values from a Python dictionary
Tags: python, beginners
Published: 2020-03-13 06:04:01

## How to get a value from a Python dictionary and not get punched by a KeyError

_Photo by [Sharon McCutcheon](https://unsplash.com/@sharonmccutcheon?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/donut?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)_

Let's say you have some dictionary with donuts:

```python
donuts = {'vanilla': 1, 'chocolate': 2}
```

What will happen if you get a value from this dictionary by slicing?

```python
donuts['vanilla']
1
```

But what if dictionary doesn't have such a key?

```python
donuts['blueberry']
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'blueberry'
```

A `KeyError` exception…

So, to gracefully get a value from a dictionary you might want to use a `get()` method:

```python
donuts.get('vanilla')
1

donuts.get('blueberry')
None
```

Even more, you can provide a default value, if that is what you need:

```python
donuts.get('blueberry', 0)
0
```

I'm not saying you should never use slicing when accessing dictionary values.
If you 100% sure the key is present then why not?
Otherwise use `get()`, it might save you a ton of time later.

And even more advanced topic would be `defaultdict` from the `collections` module. When you can assign a value to a key if that key doesn't exist.
I am applying for front end dev but the interview will have one hour of "scaling web app", what does it involve?
Tags: question, interview, discuss, scalability
Published: 2020-03-13 05:40:18

If I develop just the webpage or webapp (such as using React or Vue), how does "scaling" the webapp have to do with my job, unless if it is related to the back end? What should I learn or how should I learn more?

One other time I interviewed for a front end dev role and they asked me how to design the Google search server infrastructure.
Things i learnt from best programmers around me
Published: 2020-03-13 04:50:49

Don’t be a lazy. Do things the right way even if it’s a lot of work.

Don’t give up on something just because you’re stuck. You’ll figure it out eventually.

Always track down the root cause of a bug. If a bug just “goes away”, it hasn’t. If you can’t explain what fixed the bug, it isn’t.

Write unit tests. It may seem unnecessary and a like lot of work, but it will help you in the long run. 

Best practices are best practices for a reason. Don’t assume that your approach is better just because it’s what you’re used to.

Writing readable code is important.
The functions/methods you write should serve one specific goal and should be optimised.

Your code should be easily understandable by the other person.

There should be code reviewing so that you get to know where you're lagging behind, and if you review other's code you can learn from them.

No one knows everything so don't be shy to ask some help if you get stuck or you're having problem in understanding some scenario.

Copy paste will not work always.

Always be willing to learn new things, try to adapt them quickly.

If the code is repetitive try to separate it and make it a separate function.

Learn to debug your code, write test cases so that you should know the problem when testing team comes to you.

Use sonarlint or similar plugin to understand the flaws and violations in your code, using which you can improve your coding reliability.
constructor.name is not working in production
Tags: angular, typescript, javascript, tips
Published: 2020-03-13 04:47:52

---
title: constructor.name is not working in production
published: true
description: 
tags: #angular #typescript #javascript #tips
---

**In angular do not use constructor.name in production directly**. When 
__ng build --prod__ fires to create production build of Angular app at the same time many techniques applied to create minimum size of build and improve performance of application. At this process **webpack minifiere** converts class name to short name, and thus you can not get real class name by constructor.name in production rather we get **minified** name of class and that is different. So to solve this we have to save class name in class property when creating class instance. This way we can maintain our class name logic in production build.

**Below image is working fine in Development mode.**

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

**Below image is Working fine production mode. so we have changed our code for getting class name by setting up class proterties of class name.**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/m84hmnknahwl7ymwdzbf.png)
Changes In Django Open Source
Tags: python, django
Published: 2020-03-13 04:38:24

There have been around 50 "core" developers with full commit access and
decision-making power, and a Technical Board to act as a tie-breaker.
But this wasn't how the project actually worked -- most "core"
developers were inactive, and most decisions were made by consensus on
the django-developers mailing list or in the bug tracker. So we are
moving to a system that formally recognizes this, and officially
adopts a more open, consensus-based process that does away with the
special group of "core" developers. Since this is mostly just saying
officially that they'll do things the way they've been working, users of
Django probably will not notice any change :)

Official Announcement was made here https://www.djangoproject.com/weblog/2020/mar/12/governance/
Swift Lesson 19 Discussion
Published: 2020-03-13 04:31:10

<h1>Why should you consider using an enum over using a String or an Int to identify options?</h1>

<p>When you’re trying to define multiple values for one object, and make sure these values are assigned only to one thing, it’s cleaner, and faster than assigning an int, and a string to one thing. For example, if you’re trying to define a car you could use both ints and strings for it: name:string, year:int, make:string, cylinder:int, etc…</p>
COVID-19: How to stay productive when working from home?
Tags: webdev, productivity, career, workstations
Published: 2020-03-13 04:08:48

## Create an ergonomically fresh environment
- Don't work from the kitchen
- Don't work from the bed
- Invest in an ergonomic chair
  - [Stability Yoga Ball Ergonomic Chair](https://amzn.to/33goawE)
  - [Swivel Chair for Back Pain](https://amzn.to/33djh7r)
- Ideal height desk
- Clear your desk and open your windows for fresh air


## Create a "smart" setup
- Open windows for ample sunlight
- Use [smart bulbs](https://amzn.to/2U6vCGa) if your room is dark
- Invest in a nice mouse, keyboard, and headphones
- Use [extra monitors](https://amzn.to/38QD0L7) 


## Exercise
- In the morning before starting work
  - Do 10 minutes yoga 
  - Or 10 minutes run
- In the evening after work
  - Do 10 minutes of meditation

## Routines
- Create a TODO list for the next day every night 
  - Put top 3 things you MUST complete
- Take regular short breaks
- Prefer video calls over messages with your team


## Other tips
- Wear something that will make you feel fresh
  - Don't work in sweatpants and sweatshirts 
- Put mobile and social media aside
- Use [Pomodoro technique](https://en.wikipedia.org/wiki/Pomodoro_Technique)


---

I write about programming and personal finance, so click the **+FOLLOW** button if it interests you!