Time Running Up

PyJWT - Generating Secret Key

import secrets
jwt_secret_key = secrets.token_hex(32)

423c984f59fff65efcbb055cdcac8f32162db4d8561b3007a6cb80703f86d702



Render - New default language versions

  • Node.js: 14.17.0 → 20.9.0
  • Ruby: 2.6.8 → 3.2.2
  • Elixir: 1.9.4 → 1.15.6
  • Python: 3.7.10 → 3.11.6

Serverless Commands

sls create -t aws-nodejs -p myService
sls deploy
sls invoke -f hello

Ref: https://www.serverless.com/framework/docs/providers/aws/examples/hello-world/node/

sls create -t aws-python3 -p myService
sls deploy
sls invoke -f hello

Ref: https://www.serverless.com/framework/docs/providers/aws/examples/hello-world/python/

sls info
sls remove

FrontEnd Interview Question

qPortal API development - Developers survey



Redux Toolkit Demo

npm install --save redux react-redux @reduxjs/toolkit

store/index.js:
import { configureStore } from '@reduxjs/toolkit';

import counterReducer from './counter';
import authReducer from './auth';

const store = configureStore({
  reducer: { counter: counterReducer, auth: authReducer },
});

export default store;
store/counter.js:
import { createSlice } from '@reduxjs/toolkit';

const initialCounterState = { counter: 0, showCounter: true };

const counterSlice = createSlice({
  name: 'counter',
  initialState: initialCounterState,
  reducers: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    },
    increase(state, action) {
      state.counter = state.counter + action.payload;
    },
    toggleCounter(state) {
      state.showCounter = !state.showCounter;
    },
  },
});

export const counterActions = counterSlice.actions;

export default counterSlice.reducer;
Component:
import { useSelector, useDispatch } from 'react-redux';

import { counterActions } from '../store/counter';

const Counter = () => {
  const dispatch = useDispatch();
  const counter = useSelector((state) => state.counter.counter);
  const show = useSelector((state) => state.counter.showCounter);

  const incrementHandler = () => {
    dispatch(counterActions.increment());
  };

  const increaseHandler = () => {
    dispatch(counterActions.increase(10)); // { type: SOME_UNIQUE_IDENTIFIER, payload: 10 }
  };

  const decrementHandler = () => {
    dispatch(counterActions.decrement());
  };

  const toggleCounterHandler = () => {
    dispatch(counterActions.toggleCounter());
  };

  return (
    <main className={classes.counter}>
      <h1>Redux Counter</h1>
      {show && <div className={classes.value}>{counter}</div>}
      <div>
        <button onClick={incrementHandler}>Increment</button>
        <button onClick={increaseHandler}>Increase by 10</button>
        <button onClick={decrementHandler}>Decrement</button>
      </div>
      <button onClick={toggleCounterHandler}>Toggle Counter</button>
    </main>
  );
};

export default Counter;
index.js:
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './store/index';

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

React Redux Demo

npm install --save redux react-redux

store/index.js:
import { createStore } from 'redux';

const initialState = { counter: 0, showCounter: true };

const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'increment':
      return {
        ...state,
        counter: state.counter + 1
      }
    case 'increase':
      return {
        ...state,
        counter: state.counter + action.amount
      }
    case 'decrement':
      return {
        ...state,
        counter: state.counter - 1
      }
    case 'toggle':
      return {
        ...state,
        showCounter: !state.showCounter
      }
    default:
      return state;
  }
};

const store = createStore(counterReducer);

export default store;
Component:
import { useSelector, useDispatch } from 'react-redux';

const Counter = () => {
  const dispatch = useDispatch();
  const counter = useSelector((state) => state.counter);
  const show = useSelector((state) => state.showCounter);

  const incrementHandler = () => {
    dispatch({ type: 'increment' });
  };

  const increaseHandler = () => {
    dispatch({ type: 'increase', amount: 10 });
  };

  const decrementHandler = () => {
    dispatch({ type: 'decrement' });
  };

  const toggleCounterHandler = () => {
    dispatch({ type: 'toggle' });
  };

  return (
    <main className={classes.counter}>
      <h1>Redux Counter</h1>
      {show && <div className={classes.value}>{counter}</div>}
      <div>
        <button onClick={incrementHandler}>Increment</button>
        <button onClick={increaseHandler}>Increase by 10</button>
        <button onClick={decrementHandler}>Decrement</button>
      </div>
      <button onClick={toggleCounterHandler}>Toggle Counter</button>
    </main>
  );
};

