ecallen

Programming

Phoenix

Plugs

module plugs must have two funcs: init, call


defmodule NothingPlug do
    def init(opts) do
        opts
    end
    def call(conn, _opts) do
        conn
    end
end

Golang


go get -u ./...

Python

Get methods

dir()

Get help

help()

identity - location in memory of an object

id() - location in memory

type()

mutable - dict,list

immutable - strings tuples, integers *reassignment changes identity

Dunder methods - Double UNDERscore methods “add” or magic methods

help(object.method)

File iterate through file

with open('somefile','r') as my_file:
    for line in my_file:
        print(line)

coerce booleans

ex.

bool(0) -> False

bool(4) -> True

singleton - one copy, example None


a = None
b = None
id(a)
id(b)

will be the same value

PEP8 prefer 4 spaces to indent code

define a list names = [‘Evee’,‘Harper’,‘Lily’,‘Linus’]

A for loop ccan have a else clause. Code in the else clause will execute if the for loop did not hit a break statement.

    
positive = False
for num in items:
    if num < 0:
        break
    else:
        postive = True
               

set default method


count = {}
for name in names:
    count.setdefault(name,0)
    count[name] += 1
    

def funcname(arg):
    body
               
stride
every_other_name[0:4:2]

Files
fin = open('etc/passwd')
for line in fin:
     print line
     
with open('/tmp/names.txt','w') as fout:
    fout.write('Evee\n')
    
Using file as seq
def add_numbers(filename):
    with open(filename) as fin:
        return add_nums_to_seq(fin)

def add_nums_to_seq(seq):
    results = []
    for num, line in enumerate(seq):
    enumerate(seq):
    results.append('{0}-{1}'.format(num,line))
    return results
               

Object - grouping together state and methods

Class - define objects

class Animal

generator example


xs = (x for x in range(4))
xs.__next__()

Introspection

objects store their type in their class attr

type()

issubclass()

isinstance()

dir()

hasattr(, ‘attr’)

getattr(, ‘attr’) or .’attr’ example a.denonminator

prefer EAFP easier to as for forgiveness

globals() - introspect the global namespace

globals()[foo] = ‘bar’ <– globals dict IS the global namespace

locals() - introspect the local namespace

f-strings - PEP 498, ex. f”{name}”

inspect module :wqa

Django

  • start a project

django-admin startproject myproject

  • run project

python manage.py runserver

  • create a app

python manage.py startapp

  • show migrations

python manage.py showmigrations

  • run all pending migrations

python manage.py migrate

  • create migrations based on models

python manage.py makemigrations

  • see a specific migration

python manage.py sqlmigrate

  • misc

python manage.py createsuperuser

Files

settings.py - INSTALLED_APPS[] list of apps

urls.py - routing

Tensorflow

rule of thumb: each layer powers of 2, decreasing

model performance/deal with over fitting:

use a dropout layer

    start with 20 - 30%

    will result in more epochs

make more data

    for image data

    ```python
    keras.preprocessing.image.ImageDataGenerator(....)
    ```

Data wrangling

example of loading train a test data sets from tf data sets:

mnist_train, info = tfds.load('mnist', split='train', as_supervised=True, with_info=True)

mnist_test = tfds.load('mnist', split='test', as_supervised=True)

use Keras to retrieve data:

tf.keras.utils.get_file(fn, url, cache_dir=cache_dir, cache_sub_dir=cache_subdir)

read csv using pandas:

import pandas as pd #<-- pd by convention
column_names = ['col1','col2'] # assuming first row in csv is not col names
some_dataframe = pd.read_csv(path_to_csv, name=column_names)

Models

example model layers:


new_model = tf.keras.models.Sequential([
    tf.keras.layers.InputLayer((None, 1)),
    tf.keras.layers.Conv1D(30,6,padding='casual', activation='relu'),
    tf.keras.layers.LSTM(68),
    tf.keras.layers.Dense(32, activation='relu'),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(1)
])

Oauth

https://www.oauth.com/

Used for integrating applictions with other services.

Important ! register redirect url’s immediately.

Redirection attack where a access token can be interpreted by an attacker.

