teleren/devto huggingface dataset:
Today I Learned: Min-Max Stack
Tags: python, algorithms, beginners, webdev
Published: 2020-09-06 13:15:42

# Problem Statement
Write a MinMaxStack class for a Min-Max Stack with these features: 
* Push & pop values from the stack. 
* Peek value at the top of the stack. 
* Get the current min and max value of the stack in constant time. 

# Sample Input & Output

```
stack = MinMaxStack()
stack.push(5) # min: 5, max: 5, current value: 5
stack.push(7) # min: 5, max: 7, current value: 7
stack.push(2) # min: 2, max: 7, current value: 2
stack.pop(2) 
stack.pop(7) # min: 5, max: 5, current value: 5
```

# Code #1

```python
class MinMaxStack:
    def __init__(self):
        self.stack = []

    def peek(self):
        if len(self.stack) == 0:
            return None
        else:
            return self.stack[len(self.stack) - 1]['value']

    def pop(self):
        if len(self.stack) == 0:
            return None
        else:
            return self.stack.pop()['value']

    def push(self, number):
        self.stack.append(
            {
                'value': number,
                'min': self._calc_min(number),
                'max': self._calc_max(number)
            }
        )

    def get_min(self):
        if len(self.stack) == 0:
            return None
        else:
            return self.stack[len(self.stack) - 1]['min']

    def get_max(self):
        if len(self.stack) == 0:
            return None
        else:
            return self.stack[len(self.stack) - 1]['max']

    def _calc_min(self, number):
        if len(self.stack) == 0:
            return number
        elif number < self.stack[len(self.stack) - 1]['min']:
            return number
        else:
            return self.stack[len(self.stack) - 1]['min']

    def _calc_max(self, number):
        if len(self.stack) == 0:
            return number
        elif number > self.stack[len(self.stack) - 1]['max']:
            return number
        else:
            return self.stack[len(self.stack) - 1]['max']


```

# Notes
* Store current, min, and max value state during pop and push. 