export default Counter;
index.js:
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './store/index';

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

Shallow vs Deep Cloning

// shallow clone/copy:
let arr2 = [].concat(arr1);
let arr3 = [...arr1];
let obj2 = Object.assign({}, obj1); 
let obj3 = {...obj1};

// deep clone/copy
let obj2 = JSON.parse(JSON.stringify(obj1)); // old approach
let obj3 = structuredClone(obj1); // new approach

Github Actions

  1. Mkdir .github/workflows in repo
  2. Create below secrets in Repo Settings
    AWS_ACCESS_KEY_ID
    AWS_SECRET_ACCESS_KEY
    AWS_REGION
    BUCKET_NAME
  3. Below is sample workflow for vue project. Add it in .github/workflows/buid-and-deploy-to-s3.yml
name: build-and-deploy-to-s3
on:
  push:
    branches:
      - master
jobs:
  build-and-deploy-to-s3:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Git Repo
        uses: actions/checkout@v4

      - name: Install Node
        uses: actions/setup-node@v4

      - name: Install Dependencies
        run: npm install

      - name: Build Website
        run: npm run build

      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_REGION }}

      - name: Delete js assets
        run: rm -rf ./dist/js

      - name: Deploy static site to S3 bucket
        run: aws s3 sync ./dist/ s3://${{ secrets.BUCKET_NAME }} --delete --no-progress

Equality Tables

== (negated: !=)

When using two equals signs for JavaScript equality testing, some funky conversions take place.

{{ keys[index1] }}
 
{{key}}

=== (negated: !==)

When using three equals signs for JavaScript equality testing, everything is as is. Nothing gets converted before being evaluated.

{{ keys[index1] }}
 
{{key}}

A standard IF statement. If(value) {/*- green -*/} else { /*- white -*/ }

Note: This row does not match up with any of the rows in the other table.

{{ key }}
 
if ({{ key }}) { /* {{ values1[index] ? 'executes' : 'does not execute' }} */ }



RedisLabs Free Plan

The Free plan lets you run a single non-highly available Redis database with up to 30MB and 30 connections, forever (or as long as you use it)! It lets you run Redis Enterprise Cloud in a selected region across all three major public clouds (Amazon Web Services, Microsoft Azure, and Google Cloud). You can use  all available Redis modules: RediSearch, RedisJSON, RedisGraph, RedisTimeSeries, and RedisBloom. Best of all, it’s totally free, no credit card required. 

 

https://redis.com/blog/new-pricing-for-redis-enterprise-cloud/

 

 

How to pick JS Frameworks?



Start time: 01:05
End time: 02:50

Markdown Editor

How to Setup Password Authentication For AWS EC2 Instances

  1. Log in to the server using ssh client of your choice using the private key.

ssh -i your-key.pem username@(public-ip-address)

  1. Open the sshd_config file.

sudo vi /etc/ssh/sshd_config

  1. Find the line containing “PasswordAuthentication” parameter and change its value from “no” to “yes“

PasswordAuthentication yes

  1. Setup ec2 user password using the “passwd” command.

sudo passwd ubuntu

  1. Now, restart the “sshd” service using the following command.

sudo service sshd restart

  1. Now you can log out and log in using the password you set for the user. For example,

ssh ubuntu@35.162.225.240

Heroku vs Render

 HerokuRender
Sleeps after 30 minutes of inactivity15 minutes of inactivity
Free Tier550 dyno hours/month750 hours of running time
No of apps/services in free tier5no limitations

Angular Lifecycle Hooks

Vue Lifecycle Hooks

Navigation Guard in Vue

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !store.getters.isAuthenticated) {
    next("/login'):
  } else if (to.meta.requiresUnauth && store.getters.isAuthenticated) {
    next("/home");
  } else {
    next():
  }
});