Dont register multiple redirect url’s to compensate for starting from multiple states in the app. Instead use the state parameter.

React

https://scrimba.com/learn/learnreact

global var ReactDOM


ReactDOM.render(<h1>Hello</h1>, document.getElementById("root"))

Components

All React components must act like pure functions with respect to their props.

Pascal case component, not camel case

Wrap it in angle brackets in ReactDOM.render()

Components can have parent child relationship


function Navbar() {
    return (
       <div></div> 
    )
}

function MainContent() {
    return (
        <div></div>
    )
}

ReactDOM.render(
    <div>
        <Navbar />
        <MainContent />
    </div>,
    document.getElementById("root")
)

JSX

Like html with some differences.

html => JSX 

class => className

organization

create a react project


npx create-react-app hello

add a router


npm install react-router-dom@6

install material ui: https://mui.com/getting-started/installation/

Props

Use mustache syntax


import React from "react"
import ReactDOM from "react-dom"

function App() {
    const userName = "me"
    
    return (
        <h1>Hello {userName} !</h1>
    )
}

ReactDOM.render(<App />, document.getElementById("root"))

// Somewhat bogus example

export default function Contact(props) {
    return (
        <div className="contact-card">
            <img src={props.image}/>
            <h3>{props.name}</h3>
            <div className="info-group">
                <p>{props.phone}</p>
            </div>
            <div className="info-group">
                <img src="./images/mail-icon.png" />
                <p>{props.email}</p>
            </div>
        </div>
    )
}

function App() {
    return (
        <div className="contacts">
            <Contact 
                image="./images/mr-whiskerson.png" 
                name="Mr. Whiskerson"
                phone="(212) 555-1234"
                email="mr.whiskaz@catnap.meow"
            />
            <Contact 
                img="./images/fluffykins.png"
                name="Fluffykins"
                phone="(212) 555-2345"
                email="fluff@me.com"
            />
        </div>
    )
}

Props and arrays


// contrived example from scrimba

jokesData = [
    {
        setup: "I got my daughter a fridge for her birthday.",
        punchline: "I can't wait to see her face light up when she opens it."
    },
    {
        setup: "How did the hacker escape the police?",
        punchline: "He just ransomware!"
    }
]

export default function Joke(props) {
    return (
        <div>
            {props.setup && <h3>Setup: {props.setup}</h3>}
            <p>Punchline: {props.punchline}</p>
            <hr />
        </div>
    )
}

export default function App() {
    const jokeElements = jokesData.map(joke => {
        return <Joke setup={joke.setup} punchline={joke.punchline} />
    })
    return (
        <div>
            {jokeElements}
        </div>
    )
}

Events

Do not use the “()” for function call in the JSX


import React from "react"

export default function App() {
    function handleClick() {
        console.log("I was clicked!")
    }
    
    function handleOnMouseOver() {
        console.log("MouseOver")
    }
    
    return (
        <div className="container">
            <img 
                src="https://picsum.photos/640/360" 
                onMouseOver={handleOnMouseOver} 
            />
            <button onClick={handleClick}>Click me</button>
        </div>
    )
}

State

React.useState()


const [someval,setterFunc] = React.useState(someInitVal)

Converting a Function to a Class

You can convert a function component like Clock to a class in five steps:

1) Create an ES6 class, with the same name, that extends React.Component.

2) Add a single empty method to it called render().

3) Move the body of the function into the render() method.

4) Replace props with this.props in the render() body.

5) Delete the remaining empty function declaration.