# Credits
* Algoexpert for the problem statement. 
* Lidya Nada for the cover image (https://unsplash.com/photos/BnzqQwerUOY).
Today I Learned: Longest Palindromic Substring
Tags: python, algorithms, webdev, beginners
Published: 2020-09-06 13:13:35

# Problem Statement
Write a function that takes in a string, and returns its longest palindromic substring. 

# Sample Input
```
string = "qazaasdffdsaawsx"
```

# Sample Result

```
"aasdffdsaa"
```

# Code #1

```python
def longest_palindromic_substring(string):
    cur_longest = [0, 1]
    for idx in range(1, len(string)):
        odd = get_longest_palindrome(string, idx - 1, idx + 1)
        even = get_longest_palindrome(string, idx - 1, idx)
        longest = max(odd, even, key=lambda x: x[1] - x[0])
        cur_longest = max(longest, cur_longest, key=lambda x: x[1] - x[0])
    return string[cur_longest[0]:cur_longest[1]]


def get_longest_palindrome(string, idx_l, idx_r):
    while idx_l > -1 and idx_r < len(string):
        if string[idx_l] != string[idx_r]:
            break
        idx_l -= 1
        idx_r += 1
    return [idx_l + 1, idx_r]

```

# Notes
* Imagine the palindrome problem as seeing the substring in a mirror. 
* The mirror could lie in between the character ("abba") or on a character itself("aba"). 
* Naive approach: generate all possible combination of substring from length 2 to length of string, then apply check_palindrome function. 

# Credits
* Algoexpert for the problem statement. 
* Suhyeon-Choi for the cover image (https://unsplash.com/photos/ZUS1xCxoQCA).
Today I Learned: Permutations
Tags: python, webdev, beginners, algorithms
Published: 2020-09-06 13:11:42

# Problem Statement
Write a function that takes in an array of unique integers and then returns an array of all unordered permutations. 

# Sample Input
```
array = [1, 2, 3]
```

# Sample Result

```
[
    [1, 2, 3],
    [1, 3, 2],
    [2, 1, 3],
    [2, 3, 1],
    [3, 1, 2],
    [3, 2, 1]
]
```

# Code #1

```python
def get_permutations(array):
    permutations = []
    helper(0, array, permutations)
    return permutations


def helper(i, array, permutations):
    if i == len(array) - 1:
        permutations.append(list(array))
    else:
        for j in range(i, len(array)):
            swap(array, i, j)
            helper(i + 1, array, permutations)
            swap(array, i, j)


def swap(array, i, j):
    array[i], array[j] = array[j], array[i]

```

# Notes
* Assumption: if the input array is empty, return empty array. 
* Try thinking of permutations as a graph. 
* TODO: try the iterative approach. 

# Credits
* Algoexpert for the problem statement. 
* Jean-Louis Paulin for the cover image (https://unsplash.com/photos/lHwmE58fW4Y).
Today I Learned: Invert Binary Tree
Tags: python, webdev, beginners, algorithms
Published: 2020-09-06 13:10:15

# Problem Statement
Write a function that takes in a binary tree and inverts it. 

# Sample Input
```
tree =      1
          /   \
        2       3
      /   \   /   \
     4    5  6     7
   /   \
  8     9
```

# Sample Result

```
tree =      1
          /   \
        3       2
      /   \   /   \
     7    6  5     4
                 /   \
                9     8
```

# Code #1

```python
def invert_binary_tree(tree):
    queue = [tree]
    while len(queue) > 0:
        cur_node = queue.pop(0)
        if cur_node is not None: 
            cur_node.left, cur_node.right = cur_node.right, cur_node.left
            queue.append(cur_node.left)
            queue.append(cur_node.right)
    return tree


# This is the class of the input binary tree.
class BinaryTree:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None
```

# Notes
* Invert the root node of the tree first. 
* Invert = swap the left child with the right child. 
* Continue swapping the childs of the subsequent node. 
* Perform breadth-first traversal. 
* Utilize queue to perform the traversal iteratively. 

# Credits
* Algoexpert for the problem statement. 
* Tomas Robertson for the cover image (https://unsplash.com/photos/wAKld_0lcmA).
Today I Learned: Breadth-First Search on a Tree
Tags: python, beginners, webdev, algorithms
Published: 2020-09-06 13:09:29

# Problem Statement
Implement breadth-first search method on a tree node. 

# Sample Input
```
tree =      A
        /   |   \
       B    C     D
     /   \      /   \
    E     F    G     H
        /   \   \
       I     J    K
```

# Sample Result

```
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"]
```

# Code #1

```python
class Node:
    def __init__(self, name):
        self.children = []
        self.name = name

    def add_child(self, name):
        self.children.append(Node(name))
        return self

    def breadth_first_search(self, array):
        # Write your code here.
        queue = [self]

        while len(queue) > 0:
            cur_node = queue.pop(0)
            for child in cur_node.children:
                queue.append(child)
            array.append(cur_node.name)

        return array

```

# Notes
* Traverse the tree level-by-level. 
* Utilize queue to perform the traversal iteratively. 

# Credits
* Algoexpert for the problem statement. 
* Tomas Robertson for the cover image (https://unsplash.com/photos/wAKld_0lcmA).
Preparing cfssl and Docker in EC2 Instance
Tags: aws, go, git, docker
Published: 2020-09-06 12:33:49

First, install `git` in your ec2 instance.

```
// press y when asked
$ sudo yum install git
$ git version
git version 2.23.3
```

Go to your `./ssh` directory and add your github account.

```
// type Enter for all the questions
~/.ssh $ ssh-keygen -t rsa -C "my-mailaddress-for-git@mail.com"

~/.ssh $ sudo chmod 600 id_rsa

~/.ssh $ cat id_rsa.pub
// copy the contents and add a new ssh key on github
```

You are ready to go when you have the following message.

```
$ ssh -T git@github.com
Hi xxxx! You've successfully authenticated, but GitHub does not provide shell access.
```

Next, we will have to install golang onto your EC2 instance. `-y` command stands for `assume y if prompted`

```
$ sudo yum install -y golang

// after installed
$ go version
go version go1.13.14 linux/amd64
```

We will need to add the go path.

```
// add path
$ vi ~/.bash_profile
// inside .bash_profile

export GOPATH=$HOME/.go
export PATH=$HOME/.go/bin:$PATH

// Exit, and source it
$ source ~/.bash_profile
```

From now, you could follow the instructions in the readme to install cfssl with more information: [cfssl readme](https://github.com/cloudflare/cfssl)

```
$ git clone git@github.com:cloudflare/cfssl.git
$ cd cfssl
$ make
```

Now we will build the cfssl. Make sure NOT to build in the cfssl repository that you cloned. It will take about a minute to build.

```
$ go get -u github.com/cloudflare/cfssl/cmd/cfssl
$ cfssl version
Version: dev
Runtime: go1.13.14
```

We will also install `cfssljson` just in case. This also takes about a minute to build.

```
$ go get -u github.com/cloudflare/cfssl/cmd/cfssljson
```

Finally, let's get Docker installed onto your EC2 instance.

```
$ sudo yum install -y docker

$ grep -i docker /etc/group
docker:x:990:

$ sudo gpasswd -a ec2-user docker # Use your own username for 'ec2-user'
Adding user username to group docker

$ grep -i docker /etc/group
docker:x:990:username

$ sudo service docker start
```

Logout first, and login back again. You should be able to use docker now. As for docker-compose, use the following commands.

```
$ sudo curl -L "https://github.com/docker/compose/releases/download/1.26.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
$ sudo chmod +x /usr/local/bin/docker-compose
$ docker-compose --version
docker-compose version 1.26.2, build eefe0d31
docker-py version: 4.2.2
CPython version: 3.7.7

```
Where to find Data?
Tags: datascience, computerscience
Published: 2020-09-06 12:31:26

I am making this list to make it easier to find sources for publically available data sources which upcoming data scientists/data enthusiasts could play with.


## Generic datasets

* U.S Government's public data: [DATA.GOV](https://www.data.gov/)
* Indian Government's public data: [DATA.GOV.IN](https://data.gov.in/)
* Public data from World Bank: [World Bank](http://data.worldbank.org/)
* Data by the Reserve Bank of India: [RBI](https://rbi.org.in/Scripts/Statistics.aspx)
* Five Thirty Eight: [F38](https://github.com/fivethirtyeight/data)

## Large Datasets

* Amazon Web Services: [AWS](https://aws.amazon.com/datasets/)
* Google Datasets: [Google DS](https://cloud.google.com/bigquery/public-data/)
* Youtube: [YT labelled video datasets](https://research.google.com/youtube8m/)

## Predictive modelling and ML

* [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/index.php)
* [Kaggle](https://www.kaggle.com/datasets)
* Financial / economic data: [Quandl](https://www.quandl.com/)
* [Driven Data](https://www.drivendata.org/)

## Image classification

* Hand-written digits: [MNIST](http://yann.lecun.com/exdb/mnist/)
* Character recognition: [Chars74k](http://www.ee.surrey.ac.uk/CVSSP/demos/chars74k/)
* Face: [Frontal Face images](http://web.mit.edu/emeyers/www/face_databases.html)
* Generic: [ImageNet](http://image-net.org/)

## Sentiment analysis

* Twitter: [Twitter sentiment analysis](http://thinknook.com/twitter-sentiment-analysis-training-corpus-dataset-2012-09-22/)

## Miscellaneous 

* [MovieLens](http://grouplens.org/)
* [KDNuggets](http://www.kdnuggets.com/datasets/index.html)
* [Awesome Public Dataset](https://github.com/caesar0301/awesome-public-datasets)
* [Dataset Search by Google](https://datasetsearch.research.google.com/)

Hope this helped 💖
Everything is Replaceable
Tags: microservices, motivation
Published: 2020-09-06 07:56:53


![Everything is replaceable](https://lh3.googleusercontent.com/proxy/U5kSAlJt5NGZ6JKf4vKxjPd6JH4zLHoKE2lmAfRqZ-DKa_ouZelXwQdJPKakPVqrxyKbywP-mKFwScTZqK13qXR8FqyrS1AaVuJN-BJL003HwEstDXI1wJW58CvwjEOfr3fmlEldLw)
Many times we think that particular person is very important for organization or company and without him project can not go on as he has been working since long time and he knows everything.

That's just belief everyone has in mind

> ***Everyone is important and same time truth is Everyone is replaceable***

We often heard founders are fired from the company which they had built from start so Better everyone should keep in mind that they are replaceable as doing that will not hurt you when you get replaced.

> ***Everyone is important for certain period of time***

Sometimes person is very important for particular job, team or company till his work is over or when his replacement is found.

## What people do to avoid they don't get replaced ?

 - Hide the information they know.
 - Don't treat other people well being egoistic of knowing everything.
 - Hinder the growth of company and other employees around.
 - Don't grow themselves by keeping them to only what they know.
 - They don't put important information on paper to avoid being used by others instead they are tried to remember everything.

## How to make ourselves aware about this Truth ?

Just think that you won't be coming to office tomorrow due to you are sick or you left the job or whatsoever it may be.

What would happen to company, team or project ? who would be able to take it over and help the company or project ?

You should have proper plan put down from start and documented everything about tasks you are doing and decision you made like so that others can pick up where you left off. Information kept in your head will be forgotten one day and it does not benefit anyone.

This little practice helps lot to you and the organization.

 - As everything is documented, you don't need to explain other team members repeatedly.
 - Helps to grow yourselves so you can focus on other important things.
 - Keeps yourselves free from remembering everything.
 - Helps others to grow by delegating your duties to them.
 - Frees yourselves to take time off as other team member can take up your tasks.
 
 I have analogy to compare this with software architecture.

> ***Don't be like tightly coupled monolithic architecture but instead
> loosely coupled microservice architecture***

Rightly it has been said in [Karmyog](https://en.wikipedia.org/wiki/Karma_yoga) of Bhagvad Gita..


> ***"Do Karma but keep yourself free from Karma instead of tied to it"***
Different ways of state management in a react app
Tags: react, redux, javascript, beginners
Published: 2020-09-06 12:04:56

---
title: Different ways of state management in a react app
published: true
tags: react, redux, javascript, beginners
---

I was always confused by the various techniques of state management. so, I have decided to build an app using different state management techniques. I hope it will be easier for beginners to compare among those techniques and they will get a basic overview of them.

I build a todo list app using react-context-api, react-redux and redux-toolkit(recommended by redux)


[React-Context-Api](https://github.com/ashiqdev/React-Context-Todo-Application)

[React-Redux] (https://github.com/ashiqdev/React-Redux-Todo-Application/tree/react-redux)

[Redux-Toolkit] (https://github.com/ashiqdev/React-Redux-Todo-Application/tree/redux-toolkit)

Probably, from now on, I will use redux-toolkit in my side projects because it reduces lots of boilerplate code and with the help of the library called `immer`, it is possible to mutate the state directly. `immer` will make the code immutable under the hood.

For example, in traditional redux reducer in order to add an item to an array we have to do this:

```
return [...state, { id: uuid(), task: payload, completed: false }];
```

But, by using redux-toolkit we can mutate the array directly like this:

```
state.push({ id: uuid(), task: action.payload, completed: false });
```
Dog Fooded My Own Website EdgeNet
Tags: saas
Published: 2020-09-06 12:03:28

Bascially, EdgeNet is going to be a SAAS service that converts your website into a static one and deploys it on a world wide CDN automatically. It also detects content changes and automatically syncs it. I am developing this because I needed a way to increase the page speed for many of my websites but wanted to retain the control that a CRM gives me. Today I used EdgeNet on EdgeNet and no, there was no disturbance noticed in the space time continuum. All I got was a website on steroids, near instant page loads, world wide CDN and insane response time compared to the single AWS instance my CRM driven website is hosted on. Here is the original one where I update my content and here is the production one which automatically syncs with the original content.
MongoDB Index types and Properties
Tags: beginners, mongodb, tutorial, devops
Published: 2020-09-06 12:02:53


MongoDB indexes are used to improve the the performance of mongoDB read queries.
###Index Types
* _Single Field_ 

   Index created on a single field of mongoDB document.
 ```db.collection.createIndex({"scores" : 1})           ```

* _Compound Index_

   Index created on more than one field of mongoDB  document.
 ```db.collection.createIndex({"scores" : 1 , "rank" : 1})```

* _Multi Key Index_

   MongoDB uses Multi Key Index to create index on field containing array elements. MongoDB creates separate index entries for every element in array.
* _Hashed indexes_ 

   MongoDB indexes the hash of the field value.

* _Wildcard Indexes_

MongoDB uses these to create index entries on the dynamic field of collection.

###Index Properties

* _Unique Indexes_

Restricts users to create duplicate entries of document containing indexed field.

* _Partial Indexes_

Only index the document satisfying the expression provided.

* _Sparse Indexes_

Only create enteries for the document containing the indexed field.
 
* _TTL Indexes_

Automatically removes document from a collection.

* _Hidden Indexes_

Used to hide the existing indexes. User can validate the impact of dropping an index without actually dropping an index.
Hamster(Alpha) - Manage your JS projects in once place
Tags: node, angular, javascript, npm
Published: 2020-09-06 12:00:41

Hamster is a small app that you can use to run, manage and group together in once place.
To ensure safety, this app does not require any internet or any db installed on user's system. All is done local.

I have used Angular and Node as the primary tools for this electron app.

Hamster is free for all to use/fork/contribute.
More than happy to hear review/opinions and critics

 Github: https://github.com/hopemanryan/hamster
 Template made product page : https://hamster-app.com/

![0150f813-5501-49e8-bcf6-4f5746ec9bf9](https://dev-to-uploads.s3.amazonaws.com/i/n06p43b1nhig2sh1xlei.png)

![053422fe-dbea-4712-a104-ec0c7e4207c8](https://dev-to-uploads.s3.amazonaws.com/i/q22vox0zfk3rnmsrzgza.png)

![97db3545-2514-4139-8050-f423dccbb37b](https://dev-to-uploads.s3.amazonaws.com/i/ly25t0h9i2ril79nhyfq.png)
Daily Developer Jokes - Sunday, Sep 6, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-09-06 12:00:17

---
title: "Daily Developer Jokes - Sunday, Sep 6, 2020"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Sunday%2C%20Sep%206%2C%202020"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e12588f481d4.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ How many Prolog programmers does it take to change a lightbulb?

___A:___ Yes.
 -->
Dotfiles - Shared Config for ZSH and Bash
Tags: zsh, bash, configs, tutorial
Published: 2020-09-06 11:52:39

> How to setup a common shell config, to avoid duplicating content in `.bashrc` and `.zshrc`

I use **ZSH** as the default shell on macOS and **Bash** on Linux, I have to maintain a both `.zshrc` and `.bashrc` files. Some code in those is specific to the OS, but most of my logic can go in a shared file.

## File structure

So I created a `.commonrc`. That gets loaded by ZSH and Bash config files. And if I make a change to the common config, it gets applied in both shells.

Here is my setup:

- `.commonrc` - common content.
- `~.bashrc` - Bash-only content.
- `~.zshrc` - ZSH-only content.

## Common config

Here is my `.commonrc` file.

```sh
### Common RC ###

# Common content here...
```

The content in there is covered in [Part 2](https://dev.to/michaelcurrin/dotfiles-shell-config-5dnf) of this post series.

## Bash config

At the top of `.bashrc`:

```sh
### BASH RC ###

source ~/.commonrc

# Bash-specific content here.
# ...

# Shell prompt.
# username@hostname:path$
PS1="\[\e]0;\u@\h: \w\a\]\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "

# Remove ZSH default warning when using Bash on macOS.
export BASH_SILENCE_DEPRECATION_WARNING=1
```
I don't have much original content to share - most of my `.bashrc` is what came with standard Linux setup.


## ZSH config

Here is part of my `.zshrc` file:

```sh
### ZSH RC ###

IS_ZSH='true'
IS_BASH='false'

source ~/.commonrc

# ZSH-specific content
# ...
```

### ZSH prompt

Again, I've left most things there as the default, or you can comment values from the standard setup.

Here some ZSH-specific values around the prompt. I set this up so that prompt will be green if there are uncommitted changes. An exclamation mark `!` is added is there are changed files as a question mark `?` for new files which are untracked by git.

This prompt can save having to run git status all the time. Though you will have to press `Enter` with no content to get to a new shell line and so update the prompt.

```sh
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$fg[blue]%})%{$reset_color%} "

ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[green]%}!"
ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$fg[green]%}?"
ZSH_THEME_GIT_PROMPT_CLEAN=""
```

## Conclusion

I hope you found this post series useful and you can add some content to your your dotfiles to make your development smoother.

If you are interested, check out these links:

- [#dotfiles](https://dev.to/t/dotfiles) tag on _dev.to_.
- [#dotfiles](https://github.com/topics/dotfiles) topic on GitHub.

Image credit: [@bill_oxfor](https://unsplash.com/@bill_oxford) on Unsplash.
Day 36 of #100DaysOfCode: The differences between Redux-thunk and Redux-saga
Tags: react, redux, saga, webdev
Published: 2020-09-06 11:49:07


## Introduction
In redux, we always need middleware to help us to handle the asynchronous operations or other side effects.
The most popular middlewares are Redux-thunk and Redux-saga.

This topic notes the differences between Redux-thunk and Redux-saga for using. We will discuss the following items.
* Overview
* Roles and usages
* Libraries
* Implementations

## Details
Please refer to my article. 
https://medium.com/a-layman/redux-middleware-the-differences-between-redux-think-and-redux-saga-1e226f5a772a

## Articles
There are some of my articles. Feel free to check if you like! 
* My blog-posts for software developing: https://medium.com/a-layman
* My web resume: https://jenhsuan.github.io/ALayman/cover.html
* Facebook page: https://www.facebook.com/imalayman