Firebase Rtdb Rules Example

{
    "rules": {
        "coaches": {
            ".read": true,
            ".write": "auth != null"
        },
        "requests" : {
            "•read": "auth != null",
            ".write": true
        }
    }
}

Setting up Drupal 9

Create a project:

$ composer create-project drupal/recommended-project:9.3.1 my_site_name_dir
 

This will create a project in 'my_site_name_dir' and automatically executes composer install to download the latest stable version of Drupal and all its dependencies.

Your 'my_site_name_dir' will contain files that should be outside of your web root and not  accessible by the web server. The web root will be 'my_site_name_dir/web'.

Install Php Filter:

$ composer require.  drupal/php
 

Alternate Installation:

Clone the below repo

https://github.com/apfromiit/drupal9

and run $ composer install

 

Add File Permissions:

$ sudo chmod +777 web/sites/default/files

Copy default.settings.php to settings.php

$ sudo chmod +777 web/sites/default/settings.php
 

Open in browser to complete the setup.

 

Remove File Permissions:

$ sudo chmod 755 web/sites/default/settings.php

 

Add new item to Main Navigation Menu:

Step 1: Create a tagname in Taxonomy:

 

1. Goto Manage → Structure → Taxonomy → VOCABULARY NAME: Tags →

 

 

2. Click

 

 

3. Enter tagname and click

 

 

 

Step 2: Create a page view for new menu item:

 

1. Goto Manage → Structure → Views and click
2. Enter View name
3. Under VIEW SETTINGS, Enter as below.
Show: of type: tagged with: Sorted by:

 

 

4. Enter PAGE SETTINGS and Menu Link details as shown below and click

 

 

5. Click

 

Now, adding tags to article will render the article in corresponding page.

 

We can remove the unwanted blocks by deleting them on the context menu provided on top right corner of every blocks.

Redux Demo

npm install --save redux

import redux from 'redux';

const reducer = (state = { counter: 0 }, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return { counter: state.counter + 1 };
        case 'DECREMENT':
            return { counter: state.counter - 1 };
        default:
            return state;
    }
};

const subscriber = () => {
    const latestState = store.getState();
    console.log(latestState);
};

const store = redux.createStore(reducer);
store.subscribe(subscriber);

store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'DECREMENT' });
Output:
{ counter: 1 }
{ counter: 2 }
{ counter: 1 }
{ counter: 0 }

Git Commands


  • git status - list untracked/modified/deleted files
  • git diff - To show line by line uncommitted local code changes
  • git show - To show diff of last commit
  • git add <filename> - To add file to be commit
  • git rm <filename> - To remove deleted file from git tracking
  • git commit - To commit the changes in local branch
  • git commit --amend - To append changes to peviously made commit
  • git push origin <branchname> - To push commit to remote (github)
  • git push origin HEAD - To push current branch to remote (github)
  • git pull origin <branchname> - To pull latest commits from remote branch (github)
  • git branch - To see current branch
  • git checkout <branchname> - To switch to another branch
  • git checkout -b <branchname> - To create and switch to new branch
  • git branch -D <branchname> - To delete a branch locally
  • git reset --hard - To clear local changes
  • git reset --hard HEAD^ - To delete last commit
  • git revert <commit-id> - To revert commit
  • git rebase -i HEAD~5 - To squash last 5 commits into single commit
  • git rebase -i --root - To squash all commits into root commit


Http Status Codes

Angular 4: Use of base-href and deploy-url build options

I use Angular 4 at work for building a single page application. Today, I faced the problem where I had to use different base paths for router and static assets. Angular makes use of the base href to tell router how to compose navigation URLs. If your application exists at the root, then you can use / as the href value as shown below.

<base href="/">

I wanted to use /users as my application base for router and /public as base for my assets.

If you build the project the Angular project for the production environment using the default values you will get the following index.html generated.

ng build -prod
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>SampleNgApp</title>
    <base href="/">
    
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link href="styles.xxxx.bundle.css" rel="stylesheet"/>
  </head>
  <body>
    <app-root>Loading...</app-root>
  </body>
