Cheatsheets


Angular


.gitignore

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
sendgrid.env

# parcel-bundler cache (https://parceljs.org/)
.cache

# next.js build output
.next

# nuxt.js build output
.nuxt

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless

# Mac Life
.DS_Store

Git

Log all commits:

$ git log

Log last commit:

$ git log -1

Log last commit + patch output:

$ git log -p -2

Create branch:

$ git pull
$ git checkout -b branch-name

Merge branch:

$ git checkout master
$ git merge branch-name
$ git commit -m
$ git push origin master

HELP!

Terminal stop command = control + C

Python exit (terminal) = control + D

VIM exit = Esc, :wq

Nano exit = control + X

Less exit = q

Posgres exit = \q


iTerm2

Window new = control + D

Configure PATH = open ~/.zshrc

Configure theme = open ~/ .zshrc


Java Setup

The Apache Tomcat® software is an open source implementation of the Java Servlet (.jsp files)

Or Maven or IntelliJ

export JAVAHOME=/Library/Java/JavaVirtualMachines/jdk1.8.0201.jdk/Contents/Home


Knex

Iterable objects and arrays are returned, but at some point how much you are grabbing will matter if you scale…so

All queries return an array of objects and can be Jshauned using res.json({data}).

Select:

Return all from table ‘users’.

knex.select().from('users')

OR

knex('users')

Match:

Return users that match an ‘id’.

knex.('users').where("id", id )

Contains:

From table ‘users’ return all where column ‘ListofItemsInString’ contains the string ‘foo’.

knex('users').where('listItemsInString', 'like', '%foo%')

Add:

Create user.

knex('users').insert(user,["Name", "Email", "Categories"])

Delete:

Delete user with matching id.

knex('users').where("id", id).del()

Update:

Update user.(takes two: id, body)

knex('users').where("id", id).update(body)

Return:

Return the result.

knex('users').where("id", id).update(body).returning(*)

If you can’t find the Knex query within 2 minutes, my advice is to look up the how to SQL the query, then control + F the Knex docs.


Mac Shortcuts

Browser Switch = command + shift + [ or ]

Browser Zoom = command + plus or minus

Display Screenshot = command + shift + 4

Display Switch = control + arrow left or right

Display Zoom = control + arrow up or down

File Search = command + option + space

File Select Muliple = shift + click

Program Force Quit = command + option + shift

Program Switch = command + tab + arrow left or right


Markdown

#Header1 ##Header2

*italics* **bold**

***horizontal line

*unordered list ⋅⋅*sub unordered list

1.ordered list ⋅⋅1.ordered list

⋅⋅⋅new paragraph

⋅⋅return = new line