(Lifecycle)[https://reactjs.org/docs/state-and-lifecycle.html]

In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.

We want to set up a timer whenever the Clock is rendered to the DOM for the first time. This is called “mounting” in React.

We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React.

useEffects

used for side effects ie API calls

react-three-fiber

https://github.com/pmndrs/react-three-fiber

https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene

Basics

scene -> camera -> renderer -> attach to canvas

geometry -> mesh -> scene.add()

frustum - A frustum is the name of a 3d shape that is like a pyramid with the tip sliced off. In other words think of the word “frustum” as another 3D shape like sphere, cube, prism, frustum.

mesh = geometry + material + orientation

Example set camera width to canvas


    function render(time) {
      time *= 0.001;
     
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
     
      ...

Create app

npx create-react-app my-app
cd my-app

Install dependencies

npm install three @react-three/fiber

npm install --save husky lint-staged prettier

Start

npm run start

Node.js

cheatsheet


## initialize minimum node project with a minimal package.json
npm init -y 

## install a package 
npm i <some package> 
npm i express 

JWT “jot”

https://datatracker.ietf.org/doc/html/rfc7519

https://www.bezkoder.com/jwt-json-web-token/

https://www.bezkoder.com/react-express-authentication-jwt/

https://blog.galmalachi.com/react-nodejs-and-jwt-authentication-the-right-way

https://jwt.io/introduction/

JWT is typically in header

x-access-token: [header].[payload].[signature]

Security

*** USE HTTPS ***

JWT does NOT secure your data. JWT does not hide, obscure, secure data at all.

The purpose of JWT is to prove that the data is generated by an authentic source.

So, what if there is a Man-in-the-middle attack that can get JWT, then decode user information? Yes, that is possible, so always make sure that your application has the HTTPS encryption.

Basic Flow

Browser Server 1) send login(usr,pw) =>
2) create JWT with secret 3) <= return JWT 4) send request with JWT in header => 5) validate JWT 6) <= return response

Storing JWT on the client side

  • Browser: Local Storage

  • IOS: Keychain

  • Android: SharedPreferences

JWT Token

  • Header

  • Payload

  • Signature

{
    "typ": "JWT",
    "alg": "HS256"
}

Payload

What is stored in the token

Standard fields

  • iss: issuer

  • iat: time issued

  • exp: expiration


{
  "userId": "some user",
  "username": "anon",
  "email": "anon@anon.io",
  // standard fields
  "iss": "zKoder, author of bezkoder.com",
  "iat": 1570238918,
  "exp": 1570238992
}

Signature


const data = Base64UrlEncode(header) + '.' + Base64UrlEncode(payload);

const hashedData = Hash(data, secret);

const signature = Base64UrlEncode(hashedData);

JWT + Node + Express + MySQL

https://www.bezkoder.com/node-js-jwt-authentication-mysql/

Signup and Login flow

User Registration

POST api/auth/signup => Check and sve user to db

                        <=      Register successfully message

User Login

POST api/suth/sigin => Authenticate

                        <=      Create JWT string with secret
                                return {token, user info, authorities}

Access Resource

JWT on x-access-token => Check JWT signature, get user info and authenticate header

                        <=      return content based in authorization

JWT Refresh flow

User Login

POST api/suth/sigin => Authenticate

                        <=      Create JWT string with secret
                                return {token, *refreshToken, user info, authorities}

Access Resources with Expired Token

Request data with JWT => Validate and throw TokenExpiredError in the header

                        <=      Return Token Expired message

Token Refresh

POST api/auth/refreshToken => Verify Refresh Token

                        <=      return {new token, resfreshToken}

Crypto

Buildspace Solana project

program:

a) piece of code that lives on the blockchain

b) programs are stateless

c) programs interact with accounts for data

accounts

a) stores data

b) users can have 1,000s of accounts 

Configuring Solana

Install rust
https://doc.rust-lang.org/book/ch01-01-installation.html

Install Solana: https://docs.solana.com/cli/install-solana-cli-tools#use-solanas-install-tool

set Solana network to localhost

```bash

solana config set –url localhost ```

start a local Solana node

solana-test-validator 

Install mocha, anchor, npm anchor, npm solana/web3.js


npm install -g mocha

cargo install --git https://github.com/project-serum/anchor anchor-cli --locked

npm install @project-serum/anchor @solana/web3.js

Create a project


anchor init myproject --javascript 

Generate local Solana wallet


solana-keygen new

Get public key for local wallet


solana address

 ```

 airdrop sol 
 
```bash

solana airdrop 5 93SAmhpBneKq6UybsFbn5gf9kzAcooCz732bGaGiBehg  --url https://api.devnet.solana.com



Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.