</html>

This generated page will not work as it router will use / as base for composing navigation URLs and static assets will be looked in the current directory.

To solve my problem, I used —-base-href and —-deploy-url options as shown below.

ng build -prod --base-href /users --deploy-url /public
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>SampleNgApp</title>
    <base href="/users">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link href="/public/styles.xxxx.bundle.css" rel="stylesheet"/>
  </head>
  <body>
    <app-root>Loading...</app-root>
  </body>
</html>

This way I solved my problem.

Temp Mail

Finding Dead Code

pip install vulture

vulture --ignore-decorators @app.route <path>

Code Prettify Demo

Embed Vue in Html

<script src="https://unpkg.com/vue@latest"></script>
<script src="https://unpkg.com/axios@latest"></script>

<div id="app">
  {{ message }}
</div>

<script>
App = {
  data() {
    return {
        message: "Hello world!"
    }
  }
}

Vue.createApp(App).mount('#app');
</script>

Heroku Static Website Hosting

How to deploy static website to Heroku?

  • git clone https://github.com/heroku/php-getting-started.git
  • Replace contents of web/ with your static website.
  • Replace contents of composer.json with {}
  • Remove composer.lock
  • Save changes and do git commit.
  • heroku login -i
  • heroku create <app-name>
  • git push heroku main
  • heroku open

CodeChef

Category Problems
Peer 13053
Beginner 434
Easy 1359
Medium 1057
Hard 469
Challenge 147
Total 16519

Fetch API

fetch(url)
.then(data => data.json())
.then(data => { console.log(data); })
.catch(error => alert(error));

Hash Functions

import hashlib

str2hash = "test"
result = hashlib.sha256(str2hash.encode()).hexdigest()
print("sha256", len(result), result)

str2hash = "test"
result = hashlib.md5(str2hash.encode()).hexdigest()
print("md5", len(result), result)

sha256 64 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
md5 32 098f6bcd4621d373cade4e832627b4f6

Assessment - Python - Mukesh

Recursive Function:

 

Solution:

 

Schedule jobs with crontab on macOS

Running scripts on your computer is great. Running them automatically is even greater. If you are on a Mac (or Linux), you can use our good friend crontab, which is a scheduling tool that will run jobs (scripts) at regular intervals.

crontab

You add a job to crontab by editing the job list. A job is specified in the following format (first line):

* * * * *  command to execute
│ │ │ │ │
│ │ │ │ └─── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
│ │ │ └──────── month (1 - 12)
│ │ └───────────── day of month (1 - 31)
│ └────────────────── hour (0 - 23)
└─────────────────────── min (0 - 59)

Example

Let's make an example job. I personally use cronjobs to make regular backups of my MySQL databases, so I will show how to set this up to run once a day.

My script is called backup.sh, and will dump my MySQL database to a zip file. We'll set it to run as a cronjob by editing the job list (with the nano editor):

env EDITOR=nano crontab -e

Now enter the following and press CTRL+O and CTRL+X to save and exit.

0 12 * * *  cd ~/my/backup/folder && ./backup.sh

This will execute the command every day at 12:00, which changes to the folder of the script and runs it. The double ampersand && allows you to specify multiple commands that will run after each other.

Notice that if your computer is shut down or sleeping at the time, the script will not run until the next day at the specified time.

To see a list of your active crontab jobs, use the following command:

crontab -l

Environment

You might get a weird "command not found" error when running your crontab jobs for the first time, even though the script works fine when you run it yourself. That's because crontab executes commands without any of the normal environment variables set up.

To fix this, you can add the PATH in the beginning of your script, so it knows how to find programs like mysqldump:

#!/bin/sh
PATH=/usr/local/bin:/usr/local/sbin:~/bin:/usr/bin:/bin:/usr/sbin:/sbin

Disable mail alerts

So after you've set up your scripts and everything is honky dory, you might notice that the Terminal suddenly have started sending you e-mails.

If being pen pals with your Terminal isn't your thing, you can disable this behavior by inserting this line at the very top of your crontab file:

MAILTO=""

Presto. Now your jobs will run silent.