[clickable word or ref](http:// or repo file ./)

<img href="http:// or repo file ./" width="" height="">

(```language(javascript) = opening code block)
code
(``` = closing code block)

<a href="http://www.youtube.com/watch?feature=player_embedded&v=YOUTUBE_VIDEO_ID_HERE" target="_blank"><img src="http://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg" alt="" width="" height="" border="" /></a>

column 1 | column 2 | column 3

--- | --- | ---

row 1 col 1 | row 1 col 2 | row 1 col 3


Mongodb Setup


Postgresql + Knex

$ createdb db-name  
$ take name-server  
$ git init  
$ npm init -y  
$ knex init  
$ npm i pg express knex morgan cors body-paser dotenv  
$ touch app.js queries.js .gitignore .env  
$ code .
  1. Edit json to include script to run node app.js

  2. Create server with Express:

    const express = require("express");
    const bodyParser = require("body-parser");
    const cors = require("cors");
    const app = express();
    const port = process.env.PORT || 4000;
    const queries = require("./queries.js");
    app.use(bodyParser.json());
    app.use(cors());
    app.listen(port, (req, res) => {
    console.log(`listening on ${port}`);
    });

    $ npm start

  3. Edit knexfile.js:

development: {
    client: "pg",
    connection: "postgresql://localhost/db-name"
  },

  production: {
    client: "pg",
    connection: process.env.DATABASE_URL
  }

$ knex migrate:make migration-name
$ knex seed:make seed-name

  1. Fill migration(s):

    return knex.schema.createTable("peppers", pepper => {
        pepper.increments("Id");
        pepper.text("Name");
        pepper.boolean("Capsaicin").notNullable().defaultTo(true)
        pepper.integer("Rating")
    });
    return knex.schema.dropTableIfExists("peppers")
  2. Fill seed(s)

$ knex migrate:latest
$ knex seed:run

  1. Edit queries.js:

    let connection = require('./knexfile')[process.env.NODE_ENV || 'development']
    let run = require('knex')(connection)
  2. Write queries:

    module.exports = {
    getById(id) {
    return knex
      .select()
      .from("classmates")
      .where("id", id);
    },
  3. Write routes:

    app.get("/", (request, response) => {
    //res.send('working')
    queries.list().then(result => response.json({ result }));
    });
    app.get("/:id", (req, res) => {
    queries.getById(req.params.id).then(data => res.json({ data }));
    });
    app.post("/", (req, res) => {
    queries.createStudent(req.body).then(data => res.json({ data }));
    });
    app.delete("/:id", (req, res) => {
    queries.deleteStudent(req.params.id).then(data => res.json({ data }));
    });
    app.put("/:id", (req, res) => {
    queries
    .updateStudent(req.params.id, req.body)
    .then(data => res.json({ data }));
    });
  4. Test routes with Postman
  5. Add error handling/auth
  6. Test routes with client
  7. Deploy, run migration, seeds

    $ npm i -g heroku
    $ heroku create database_name
    $ git remote -v // verify
    $ heroku addons:create heroku-postgresql:hobby-dev // add db setup
    $ heroku pg:info // get database name
    $ heroku pg:credentials:url <database_name_from_last_step> // get database url
    $ heroku info // get app name
    $ heroku config:set DATABASE_URL='<the_database_url_from_the_last_step>//postgres...' -a <app_name_from_last_step> // set heroku env variable
    $ git push heroku master
    $ heroku run knex migrate:latest
    $ heroku run knex seed:run
    $ heroku logs -t
  8. Test routes with client

Postgresql

Terminal

Download: brew install postgresql Check Version: postgres —version Upgrade:

Steps to install and run PostgreSQL 9.2 using Homebrew (Mac OS X) (if you aren’t using version 9.1.5, change line 6 with the correct version)

  1. launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
  2. mv /usr/local/var/postgres /usr/local/var/postgres91
  3. brew update
  4. brew upgrade postgresql
  5. initdb /usr/local/var/postgres -E utf8
  6. pg_upgrade -b /usr/local/Cellar/postgresql/9.1.5/bin -B /usr/local/Cellar/postgresql/9.2.0/bin -d /usr/local/var/postgres91 -D /usr/local/var/postgres
  7. cp /usr/local/Cellar/postgresql/9.2.0/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
  8. pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

Create DB: create db-name

Connect to PG: psql postgres
List All DB: \l
List All Users: \du

Connect to DB: psql db-name
List Tables of DB: \dt
Show All From Table: SELECT * FROM table-name;

Delete DB: DROP DATABASE db-name

Only the database owner can execute the DROP DATABASE statement. In addition, you cannot execute the DROP DATABASE statement if there is any active connection to the database. You have to connect to another database e.g., postgresqlto execute the DROP DATABASE statement.


Raspberry Pi

SSH Enter = ssh pi@raspberrypi.local

SSH Exit = control + D

SSH Unresponsive = Enter, ~

SSH Default Password = raspberry

Terminal Take Screenshot = scrot (-d 10(seconds to wait in delayed screenshot))

Terminal Copy/Paste = control + shift + C or V

VNC Terminal Thonny = thonny

Terminal Shutdown = sudo halt

Terminal Reboot = sudo reboot

Terminal Grep Port = ps aux | grep portname

Terminal Grep Program = ps -ef | grep program

Terminal Kill = sudo kill idnumber

ADAfruit

Commands: sudo systemctl {start,stop,restart} adafruit-webide Navigate to http://raspberrypi.local:8080 to use the WebIDE


React

Start up:

$ npx create-react-app my-app
$ cd my-app
$ npm start

Component lifecycle: Mount -> Update -> Unmount

Mounting methods:

constructor()
static getDerivedStateFromProps()
render()
componentDidMount()

State management:

  • Redux
  • local state
  • Relay
  • Context api
  • Hooks
  • Apollo
  • Mobx

Async calls:

state = {
    people: ''
    fetching: true
}

async componentDidMount() {
    const linksResponse = await fetch(`${baseURL}/api`)
    const linksJson = await LinksResponse.json()
    const peopleResponse = await fetch(LinksJson.peopleHref)
    const peopleJson = await peopleResponse.json()
    this.setState(PrevState => ({
        ...PrevState,
        people: normalize(peopleJson.people)
    }))

    Or 

    selectPerson = async (id) => {
        //set state.fetching = true
        //await fetch
        //set state.fetching = false
    }
}

{this.state.fetching ? this.spinner() : <div>this.state.people<div> }

VS Code Shortcuts

Terminal = control + backtick

Lines change multiple = control + D


Unix Commands

Directory Change = cd directory-name

Directory New = mkdir new-directory-name

Directory New + Change to = take new-directory name

Directory Home = cd

Directory Back One = cd..

Directory Back Two = cd…

Directory Path of Working Directory = pwd

Directory List Files = ls or echo *


¡Warning!

Directory Remove Verbose = rm -v

Directory Force Remove = rm -rf

¡Warning!


File Move = mv

File Copy = cp

File Open = open

File Run = program filename

File Read = cat

File Nano Open = nano filename

File Nano Close = control + X, Y to save

File Vim Open = vi filename

File Vim Close = Press Esc, :wq

File Filter = grep

File Input = echo input >


Redux


Spanish Letters

Las letras españolas

How to type Spanish accents, Spanish letters, and special characters.

Tildes:

Opt + e, then a = á

Opt + e, then e = é

Opt + e, then i = í

Opt + e, then o = ó

Opt + e, then u = ú

Eñe:

Opt + n, then n = ñ

Umlaut:

Opt + u, then u = ü

Signos de apertura:

Opt + 1 = ¡

Opt + shift + ? = ¿