Tips

Here's a few small snippets which might come in handy:

Description Script
Execute on workdays 1AM 0 1 * * 1-5 /bin/execute/this/script.sh
Execute every 10 minutes */10 * * * * /bin/execute/this/script.sh
Log output to file */10 * * * * /bin/execute/this/script.sh >> /var/log/script_output.log 2>&1

Deploy Json Server to Heroku

  1. Clone json-server-heroku repo
  2. Place json data in db.json and commit
  3. heroku login
  4. heroku create
  5. git push heroku master

Note: Changes to db are non persistent. Heroku free dyno would become idle if no api request for 30 minutes. Heroku loads original db on next cold start.

CSV to JSON

import pandas as pd

df = pd.read_csv("data.csv", low_memory=False)
df.to_json("data.json", orient="records")
print("Done")

How to set up virtual environment

Mac

  1. pip install virtualenv
  2. virtualenv -p python3.11 venv
  3. source venv/bin/activate

Windows

  1. pip install virtualenv
  2. virtualenv venv
  3. .\venv\Scripts\activate
PS: venv is <virtual env name>

{JSON} Placeholder

JSONPlaceholder is a free online REST API that you can use whenever you need some fake data. It can be in a README on GitHub, for a demo on CodeSandbox, in code examples on Stack Overflow, ...or simply to test things locally.

Resources

JSONPlaceholder comes with a set of 6 common resources:

/posts 100 posts
/comments 500 comments
/albums 100 albums
/photos 5000 photos
/todos 200 todos
/users 10 users

Note: resources have relations. For example: posts have many comments, albums have many photos, ... see guide for the full list.

Routes

All HTTP methods are supported. You can use http or https for your requests.

GET /posts
GET /posts/1
GET /posts/1/comments
GET /comments?postId=1
Ref: http://jsonplaceholder.typicode.com/


Flask Rest API

Firebase SDK

Requirements:

pip install firebase-admin
Goto Project Settings -> Service Accounts -> Click Generate new private key and save the file as credentials.json

Write to firebase RTDB:

import firebase_admin, json
from firebase_admin import credentials, db

cred = credentials.Certificate("credentials.json")
firebase_app = firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://<projectid>-default-rtdb.firebaseio.com'
})
with open("data.json") as json_file:
    data = json.load(json_file)
    ref = db.reference("sample_key")
    ref.set(data)
firebase_admin.delete_app(firebase_app)

Read from firebase RTDB:

import firebase_admin
from firebase_admin import credentials, db

cred = credentials.Certificate("credentials.json")
firebase_app = firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://<projectid>-default-rtdb.firebaseio.com'
})
ref = db.reference("sample_key")
data = ref.get()
firebase_admin.delete_app(firebase_app)

RTDB security rules:

{
  "rules": {
    ".read": false,
    ".write": false
  }
}

How to fix wkhtmltopdf in AWS Amazon Linux EC2 older version?

Error:

wkhtmltopdf: error while loading shared libraries: libpng15.so.15: cannot open shared object file: No such file or directory

Solution:

  1. wget https://sourceforge.net/projects/libpng/files/libpng15/older-releases/1.5.15/libpng-1.5.15.tar.gz/download -O libpng-1.5.15.tar.gz
  2. tar -zxvf libpng-1.5.15.tar.gz
  3. cd libpng-1.5.15
  4. sudo yum groupinstall -y "Development Tools"
  5. ./configure --prefix=/usr
  6. sudo make install
  7. sudo yum install -y libtiff
Ref: https://majestic.cloud/how-to-install-wkhtmltopdf-on-amazon-linux/

Error:

Kerning error in pdf document created

Solution:

  • sudo wget http://pastebin.com/raw.php?i=AmfYN3er -O /etc/fonts/conf.d/10-wkhtmltopdf.conf
Ref: https://www.jeremydaly.com/how-to-install-wkhtmltopdf-on-amazon-linux/

Picture Tag

<picture>
  <source media="(min-width: 650px)" srcset="img1.jpg">
  <source media="(min-width: 465px)" srcset="img2.jpg">
  <img src="img3.jpg">
</picture>

Monaco Editor

$ npm install ngx-monaco-editor@9 --save

Add below to assets in angular.json:
{
    "glob": "**/*",
    "input": "node_modules/ngx-monaco-editor/assets/monaco",
    "output": "./assets/monaco/"
}
app.module.ts:

import { MonacoEditorModule, NgxMonacoEditorConfig } from 'ngx-monaco-editor';

const defaultEditorConfig: NgxMonacoEditorConfig = {
  defaultOptions: {
    theme: 'vs-dark',
    automaticLayout: true,
    minimap: {
      enabled: false
    },
    scrollBeyondLastLine: false,
    scrollbar: {
      vertical: "hidden",
      horizontal: "hidden"
    }
  }
};
Add below to imports:
MonacoEditorModule.forRoot(defaultEditorConfig)
Typescript:
editorOptions = { language: 'python' };
Template:
<ngx-monaco-editor [options]="editorOptions" [(ngModel)]="html"></ngx-monaco-editor>

Granting Full Disk Access to cron

  1. Go to System Preferences > Security & Privacy > Privacy > Full Disk Access:

2. Click on the (+) icon to add an item to the list. Press command+shift+G to open the Go to Folder… dialog, type /usr/sbin/cron and press Enter:

3. Select the cron file and click Open:

That’s it!

ESLint

  • npm install eslint --save-dev
  • npx eslint --init
  • npx eslint yourfile.js

Reference: ESLint

Type Conversions in JS

Original
Value
Converted
to Number
Converted
to String
Converted
to Boolean
false 0 "false" false
true 1 "true" true
0 0 "0" false
1 1 "1" true
"0" 0 "0" true
"000" 0 "000" true
"1" 1 "1" true
NaN NaN "NaN" false
Infinity Infinity "Infinity" true
-Infinity -Infinity "-Infinity" true
"" 0 "" false
"20" 20 "20" true
"twenty" NaN "twenty" true
[ ] 0 "" true
[20] 20 "20" true
[10,20] NaN "10,20" true
["twenty"] NaN "twenty" true
["ten","twenty"] NaN "ten,twenty" true
function(){} NaN "function(){}" true
{ } NaN "[object Object]" true
null 0 "null" false
undefined NaN "undefined" false

Calculators

AWS EC2 vs Lambda hosting

EC2 - CodeStar Lambda - CodeStar Lambda - Chalice Lambda - Serverless Lambda - Zappa
Uses EC2 instances Uses AWS Lambda and API Gateway Uses S3, AWS Lambda and API Gateway
Can run in local environment Cannot run in local environment Can run in local environment Cannot run in local environment Can run in local environment
Cheapest config: Free tier - t2.micro - 1 vCPU - 1 GB Memory - 8 GB EBS Cheapest config: 128 MB Memory
Based on Servers installed in EC2. For Eg: Python Flask or Node Serverless. Based on lambda functions and layers Serverless. Based on lambda functions and layers. Uses Chalice micro framework Serverless. Based on lambda functions and layers. Uses Serverless framework Serverless. Based on lambda functions and layers. Uses Zappa micro framework
Supports Python, Nodejs, etc Supports Python Supports Python, Nodejs, etc Supports Python
Supports Flask and Flask-Restful No support for Flask Flask like routing No support for Flask. Supports Flask. Seems not supporting Flask-Restful
Flask file structure No specific file structure Multi file structure using blueprints Single file structure
1 EC2 + 1 Code Pipeline 1 Lambda Function + 1 Code Pipeline 1 Lambda Function 1 Lambda Function for each route 1 Lambda Function
t2.micro: 1GB Default Memory: 128MB Default Memory: 128MB Default Memory: 1024MB Default Memory: 512MB
Dependency added using pip and build scripts Dependency added using pip and lambda layers Dependency added using requirements.txt and lambda layers Dependency added using yml Dependency added using virtual env
Available when EC2 is on 24x7
Dynamic IP or URL.
Static IP is billed.
No dynamic IP or URL.
Free Static URL.
750 EC2 hours/month free.
30 GB EBS free.
1 Million request/month free.
3.2 Million exec seconds/month free.
Free tier for 1 year. Lambda: Free tier for ever.
API Gateway: Free tier for 1 year.
Suitable for complex REST based Web Services and Web Apps. Suitable for simple web services and static Web Apps.
Best for demo or hobby use.
Not suitable for apis with low level dependencies.
No limitation on api execution time Lambda time limit: 15 minutes
API Gateway time limit: 30 seconds
Runs over http Runs over https
Restful APIs. Flask routing. Functions mapped as APIs Restful APIs. Flask like routing. Restful APIs. Routing in yml Restful APIs. Flask routing
Trivial stand alone APIs are not recommened. Advanced or complex or low level implementations are not recommended.

Web Scraping

Commands:
$ pip install scrapy
$ pip install autopep8
$ pip install ipython
$ scrapy shell
$ scrapy startproject worldometers
$ cd worldometers
$ scrapy genspider countries www.worldometers.info/world-population/population-by-country
# Modify spider
$ scrapy crawl countries

$ scrapy shell
> url = "https://www.worldometers.info/world-population/population-by-country"
> r = scrapy.Request(url)
> fetch(r)
> view(response)
> title = response.xpath('//h1/text()').get()
> countries = response.xpath('//td/a/text()').getall()
> title = response.css('h1::text').get()
> countries = response.css('td a::text').getall()

Code Prettify Snippets

declare const PR: any;

ngAfterViewChecked() {
    PR.prettyPrint();
}
Styles:
li.L0, li.L1, li.L2, li.L3,
li.L5, li.L6, li.L7, li.L8 {
    list-style-type: decimal !important;
}

pre.prettyprint {
    border-radius: 0;
    white-space: pre;
}
Template:
<pre class="prettyprint linenums lang-cpp">
...
Place the code here
...
</pre>

How to create lambda layers?

Example: Create requests layer

$ mkdir python
$ cd python
$ pip install requests -t .
$ cd ..
$ zip -r python.zip python

Rename the zip file to requests.zip
Create a lambda layer by uploading this zip file.

How to add labels in repo for Issue Tracker?

  • pip install labels
  • labels -u <username> -t <token> fetch -o <owner> -r <repo>
  • labels -u <username> -t <token> sync -o <owner> -r <repo> -f <path/to/labels.toml>

Reference: https://github.com/apfromiit/labels

LocalTunnel

$ npm install -g localtunnel
$ lt --port <port> --subdomain <subdomain>

Example:
$ lt --port 8000 --subdomain apdesk

Sample output url: https://apdesk.loca.lt

Reference: https://github.com/localtunnel/localtunnel

How to run commands at machine startup?

OS: Amazon Linux
Add your commands in /etc/rc.local

Where to check for AWS CodeStar deployment logs in EC2?

/opt/codedeploy-agent/deployment-root/deployment-group-ID/deployment-ID/logs/scripts.log

How to fix broken pip?

python -m pip install --upgrade pip
pip install -r requirements.txt

Angular Commands

> sudo npm install -g @angular/cli[@latest]

> ng new <project_name>

> ng serve [--port <port>]

> ng test

> ng build --prod

> ng g c <component_name>

> npm install --save bootstrap@3

Some good themes

Some good looking themes

  1. bluegrasshopper ✅
  2. bold ✅
  3. bootstrap
  4. bootstrap2
  5. bootstrap2-dark ✅
  6. brownstone
  7. Flex ✅
  8. foundation-default-colors ✅
  9. franticworld
  10. fresh
  11. gum
  12. Just-Read
  13. lannisport ✅
  14. martyalchin
  15. materialistic
  16. mediumfox
  17. mg
  18. monospace
  19. nice-blog
  20. nmnlist ✅
  21. Nuja
  22. octopress ✅
  23. pelican-b-side
  24. pelican-cait
  25. pelican-twitchy ✅
  26. plumage
  27. relapse
  28. semantic-ui
  29. sneakyidea ✅
  30. subtle
  31. svbhack
  32. tuxlite_tbs
  33. w3-personal-blog

Population Chart

Loading...

Top most populated countries

Loading...