[ { "id": "101", "title": 101, "url": "/101", "category": "JavaScript libraries", "keywords": null, "content_html": "

Usage

\n\n
const isObject = require('101/isObject')\nisObject({}) // → true\n
\n\n

Every function is exposed as a module.

\n\n

See: 101

\n\n

Type checking

\n\n
isObject({})\nisString('str')\nisRegExp(/regexp/)\nisBoolean(true)\nisEmpty({})\nisfunction(x => x)\nisInteger(10)\nisNumber(10.1)\ninstanceOf(obj, 'string')\n
\n\n

Objects

\n\n

Example

\n\n
let obj = {}\n
\n\n

Update

\n\n
obj = put(obj, 'user.name', 'John')\n// → { user: { name: 'John' } }\n
\n\n

Read

\n\n
pluck(name, 'user.name')\n// → 'John'\n
\n\n

Delete

\n\n
obj = del(obj, 'user')\n// → { }\n
\n\n

Getting

\n\n
pluck(state, 'user.profile.name')\n
\n\n
pick(state, ['user', 'ui'])\npick(state, /^_/)\n
\n\n

pluck returns values, pick returns subsets of objects.

\n\n

See:\npluck,\npick

\n\n

Setting

\n\n
put(state, 'user.profile.name', 'john')\n
\n\n

See:\nput

\n\n

Deleting

\n\n
del(state, 'user.profile')\nomit(state, ['user', 'data'])\n
\n\n

omit is like del, but supports multiple keys to be deleted.

\n\n

See:\nomit,\ndel

\n\n

Keypath check

\n\n
hasKeypaths(state, ['user'])\nhasKeypaths(state, { 'user.profile.name': 'john' })\n
\n\n

See:\nhasKeypaths

\n\n

Get values

\n\n
values(state)\n
\n\n

Functions

\n\n

Simple functions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
and(x, y)x && y
or(x, y)x || y
xor(x, y)!(!x && !y) && !(x && y)
equals(x, y)x === y
exists(x)!!x
not(x)!x
\n\n

Useful for function composition.

\n\n

See:\nand,\nequals,\nexists

\n\n

Composition

\n\n
compose(f, g)       // x => f(g(x))\ncurry(f)            // x => y => f(x, y)\nflip(f)             // f(x, y) --> f(y, x)\n
\n\n

See:\ncompose,\ncurry,\nflip

\n\n

And/or

\n\n
passAll(f, g)       // x => f(x) && g(x)\npassAny(f, g)       // x => f(x) || g(x)\n
\n\n

See:\npassAll,\npassAny

\n\n

Converge

\n\n
converge(and, [pluck('a'), pluck('b')])(x)\n
\n\n
// → and(pluck(x, 'a'), pluck(x, 'b'))\n
\n\n

See:\nconverge

\n\n

Arrays

\n\n

Finding

\n\n
find(list, x => x.y === 2)\nfindIndex(list, x => ...)\nincludes(list, 'item')\nlast(list)\n
\n\n
find(list, hasProps('id'))\n
\n\n

Grouping

\n\n
groupBy(list, 'id')\nindexBy(list, 'id')\n
\n\n

Examples

\n\n

Function composition

\n\n
isFloat = passAll(isNumber, compose(isInteger, not))\n// n => isNumber(n) && not(isInteger(n))\n
\n\n
function doStuff (object, options) { ... }\n\ndoStuffForce = curry(flip(doStuff))({ force: true })\n
\n\n

Reference

\n\n", "intro_html": "

101 is a JavaScript library for dealing with immutable data in a functional manner.

", "description_html": "", "tags": null, "updated": "2017-09-21" },{ "id": "absinthe", "title": "Absinthe", "url": "/absinthe", "category": "Hidden", "keywords": null, "content_html": "

Introduction

\n\n

Concepts

\n\n\n\n

Plug

\n\n

web/router.ex

\n\n
defmodule Blog.Web.Router do\n  use Phoenix.Router\n\n  forward \"/\", Absinthe.Plug,\n    schema: Blog.Schema\nend\n
\n\n

Absinthe is a Plug, and you pass it one Schema.

\n\n

See: Our first query

\n\n

Main concepts

\n\n

Schema

\n\n

web/schema.ex

\n\n
defmodule Blog.Schema do\n  use Absinthe.Schema\n  import_types Blog.Schema.Types\n\n  query do\n    @desc \"Get a list of blog posts\"\n    field :posts, list_of(:post) do\n      resolve &Blog.PostResolver.all/2\n    end\n  end\nend\n
\n\n

This schema will account for { posts { ··· } }. It returns a Type of :post, and delegates to a Resolver.

\n\n

Resolver

\n\n

web/resolvers/post_resolver.ex

\n\n
defmodule Blog.PostResolver do\n  def all(_args, _info) do\n    {:ok, Blog.Repo.all(Blog.Post)}\n  end\nend\n
\n\n

This is the function that the schema delegated the posts query to.

\n\n

Type

\n\n

web/schema/types.ex

\n\n
defmodule Blog.Schema.Types do\n  use Absinthe.Schema.Notation\n\n  @desc \"A blog post\"\n  object :post do\n    field :id, :id\n    field :title, :string\n    field :body, :string\n  end\nend\n
\n\n

This defines a type :post, which is used by the resolver.

\n\n

Schema

\n\n

Query arguments

\n\n

GraphQL query

\n\n
{ user(id: \"1\") { ··· } }\n
\n\n

web/schema.ex

\n\n
query do\n  field :user, type: :user do\n    arg :id, non_null(:id)\n    resolve &Blog.UserResolver.find/2\n  end\nend\n
\n\n

Resolver

\n\n
def find(%{id: id} = args, _info) do\n  ···\nend\n
\n\n

See: Query arguments

\n\n

Mutations

\n\n

GraphQL query

\n\n
{\n  mutation CreatePost {\n    post(title: \"Hello\") { id }\n  }\n}\n
\n\n

web/schema.ex

\n\n
mutation do\n  @desc \"Create a post\"\n  field :post, type: :post do\n    arg :title, non_null(:string)\n    resolve &Blog.PostResolver.create/2\n  end\nend\n
\n\n

See: Mutations

\n\n

References

\n\n", "intro_html": "

Absinthe allows you to write GraphQL servers in Elixir.

", "description_html": "", "tags": ["WIP"], "updated": "2017-10-10" },{ "id": "activeadmin", "title": "ActiveAdmin", "url": "/activeadmin", "category": "Ruby", "keywords": null, "content_html": "

Listing scopes

\n\n

Allows you to filter listings by a certain scope.

\n\n
scope :draft\nscope :for_approval\n
\n\n
scope :public, if: ->{ current_admin_user.can?(...) }\nscope \"Unapproved\", :pending\nscope(\"Published\") { |books| books.where(:published: true) }\n
\n\n

Sidebar filters

\n\n
filter :email\nfilter :username\n
\n\n

Custom actions

\n\n

You can define custom actions for models.

\n\n
before_filter only: [:show, :edit, :publish] do\n  @post = Post.find(params[:id])\nend\n
\n\n

Make the route

\n\n
member_action :publish, method: :put do\n  @post.publish!\n  redirect_to admin_posts_path, notice: \"The post '#{@post}' has been published!\"\nend\n
\n\n\n\n
index do\n  column do |post|\n    link_to 'Publish', publish_admin_post_path(post), method: :put\n  end\nend\n
\n\n\n\n
action_item only: [:edit, :show] do\n  @post = Post.find(params[:id])\n  link_to 'Publish', publish_admin_post_path(post), method: :put\nend\n
\n\n

Columns

\n\n
column :foo\n
\n\n
column :title, sortable: :name do |post|\n  strong post.title\nend\n
\n\n

Other helpers

\n\n
status_tag \"Done\"           # Gray\nstatus_tag \"Finished\", :ok  # Green\nstatus_tag \"You\", :warn     # Orange\nstatus_tag \"Failed\", :error # Red\n
\n\n

Disabling ‘new post’

\n\n
ActiveAdmin.register Post do\n  actions :index, :edit\n  # or: config.clear_action_items!\nend\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "adb", "title": "adb (Android Debug Bridge)", "url": "/adb", "category": "CLI", "keywords": null, "content_html": "

Device Basics

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
adb devicesLists connected devices
adb devices -lLists connected devices and kind
adb rootRestarts adbd with root permissions
adb start-serverStarts the adb server
adb kill-serverKills the adb server
adb remountRemounts file system with read/write access
adb rebootReboots the device
adb reboot bootloaderReboots the device into fastboot
adb disable-verityReboots the device into fastboot
\n\n

wait-for-device can be specified after adb to ensure that the command will run once the device is connected.

\n\n

-s can be used to send the commands to a specific device when multiple are connected.

\n\n

Examples

\n\n
$ adb wait-for-device devices\n List of devices attached\n somedevice-1234 device\n someotherdevice-1234 device\n
\n\n
$ adb -s somedevice-1234 root\n
\n\n

Logcat

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
adb logcatStarts printing log messages to stdout
adb logcat -gDisplays current log buffer sizes
adb logcat -G <size>Sets the buffer size (K or M)
adb logcat -cClears the log buffers
adb logcat *:VEnables ALL log messages (verbose)
adb logcat -f <filename>Dumps to specified file
\n\n

Examples

\n
$ adb logcat -G 16M\n$ adb logcat *:V > output.log\n
\n\n

File Management

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
adb push <local> <remote>Copies the local to the device at remote
adb pull <remote> <local>Copies the remote from the device to local
\n\n

Examples

\n\n
$ echo \"This is a test\" > test.txt\n$ adb push  test.txt /sdcard/test.txt\n$ adb pull /sdcard/test.txt pulledTest.txt\n
\n\n

Remote Shell

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
adb shell <command>Runs the specified command on device (most unix commands work here)
adb shell wm sizeDisplays the current screen resolution
adb shell wm size WxHSets the resolution to WxH
adb shell pm list packagesLists all installed packages
adb shell pm list packages -3Lists all installed 3rd-party packages
adb shell monkey -p app.package.nameStarts the specified package
", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-03-06" },{ "id": "analytics.js", "title": "Google Analytics's analytics.js", "url": "/analytics.js", "category": "Analytics", "keywords": null, "content_html": "

Page view

\n\n
ga('create', 'UA-XXXX-Y', 'auto')\nga('create', 'UA-XXXX-Y', { userId: 'USER_ID' })\n
\n\n
ga('send', 'pageview')\nga('send', 'pageview', { 'dimension15': 'My custom dimension' })\n
\n\n

Events

\n\n
ga('send', 'event', 'button',  'click', {color: 'red'});\n
\n\n
ga('send', 'event', 'button',  'click', 'nav buttons',  4);\n/*                  ^category  ^action  ^label          ^value */\n
\n\n

Exceptions

\n\n
ga('send', 'exception', {\n  exDescription: 'DatabaseError',\n  exFatal: false,\n  appName: 'myapp',\n  appVersion: '0.1.2'\n})\n
", "intro_html": "

Google Analytics’s analytics.js is deprecated.

", "description_html": "", "tags": null, "updated": "2017-10-29" },{ "id": "analytics", "title": "Analytics libraries", "url": "/analytics", "category": "Analytics", "keywords": null, "content_html": "

Mixpanel

\n\n
mixpanel.identify('284');\nmixpanel.people.set({ $email: 'hi@gmail.com' });\nmixpanel.register({ age: 28, gender: 'male' }); /* set common properties */\n
\n\n

mixpanel

\n\n

Google Analytics’s analytics.js

\n\n
ga('create', 'UA-XXXX-Y', 'auto');\nga('create', 'UA-XXXX-Y', { userId: 'USER_ID' });\n
\n\n
ga('send', 'pageview');\nga('send', 'pageview', { 'dimension15': 'My custom dimension' });\n
\n\n

analytics.js

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "angularjs", "title": "Angular.js", "url": "/angularjs", "category": "JavaScript libraries", "keywords": null, "content_html": "
    <html ng-app=\"nameApp\">\n
\n\n

Lists (ng-repeat)

\n
    <ul ng-controller=\"MyListCtrl\">\n      <li ng-repeat=\"phone in phones\">\n        \n      </li>\n    </ul>\n
\n\n

Model (ng-model)

\n\n
    <select ng-model=\"orderProp\">\n      <option value=\"name\">Alphabetical</option>\n      <option value=\"age\">Newest</option>\n    </select>\n
\n\n

Defining a module

\n
    App = angular.module('myApp', []);\n\n    App.controller('MyListCtrl', function ($scope) {\n      $scope.phones = [ ... ];\n    });\n
\n\n

Controller with protection from minification

\n
    App.controller('Name', [\n      '$scope',\n      '$http',\n      function ($scope, $http) {\n      }\n    ]);\n\n    a.c 'name', [\n      '$scope'\n      '$http'\n      ($scope, $http) ->\n    ]\n
\n\n

Service

\n
    App.service('NameService', function($http){\n      return {\n        get: function(){\n          return $http.get(url);\n        }\n      }\n    });\n
\n

In controller you call with parameter and will use promises to return data from server.

\n\n
    App.controller('controllerName',\n    function(NameService){\n      NameService.get()\n      .then(function(){})\n    })\n
\n\n

Directive

\n
    App.directive('name', function(){\n      return {\n        template: '<h1>Hello</h1>'\n      }\n    });\n
\n\n

In HTML will use <name></name> to render your template <h1>Hello</h1>

\n\n

HTTP

\n
    App.controller('PhoneListCtrl', function ($scope, $http) {\n        $http.get('/data.json').success(function (data) {\n            $scope.phones = data;\n        })\n    });\n
\n

References:

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "animated_gif", "title": "Animated GIFs", "url": "/animated_gif", "category": "CLI", "keywords": null, "content_html": "

Animated GIFs

\n\n

Convert MP4 to GIF

\n\n
mkdir -p gif\nmplayer -ao null -vo gif89a:outdir=gif $INPUT\nmogrify -format gif *.png\ngifsicle --colors=256 --delay=4 --loopcount=0 --dither -O3 gif/*.gif > ${INPUT%.*}.gif\nrm -rf gif\n
\n\n

You’ll need mplayer, imagemagick and gifsicle. This converts frames to .png, then turns them into an animated gif.

\n\n

A given range

\n\n
mplayer -ao null -ss 0:02:06 -endpos 0:05:00 -vo gif89a:outdir=gif videofile.mp4\n
\n\n

See -ss and -endpos.

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ansi", "title": "Ansi codes", "url": "/ansi", "category": "CLI", "keywords": null, "content_html": "

Format

\n\n
\\033[#m\n
\n\n

ANSI codes

\n\n
0      clear\n1      bold\n4      underline\n5      blink\n\n30-37  fg color\n40-47  bg color\n\n1K     clear line (to beginning of line)\n2K     clear line (entire line)\n2J     clear screen\n0;0H   move cursor to 0;0\n\n1A     move up 1 line\n
\n\n

Colors

\n\n
0      black\n1      red\n2      green\n3      yellow\n4      blue\n5      magenta\n6      cyan\n7      white\n
\n\n

Bash utilities

\n\n
hide_cursor() { printf \"\\e[?25l\"; }\nshow_cursor() { printf \"\\e[?25h\"; }\n
", "intro_html": "

Quick reference to ANSI color codes.

", "description_html": "", "tags": null, "updated": null },{ "id": "ansible-examples", "title": "Ansible examples", "url": "/ansible-examples", "category": "Ansible", "keywords": null, "content_html": "

Examples

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ansible-guide", "title": "Ansible quickstart", "url": "/ansible-guide", "category": "Ansible", "keywords": null, "content_html": "

Install Ansible

\n\n
$ brew install ansible            # OSX\n$ [sudo] apt install ansible      # elsewhere\n
\n\n

Ansible is available as a package in most OS’s.

\n\n

See: Installation

\n\n

Start your project

\n\n
~$ mkdir setup\n~$ cd setup\n
\n\n

Make a folder for your Ansible files.

\n\n

See: Getting started

\n\n

Creating your files

\n\n

Inventory file

\n\n

~/setup/hosts

\n\n
[sites]\n127.0.0.1\n192.168.0.1\n192.168.0.2\n192.168.0.3\n
\n\n

This is a list of hosts you want to manage, grouped into groups. (Hint: try\nusing localhost ansible_connection=local to deploy to your local machine.)

\n\n

See: Intro to Inventory

\n\n

Playbook

\n\n

~/setup/playbook.yml

\n\n
- hosts: 127.0.0.1\n  user: root\n  tasks:\n    - name: install nginx\n      apt: pkg=nginx state=present\n\n    - name: start nginx every bootup\n      service: name=nginx state=started enabled=yes\n\n    - name: do something in the shell\n      shell: echo hello > /tmp/abc.txt\n\n    - name: install bundler\n      gem: name=bundler state=latest\n
\n\n

See: Intro to Playbooks

\n\n

Running

\n\n

Running ansible-playbook

\n\n
~/setup$ ls\nhosts\nplaybook.yml\n
\n\n

Running the playbook

\n\n
~/setup$ ansible-playbook -i hosts playbook.yml\nPLAY [all] ********************************************************************\n\nGATHERING FACTS ***************************************************************\nok: [127.0.0.1]\n\nTASK: [install nginx] *********************************************************\nok: [127.0.0.1]\n\nTASK: start nginx every bootup] ***********************************************\nok: [127.0.0.1]\n...\n
\n\n

Read more

\n\n", "intro_html": "", "description_html": "

A quick guide to getting started with your first Ansible playbook.

", "tags": null, "updated": null },{ "id": "ansible-modules", "title": "Ansible modules", "url": "/ansible-modules", "category": "Ansible", "keywords": null, "content_html": "

Format

\n\n

Basic file

\n\n
---\n- hosts: production\n  remote_user: root\n  tasks:\n  - ···\n
\n\n

Place your modules inside tasks.

\n\n

Task formats

\n\n

One-line

\n\n
- apt: pkg=vim state=present\n
\n\n

Map

\n\n
- apt:\n    pkg: vim\n    state: present\n
\n\n

Foldable scalar

\n\n
- apt: >\n    pkg=vim\n    state=present\n
\n\n

Define your tasks in any of these formats. One-line format is preferred for short declarations, while maps are preferred for longer.

\n\n

Modules

\n\n

Aptitude

\n\n

Packages

\n\n
- apt:\n    pkg: nodejs\n    state: present # absent | latest\n    update_cache: yes\n    force: no\n
\n\n

Deb files

\n\n
- apt:\n    deb: \"https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb\"\n
\n\n

Repositories

\n\n
- apt_repository:\n    repo: \"deb https://··· raring main\"\n    state: present\n
\n\n

Repository keys

\n\n
- apt_key:\n    id: AC40B2F7\n    url: \"http://···\"\n    state: present\n
\n\n

git

\n\n
- git:\n    repo: git://github.com/\n    dest: /srv/checkout\n    version: master\n    depth: 10\n    bare: yes\n
\n\n

See: git module

\n\n

git_config

\n\n
- git_config:\n    name: user.email\n    scope: global # local | system\n    value: hi@example.com\n
\n\n

See: git_config module

\n\n

user

\n\n
- user:\n    state: present\n    name: git\n    system: yes\n    shell: /bin/sh\n    groups: admin\n    comment: \"Git Version Control\"\n
\n\n

See: user module

\n\n

service

\n\n
- service:\n    name: nginx\n    state: started\n    enabled: yes     # optional\n
\n\n

See: service module

\n\n

Shell

\n\n

shell

\n\n
- shell: apt-get install nginx -y\n
\n\n

Extra options

\n\n
- shell: echo hello\n  args:\n    creates: /path/file  # skip if this exists\n    removes: /path/file  # skip if this is missing\n    chdir: /path         # cd here before running\n
\n\n

Multiline example

\n\n
- shell: |\n    echo \"hello there\"\n    echo \"multiple lines\"\n
\n\n

See: shell module

\n\n

script

\n\n
- script: /x/y/script.sh\n  args:\n    creates: /path/file  # skip if this exists\n    removes: /path/file  # skip if this is missing\n    chdir: /path         # cd here before running\n
\n\n

See: script module

\n\n

Files

\n\n

file

\n\n
- file:\n    path: /etc/dir\n    state: directory # file | link | hard | touch | absent\n\n    # Optional:\n    owner: bin\n    group: wheel\n    mode: 0644\n    recurse: yes  # mkdir -p\n    force: yes    # ln -nfs\n
\n\n

See: file module

\n\n

copy

\n\n
- copy:\n    src: /app/config/nginx.conf\n    dest: /etc/nginx/nginx.conf\n\n    # Optional:\n    owner: user\n    group: user\n    mode: 0644\n    backup: yes\n
\n\n

See: copy module

\n\n

template

\n\n
- template:\n    src: config/redis.j2\n    dest: /etc/redis.conf\n\n    # Optional:\n    owner: user\n    group: user\n    mode: 0644\n    backup: yes\n
\n\n

See: template module

\n\n

Local actions

\n\n

local_action

\n\n
- name: do something locally\n  local_action: shell echo hello\n
\n\n

debug

\n\n
- debug:\n    msg: \"Hello {{ var }}\"\n
\n\n

See: debug module

", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-10-03" },{ "id": "ansible-roles", "title": "Ansible roles", "url": "/ansible-roles", "category": "Ansible", "keywords": null, "content_html": "

Structure

\n\n
roles/\n  common/\n    tasks/\n    handlers/\n    files/              # 'copy' will refer to this\n    templates/          # 'template' will refer to this\n    meta/               # Role dependencies here\n    vars/\n    defaults/\n      main.yml\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ansible", "title": "Ansible", "url": "/ansible", "category": "Ansible", "keywords": null, "content_html": "

Getting started

\n\n

Hosts

\n\n
$ sudo mkdir /etc/ansible\n$ sudo vim /etc/ansible/hosts\n\n[example]\n192.0.2.101\n192.0.2.102\n
\n\n

Running a playbook

\n\n
$ ansible-playbook playbook.yml\n
\n\n

Tasks

\n\n
- hosts: all\n  user: root\n  sudo: no\n  vars:\n    aaa: bbb\n  tasks:\n    - ...\n  handlers:\n    - ...\n
\n\n

Includes

\n\n
tasks:\n  - include: db.yml\nhandlers:\n  - include: db.yml user=timmy\n
\n\n

Handlers

\n\n
handlers:\n  - name: start apache2\n    action: service name=apache2 state=started\n\ntasks:\n  - name: install apache\n    action: apt pkg=apache2 state=latest\n    notify:\n      - start apache2\n
\n\n

Vars

\n\n
- host: lol\n  vars_files:\n    - vars.yml\n  vars:\n    project_root: /etc/xyz\n  tasks:\n    - name: Create the SSH directory.\n      file: state=directory path=${project_root}/home/.ssh/\n      only_if: \"$vm == 0\"\n
\n\n

Roles

\n\n
- host: xxx\n  roles:\n    - db\n    - { role:ruby, sudo_user:$user }\n    - web\n\n# Uses:\n# roles/db/tasks/*.yml\n# roles/db/handlers/*.yml\n
\n\n

Task: Failures

\n\n
- name: my task\n  command: ...\n  register: result\n  failed_when: \"'FAILED' in result.stderr\"\n\n  ignore_errors: yes\n\n  changed_when: \"result.rc != 2\"\n
\n\n

Env vars

\n\n
vars:\n  local_home: \"{{ lookup('env','HOME') }}\"\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "appcache", "title": "Appcache", "url": "/appcache", "category": "HTML", "keywords": null, "content_html": "

Format

\n\n
CACHE MANIFEST\n# version\n\nCACHE:\nhttp://www.google.com/jsapi\n/assets/app.js\n/assets/bg.png\n\nNETWORK:\n*\n
\n\n

Note that Appcache is deprecated!

\n\n

See: Using the application cache (developer.mozilla.org)

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "applescript", "title": "AppleScript", "url": "/applescript", "category": "macOS", "keywords": null, "content_html": "

Running

\n\n
osascript -e \"...\"\n
\n\n
display notification \"X\" with title \"Y\"\n
\n\n

Comments

\n\n
-- This is a single line comment\n
\n\n
# This is another single line comment\n
\n\n
(*\nThis is\na multi\nline comment\n*)\n
\n\n

Say

\n\n
-- default voice\nsay \"Hi I am a Mac\"\n
\n\n
-- specified voice\nsay \"Hi I am a Mac\" using \"Zarvox\"\n
\n\n

Beep

\n\n
-- beep once\nbeep\n
\n\n
-- beep 10 times\nbeep 10\n
\n\n

Delay

\n\n
-- delay for 5 seconds\ndelay 5\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "applinks", "title": "Applinks", "url": "/applinks", "category": "HTML", "keywords": null, "content_html": "
<meta property=\"al:ios:url\" content=\"applinks://docs\" />\n<meta property=\"al:ios:app_store_id\" content=\"12345\" />\n<meta property=\"al:ios:app_name\" content=\"App Links\" />\n\n<meta property=\"al:android:url\" content=\"applinks://docs\" />\n<meta property=\"al:android:app_name\" content=\"App Links\" />\n<meta property=\"al:android:package\" content=\"org.applinks\" />\n\n<meta property=\"al:web:url\" content=\"http://applinks.org/documentation\" />\n
\n\n

Device types

\n\n\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "arel", "title": "Arel", "url": "/arel", "category": "Rails", "keywords": null, "content_html": "

Tables

\n\n
users = Arel::Table.new(:users)\nusers = User.arel_table  # ActiveRecord model\n
\n\n

Fields

\n\n
users[:name]\nusers[:id]\n
\n\n

where (restriction)

\n\n
users.where(users[:name].eq('amy'))\n# SELECT * FROM users WHERE users.name = 'amy'\n
\n\n

select (projection)

\n\n
users.project(users[:id])\n# SELECT users.id FROM users\n
\n\n

join

\n

basic join

\n

In ActiveRecord (without Arel), if :photos is the name of the association, use joins

\n
users.joins(:photos)\n
\n\n

In Arel, if photos is defined as the Arel table,

\n
photos = Photo.arel_table\nusers.join(photos) \nusers.join(photos, Arel::Nodes::OuterJoin).on(users[:id].eq(photos[:user_id]))\n
\n\n

join with conditions

\n
users.joins(:photos).merge(Photo.where(published: true))\n
\n\n

If the simpler version doesn’t help and you want to add more SQL statements to it:

\n
users.join(\n   users.join(photos, Arel::Nodes::OuterJoin)\n   .on(photos[:user_id].eq(users[:id]).and(photos[:published].eq(true)))\n)\n
\n\n

advanced join

\n

multiple joins with the same table but different meanings and/or conditions

\n
creators = User.arel_table.alias('creators')\nupdaters = User.arel_table.alias('updaters')\nphotos = Photo.arel_table\n\nphotos_with_credits = photos\n.join(photos.join(creators, Arel::Nodes::OuterJoin).on(photos[:created_by_id].eq(creators[:id])))\n.join(photos.join(updaters, Arel::Nodes::OuterJoin).on(photos[:assigned_id].eq(updaters[:id])))\n.project(photos[:name], photos[:created_at], creators[:name].as('creator'), updaters[:name].as('editor'))\n\nphotos_with_credits.to_sql\n# => \"SELECT `photos`.`name`, `photos`.`created_at`, `creators`.`name` AS creator, `updaters`.`name` AS editor FROM `photos` INNER JOIN (SELECT FROM `photos` LEFT OUTER JOIN `users` `creators` ON `photos`.`created_by_id` = `creators`.`id`) INNER JOIN (SELECT FROM `photos` LEFT OUTER JOIN `users` `updaters` ON `photos`.`updated_by_id` = `updaters`.`id`)\"\n\n# after the request is done, you can use the attributes you named\n# it's as if every Photo record you got has \"creator\" and \"editor\" fields, containing creator name and editor name\nphotos_with_credits.map{|x|\n  \"#{photo.name} - copyright #{photo.created_at.year} #{photo.creator}, edited by #{photo.editor}\"\n}.join('; ')\n
\n\n

limit / offset

\n\n
users.take(5) # => SELECT * FROM users LIMIT 5\nusers.skip(4) # => SELECT * FROM users OFFSET 4\n
\n\n

Aggregates

\n\n
users.project(users[:age].sum) # .average .minimum .maximum\nusers.project(users[:id].count)\nusers.project(users[:id].count.as('user_count'))\n
\n\n

order

\n\n
users.order(users[:name])\nusers.order(users[:name], users[:age].desc)\nusers.reorder(users[:age])\n
\n\n

With ActiveRecord

\n\n
User.arel_table\nUser.where(id: 1).arel\n
\n\n

Clean code with arel

\n\n

Most of the clever stuff should be in scopes, e.g. the code above could become:

\n
photos_with_credits = Photo.with_creator.with_editor\n
\n\n

You can store requests in variables then add SQL segments:

\n
all_time      = photos_with_credits.count\nthis_month    = photos_with_credits.where(photos[:created_at].gteq(Date.today.beginning_of_month))\nrecent_photos = photos_with_credits.where(photos[:created_at].gteq(Date.today.beginning_of_month)).limit(5)\n
\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "atom", "title": "Atom", "url": "/atom", "category": "Apps", "keywords": null, "content_html": "

Shortcuts

\n\n

Tree

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘\\Toggle tree
⌘⇧\\Reveal current file
\n\n

Comments

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘/Toggle comments
\n\n

View

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘k Split pane to the left
⌘⌥=Grow pane
⌘⌥-Shrink pane
^⇧←Move tab to left
\n\n

Bracket matcher

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
^mGo to matching bracket
^]Remove brackets from selection
^⌘mSelect inside brackets
⌥⌘.Close tag
\n\n

Symbols view

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
^⌥↓Jump to declaration under cursor
^⇧rShow tags
\n\n

Symbols view enables Ctags support for Atom.

\n\n

See: Symbols view

\n\n

Git

\n\n\n \n \n \n \n \n \n \n \n \n \n
^⇧9Show Git pane
^⇧8Show GitHub pane
\n\n

Editing

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘dSelect word
⌘lSelect line
⌘↓Move line down
⌘↑Move line up
⌘⏎New line below
⌘⇧⏎New line above
⌘⇧kDelete line
⌘⇧dDuplicate line
\n\n

Project

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘⇧pCommand palette
⌘⇧aAdd project folder
⌘nNew file
⌘⇧nNew window
⌘fFind in file
⌘⇧fFind in project
⌘tSearch files in project
\n\n

Notes

\n\n

\n\n\n\n

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-06-14" },{ "id": "awesome-redux", "title": "Awesome Redux", "url": "/awesome-redux", "category": "React", "keywords": null, "content_html": "

redux-actions

\n\n

Create action creators in flux standard action format.

\n\n
increment = createAction('INCREMENT', amount => amount)\nincrement = createAction('INCREMENT')  // same\n
\n\n
increment(42) === { type: 'INCREMENT', payload: 42 }\n
\n\n
// Errors are handled for you:\nerr = new Error()\nincrement(err) === { type: 'INCREMENT', payload: err, error: true }\n
\n\n

redux-actions

\n\n

flux-standard-action

\n\n

A standard for flux action objects. An action may have an error, payload and meta and nothing else.

\n\n
{ type: 'ADD_TODO', payload: { text: 'Work it' } }\n{ type: 'ADD_TODO', payload: new Error(), error: true }\n
\n\n

flux-standard-action

\n\n

redux-multi

\n\n

Dispatch multiple actions in one action creator.

\n\n
store.dispatch([\n  { type: 'INCREMENT', payload: 2 },\n  { type: 'INCREMENT', payload: 3 }\n])\n
\n\n

redux-multi

\n\n

reduce-reducers

\n

Combines reducers (like combineReducers()), but without namespacing magic.

\n\n
re = reduceReducers(\n  (state, action) => state + action.number,\n  (state, action) => state + action.number\n)\n\nre(10, { number: 2 })  //=> 14\n
\n\n

reduce-reducers

\n\n

redux-logger

\n\n

Logs actions to your console.

\n\n
// Nothing to see here\n
\n\n

redux-logger

\n\n

Async

\n\n

redux-promise

\n\n

Pass promises to actions. Dispatches a flux-standard-action.

\n\n
increment = createAction('INCREMENT')  // redux-actions\nincrement(Promise.resolve(42))\n
\n\n

redux-promise

\n\n

redux-promises

\n\n

Sorta like that, too. Works by letting you pass thunks (functions) to dispatch(). Also has ‘idle checking’.

\n\n
fetchData = (url) => (dispatch) => {\n  dispatch({ type: 'FETCH_REQUEST' })\n  fetch(url)\n    .then((data) => dispatch({ type: 'FETCH_DONE', data })\n    .catch((error) => dispatch({ type: 'FETCH_ERROR', error })\n})\n\nstore.dispatch(fetchData('/posts'))\n
\n\n
// That's actually shorthand for:\nfetchData('/posts')(store.dispatch)\n
\n\n

redux-promises

\n\n

redux-effects

\n\n

Pass side effects declaratively to keep your actions pure.

\n\n
{\n  type: 'EFFECT_COMPOSE',\n  payload: {\n    type: 'FETCH'\n    payload: {url: '/some/thing', method: 'GET'}\n  },\n  meta: {\n    steps: [ [success, failure] ]\n  }\n}\n
\n\n

redux-effects

\n\n

redux-thunk

\n\n

Pass “thunks” to as actions. Extremely similar to redux-promises, but has support for getState.

\n\n
fetchData = (url) => (dispatch, getState) => {\n  dispatch({ type: 'FETCH_REQUEST' })\n  fetch(url)\n    .then((data) => dispatch({ type: 'FETCH_DONE', data })\n    .catch((error) => dispatch({ type: 'FETCH_ERROR', error })\n})\n\nstore.dispatch(fetchData('/posts'))\n
\n\n
// That's actually shorthand for:\nfetchData('/posts')(store.dispatch, store.getState)\n
\n\n
// Optional: since fetchData returns a promise, it can be chained\n// for server-side rendering\nstore.dispatch(fetchPosts()).then(() => {\n  ReactDOMServer.renderToString(<MyApp store={store} />)\n})\n
\n\n

redux-thunk

", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-11-19" },{ "id": "awscli", "title": "AWS CLI", "url": "/awscli", "category": "Devops", "keywords": null, "content_html": "

EC2

\n\n
aws ec2 describe-instances\naws ec2 start-instances --instance-ids i-12345678c\naws ec2 terminate-instances --instance-ids i-12345678c\n
\n\n

S3

\n\n
aws s3 ls s3://mybucket\naws s3 rm s3://mybucket/folder --recursive\naws s3 cp myfolder s3://mybucket/folder --recursive\naws s3 sync myfolder s3://mybucket/folder --exclude *.tmp\n
\n\n

ECS

\n\n
aws ecs create-cluster\n  --cluster-name=NAME\n  --generate-cli-skeleton\n\naws ecs create-service\n
\n\n

Homebrew

\n\n
brew install awscli\naws configure\n
\n\n

Configuration profiles

\n\n
aws configure --profile project1\naws configure --profile project2\n
\n\n

Elastic Beanstalk

\n\n

Configuration

\n\n\n\n
eb config\n
\n\n

See: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html

\n\n

ebextensions

\n\n\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "backbone", "title": "Backbone.js", "url": "/backbone", "category": "JavaScript libraries", "keywords": null, "content_html": "

Binding events

\n\n
.on('event', callback)\n.on('event', callback, context)\n
\n\n
.on({\n  'event1': callback,\n  'event2': callback\n})\n
\n\n
.on('all', callback)\n
\n\n
.once('event', callback)   // Only happens once\n
\n\n

Unbinding events

\n\n
object.off('change', onChange)    // just the `onChange` callback\nobject.off('change')              // all 'change' callbacks\nobject.off(null, onChange)        // `onChange` callback for all events\nobject.off(null, null, context)   // all callbacks for `context` all events\nobject.off()                      // all\n
\n\n

Events

\n\n
object.trigger('event')\n
\n\n
view.listenTo(object, event, callback)\nview.stopListening()\n
\n\n

List of events

\n\n\n\n

Views

\n\n

Defining

\n\n
// All attributes are optional\nvar View = Backbone.View.extend({\n  model: doc,\n
\n\n
  tagName: 'div',\n  className: 'document-item',\n  id: \"document-\" + doc.id,\n  attributes: { href: '#' },\n
\n\n
  el: 'body',\n
\n\n
  events: {\n    'click button.save': 'save',\n    'click .cancel': function() { ··· },\n    'click': 'onclick'\n  },\n
\n\n
  constructor: function() { ··· },\n  render: function() { ··· }\n})\n
\n

Instantiating

\n\n
view = new View()\nview = new View({ el: ··· })\n
\n\n

Methods

\n\n
view.$el.show()\nview.$('input')\n
\n\n
view.remove()\n
\n\n
view.delegateEvents()\nview.undelegateEvents()\n
\n\n

Models

\n\n

Defining

\n\n
// All attributes are optional\nvar Model = Backbone.Model.extend({\n  defaults: {\n    'author': 'unknown'\n  },\n  idAttribute: '_id',\n  parse: function() { ··· }\n})\n
\n\n

Instantiating

\n\n
var obj = new Model({ title: 'Lolita', author: 'Nabokov' })\n
\n\n
var obj = new Model({ collection: ··· })\n
\n\n

Methods

\n\n
obj.id\nobj.cid   // → 'c38' (client-side ID)\n
\n\n
obj.clone()\n
\n\n
obj.hasChanged('title')\nobj.changedAttributes()  // false, or hash\nobj.previousAttributes() // false, or hash\nobj.previous('title')\n
\n\n
obj.isNew()\n
\n\n
obj.set({ title: 'A Study in Pink' })\nobj.set({ title: 'A Study in Pink' }, { validate: true, silent: true })\nobj.unset('title')\n
\n\n
obj.get('title')\nobj.has('title')\nobj.escape('title')     /* Like .get() but HTML-escaped */\n
\n\n
obj.clear()\nobj.clear({ silent: true })\n
\n\n
obj.save()\nobj.save({ attributes })\nobj.save(null, {\n  silent: true, patch: true, wait: true,\n  success: callback, error: callback\n})\n
\n\n
obj.destroy()\nobj.destroy({\n  wait: true,\n  success: callback, error: callback\n})\n
\n\n
obj.toJSON()\n
\n\n
obj.fetch()\nobj.fetch({ success: callback, error: callback })\n
\n\n

Validation

\n\n
var Model = Backbone.Model.extend({\n  validate: function(attrs, options) {\n    if (attrs.end < attrs.start) {\n      return \"Can't end before it starts\"\n    }\n  }\n})\n
\n\n
obj.validationError  //=> \"Can't end before it starts\"\nobj.isValid()\nobj.on('invalid', function (model, error) { ··· })\n
\n\n
// Triggered on:\nobj.save()\nobj.set({ ··· }, { validate: true })\n
\n\n

Custom URLs

\n\n
var Model = Backbone.Model.extend({\n  // Single URL (string or function)\n  url: '/account',\n  url: function() { return '/account' },\n
\n\n
  // Both of these two work the same way\n  url: function() { return '/books/' + this.id }),\n  urlRoot: '/books'\n})\n
\n\n
var obj = new Model({ url: ··· })\nvar obj = new Model({ urlRoot: ··· })\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "badges", "title": "Code badges", "url": "/badges", "category": "Others", "keywords": null, "content_html": "

Here are some badges for open source projects.

\n\n

Badge markdown

\n\n
Travis\n[![Status](https://travis-ci.org/rstacruz/REPO.svg?branch=master)](https://travis-ci.org/rstacruz/REPO)  \nCodeClimate (shields.io)\n[![CodeClimate](http://img.shields.io/codeclimate/github/rstacruz/REPO.svg?style=flat)](https://codeclimate.com/github/rstacruz/REPO \n\"CodeClimate\")\n\nCoveralls (shields.io)\n[![Coveralls](http://img.shields.io/coveralls/rstacruz/REPO.svg?style=flat)](https://coveralls.io/r/rstacruz/REPO)\n\nTravis (shields.io)\n[![Status](http://img.shields.io/travis/rstacruz/REPO/master.svg?style=flat)](https://travis-ci.org/rstacruz/REPO \"See test builds\")\n\nNPM (shields.io)\n[![npm version](http://img.shields.io/npm/v/REPO.svg?style=flat)](https://npmjs.org/package/REPO \"View this project on npm\")\n\nRuby gem (shields.io)\n[![Gem](https://img.shields.io/gem/v/GEMNAME.svg?style=flat)](http://rubygems.org/gems/GEMNAME \"View this project in Rubygems\")\n
\n\n

Etc

\n\n
Gitter chat\n[![Gitter chat](https://badges.gitter.im/USER/REPO.png)](https://gitter.im/REPO/GITTERROOM \"Gitter chat\")\n\nGitter chat (shields.io)\n[![Chat](http://img.shields.io/badge/gitter-USER / REPO-blue.svg)]( https://gitter.im/USER/REPO )\n\ndavid-dm\n[![Dependencies](http://img.shields.io/david/rstacruz/REPO.svg?style=flat)](https://david-dm.org/rstacruz/REPO)\n\n[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT)\n
\n\n

Support stuff

\n\n
Support\n-------\n\n__Bugs and requests__: submit them through the project's issues tracker.<br>\n[![Issues](http://img.shields.io/github/issues/USER/REPO.svg)]( https://github.com/USER/REPO/issues )\n\n__Questions__: ask them at StackOverflow with the tag *REPO*.<br>\n[![StackOverflow](http://img.shields.io/badge/stackoverflow-REPO-blue.svg)]( http://stackoverflow.com/questions/tagged/REPO )\n\n__Chat__: join us at gitter.im.<br>\n[![Chat](http://img.shields.io/badge/gitter.im-USER/REPO-blue.svg)]( https://gitter.im/USER/REPO )\n
\n\n

Frontend js installation

\n\n
Installation\n------------\n\nAdd [nprogress.js] and [nprogress.css] to your project.\n\n```html\n<script src='nprogress.js'></script>\n<link rel='stylesheet' href='nprogress.css'/>\n```\n\nNProgress is available via [bower] and [npm].\n\n    $ bower install --save nprogress\n    $ npm install --save nprogress\n\n[bower]: http://bower.io/search/?q=nprogress\n[npm]: https://www.npmjs.org/package/nprogress\n
\n\n

Acknowledgements

\n\n
**PROJECTNAME** © 2014+, Rico Sta. Cruz. Released under the [MIT] License.<br>\nAuthored and maintained by Rico Sta. Cruz with help from contributors ([list][contributors]).\n\n> [ricostacruz.com](http://ricostacruz.com) &nbsp;&middot;&nbsp;\n> GitHub [@rstacruz](https://github.com/rstacruz) &nbsp;&middot;&nbsp;\n> Twitter [@rstacruz](https://twitter.com/rstacruz)\n\n[MIT]: http://mit-license.org/\n[contributors]: http://github.com/rstacruz/nprogress/contributors\n
\n\n

Links

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "bash", "title": "Bash scripting", "url": "/bash", "category": "CLI", "keywords": ["Variables","Functions","Interpolation","Brace expansions","Loops","Conditional execution","Command substitution"], "content_html": "

Getting started

\n\n

Introduction

\n\n

This is a quick reference to getting started with Bash scripting.

\n\n\n\n

Example

\n\n
#!/usr/bin/env bash\n\nNAME=\"John\"\necho \"Hello $NAME!\"\n
\n\n

Variables

\n\n
NAME=\"John\"\necho $NAME\necho \"$NAME\"\necho \"${NAME}!\"\n
\n\n

String quotes

\n\n
NAME=\"John\"\necho \"Hi $NAME\"  #=> Hi John\necho 'Hi $NAME'  #=> Hi $NAME\n
\n\n

Shell execution

\n\n
echo \"I'm in $(pwd)\"\necho \"I'm in `pwd`\"\n# Same\n
\n\n

See Command substitution

\n\n

Conditional execution

\n\n
git commit && git push\ngit commit || echo \"Commit failed\"\n
\n\n

Functions

\n\n
get_name() {\n  echo \"John\"\n}\n\necho \"You are $(get_name)\"\n
\n\n

See: Functions

\n\n

Conditionals

\n\n
if [[ -z \"$string\" ]]; then\n  echo \"String is empty\"\nelif [[ -n \"$string\" ]]; then\n  echo \"String is not empty\"\nfi\n
\n\n

See: Conditionals

\n\n

Strict mode

\n\n
set -euo pipefail\nIFS=$'\\n\\t'\n
\n\n

See: Unofficial bash strict mode

\n\n

Brace expansion

\n\n
echo {A,B}.js\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExpressionDescription
{A,B}Same as A B
{A,B}.jsSame as A.js B.js
{1..5}Same as 1 2 3 4 5
\n\n

See: Brace expansion

\n\n

Parameter expansions

\n\n

Basics

\n\n
name=\"John\"\necho ${name}\necho ${name/J/j}    #=> \"john\" (substitution)\necho ${name:0:2}    #=> \"Jo\" (slicing)\necho ${name::2}     #=> \"Jo\" (slicing)\necho ${name::-1}    #=> \"Joh\" (slicing)\necho ${name:(-1)}   #=> \"n\" (slicing from right)\necho ${name:(-2):1} #=> \"h\" (slicing from right)\necho ${food:-Cake}  #=> $food or \"Cake\"\n
\n\n
length=2\necho ${name:0:length}  #=> \"Jo\"\n
\n\n

See: Parameter expansion

\n\n
STR=\"/path/to/foo.cpp\"\necho ${STR%.cpp}    # /path/to/foo\necho ${STR%.cpp}.o  # /path/to/foo.o\necho ${STR%/*}      # /path/to\n\necho ${STR##*.}     # cpp (extension)\necho ${STR##*/}     # foo.cpp (basepath)\n\necho ${STR#*/}      # path/to/foo.cpp\necho ${STR##*/}     # foo.cpp\n\necho ${STR/foo/bar} # /path/to/bar.cpp\n
\n\n
STR=\"Hello world\"\necho ${STR:6:5}   # \"world\"\necho ${STR: -5:5}  # \"world\"\n
\n\n
SRC=\"/path/to/foo.cpp\"\nBASE=${SRC##*/}   #=> \"foo.cpp\" (basepath)\nDIR=${SRC%$BASE}  #=> \"/path/to/\" (dirpath)\n
\n\n

Substitution

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescription
${FOO%suffix}Remove suffix
${FOO#prefix}Remove prefix
${FOO%%suffix}Remove long suffix
${FOO##prefix}Remove long prefix
${FOO/from/to}Replace first match
${FOO//from/to}Replace all
${FOO/%from/to}Replace suffix
${FOO/#from/to}Replace prefix
\n\n

Comments

\n\n
# Single line comment\n
\n\n
: '\nThis is a\nmulti line\ncomment\n'\n
\n\n

Substrings

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExpressionDescription
${FOO:0:3}Substring (position, length)
${FOO:(-3):3}Substring from the right
\n\n

Length

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
ExpressionDescription
${#FOO}Length of $FOO
\n\n

Manipulation

\n\n
STR=\"HELLO WORLD!\"\necho ${STR,}   #=> \"hELLO WORLD!\" (lowercase 1st letter)\necho ${STR,,}  #=> \"hello world!\" (all lowercase)\n\nSTR=\"hello world!\"\necho ${STR^}   #=> \"Hello world!\" (uppercase 1st letter)\necho ${STR^^}  #=> \"HELLO WORLD!\" (all uppercase)\n
\n\n

Default values

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExpressionDescription
${FOO:-val}$FOO, or val if unset (or null)
${FOO:=val}Set $FOO to val if unset (or null)
${FOO:+val}val if $FOO is set (and not null)
${FOO:?message}Show error message and exit if $FOO is unset (or null)
\n\n

Omitting the : removes the (non)nullity checks, e.g. ${FOO-val} expands to val if unset otherwise $FOO.

\n\n

Loops

\n\n

Basic for loop

\n\n
for i in /etc/rc.*; do\n  echo $i\ndone\n
\n\n

C-like for loop

\n\n
for ((i = 0 ; i < 100 ; i++)); do\n  echo $i\ndone\n
\n\n

Ranges

\n\n
for i in {1..5}; do\n    echo \"Welcome $i\"\ndone\n
\n\n

With step size

\n\n
for i in {5..50..5}; do\n    echo \"Welcome $i\"\ndone\n
\n\n

Reading lines

\n\n
cat file.txt | while read line; do\n  echo $line\ndone\n
\n\n

Forever

\n\n
while true; do\n  ···\ndone\n
\n\n

Functions

\n\n

Defining functions

\n\n
myfunc() {\n    echo \"hello $1\"\n}\n
\n\n
# Same as above (alternate syntax)\nfunction myfunc() {\n    echo \"hello $1\"\n}\n
\n\n
myfunc \"John\"\n
\n\n

Returning values

\n\n
myfunc() {\n    local myresult='some value'\n    echo $myresult\n}\n
\n\n
result=\"$(myfunc)\"\n
\n\n

Raising errors

\n\n
myfunc() {\n  return 1\n}\n
\n\n
if myfunc; then\n  echo \"success\"\nelse\n  echo \"failure\"\nfi\n
\n\n

Arguments

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExpressionDescription
$#Number of arguments
$*All arguments
$@All arguments, starting from first
$1First argument
$_Last argument of the previous command
\n\n

See Special parameters.

\n\n

Conditionals

\n\n

Conditions

\n\n

Note that [[ is actually a command/program that returns either 0 (true) or 1 (false). Any program that obeys the same logic (like all base utils, such as grep(1) or ping(1)) can be used as condition, see examples.

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConditionDescription
[[ -z STRING ]]Empty string
[[ -n STRING ]]Not empty string
[[ STRING == STRING ]]Equal
[[ STRING != STRING ]]Not Equal
[[ NUM -eq NUM ]]Equal
[[ NUM -ne NUM ]]Not equal
[[ NUM -lt NUM ]]Less than
[[ NUM -le NUM ]]Less than or equal
[[ NUM -gt NUM ]]Greater than
[[ NUM -ge NUM ]]Greater than or equal
[[ STRING =~ STRING ]]Regexp
(( NUM < NUM ))Numeric conditions
\n\n

More conditions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConditionDescription
[[ -o noclobber ]]If OPTIONNAME is enabled
[[ ! EXPR ]]Not
[[ X && Y ]]And
[[ X || Y ]]Or
\n\n

File conditions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConditionDescription
[[ -e FILE ]]Exists
[[ -r FILE ]]Readable
[[ -h FILE ]]Symlink
[[ -d FILE ]]Directory
[[ -w FILE ]]Writable
[[ -s FILE ]]Size is > 0 bytes
[[ -f FILE ]]File
[[ -x FILE ]]Executable
[[ FILE1 -nt FILE2 ]]1 is more recent than 2
[[ FILE1 -ot FILE2 ]]2 is more recent than 1
[[ FILE1 -ef FILE2 ]]Same files
\n\n

Example

\n\n
# String\nif [[ -z \"$string\" ]]; then\n  echo \"String is empty\"\nelif [[ -n \"$string\" ]]; then\n  echo \"String is not empty\"\nelse\n  echo \"This never happens\"\nfi\n
\n\n
# Combinations\nif [[ X && Y ]]; then\n  ...\nfi\n
\n\n
# Equal\nif [[ \"$A\" == \"$B\" ]]\n
\n\n
# Regex\nif [[ \"A\" =~ . ]]\n
\n\n
if (( $a < $b )); then\n   echo \"$a is smaller than $b\"\nfi\n
\n\n
if [[ -e \"file.txt\" ]]; then\n  echo \"file exists\"\nfi\n
\n\n

Arrays

\n\n

Defining arrays

\n\n
Fruits=('Apple' 'Banana' 'Orange')\n
\n\n
Fruits[0]=\"Apple\"\nFruits[1]=\"Banana\"\nFruits[2]=\"Orange\"\n
\n\n

Working with arrays

\n\n
echo ${Fruits[0]}           # Element #0\necho ${Fruits[-1]}          # Last element\necho ${Fruits[@]}           # All elements, space-separated\necho ${#Fruits[@]}          # Number of elements\necho ${#Fruits}             # String length of the 1st element\necho ${#Fruits[3]}          # String length of the Nth element\necho ${Fruits[@]:3:2}       # Range (from position 3, length 2)\necho ${!Fruits[@]}          # Keys of all elements, space-separated\n
\n\n

Operations

\n\n
Fruits=(\"${Fruits[@]}\" \"Watermelon\")    # Push\nFruits+=('Watermelon')                  # Also Push\nFruits=( ${Fruits[@]/Ap*/} )            # Remove by regex match\nunset Fruits[2]                         # Remove one item\nFruits=(\"${Fruits[@]}\")                 # Duplicate\nFruits=(\"${Fruits[@]}\" \"${Veggies[@]}\") # Concatenate\nlines=(`cat \"logfile\"`)                 # Read from file\n
\n\n

Iteration

\n\n
for i in \"${arrayName[@]}\"; do\n  echo $i\ndone\n
\n\n

Dictionaries

\n\n

Defining

\n\n
declare -A sounds\n
\n\n
sounds[dog]=\"bark\"\nsounds[cow]=\"moo\"\nsounds[bird]=\"tweet\"\nsounds[wolf]=\"howl\"\n
\n\n

Declares sound as a Dictionary object (aka associative array).

\n\n

Working with dictionaries

\n\n
echo ${sounds[dog]} # Dog's sound\necho ${sounds[@]}   # All values\necho ${!sounds[@]}  # All keys\necho ${#sounds[@]}  # Number of elements\nunset sounds[dog]   # Delete dog\n
\n\n

Iteration

\n\n

Iterate over values

\n\n
for val in \"${sounds[@]}\"; do\n  echo $val\ndone\n
\n\n

Iterate over keys

\n\n
for key in \"${!sounds[@]}\"; do\n  echo $key\ndone\n
\n\n

Options

\n\n

Options

\n\n
set -o noclobber  # Avoid overlay files (echo \"hi\" > foo)\nset -o errexit    # Used to exit upon error, avoiding cascading errors\nset -o pipefail   # Unveils hidden failures\nset -o nounset    # Exposes unset variables\n
\n\n

Glob options

\n\n
shopt -s nullglob    # Non-matching globs are removed  ('*.foo' => '')\nshopt -s failglob    # Non-matching globs throw errors\nshopt -s nocaseglob  # Case insensitive globs\nshopt -s dotglob     # Wildcards match dotfiles (\"*.sh\" => \".foo.sh\")\nshopt -s globstar    # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')\n
\n\n

Set GLOBIGNORE as a colon-separated list of patterns to be removed from glob\nmatches.

\n\n

History

\n\n

Commands

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
historyShow history
shopt -s histverifyDon’t execute expanded result immediately
\n\n

Expansions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExpressionDescription
!$Expand last parameter of most recent command
!*Expand all parameters of most recent command
!-nExpand nth most recent command
!nExpand nth command in history
!<command>Expand most recent invocation of command <command>
\n\n

Operations

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescription
!!Execute last command again
!!:s/<FROM>/<TO>/Replace first occurrence of <FROM> to <TO> in most recent command
!!:gs/<FROM>/<TO>/Replace all occurrences of <FROM> to <TO> in most recent command
!$:tExpand only basename from last parameter of most recent command
!$:hExpand only directory from last parameter of most recent command
\n\n

!! and !$ can be replaced with any valid expansion.

\n\n

Slices

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescription
!!:nExpand only nth token from most recent command (command is 0; first argument is 1)
!^Expand first argument from most recent command
!$Expand last token from most recent command
!!:n-mExpand range of tokens from most recent command
!!:n-$Expand nth token to last from most recent command
\n\n

!! can be replaced with any valid expansion i.e. !cat, !-2, !42, etc.

\n\n

Miscellaneous

\n\n

Numeric calculations

\n\n
$((a + 200))      # Add 200 to $a\n
\n\n
$((RANDOM%=200))  # Random number 0..200\n
\n\n

Subshells

\n\n
(cd somedir; echo \"I'm now in $PWD\")\npwd # still in first directory\n
\n\n

Redirection

\n\n
python hello.py > output.txt   # stdout to (file)\npython hello.py >> output.txt  # stdout to (file), append\npython hello.py 2> error.log   # stderr to (file)\npython hello.py 2>&1           # stderr to stdout\npython hello.py 2>/dev/null    # stderr to (null)\npython hello.py &>/dev/null    # stdout and stderr to (null)\n
\n\n
python hello.py < foo.txt      # feed foo.txt to stdin for python\n
\n\n

Inspecting commands

\n\n
command -V cd\n#=> \"cd is a function/alias/whatever\"\n
\n\n

Trap errors

\n\n
trap 'echo Error at about $LINENO' ERR\n
\n\n

or

\n\n
traperr() {\n  echo \"ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}\"\n}\n\nset -o errtrace\ntrap traperr ERR\n
\n\n

Case/switch

\n\n
case \"$1\" in\n  start | up)\n    vagrant up\n    ;;\n\n  *)\n    echo \"Usage: $0 {start|stop|ssh}\"\n    ;;\nesac\n
\n\n

Source relative

\n\n
source \"${0%/*}/../share/foo.sh\"\n
\n\n

printf

\n\n
printf \"Hello %s, I'm %s\" Sven Olga\n#=> \"Hello Sven, I'm Olga\n\nprintf \"1 + 1 = %d\" 2\n#=> \"1 + 1 = 2\"\n\nprintf \"This is how you print a float: %f\" 2\n#=> \"This is how you print a float: 2.000000\"\n
\n\n

Directory of script

\n\n
DIR=\"${0%/*}\"\n
\n\n

Getting options

\n\n
while [[ \"$1\" =~ ^- && ! \"$1\" == \"--\" ]]; do case $1 in\n  -V | --version )\n    echo $version\n    exit\n    ;;\n  -s | --string )\n    shift; string=$1\n    ;;\n  -f | --flag )\n    flag=1\n    ;;\nesac; shift; done\nif [[ \"$1\" == '--' ]]; then shift; fi\n
\n\n

Heredoc

\n\n
cat <<END\nhello world\nEND\n
\n\n

Reading input

\n\n
echo -n \"Proceed? [y/n]: \"\nread ans\necho $ans\n
\n\n
read -n 1 ans    # Just one character\n
\n\n

Special variables

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExpressionDescription
$?Exit status of last task
$!PID of last background task
$$PID of shell
$0Filename of the shell script
\n\n

See Special parameters.

\n\n

Go to previous directory

\n\n
pwd # /home/user/foo\ncd bar/\npwd # /home/user/foo/bar\ncd -\npwd # /home/user/foo\n
\n\n

Check for command’s result

\n\n
if ping -c 1 google.com; then\n  echo \"It appears you have a working internet connection\"\nfi\n
\n\n

Grep check

\n\n
if grep -q 'foo' ~/.bash_history; then\n  echo \"You appear to have typed 'foo' in the past\"\nfi\n
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": ["Featured"], "updated": "2020-07-05" },{ "id": "blessed", "title": "Blessed", "url": "/blessed", "category": "JavaScript libraries", "keywords": null, "content_html": "

Screen

\n\n
screen = blessed.screen({\n  smartCSR: true       // optimize for flickering\n  autoPadding: true    // ..\n})\n\nscreen.append(Element)\nscreen.destroy()\n\nscreen.width\nscreen.height\nscreen.title = 'My window title'\nscreen.key(['escape', 'q', 'C-c'], (ch, key) => { ... })\n
\n\n

Element

\n\n
box = blessed.box({\n  style: { fg, bg, border.fg, scrollbar.bg, focus.bg, hover.bg },\n  border: { type: 'line'|'bg', bg, fg, bold, underline }\n  tags: true,  // parse {bold}tags{/bold}\n\n  top, left, width, height,\n  width: '100%',\n  height: '100%-1',\n  top: 'center'\n})\n
\n\n

Tags

\n\n
{bold}\n{right} {center}\n{|}    left-right separator\n{#c0ff33-fg}{/}\n
\n\n
blessed.escape('...')\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "bluebird", "title": "bluebird.js", "url": "/bluebird", "category": "JavaScript libraries", "keywords": null, "content_html": "

Also see

\n\n

Also see the promise cheatsheet and Bluebird.js API (github.com).

\n\n

Example

\n\n
promise\n  .then(okFn, errFn)\n  .spread(okFn, errFn)        // *\n  .catch(errFn)\n  .catch(TypeError, errFn)    // *\n  .finally(fn)\n  .map(function (e) { ··· })  // *\n  .each(function (e) { ··· }) // *\n
\n\n

Those marked with * are non-standard Promise API that only work with Bluebird promises.

\n\n

Multiple return values

\n\n
.then(function () {\n  return [ 'abc', 'def' ]\n})\n.spread(function (abc, def) {\n  ···\n})\n
\n\n

Use Promise.spread

\n\n

Multiple promises

\n\n
Promise.join(\n  getPictures(),\n  getMessages(),\n  getTweets(),\n  function (pics, msgs, tweets) {\n    return ···\n  }\n)\n
\n\n

Use Promise.join

\n\n

Multiple promises (array)

\n\n\n\n
Promise.all([ promise1, promise2 ])\n  .then(results => {\n    results[0]\n    results[1]\n  })\n\n// succeeds if one succeeds first\nPromise.any(promises)\n  .then(results => {\n  })\n
\n\n
Promise.map(urls, url => fetch(url))\n  .then(···)\n
\n\n

Use Promise.map to “promisify” a list of values.

\n\n

Object

\n\n
Promise.props({\n  photos: get('photos'),\n  posts: get('posts')\n})\n.then(res => {\n  res.photos\n  res.posts\n})\n
\n\n

Use Promise.props.

\n\n

Chain of promises

\n\n
function getPhotos() {\n  return Promise.try(() => {\n    if (err) throw new Error(\"boo\")\n    return result\n  })\n}\n\ngetPhotos().then(···)\n
\n\n

Use Promise.try.

\n\n

Node-style functions

\n\n
var readFile = Promise.promisify(fs.readFile)\nvar fs = Promise.promisifyAll(require('fs'))\n
\n\n

See Promisification.

\n\n

Promise-returning methods

\n\n
User.login = Promise.method((email, password) => {\n  if (!valid)\n    throw new Error(\"Email not valid\")\n\n  return /* promise */\n})\n
\n\n

See Promise.method.

\n\n

Generators

\n\n
User.login = Promise.coroutine(function* (email, password) {\n  let user = yield User.find({email: email}).fetch()\n  return user\n})\n
\n\n

See Promise.coroutine.

\n\n

Reference

\n\n

http://bluebirdjs.com/docs/api-reference.html

", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-08" },{ "id": "bolt", "title": "Bolt Quickstart", "url": "/bolt", "category": "Bolt", "keywords": ["Puppet","tasks","modules"], "content_html": "

Install Bolt

\n\n
# On MacOS\nbrew cask install puppetlabs/puppet/puppet-bolt\n# On Windows\nchoco install puppet-bolt\n
\n\n

Bolt is available as a package for most platforms. See installing bolt

\n\n

Create a module with a task

\n\n
mkdir -p ~/.puppetlabs/bolt/modules/mymodule/tasks\ncp myscript.sh ~/.puppetlabs/bolt/modules/mymodule/tasks/\n
\n\n

Tasks can be written in any language your targets can run. See writing tasks for more details.

\n\n

Run Bolt

\n\n
bolt task run mymodule::myscript -n node1.example.com,node2.example.com --private-key ~/.ssh/id_rsa-private\n
\n\n

See bolt task run --help for more information and command line options.

", "intro_html": "", "description_html": "

A quick guide to getting started writing Bolt tasks

", "tags": null, "updated": "2018-12-25" },{ "id": "bookshelf", "title": "Bookshelf.js", "url": "/bookshelf", "category": "JavaScript libraries", "keywords": null, "content_html": "

Model

\n\n
Summary = bookshelf.Model.extend({\n  tableName: 'summaries',\n  hasTimestamps: true,\n  hasTimestamps: ['created_at', 'updated_at'],\n})\n
\n\n

Associations

\n\n
Summary = bookshelf.Model.extend({\n  book () {\n    return this.belongsTo(Book)\n  },\n  author () {\n    return this.hasOne(Author)\n  }\n  // belongsToMany\n  // hasMany\n  // hasMany().through()\n})\n
\n\n

CRUD

\n\n
Book.create({ title: '..' }).save()\nnew Book({ title: '..' }).save()\n\nnew Book({ id: 1 }).fetch()\n\nBook.where({ id: 1 }).fetch()\nBook.where('favorite_color', 'red').fetch()\nBook.where('favorite_color', '<>', 'red').fetch()\nBook\n  .query((q) => q.orderBy('updated_at')\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "bootstrap", "title": "Bootstrap", "url": "/bootstrap", "category": "CSS", "keywords": null, "content_html": "

Screen sizes

\n\n
         768          992                1200\n'     '     '     '     '     '     '     '     '\n<---------^------------^------------------^--------->\n     xs         sm              md             lg\n   (phone)   (tablet)        (laptop)       (desktop)\n
\n\n

Min:

\n\n
@media (min-width: @screen-sm-min) // >= 768px (small tablet)\n@media (min-width: @screen-md-min) // >= 992px (medium laptop)\n@media (min-width: @screen-lg-min) // >= 1200px (large desktop)\n
\n\n

Max:

\n\n
@media (max-width: @screen-xs-max) { // < 768px (xsmall phone)\n@media (max-width: @screen-sm-max) { // < 992px (small tablet)\n@media (max-width: @screen-md-max) { // < 1200px (medium laptop)\n
\n\n

Columns

\n\n
.container\n.container-fluid\n
\n\n
.col-xs-1\n.col-sm-1\n.col-md-1\n.col-lg-1\n.col-md-offset-1\n
\n\n

Mixins:

\n\n
@include make-xs-column(12);\n@include make-sm-column(6);\n@include make-md-column(3);\n@include make-lg-column(3);\n
\n\n
@include make-sm-column-offset(1);\n@include make-sm-column-push(1);\n@include make-sm-column-pull(1);\n
\n\n

Utilities

\n\n
.pull-left\n.pull-right\n
\n\n
.hidden-{xs,sm,md,lg}\n.visible-{xs,sm,md,lg}\n.visible-{xs,sm,md,lg,print}-{block,inline,inline-block}\n
\n\n
.center-block  /* margin: auto */\n.clearfix\n.text-{center,left,right,justify,nowrap}\n.text-{lowercase,uppercase,capitalize}\n
\n\n
.show\n.hidden\n
\n\n

Modal

\n\n
<a data-toggle='modal' data-target='#new'>\n
\n\n
#new.modal.fade(role='dialog')\n  .modal-dialog // .modal-lg, .modal-sm\n    .modal-content\n      .modal-header\n        %h4.modal-title hello\n        %button.close{type: 'button', data: { dismiss: 'modal' }}\n          %span{'aria-hidden' => true}!= \"&times;\"\n          %span.sr-only Close\n      .modal-body\n        ...\n      .modal-footer\n        ...\n
\n\n

Modal via ajax (Rails)

\n\n
%button.btn{data: { |\n  toggle: 'modal', |\n  target: '#chooseTheme', |\n  remote: '/path/to/remote'}\n  Change Theme\n
\n\n
.modal.fade#chooseTheme\n  .modal-dialog.modal-xl\n    .modal-content\n      .modal-header\n        %h4.modal-title Choose a theme\n\n      .modal-body\n        .spinner-panel.-lg\n          %i\n
\n\n

Tooltip

\n\n
<span\n  data-toggle='tooltip'\n  title='tooltip'\n  data-placement='left|top|bottom|right'>\n
\n\n
$(function () {\n  $('[data-toogle~=\"tooltip\"]').tooltip()\n})\n
\n\n

Input groups

\n\n
.input-group\n    input.form-control(type='text')\n    .input-group-addon years\n
", "intro_html": "", "description_html": "

.container .row .col-md-6, @screen-sm-min, .form-control, grids, .modal-content, tooltips, and other Bootstrap CSS examples.

", "tags": null, "updated": null },{ "id": "deprecated/bower-api", "title": "Bower API", "url": "/deprecated/bower-api", "category": "JavaScript libraries", "keywords": null, "content_html": "
require('bower').config\n
\n\n
{ cwd: '/Users/rsc',\n  directory: 'bower_components',\n  registry:\n   { search: [ 'https://bower.herokuapp.com' ],\n     register: 'https://bower.herokuapp.com',\n     publish: 'https://bower.herokuapp.com' },\n  shorthandResolver: 'git://github.com//.git',\n  tmp: '/var/folders/5y/190gjd_j2c5bfkn563dk2xdr0000gn/T/rsc/bower',\n  timeout: 30000,\n  ca: { search: [] },\n  strictSsl: true,\n  userAgent: 'node/v0.10.33 darwin x64',\n  color: true,\n  storage:\n   { packages: '/Users/rsc/.cache/bower/packages',\n     links: '/Users/rsc/.local/share/bower/links',\n     completion: '/Users/rsc/.local/share/bower/completion',\n     registry: '/Users/rsc/.cache/bower/registry',\n     empty: '/Users/rsc/.local/share/bower/empty' },\n  interactive: false,\n  argv: { remain: [], cooked: [], original: [] } }\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "browser-sync", "title": "Browsersync", "url": "/browser-sync", "category": "JavaScript libraries", "keywords": null, "content_html": "
npm i -g browser-sync\n
\n\n

Start a server

\n\n
browser-sync start --server <path> --files='**/*.html, **/*.css'\n
\n\n

Options

\n\n
  --port=N\n  --proxy=\"http://127.0.0.1:3000\"\n
\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "browserify", "title": "Browserify", "url": "/browserify", "category": "JavaScript libraries", "keywords": null, "content_html": "
browserify input.js\n  -o output.js\n  -t coffeeify\n  -t [ coffeeify --extension coffee ]\n\n  -u react (--exclude: omit a file)\n  -x react (--external: reference in another bundle)\n  -i react (--ignore: stub a file)\n  -s Myapp (--standalone: generate a UMD bundle)\n  --debug\n
\n\n

Programmatic usage

\n\n
browserify = require('browserify')\nbrowserify()\n  .add('main.js')\n  .bundle()\n  .transform(coffeeify)\n  .transform({extensions: '.coffee'}, coffeeify)\n  .pipe(process.stdout)\n\nbrowserify({})\n
\n\n

Tools

\n\n\n\n

Transforms

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "bulma", "title": "Bulma", "url": "/bulma", "category": "CSS", "keywords": null, "content_html": "

Screen sizes

\n\n
         768         1024                1216         1408\n'     '     '     '     '     '     '     '     '     '     '     '\n<---------^------------^------------------^-------------^------------->\n  mobile      tablet         desktop         widescreen      fullhd\n
\n\n

Columns

\n\n
.container\n
\n

Wrap as many .column’s’ as you like in a .columns wrapper

\n
<div class=\"columns\">\n    <div class=\"column\"></div>\n    <div class=\"column\"></div>\n    <div class=\"column\"></div>\n    <div class=\"column\"></div>\n    <div class=\"column\"></div>\n</div>\n
\n\n

Modifiers

\n\n

The following CSS classes affect the colour.

\n\n
.is-primary\n.is-link\n.is-info\n.is-success\n.is-warning\n.is-danger\n
\n\n

The following classes modify the size.

\n
.is-small\n.is-medium\n.is-large\n
\n\n

The following classes modify the state.

\n
.is-outlined\n.is-loading\n
\n\n

Typography Helpers

\n\n

The following classes modify the font-size

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ClassFont-size
.is-size-13rem
.is-size-22.5rem
.is-size-32rem
.is-size-41.5rem
.is-size-51.25rem
.is-size-61rem
.is-size-70.75rem
\n\n

The following classes align the text

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ClassAlignment
.has-text-centeredMakes the text centered
.has-text-justifiedMakes the text justified
.has-text-left.Makes the text align to the left
.has-text-rightMakes the text align to the right
\n\n

The following classes transform the text

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ClassTransformation
.is-capitalizedTransforms the first character of each word to uppercase
.is-lowercaseTransforms all characters to lowercase
.is-uppercaseTransforms all characters to uppercase
\n\n

WYSIWYG Content

\n\n
<div class=\"content\">\n  <!-- start WYSIWYG contents -->\n  <h1>Heading</h1>\n  <p>Paragraph</p>\n\n  <ul>\n    <li>Item 1</li>\n    <li>Item 2</li>\n  </ul>\n  <!-- end WYSIWYG contents -->\n</div>\n
\n\n

To provide default stylings for commonly generated WYSIWYG contents, use the .content class.

", "intro_html": "", "description_html": "

Basic guide on how to use Bulma, the lightweight css flexbox framework.

", "tags": null, "updated": "2018-11-19" },{ "id": "bundler", "title": "Bundler", "url": "/bundler", "category": "Ruby", "keywords": null, "content_html": "

Commands

\n\n
bundle                  # same as bundle install\nbundle install          # installs gems\nbundle install -j3      # faster (3 jobs)\nbundle update           # update all gems\nbundle update --source gemname  # update specified gem\n\nbundle outdated         # show outdated gems\ncd `bundle show rails`  # inspect a gem's dir\n\nbundle gem              # new gem skeleton\n
\n\n

Gems

\n\n
gem 'hello'\ngem 'hello', group: 'development'\n
\n\n

Github support

\n\n
gem 'hello', github: 'rstacruz/hello'\ngem 'hello', github: 'rstacruz/hello', 'branch: master'\n
\n\n

Grouping

\n\n
group :development do\n  gem 'hello'\nend\n
\n\n

Deployment

\n\n
$ bundle install --without=test,development --deployment\n
\n\n

Local gem development

\n\n

In your Gemfile, define a Git source and a branch:

\n\n
gem 'hello', github: 'rstacruz/hello', branch: 'master'\n
\n\n

And then:

\n\n
$ bundle config --global local.xxx ~/projects/xxx\n
\n\n

Rake Gem tasks

\n\n
# Rakefile\nrequire 'bundler/gem_tasks'\n
\n\n

Terminal:

\n\n
$ rake release\n$ rake build\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "c_preprocessor", "title": "C Preprocessor", "url": "/c_preprocessor", "category": "C-like", "keywords": null, "content_html": "

Reference

\n\n

Compiling

\n\n
$ cpp -P file > outfile\n
\n\n

Includes

\n\n
#include \"file\"\n
\n\n

Defines

\n\n
#define FOO\n#define FOO \"hello\"\n\n#undef FOO\n
\n\n

If

\n\n
#ifdef DEBUG\n  console.log('hi');\n#elif defined VERBOSE\n  ...\n#else\n  ...\n#endif\n
\n\n

Error

\n\n
#if VERSION == 2.0\n  #error Unsupported\n  #warning Not really supported\n#endif\n
\n\n

Macro

\n\n
#define DEG(x) ((x) * 57.29)\n
\n\n

Token concat

\n\n
#define DST(name) name##_s name##_t\nDST(object);   #=> \"object_s object_t;\"\n
\n\n

file and line

\n\n
#define LOG(msg) console.log(__FILE__, __LINE__, msg)\n#=> console.log(\"file.txt\", 3, \"hey\")\n
", "intro_html": "

Quick reference for the C macro preprocessor, which can be used independent of C/C++.

", "description_html": "", "tags": null, "updated": null },{ "id": "camp", "title": "Camp", "url": "/camp", "category": "JavaScript libraries", "keywords": null, "content_html": "

Getting started

\n\n

Quick start

\n\n

app.js

\n\n
const Camp = require('camp')\nconst camp = Camp.start({ port: 1234 })\n
\n\n

web/index.html

\n\n
<!doctype html>\n<body>Hello world!</body>\n
\n\n

Camp serves files in web/ by default.

\n\n

Routes

\n\n

Handles /search?q=rainbows

\n\n
camp.path('/search', (req, res) => {\n  const q = res.query.q\n  res.json({ results: ··· })\n})\n
\n\n

Also available: camp.post, camp.get.

\n\n

Templates

\n\n
const tpl = Camp.template('./templates/post.html')\n\ncamp.path('/blog/:post.html', (req, res) => {\n  res.template({\n    text: 'Hello world'\n  }, tpl)\n})\n
\n\n

See: Templates

\n\n

Not found

\n\n
camp.notFound('/*.lol', (req, res) => {\n  res.file('/404.html')\n})\n
\n\n

See: Fall through

\n\n

Low level handler

\n\n
camp.handle((req, res, next) => {\n  res.setHeader('X-Hello', 'world')\n  next()\n})\n
\n\n

See: Handlers

\n\n

Templates

\n\n

Basic templates

\n\n
const tpl = Camp.template('/templates/post.html')\n\ncamp.path('/blog/:post.html', (req, res) => {\n  res.template({\n    text: 'Hello world'\n  }, tpl)\n})\n
\n\n

Implicit templates

\n\n
camp.path('blog.html')\n
\n\n

Uses blog.html as a template.

\n\n

See: Templates

\n\n

Advanced features

\n\n

Web sockets

\n\n
camp.ws('/path', (socket) => { ··· })\n
\n\n
camp.wsChannels[path]\n
\n\n
camp.wsBroadcast('/path', (req, res) => {\n})\n
\n\n

Sorry I don’t completely understand this yet, but check it out in their docs.

\n\n

See: WebSocket

", "intro_html": "

Camp is a Node.js web server framework. This guide targets Camp v17.x.

", "description_html": "", "tags": null, "updated": "2017-09-21" },{ "id": "canvas", "title": "Canvas", "url": "/canvas", "category": "JavaScript", "keywords": null, "content_html": "

Getting the context

\n\n
var canvas = document.getElementById('c')\nvar c = canvas.getContext('2d')\n
\n\n

Basic drawing

\n\n
// x = 10, y = 20, width = 200, height = 100\nc.fillStyle = '#ff0000'\nc.strokeStyle = '#ff00ff'\n
\n\n
c.lineWidth = 5\nc.lineCap = 'round'\n
\n\n
c.fillRect(10, 20, 200, 100)\n
\n\n
c.stroke()\nc.fill()\n
\n\n

Saving and restoring

\n\n
c.save()\n
\n\n
c.restore()\n
\n\n

Saves: strokeStyle fillStyle globalAlpha lineWidth lineCap lineJoin miterLimit shadowOffsetX shadowOffsetY shadowBlur shadowColor\nglobalCompositeOperation, Transformations (translate rotate scale transform setTransform), Clipping path

\n\n

Animation

\n\n
onframe: function() {\n  c.clearRect(0, 0, w, h)\n}\n
\n\n

Transformations

\n\n
c.translate(0, 0)\nc.rotate(Math.PI*2/5)\nc.scale(1.0, 1.0)\n
\n\n

To rotate along origin:

\n\n
c.translate(ox, oy)\nc.rotate(theta)\nc.translate(-ox, -oy)\n
\n\n

To scale along origin:

\n\n
c.translate(-ox*x, -oy*y)\nc.scale(x, y)\nc.translate(ox/x, oy/y)\n
\n\n

See MDN: Transformations.

\n\n

Image drawing

\n\n
c.drawImage(image, dx, dy, [dw, dh]);\n/* `image` can be HTML Image/Canvas/Video */\n
\n\n

See MDN: Images.

\n\n

Colors, styles shadows

\n\n
c.strokeStyle = '#ff00ff';\nc.fillStyle = '#ff00ff';\n
\n\n
c.shadowOffsetX = 0;\nc.shadowOffsetY = 0;\nc.shadowOffsetBlur = 3.0;\nc.shadowColor = 'rgba(0,0,0,0.2)';\n
\n\n

See MDN: Styles

\n\n

Gradients

\n\n
gr = c.createLinearGradient(x0,y0,x1,y1)\ngr = c.createRadialGradient(x0,y0,r0,x1,y1,r1)\npat = c.createPattern(image, 'repeat-x')\n
\n\n
c.fillStyle = gr\n
\n\n

Drawing

\n\n
c.beginPath()\nc.moveTo(x,y)\nc.lineTo(x,y)\nc.quadraticCurveTo(cpx,cpy,x,y)\nc.bezierCurveTo(cp1x,cp1y,cp2x,cp2y)\nc.arcTo(...)\nc.arc(...)\nc.closePath()\n
\n\n

More resources

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "capybara", "title": "Capybara", "url": "/capybara", "category": "Ruby libraries", "keywords": null, "content_html": "

Navigating

\n\n
visit articles_path\n
\n\n\n\n
click_on 'Link Text'\nclick_button\nclick_link\n
\n\n

Interacting with forms

\n\n
attach_file 'Image', '/path/to/image.jpg'\nfill_in 'First Name', with: 'John'\n
\n\n
check 'A checkbox'\nuncheck 'A checkbox'\n
\n\n
choose 'A radio button'\n
\n\n
select 'Option', from: 'Select box'\nunselect\n
\n\n

Limiting

\n\n
within '.classname' do\n  click '...'\nend\n
\n\n
within_fieldset :id do\n  ...\nend\n
\n\n

Querying

\n\n

Predicates

\n\n
page.has_css?('.button')\nexpect(page).to have_css('.button')\npage.should have_css('.button')\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PositiveNegative
has_content?has_no_content?
has_css? (selector)has_no_css?
has_xpath? (path)has_no_xpath?
has_link? (selector)has_no_link?
has_button? (selector)has_no_button?
has_field? (selector)has_no_field?
has_checked_field? (selector)has_unchecked_field?
has_table? (selector)has_no_table?
has_select? (selector)has_no_select?
\n\n

In Rspec, these also map to matchers like page.should have_content.

\n\n

Selectors

\n\n
expect(page).to have_button('Save')\n
\n\n
expect(page).to have_button('#submit')\n
\n\n
expect(page).to have_button('//[@id=\"submit\"]')\n
\n\n

The selector arguments can be text, CSS selector, or XPath expression.

\n\n

RSpec assertions

\n\n
page.has_button?('Save')\n
\n\n
expect(page).to have_no_button('Save')\n
\n\n

In RSpec, you can use page.should assertions.

\n\n

About negatives

\n\n
expect(page).to have_no_button('Save')   # OK\n
\n
expect(page).not_to have_button('Save')  # Bad\n
\n\n

Use should have_no_* versions with RSpec matchers because\nshould_not have_* doesn’t wait for a timeout from the driver.

\n\n

RSpec

\n\n

Matchers

\n\n
expect(page).to \\\n
\n\n
  have_selector '.blank-state'\n  have_selector 'h1#hola', text: 'Welcome'\n  have_button 'Save'\n  have_checked_field '#field'\n  have_unchecked_field\n  have_css '.class'\n  have_field '#field'\n  have_table '#table'\n  have_xpath '//div'\n
\n\n
  have_link 'Logout', href: logout_path\n
\n\n
  have_select 'Language',\n    selected: 'German'\n    options: ['Engish', 'German']\n    with_options: ['Engish', 'German'] # partial match\n
\n\n
  have_text 'Hello',\n    type: :visible # or :all\n    # alias: have_content\n
\n\n

Common options

\n\n

All matchers have these options:

\n\n
  text: 'welcome'\n  text: /Hello/\n  visible: true\n  count: 4\n  between: 2..5\n  minimum: 2\n  maximum: 5\n  wait: 10\n
\n\n

Other features

\n\n

Finding

\n\n
find(selector)\nfind_button(selector)\nfind_by_id(id)\nfind_field(selector)\nfind_link(selector)\nlocate\n
\n\n

Scoping

\n\n
within '#delivery' do\n  fill_in 'Street', with: 'Hello'\nend\n
\n\n
within :xpath, '//article'\nwithin_fieldset\nwithin_table\nwithin_frame\nscope_to\n
\n\n
find('#x').fill_in('Street', with: 'Hello')\n# same as within\n
\n\n

Scripting

\n\n
execute_script('$(\"input\").trigger(\"change\")')\nevaluate_script('window.ga')\n
\n\n

Executes JavaScript.

\n\n

Debugging

\n\n
save_and_open_page\n
\n\n

Opens the webpage in your browser.

\n\n

Page

\n\n
page\n  .all('h3')\n  .body\n  .html\n  .source\n  .current_host\n  .current_path\n  .current_url\n
\n\n

AJAX

\n\n
using_wait_time 10 do\n  ...\nend\n
\n\n

Misc

\n\n
drag\nfield_labeled\n
\n\n

Page object

\n\n
page.status_code == 200\npage.response_headers\n
\n\n

See: http://www.rubydoc.info/github/jnicklas/capybara/master/Capybara/Session

\n\n

Poltergeist

\n\n
Capybara.register_driver :poltergeist do |app|\n  Capybara::Poltergeist::Driver.new(app, :inspector => true)\nend\nCapybara.javascript_driver = :poltergeist\n
\n\n

Use poltergeist to integrate PhantomJS.

\n\n

Blacklist

\n\n
config.before :each, :js do\n  page.driver.browser.url_blacklist = [\n    'fonts.googleapis.com',\n    'use.typekit.net',\n    'f.vimeocdn.com',\n    'player.vimeo.com',\n    'www.googletagmanager.com'\n  ].flat_map { |domain| [ \"http://#{domain}\", \"https://#{domain}\" ] }\nend\n
\n\n

Debugging

\n\n

Enable inspector: true and then:

\n\n
page.driver.debug\n
\n\n

To pause execution for a while:

\n\n
page.driver.pause\n
\n\n

Selenium

\n\n

Accepting confirm() and alert()

\n\n
accept_alert { ... }\ndismiss_confirm { ... }\naccept_prompt(with: 'hi') { ... }\n
\n\n

Alternatively:

\n\n
page.driver.browser.switch_to.alert.accept\n
\n\n

Updating session

\n\n
page.set_rack_session(foo: 'bar')\n
\n\n

See also

\n\n", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2020-06-13" },{ "id": "cask-index", "title": "Caskroom index", "url": "/cask-index", "category": "Others", "keywords": null, "content_html": "

Caskroom

\n\n

A

\n\n\n\n

B

\n\n\n\n

C

\n\n\n\n

D

\n\n\n\n

E

\n\n\n\n

F

\n\n\n\n

G

\n\n\n\n

H

\n\n\n\n

I

\n\n\n\n

J

\n\n\n\n

K

\n\n\n\n

L

\n\n\n\n

M

\n\n\n\n

N

\n\n\n\n

O

\n\n\n\n

P

\n\n\n\n

Q

\n\n\n\n

R

\n\n\n\n

S

\n\n\n\n

T

\n\n\n\n

U

\n\n\n\n

V

\n\n\n\n

W

\n\n\n\n

X

\n\n\n\n

Y

\n\n\n\n

Z

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "chai", "title": "Chai.js", "url": "/chai", "category": "JavaScript libraries", "keywords": null, "content_html": "

Assert

\n\n
const { assert } = require('chai')\n
\n\n
assert(val)\nassert.fail(actual, expected)\nassert.ok(val)                        // is truthy\nassert.equal(actual, expected)        // compare with ==\nassert.strictEqual(actual, expected)  // compare with ===\nassert.deepEqual(actual, expected)    // deep equal check\n
\n\n
assert.isTrue(val)\nassert.isFalse(val)\n
\n\n
assert.isNull(val)\nassert.isNotNull(val)\nassert.isUndefined(val)\nassert.isDefined(val)\nassert.isFunction(val)\nassert.isObject(val)\nassert.isArray(val)\nassert.isString(val)\nassert.isNumber(val)\nassert.isBoolean(val)\n
\n\n
assert.typeOf(/tea/, 'regexp') // Object.prototype.toString()\nassert.instanceOf(chai, Tea)\nassert.include([ a,b,c ], a)\nassert.match(val, /regexp/)\nassert.property(obj, 'tea') // 'tea' in object\nassert.deepProperty(obj, 'tea.green')\nassert.propertyVal(person, 'name', 'John')\nassert.deepPropertyVal(post, 'author.name', 'John')\n
\n\n
assert.lengthOf(object, 3)\nassert.throws(function() { ... })\nassert.throws(function() { ... }, /reference error/)\nassert.doesNotThrow\n
\n\n
assert.operator(1, '<', 2)\nassert.closeTo(actual, expected)\n
\n\n

See: Assert API (chaijs.com)

\n\n

BDD syntax

\n\n
const { expect } = require('chai')\n
\n\n
expect(object)\n  .to.equal(expected)\n  .to.eql(expected)        // deep equality\n  .to.deep.equal(expected) // same as .eql\n  .to.be.a('string')\n  .to.include(val)\n
\n\n
  .be.ok(val)\n  .be.true\n  .be.false\n  .to.exist\n
\n\n
  .to.be.null\n  .to.be.undefined\n  .to.be.empty\n  .to.be.arguments\n  .to.be.function\n  .to.be.instanceOf\n
\n\n
  .to.be.gt(5)  // aka: .above .greaterThan\n  .to.be.gte(5) // aka: .at.least\n  .to.be.lt(5)  // aka: .below\n
\n\n
  .to.respondTo('bar')\n  .to.satisfy((n) => n > 0)\n
\n\n
  .to.have.members([2, 3, 4])\n  .to.have.keys(['foo'])\n  .to.have.key('foo')\n  .to.have.lengthOf(3)\n
\n\n
expect(() => { ··· })\n  .to.throw(/not a function/)\n
\n\n

See: BDD (chaijs.com)

\n\n

Should: chains

\n\n
.to .be .been .is .that .and .have .with .at .of .same\n
\n\n

These don’t do anything and can be chained.

\n\n

Should not

\n\n
expect(object).not.equal('x')\n
\n\n

Chai with jQuery

\n\n

Using chai-jquery

\n\n
global.jQuery = ···\nchai.use(require('chai-jquery'))\n
\n\n
expect($body)\n  .have.attr('foo')\n  .have.prop('disabled')\n  .have.css('background')\n  .have.css('background-color', '#ffffff')\n  .have.data('foo')\n
\n\n
  .have.class('active')\n  .have.id('id')\n
\n\n
  .have.html('<em>hi</em>')\n  .have.text('hello')\n  .have.value('2013')\n
\n\n

Continued

\n\n
expect($body)\n
\n\n
  .be.visible\n  .be.hidden\n
\n\n
  .be.checked\n  .be.selected\n
\n\n
  .be.enabled\n  .be.disabled\n
\n\n
  .be.empty\n  .to.exist\n  .to.contain('text')\n  .to.have('.selector')\n
", "intro_html": "", "description_html": "

expect(x).to.be.equal(y) 〉 assert.equal(x, y) 〉 .to.be.true 〉 jQuery, assertions, TDD and BDD, and other Chai examples.

", "tags": null, "updated": "2018-06-25" },{ "id": "cheatsheet-styles", "title": "Cheatsheet styles", "url": "/cheatsheet-styles", "category": "Others", "keywords": null, "content_html": "

Intro

\n\n

Variants

\n\n

H2 sections

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-one-column 
-two-column(default)
-three-column 
-left-reference3 columns
(short first column)
-no-hideDon’t hide H2
\n\n

See: H2 sections

\n\n

H3 sections

\n\n\n \n \n \n \n \n \n
-primeHighlight
\n\n

See: H3 sections

\n\n

Tables

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-bold-firstBold first column
-headersShow headers
-left-alignDon’t right align last column
-mute-emLower opacity for italics
-no-wrapDon’t wrap text
-shortcutsShortcut keys
\n\n

See: Tables

\n\n

Code

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-box-charsLess line height
for box drawing chars
-setupGray background
-wrapEnables line-wrapping
\n\n

See: Code

\n\n

Paragraphs

\n\n\n \n \n \n \n \n \n \n \n \n \n
-setupGray background
-crosslinkHas arrow on the link
\n\n

See: Paragraphs

\n\n

Lists

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-also-seeLighter background
-four-column 
-six-column 
\n\n

See: Lists

\n\n

Adding variants

\n\n
## Section\n{: .-two-column}\n
\n\n

Devhints uses Kramdown, and supports adding classes via Kramdown’s syntax.

\n\n

H3 sections

\n\n

Supported

\n\n

Each section can have the following children:

\n\n

White

\n\n\n\n

Gray

\n\n\n\n

Prime section

\n\n

This is a section with {: .-prime}. Notice the fancy highlight! Great for “getting started” kind of snippets.

\n\n

H3 section

\n\n

Every box is an H3 section. The box will encompass everything inside the body of the H3.

\n\n

This is a basic section with paragraphs in it.

\n\n

Code

\n\n

Basic code

\n\n
here.is(() => {\n  some.code()\n})\n
\n\n
here.is.some.more()\n
\n\n

Code blocks can be placed one after the other.

\n\n

See: Cheatsheets

\n\n

Code with headings

\n\n

index.js

\n\n
here.is(() => {\n  some.code()\n})\n
\n\n

other.js

\n\n
here.is.some.more()\n
\n\n

Code blocks can have headings.

\n\n

Highlighted lines

\n\n
app.start(() => {\n  const port = app.server.port\n  console.log(`Started at ${port}`)\n})\n
\n\n

Add {: data-line=\"3\"} to add line highlights.

\n\n

Multiple highlights

\n\n
app.start(() => {\n  const port = app.server.port\n  console.log(`Started at ${port}`)\n})\n
\n\n

Add {: data-line=\"2,3\"} to add multiple line highlights.

\n\n

Setup blocks

\n\n
import React from 'react'\n
\n\n
class Hello extends React.Component {\n  render () {\n    return <span>Hello</span>\n  }\n}\n
\n\n

Add {: .-setup} to a pre or table or ul.

\n\n

Long lines

\n\n
function createNode(nodeName: string, options: { key: string }) {\n  return true\n}\n
\n\n

Long lines will have scrollbars.

\n\n

Line wrapping

\n\n
<script>(function(d,s){if(window.Promise&&[].includes&&Object.assign&&window.Map)return;var js,sc=d.getElementsByTagName(s)[0];js=d.createElement(s);js.src='https://cdn.polyfill.io/v2/polyfill.min.js';sc.parentNode.insertBefore(js, sc);}(document,'script'))</script>\n
\n\n

Add -wrap to wrap long lines.

\n\n

Lists

\n\n

Lists

\n\n\n\n

Here’s an extra paragraph after the list.

\n\n

Lists with headings

\n\n

Part 1

\n\n\n\n

Part 2

\n\n\n\n

Here’s an extra paragraph after the list.

\n\n

List columns

\n\n

Six columns

\n\n\n\n

Add {: .-six-column} to make large lists.

\n\n

Four columns

\n\n\n\n

Add {: .-four-column} to make large lists.

\n\n

Also see

\n\n\n\n

Add {: .-also-see}.

\n\n

Paragraphs

\n\n

Basic paragraphs

\n\n

This is a basic section with paragraphs in it. When paragraphs are the first elements in an H3 section’s body, they appear as white.

\n\n

Basic paragraphs

\n\n
···\n
\n\n

When paragraphs appear after pre/table/ul, they appear with a gray background.

\n\n

Preludes

\n\n

Here’s a prelude paragraph. Add {: .-setup} to make paragraphs appear with a gray background.

\n\n
···\n
\n\n

Crosslink

\n\n

Add {: .-crosslink} to make big loud external links:

\n\n
···\n
\n\n

Home

\n\n

Tables

\n\n

Basic table

\n\n

Date

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
%m/%d/%Y06/05/2013
%A, %B %e, %YSunday, June 5, 2013
%b %e %aJun 5 Sun
\n\n

Time

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
%H:%M23:05
%I:%M %p11:05 PM
\n\n

This is a basic table with h4’s.

\n\n

Shortcuts

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VVector
PPencil
TText
LLine
RRectangle
OOval
URounded
\n\n

Add {: .-shortcuts} to tables.

\n\n

With headers

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PrefixExampleWhat
////hr[@class='edge']Anywhere
././aRelative
//html/body/divRoot
\n\n

Add {: .-headers} to add headers.

\n\n

Two columns

\n\n

One

\n\n
···\n
\n\n

Two

\n\n
···\n
\n\n

Left reference

\n\n

One

\n\n
···\n···\n···\n···\n···\n···\n···\n···\n
\n\n

Two

\n\n
···\n
\n\n

Three

\n\n
···\n
\n\n

One column

\n\n

One

\n\n
···\n
", "intro_html": "

This is a reference of styles that you can use on Devhints cheatsheets. How\nmeta!\nYou can refer to this when contributing your own cheatsheets to the GitHub repo.

", "description_html": "", "tags": ["WIP"], "updated": "2017-10-26" },{ "id": "chef", "title": "Chef", "url": "/chef", "category": "Devops", "keywords": null, "content_html": "

Install

\n\n

In your server:

\n\n
$ sudo apt-get install curl\n
\n\n
$ curl -L https://omnitruck.chef.io/install.sh | sudo bash\nThank you for installing Chef!\n
\n\n
$ chef-solo -v\n...\nChef: 14.5.33\n
\n\n

Start the cookbook

\n\n
 wget http://github.com/chef-cookbooks/chef-repo/tarball/master -O - | tar xzf - --strip-components=1\n
\n\n

Knife

\n\n
$ knife supermarket download mysql\n
\n\n

Invoking chef-solo

\n\n
$ chef-solo -c solo.rb -j web.json\n
\n\n

Examples

\n\n

Simple compile-from-source

\n\n
execute \"tar --no-same-owner -zxf hi.tar.gz\" do\n  cwd \"/usr/local/src\"\n  creates \"/usr/local/src/node-v#{version}\"\nend\n
\n\n
bash \"compile\" do\n  cwd \"/usr/local/src/node-v#{version}\"\n  code %[\n    PATH=/usr/local/bin:$PATH\n    ./configure\n    make\n  ]\n  creates \"/usr/local/src/node-v#{version}/node\"\nend\n
\n\n

remote file

\n\n
remote_file \"/usr/local/src/hi.tar.gz\" do\n  source \"http://...\"\n  checksum \"ab83be...\"\n  mode 0644\n  action :create_if_missing\nend\n
\n\n

ruby_block

\n\n
ruby_block \"name\" do\n  block { File.read ... }\n  not_if { File.exists?(...) }\nend\n
\n\n

Execute

\n\n
execute \"name\" do\n  cwd \"...\"\n  environment({ \"PATH\" => \"...\" })\n  command \"make install\"\n  creates \"...\"\nend\n
\n\n

Conditions

\n\n
  creates \"/usr/local/src/node-v#{version}/node\"\n  not_if { File.exists?('...') }\n
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "chunky_png", "title": "Chunky PNG", "url": "/chunky_png", "category": "Ruby libraries", "keywords": null, "content_html": "

Loading

\n\n
image = ChunkyPNG::Image.from_file('file.png')\n
\n\n

Alternate ways

\n\n
image = ChunkyPNG::Image.from_blob(File.read('file.png'))\nimage = ChunkyPNG::Image.from_io(io) \n
\n\n

Loads from file.png.

\n\n

Saving

\n\n
image.save('filename.png')\n
\n\n

Alternate ways

\n\n
File.open('newfile.png', 'wb') { |io| image.write(io) }\nbinary_string = image.to_blob\n
\n\n

Writes an image to newfile.png.

\n\n

Drawing

\n\n
image[0, 0] = ChunkyPNG::Color.rgba(255, 0,0, 128)\nimage.line(1, 1, 10, 1, ChunkyPNG::Color.from_hex('#aa007f'))\n
\n\n

Canvas

\n\n
crop(x, y, w, h)\n
\n\n

Transforms

\n\n
new_image = image.flip_horizontally.rotate_right\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "cidr", "title": "CIDR", "url": "/cidr", "category": "Misc", "keywords": null, "content_html": "

CIDR ranges

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RangeFirst IPLast IP
10.0.0.0/2410.0.0.010.0.0.255
10.0.0.0/1610.0.0.010.0.255.255
10.0.0.0/810.0.0.010.255.255.255
0.0.0.0/0(all)(all)
\n\n

Resources

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-05-14" },{ "id": "circle", "title": "CircleCI", "url": "/circle", "category": "Devops", "keywords": null, "content_html": "

circle.yml

\n\n\n\n

See: https://circleci.com/docs/configuration

\n\n

Sample

\n\n
## Customize the test machine\nmachine:\n\n  timezone:\n    America/Los_Angeles # Set the timezone\n\n  # Version of ruby to use\n  ruby:\n    version:\n      1.8.7-p358-falcon-perf\n\n  # Override /etc/hosts\n  hosts:\n    circlehost: 127.0.0.1\n    dev.mycompany.com: 127.0.0.1\n\n  # Add some environment variables\n  environment:\n    CIRCLE_ENV: test\n    DATABASE_URL: postgres://ubuntu:@127.0.0.1:5432/circle_test\n\n## Customize checkout\ncheckout:\n  post:\n    - git submodule sync\n    - git submodule update --init # use submodules\n\n## Customize dependencies\ndependencies:\n  pre:\n    - npm install coffeescript # install from a different package manager\n    - gem uninstall bundler # use a custom version of bundler\n    - gem install bundler --pre\n\n  override:\n    - bundle install: # note ':' here\n        timeout: 180 # fail if command has no output for 3 minutes\n\n  # we automatically cache and restore many dependencies between\n  # builds. If you need to, you can add custom paths to cache:\n  cache_directories:\n    - \"custom_1\"   # relative to the build directory\n    - \"~/custom_2\" # relative to the user's home directory\n\n## Customize database setup\ndatabase:\n  override:\n    # replace CircleCI's generated database.yml\n    - cp config/database.yml.ci config/database.yml\n    - bundle exec rake db:create db:schema:load\n\n## Customize test commands\ntest:\n  override:\n    - phpunit test/unit-tests # use PHPunit for testing\n  post:\n    - bundle exec rake jasmine:ci: # add an extra test type\n        environment:\n          RAILS_ENV: test\n          RACK_ENV: test\n\n## Customize deployment commands\ndeployment:\n  staging:\n    branch: master\n    heroku:\n      appname: foo-bar-123\n\n## Custom notifications\nnotify:\n  webhooks:\n    # A list of hashes representing hooks. Only the url field is supported.\n    - url: https://someurl.com/hooks/circle\n
\n\n

See: https://circleci.com/docs/config-sample

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "co", "title": "co", "url": "/co", "category": "JavaScript libraries", "keywords": null, "content_html": "

Running generators

\n\n
co(function * () {\n  yield Promise.resolve(true)\n}).then(...)\n
\n\n

A generator can yield a thunk or promise. Using co() will immediately invoke the block inside it.

\n\n

Generator → Promise

\n\n
var fn = co.wrap(function * (val) {\n  return yield Promise.resolve(val)\n})\n\nfn().then(...)\n
\n\n

Use co.wrap(). Most of the time, you’ll be using co.wrap.

\n\n

Generator → Node callback

\n\n
var get = unyield(function * () {\n})\n\nget(function (err, res) { ... })\n
\n\n

Use unyield. (You can thunkify this later)

\n\n

Node callback → Thunk

\n\n
var readFile = thunkify(fs.readFile)\n\nco(function * () {\n  var data = yield readFile('index.txt', 'utf-8')\n})\n
\n\n

Use thunkify. You can yield this. You can also use thenify too.

\n\n

Using Node.js API

\n\n
var readFile = require('mz/fs').readFile\n\nvar getLines = co.wrap(function * (filename) {\n  var data = yield readFile(filename, 'utf-8')\n  return data.split('\\n')\n})\n\ngetLines('file.txt').then((lines) => { ... })\n
\n\n

Use mz for async Node.js API. You can also either thunkify or thenify them instead.

", "intro_html": "

co allows you to use generators to manage async flow.

", "description_html": "", "tags": null, "updated": "2017-10-27" },{ "id": "command_line", "title": "Command line stuff", "url": "/command_line", "category": "Others", "keywords": null, "content_html": "

List (ls)

\n\n
ls [options] [paths]\n
\n\n

Format

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SwitchDescription
-1One entry per line
-lLong view
-oLong view (without groups)
-CMulticolumn (sorted horizontally)
-xMulticolumn (sorted vertically)
-FAdd / after directories
-GColor
\n\n

Options

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-RRecurse
-aInclude hidden (dotfiles)
-AInclude hidden (but not . and ..)
\n\n

Sorting

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SwitchDescription
-rreverse order
-Ssort by size
-tsort by time modified
-usort by time accessed
-Usort by time created
-csort by time status was changed
-hHuman-readable size (3k)
\n\n


\n\n

Tail

\n\n
tail [-F | -f | -r] [-bN | -cN | -nN] [file ...]\n
\n\n

Modes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-ffollow
-Ffollow by filename (accounts for log rotation)
-rReverse order
\n\n

Options

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-bNN*512 bytes
-cNN bytes
-nNN lines
+NStart from line N
\n\n


\n\n

Sudo

\n\n
sudo [options] <command>\n
\n\n

Listing

\n\n\n \n \n \n \n \n \n
-lList allowed commands
\n\n

Options

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-AUse $SUDO_ASKPASS
-bRun in background
-EPreserve environment
-Huse target’s $HOME
-nDon’t prompt for password
-PPreserve group vector
-SRead password from stdin
\n\n

File descriptors

\n\n\n \n \n \n \n \n \n
-C fdClose all open file descriptors
\n\n

Prompt

\n\n\n \n \n \n \n \n \n
-p promptCustom prompt (-p “%p password:”)
\n\n

Interactive

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SwitchDescription
-i [cmd]Interactive shell without variables
-s [cmd]Interactive shell
-u userrun as this user
-g grouprun as this group
\n\n

Timestamp

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-vrevalidate timestamp for 5 mins
-kinvalidate timestamp
-Kjust like -k
\n\n


\n\n

wc (Word count)

\n\n
... | wc [options]\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-cBytes
-lLines
-mCharacters (incl multi-byte)
-wWords
\n\n


\n\n

Search-and-replace in all files

\n\n
perl -p -i -e 's/hello/HELLO/g' **/*\n
\n\n


\n\n

Grep

\n\n
grep [options] [pattern] [file ...]\n
\n\n

Options

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SwitchDescription
-A numPrint num lines of training context
-G–basic-regexp (default)
-E–extended-regexp
-P–perl-regexp
-f file–file (Get patterns for file)
-F–fixed-strings
-h–no-filename
-H–with-filename
-l–files-with-matches (just print filenames)
-L–files-without-match
-r, -R–recursive
-v–invert-match
-i–ignore-case
\n\n

Synonyms

\n\n
egrep  =>  grep -E\nfgrep  =>  grep -F\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "commander.js", "title": "Commander.js", "url": "/commander.js", "category": "JavaScript libraries", "keywords": null, "content_html": "

Initialize

\n\n
var cli = require('commander');\n
\n\n

Options

\n\n
cli\n  .version(require('../package').version)\n  .usage('[options] <command>')\n  .option('-w, --words <n>', 'generate <n> words')\n  .option('-i, --interval <n>', 'interval [1000]', 1000)\n  .option('-s, --symbols', 'include symbols')\n  .parse(process.argv);\n
\n\n

Help

\n\n
.on('--help', function() {\n  console.log('');\n})\n
\n\n

Commands

\n\n
cli.outputHelp();\ncli.args == [\"hello\"];\n
\n\n

Other useful things

\n\n
process.exit(0);\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "composer", "title": "composer", "url": "/composer", "category": "CLI", "keywords": null, "content_html": "

All composer commands, depending on your install, may need to use php composer.phar in the install folder for composer, instead of plain composer.

\n\n

Installing dependencies

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
composer installDownloads and installs all the libraries and dependencies outlined in the composer.lock file. If the file does not exist it will look for composer.json and do the same, creating a composer.lock file.
composer install --dry-runSimulates the install without installing anything
\n\n

This command doesn’t change any file. If composer.lock is not present, it will create it.

\n\n

composer.lock should always be committed to the repository. It has all the information needed to bring the \nlocal dependencies to the last committed state. If that file is modified on the repository, you will need to run \ncomposer install again after fetching the changes to update your local dependencies to those on that file.

\n\n

Updating packages

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
composer updateUpdates all packages
composer update --with-dependenciesUpdates all packages and its dependencies
composer update vendor/packageUpdates a certain package from vendor
composer update vendor/*Updates all packages from vendor
composer update --lockUpdates composer.lock hash without updating any packages
\n\n

This command changes only the composer.lock file.

\n\n

Updating autoloader

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
composer dumpautoload -oGenerates optimized autoload files
\n\n

Adding packages

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
composer require vendor/package.Adds package from vendor to composer.json’s require section and installs it
composer require vendor/package --devAdds package from vendor to composer.json’s require-dev section and installs it.
\n\n

This command changes both the composer.json and composer.lock files.

\n\n

Passing versions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
composer require vendor/pkg \"1.3.2\"Installs 1.3.2
composer require vendor/pkg \">=1.3.2\"Above or equal 1.3.2
composer require vendor/pkg \"<1.3.2\"Below 1.3.2
composer require vendor/pkg \"1.3.*\"Latest of >=1.3.0 <1.4.0
composer require vendor/pkg \"~1.3.2\"Latest of >=1.3.2 <1.4.0
composer require vendor/pkg \"~1.3\"Latest of >=1.3.0 <2.0.0
composer require vendor/pkg \"^1.3.2\"Latest of >=1.3.2 <2.0.0
composer require vendor/pkg \"^1.3\"Latest of >=1.3.0 <2.0.0
composer require vendor/pkg \"^0.3.2\"Latest of >=0.3.0 <0.4.0 (for pre-1.0)
composer require vendor/pkg \"dev-BRANCH_NAME\"From the branch BRANCH_NAME
\n\n

Removing packages

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
composer remove vendor/packageRemoves vendor/package from composer.json and uninstalls it
\n\n

This command changes both the composer.json and composer.lock files.

", "intro_html": "", "description_html": "

Basic guide on how to use Composer, the PHP Package manager.

", "tags": null, "updated": "2020-02-23" },{ "id": "cordova", "title": "Apache Cordova", "url": "/cordova", "category": "Others", "keywords": null, "content_html": "

Common commands

\n\n
cordova plugin ls\ncordova plugin search facebook\ncordova plugin add com.phonegap.plugins.facebookconnect\n
\n\n
cordova platform add ios\ncordova platform ls\ncordova platform update ios\ncordova platform check\n
\n\n

Common plugins

\n\n

Some commonly-used plugins:

\n\n\n\n

Also:

\n\n", "intro_html": "

A quick reference to common Apache Cordova commands.

", "description_html": "", "tags": null, "updated": null },{ "id": "cron", "title": "Cron", "url": "/cron", "category": "CLI", "keywords": null, "content_html": "

Format

\n\n

Format

\n\n
Min  Hour Day  Mon  Weekday\n
\n\n
*    *    *    *    *  command to be executed\n
\n\n
┬    ┬    ┬    ┬    ┬\n│    │    │    │    └─  Weekday  (0=Sun .. 6=Sat)\n│    │    │    └──────  Month    (1..12)\n│    │    └───────────  Day      (1..31)\n│    └────────────────  Hour     (0..23)\n└─────────────────────  Minute   (0..59)\n
\n\n

Examples

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleDescription
0 * * * *every hour
*/15 * * * *every 15 mins
0 */2 * * *every 2 hours
0 0 * * 0every Sunday midnight
@rebootevery reboot
\n\n

Crontab

\n\n
# Adding tasks easily\necho \"@reboot echo hi\" | crontab\n
\n\n
# Open in editor\ncrontab -e\n
\n\n
# List tasks\ncrontab -l [-u user]\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-05-03" },{ "id": "csharp7", "title": "C# 7", "url": "/csharp7", "category": "C-like", "keywords": null, "content_html": "

Out Variables

\n\n
public void PrintCoordinates(Point p)\n{\n    p.GetCoordinates(out int x, out int y);\n    WriteLine($\"({x}, {y})\");\n}\n
\n\n

out is used to declare a variable at the point where it is passed as an argument.

\n\n

Pattern Matching

\n\n

Is-expressions with patterns

\n\n
public void PrintStars(object o)\n{\n    if (o is null) return;     // constant pattern \"null\"\n    if (!(o is int i)) return; // type pattern \"int i\"\n    WriteLine(new string('*', i));\n}\n
\n\n

Switch statements with patterns

\n\n
switch(shape)\n{\n    case Circle c:\n        WriteLine($\"circle with radius {c.Radius}\");\n        break;\n    case Rectangle s when (s.Length == s.Height):\n        WriteLine($\"{s.Length} x {s.Height} square\");\n        break;\n    case Rectangle r:\n        WriteLine($\"{r.Length} x {r.Height} rectangle\");\n        break;\n    default:\n        WriteLine(\"<unknown shape>\");\n        break;\n    case null:\n        throw new ArgumentNullException(nameof(shape));\n}\n
\n\n

Tuples

\n\n

Tuple type

\n\n
(string, string, string) LookupName(long id) // tuple return type\n{\n    ... // retrieve first, middle and last from data storage\n    return (first, middle, last); // tuple literal\n}\n
\n\n
var names = LookupName(id);\nWriteLine($\"found {names.Item1} {names.Item3}.\");\n
\n\n

Tuple elements with name

\n\n
(string first, string middle, string last) LookupName(long id) // tuple elements have names\n
\n\n
var names = LookupName(id);\nWriteLine($\"found {names.first} {names.last}.\");\n
\n\n

Tuple Literals

\n\n
   return (first: first, middle: middle, last: last); // named tuple elements in a literal\n
\n\n

Tuple Deconstruction

\n\n
(var first, var middle, var last) = LookupName(id1);\nWriteLine($\"found {first} {last}.\");\n
\n

or

\n
var (first, middle, last) = LookupName(id1); // var outside\n
\n

or

\n
(first, middle, last) = LookupName(id2); // assign onto existing variables\n
\n\n

Local Functions

\n\n
public int Fibonacci(int x)\n{\n    if (x < 0) throw new ArgumentException(\"Less negativity please!\", nameof(x));\n    return Fib(x).current;\n\n    (int current, int previous) Fib(int i)\n    {\n        if (i == 0) return (1, 0);\n        var (p, pp) = Fib(i - 1);\n        return (p + pp, p);\n    }\n}\n
\n\n

Literal Improvements

\n\n

Digit Separator inside numbers literals

\n\n
var d = 123_456;\nvar x = 0xAB_CD_EF;\n
\n\n

Binary Literals

\n\n
var b = 0b1010_1011_1100_1101_1110_1111;\n
\n\n

Ref Returns and Locals

\n\n
public ref int Find(int number, int[] numbers)\n{\n    for (int i = 0; i < numbers.Length; i++)\n    {\n        if (numbers[i] == number) \n        {\n            return ref numbers[i]; // return the storage location, not the value\n        }\n    }\n    throw new IndexOutOfRangeException($\"{nameof(number)} not found\");\n}\n\nint[] array = { 1, 15, -39, 0, 7, 14, -12 };\nref int place = ref Find(7, array); // aliases 7's place in the array\nplace = 9; // replaces 7 with 9 in the array\nWriteLine(array[4]); // prints 9\n
\n\n

More Expression Bodied Members

\n\n

C# 7.0 adds accessors, constructors and finalizers to the list of things that can have expression bodies:

\n\n
class Person\n{\n    private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>();\n    private int id = GetId();\n\n    public Person(string name) => names.TryAdd(id, name); // constructors\n    ~Person() => names.TryRemove(id, out *);              // destructors\n    public string Name\n    {\n        get => names[id];                                 // getters\n        set => names[id] = value;                         // setters\n    }\n}\n
\n\n

Throw Expressions

\n\n
class Person\n{\n    public string Name { get; }\n    public Person(string name) => Name = name ?? throw new ArgumentNullException(name);\n    public string GetFirstName()\n    {\n        var parts = Name.Split(\" \");\n        return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException(\"No name!\");\n    }\n    public string GetLastName() => throw new NotImplementedException();\n}\n
", "intro_html": "", "description_html": "

A quick overview of C# 7

", "tags": null, "updated": "2018-12-06" },{ "id": "css-antialias", "title": "CSS antialiasing", "url": "/css-antialias", "category": "CSS", "keywords": null, "content_html": "

Antialias

\n\n
* {\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n
\n\n

Support

\n\n\n\n

References

\n\n", "intro_html": "

Here’s a 4-line snippet on how to get beautiful, antialiased text with CSS.

", "description_html": "", "tags": null, "updated": "2017-10-13" },{ "id": "css-flexbox", "title": "CSS flexbox", "url": "/css-flexbox", "category": "CSS", "keywords": null, "content_html": "

Simple example

\n\n
.container {\n  display: flex;\n}\n
\n\n
.container > div {\n  flex: 1 1 auto;\n}\n
\n\n

Container

\n\n
.container {\n
\n\n
  display: flex;\n  display: inline-flex;\n
\n\n
  flex-direction: row;            /* ltr - default */\n  flex-direction: row-reverse;    /* rtl */\n  flex-direction: column;         /* top-bottom */\n  flex-direction: column-reverse; /* bottom-top */\n
\n\n
  flex-wrap: nowrap; /* one-line */\n  flex-wrap: wrap;   /* multi-line */\n
\n\n
  align-items: flex-start; /* vertical-align to top */\n  align-items: flex-end;   /* vertical-align to bottom */\n  align-items: center;     /* vertical-align to center */\n  align-items: stretch;    /* same height on all (default) */\n
\n\n
  justify-content: flex-start;    /* [xxx        ] */\n  justify-content: center;        /* [    xxx    ] */\n  justify-content: flex-end;      /* [        xxx] */\n  justify-content: space-between; /* [x    x    x] */\n  justify-content: space-around;  /* [ x   x   x ] */\n  justify-content: space-evenly;  /* [  x  x  x  ] */\n
\n\n
}\n
\n\n

Child

\n\n
.container > div {\n
\n\n
  /* This: */\n  flex: 1 0 auto;\n\n  /* Is equivalent to this: */\n  flex-grow: 1;\n  flex-shrink: 0;\n  flex-basis: auto;\n
\n\n
  order: 1;\n
\n\n
  align-self: flex-start;  /* left */\n  margin-left: auto;       /* right */\n
\n\n
}\n
\n\n

Tricks

\n\n

Vertical center

\n\n
.container {\n  display: flex;\n}\n\n.container > div {\n  width: 100px;\n  height: 100px;\n  margin: auto;\n}\n
\n\n

Vertical center (2)

\n\n
.container {\n  display: flex;\n  align-items: center;     /* vertical */\n  justify-content: center; /* horizontal */\n}\n
\n\n

Reordering

\n\n
.container > .top {\n order: 1;\n}\n\n.container > .bottom {\n order: 2;\n}\n
\n\n

Mobile layout

\n\n
.container {\n  display: flex;\n  flex-direction: column;\n}\n\n.container > .top {\n  flex: 0 0 100px;\n}\n\n.container > .content {\n  flex: 1 0 auto;\n}\n
\n\n

A fixed-height top bar and a dynamic-height content area.

\n\n

Table-like

\n\n
.container {\n  display: flex;\n}\n\n/* the 'px' values here are just suggested percentages */\n.container > .checkbox { flex: 1 0 20px; }\n.container > .subject  { flex: 1 0 400px; }\n.container > .date     { flex: 1 0 120px; }\n
\n\n

This creates columns that have different widths, but size accordingly according\nto the circumstances.

\n\n

Vertical

\n\n
.container {\n  align-items: center;\n}\n
\n\n

Vertically-center all items.

\n\n

Left and right

\n\n
.menu > .left  { align-self: flex-start; }\n.menu > .right { align-self: flex-end; }\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-06-13" },{ "id": "css-grid", "title": "CSS Grid", "url": "/css-grid", "category": "CSS", "keywords": null, "content_html": "

Container

\n\n
.grid-container {\n
\n\n
  /* Display properties */\n  display: grid;\n  display: inline-grid;\n  display: subgrid;\n
\n\n
  /* Columns and rows */\n  grid-template-columns: 1rem 2rem 1rem; /* Measurement units */\n  grid-template-columns: 25% 50% 25%; /* Percentage units */\n  grid-template-columns: 1rem auto 1rem 2fr; /* Fill remaining widths with auto or fr units */\n  grid-template-columns: repeat(12, 1fr); /* Repeat columns without needing to write them */\n  \n  grid-template-rows: 1rem 10% auto repeat(5, 10px); /* Mix any group, same rules work for rows */\n
\n\n
  /* Automatic columns and rows */\n\n  grid-auto-columns: 10px; /* No matter how many columns of content end up in the grid, each column will be this same width */\n  grid-auto-rows: 1rem; /* No matter how many rows of content end up in the grid, each row will be this same height */\n
\n\n
  /* Areas */\n  grid-template-areas:\n    \"header header\"\n    \"main aside\"\n    \"footer footer\"; /* Grid-style */\n\n  grid-template-areas: \"header header\" \"main aside\" \"footer footer\"; /* Inline-style */\n
\n\n
  /* Template shorthand */\n  grid-template:\n    \"header header\" auto\n    \"main aside\" 100vh\n    \"footer footer\" 10rem\n    / 80% 20%;\n\n  /* The above is the same as below long-hand */\n  grid-template-columns: 80% 20%;\n  grid-template-rows: auto 100vh 10rem;\n  grid-template-areas:\n    \"header header\"\n    \"main aside\"\n    \"footer footer\";\n
\n\n
  /* Gaps */\n  grid-row-gap: 1rem;\n  grid-column-gap: 0.5rem; /* Define values separately */\n\n  grid-gap: 1rem 0.5rem; /* Short-hand for row / column */\n  grid-gap: 1rem; /* Gap in both dimensions */\n
\n\n
  /* Item justification (horizontal or column alignment) */\n  justify-items: start; /* Align items to the left */\n  justify-items: center; /* Align items centered within its column */\n  justify-items: end; /* Align items to the right */\n  justify-items: stretch; /* (default) Fills available area (horizontally) */\n
\n\n
  /* Item alignment (vertical or row alignment) */\n  align-items: start; /* Align items to the top */\n  align-items: center; /* Align items centered within its row */\n  align-items: end; /* Align items to the bottom */\n  align-items: stretch; /* (default) Fills available area (vertically) */\n
\n\n
  /* Place item shorthand */\n  place-items: start stretch;\n\n  /* The above is the same as below long-hand */\n  align-items: start;\n  justify-items: stretch;\n
\n\n
  /* Content justification (horizontal or column alignment) */\n  justify-content: start; /* Align content to the left */\n  justify-content: center; /* Align content centered horizontally within the grid */\n  justify-content: end; /* Align content to the right */\n  justify-content: stretch; /* (default) Fills available area (horizontally) */\n\n  justify-content: space-around; /* Chooses a space for both sides of the columns like a left and right margin */\n  justify-content: space-between; /* Chooses a space to go between columns, no margins on outside of content */\n  justify-content: space-evenly; /* Chooses a space that goes between all columns and edges consistently */\n
\n\n
  /* Content alignment (horizontal or column alignment) */\n  align-content: start; /* Align content to the top */\n  align-content: center; /* Align content centered vertically within the grid */\n  align-content: end; /* Align content to the bottom */\n  align-content: stretch; /* (default) Fills available area (vertically) */\n\n  align-content: space-around; /* Chooses a space for the top and bottom of the rows like a top and bottom margin */\n  align-content: space-between; /* Chooses a space to go between rows, no margins on outside of content */\n  align-content: space-evenly; /* Chooses a space that goes between all rows and edges consistently */\n
\n\n
  /* Place item shorthand */\n  place-content: center start;\n\n  /* The above is the same as below long-hand */\n  align-content: center;\n  justify-content: start;\n
\n\n
  /* Automatic grid positioning */\n\n  grid-auto-flow: row; /* Left-to-right rows, then top-to-bottom*/\n  grid-auto-flow: column; /* Top-to-bottom columns, then left-to-right */\n  grid-auto-flow: dense; /* Responds with best-guess on left-to-right, top-to-bottom order with advanced layouts */\n
\n\n
  /* There is one final shorthand for all container properties in one */\n\n  /* Explicit grid columns, rows, and areas */\n  grid:\n    \"header header\" auto\n    \"main aside\" 100vh\n    \"footer footer\" 10rem\n    / 80% 20%; /* You can include a template as the only value, which is equivalent to below */\n  grid-template:\n    \"header header\" auto\n    \"main aside\" 100vh\n    \"footer footer\" 10rem\n    / 80% 20%; /* Which is again equivalent to below */\n  grid-template-columns: 80% 20%;\n  grid-template-rows: auto 100vh 10rem;\n  grid-template-areas:\n    \"header header\"\n    \"main aside\"\n    \"footer footer\";\n\n  /* Automatic grid flows */\n  grid: 1rem / auto-flow dense 1fr; /* You can include rows, a flow, and automatic columns, which is equivalent to below */\n  grid-template-rows: 1rem;\n  grid-auto-flow: dense;\n  grid-auto-columns: 1fr;\n\n  grid: auto-flow dense 1rem / repeat(10, 10%); /* Conversely, you can do the same thing with automatic rows, and defined columns */\n  grid-auto-flow: dense;\n  grid-auto-rows: 1rem;\n  grid-template-columns: repeat(10, 10%);\n
\n\n
}\n
\n\n

Child

\n\n
.grid-child {\n
\n\n
  /* Column position */\n  grid-column-start: 1;\n  grid-column-end: 2;\n\n  grid-column: 1 / 2; /* Short hand */\n  grid-column: 1 / span 2; /* Span 2 columns without explicitly defining an endpoint */\n  grid-column: 1; /* Start in and occupy a single column */\n
\n\n
  /* Row position */\n  grid-row-start: 2;\n  grid-row-end: 4;\n\n  grid-row: 2 / 4; /* Short hand */\n  grid-row: 2 / span 3;/* Span 3 rows without explicitly defining an endpoint */\n  grid-row: 1; /* Start in and occupy a single row */\n
\n\n
  /* Area positioning */\n  grid-area: header; /* You can use a named grid area from the container */\n\n  grid-area: 2 / 1 / 4 / 2; /* Or you can use positioning. This is equivalent to... */\n  grid-row-start: 2;\n  grid-column-start: 1;\n  grid-row-end: 4;\n  grid-column-end: 2;\n
\n\n
  /* Self justification (horizontal or column alignment) */\n  justify-self: start; /* Align item to the left */\n  justify-self: center; /* Align item centered within its column */\n  justify-self: end; /* Align item to the right */\n  justify-self: stretch; /* (default) Fills available area (horizontally) */\n
\n\n
  /* Self alignment (vertical or row alignment) */\n  align-self: start; /* Align item to the top */\n  align-self: center; /* Align item centered within its row */\n  align-self: end; /* Align item to the bottom */\n  align-self: stretch; /* (default) Fills available area (vertically) */\n
\n\n
  /* Placement shorthand */\n  place-self: start stretch;\n\n  /* The above is the same as below long-hand */\n  align-self: start;\n  justify-self: stretch;\n
\n\n
}\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2019-08-23" },{ "id": "css-system-font-stack", "title": "CSS system fonts", "url": "/css-system-font-stack", "category": "CSS", "keywords": null, "content_html": "

System fonts

\n\n
font-family: -apple-system, BlinkMacSystemFont,\n    \"Segoe UI\", \"Roboto\", \"Oxygen\",\n    \"Ubuntu\", \"Cantarell\", \"Fira Sans\",\n    \"Droid Sans\", \"Helvetica Neue\", sans-serif;\n
\n\n

This uses whatever system font is available. See: System shock - Designing Medium (medium.com)

\n\n

Explanation

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FontOS
-apple-systemOS X (10.11+), iOS (9+)
BlinkMacSystemFontOS X, Chrome
Segoe UIWindows
RobotoAndroid 4.0+
OxygenLinux, KDE
UbuntuLinux, Ubuntu
CantarellLinux, GNOME
Fira SansFirefox OS
Droid SansAndroid (until 3.2)
Helvetica NeueOS X (10.9)
", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": null },{ "id": "css-tricks", "title": "CSS tricks", "url": "/css-tricks", "category": "CSS", "keywords": null, "content_html": "

Heading kerning pairs and ligature

\n\n
h1, h2, h3 {\n  text-rendering: optimizeLegibility;\n}\n
\n\n

Native-like iOS scrolling

\n\n
-webkit-overflow-scrolling: touch;\noverflow-y: auto;\n
\n\n

Gradient text

\n\n
background: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#333));\n-webkit-background-clip: text;\n-webkit-text-fill-color: transparent;\n
\n\n

Text stroke

\n\n
-webkit-text-stroke: 3px black;\n
\n\n

See: Introducing text stroke

\n\n

iOS Scrolling prevention

\n\n
document.ontouchstart = (e) ->\n  $pane = $(e.target).closest('.scrollable>div')\n  if $pane.length is 0 or $pane[0].scrollHeight <= $pane.innerHeight()\n    e.preventDefault()\n
\n\n
%ios-scrollable {\n  &, >div {\n    -webkit-overflow-scrolling: touch;\n    overflow: auto;\n  }\n\n  >div {\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n  }\n}\n
\n\n

Relevant in iOS6, but maybe not anymore.

\n\n

UIWebView optimizations

\n\n
* {\n  -webkit-tap-highlight-color: rgba(0,0,0,0);\n  -webkit-user-select: none;                /* disable text select */\n  -webkit-touch-callout: none;              /* disable callout, image save panel (popup) */\n  -webkit-tap-highlight-color: transparent; /* \"turn off\" link highlight */\n}\n\na:focus {\n  outline: 0; // Firefox (remove border on link click)\n}\n
\n\n

See: http://www.bitsandpix.com/entry/ios-webkit-uiwebview-remove-tapclick-highlightborder-with-css/

\n\n

See: http://www.yuiblog.com/blog/2010/10/01/quick-tip-customizing-the-mobile-safari-tap-highlight-color/

\n\n

Browser hacks

\n\n

Disclaimer

\n\n

Not recommended, but here they are if you ever need them. Note that vendor\nprefixes may go away eventually.

\n\n

Mozilla-only

\n\n
@-moz-document url-prefix() {\n  .box { color: blue; }\n}\n
\n\n

Webkit-only

\n\n
@media all and (-webkit-min-device-pixel-ratio: 1) {\n}\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "css", "title": "CSS", "url": "/css", "category": "CSS", "keywords": ["margin, padding, border","div, .class, #id, [attr]","font, background","display: block, inline, flex","Selectors","Properties"], "content_html": "

Basics

\n\n

Selectors

\n\n
.class {\n  font-weight: bold;\n}\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SelectorDescription
*All elements
divElement
.classClass
#idID
[disabled]Attribute
[role=\"dialog\"]Attribute
\n\n

Combinators

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SelectorDescription
.parent .childDescendant
.parent > .childDirect descendant
.child + .siblingAdjacent sibling
.child ~ .siblingFar sibling
.class1.class2Have both classes
\n\n

Attribute selectors

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SelectorDescription
[role=\"dialog\"]= Exact
[class~=\"box\"]~= Has word
[class|=\"box\"]|= Exact or prefix (eg, value-)
[href$=\".doc\"]$= Ends in
[href^=\"/index\"]^= Begins with
[class*=\"-is-\"]*= Contains
\n\n

Pseudo-classes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SelectorDescription
:targeteg, h2#foo:target
:disabled 
:focus 
:active 
:nth-child(3)3rd child
:nth-child(3n+2)2nd child in groups of 3
:nth-child(-n+4) 
:nth-last-child(2) 
:nth-of-type(2) 
:checkedChecked inputs
:disabledDisabled elements
:defaultDefault element in a group
:emptyElements without children
\n\n

Pseudo-class variations

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Selector
:first-of-type
:last-of-type
:nth-of-type(2)
:only-of-type
:first-child
:last-child
:nth-child(2)
:only-child
\n\n

Fonts

\n\n

Properties

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PropertyDescription
font-family:<font>, <fontN>
font-size:<size>
letter-spacing:<size>
line-height:<number>
font-weight:bold normal
font-style:italic normal
text-decoration:underline none
text-align:left right center justify
text-transform:capitalize uppercase lowercase
\n\n

Shorthand

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
 styleweightsize (required) line-heightfamily
font:italic40014px/1.5sans-serif
 styleweightsize (required) line-heightfamily (required)
\n\n

Example

\n\n
font-family: Arial;\nfont-size: 12pt;\nline-height: 1.5;\nletter-spacing: 0.02em;\ncolor: #aa3322;\n
\n\n

Case

\n\n
text-transform: capitalize; /* Hello */\ntext-transform: uppercase; /* HELLO */\ntext-transform: lowercase; /* hello */\n
\n\n

Background

\n\n

Properties

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PropertyDescription
background:(Shorthand)
background-color:<color>
background-image:url(...)
background-position:left/center/right top/center/bottom
background-size:cover X Y
background-clip:border-box padding-box content-box
background-repeat:no-repeat repeat-x repeat-y
background-attachment:scroll fixed local
\n\n

Shorthand

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
 colorimagepositionXpositionY sizerepeatattachment
background:#ff0url(bg.jpg)lefttop/100px autono-repeatfixed;
background:#abcurl(bg.png)centercenter/coverrepeat-xlocal;
 colorimagepositionXpositionY sizerepeatattachment
\n\n

Multiple backgrounds

\n\n
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),\n  url('background.jpg') center center / cover, #333;\n
\n\n

Animation

\n\n

Properties

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PropertyValue
animation:(shorthand)
animation-name:<name>
animation-duration:<time>ms
animation-timing-function:ease linear ease-in ease-out ease-in-out
animation-delay:<time>ms
animation-iteration-count:infinite <number>
animation-direction:normal reverse alternate alternate-reverse
animation-fill-mode:none forwards backwards both initial inherit
animation-play-state:normal reverse alternate alternate-reverse
\n\n

Shorthand

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
 namedurationtiming-functiondelaycountdirectionfill-modeplay-state
animation:bounce300mslinear100msinfinitealternate-reversebothreverse
 namedurationtiming-functiondelaycountdirectionfill-modeplay-state
\n\n

Example

\n\n
animation: bounce 300ms linear 0s infinite normal;\nanimation: bounce 300ms linear infinite;\nanimation: bounce 300ms linear infinite alternate-reverse;\nanimation: bounce 300ms linear 2s infinite alternate-reverse forwards normal;\n
\n\n

Event

\n\n
.one('webkitAnimationEnd oanimationend msAnimationEnd animationend')\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "cssnext", "title": "cssnext", "url": "/cssnext", "category": "CSS", "keywords": null, "content_html": "

Variables

\n\n
:root {\n  --text-color: #30333a;\n}\n
\n\n
body {\n  background: var(--text-color);\n  background: color(var(--text-color) shade(30%));\n}\n
\n\n

Colors

\n\n
a {\n  /* Adjustments */\n  color: color(red alpha(-10%));\n  color: color(red tint(-10%));    /* lighten */\n  color: color(red shade(-10%));   /* darken */\n\n  /* Absolute */\n  color: color(red alpha(50%));\n  color: color(red hue(225));\n  color: color(red saturation(100%));\n  color: color(red lightness(50%));\n\n  color: gray(33);       /* rgb(33, 33, 33) */\n  color: gray(33%);      /* rgb(84, 84, 84) */\n  color: gray(33%, 50%); /* rgba(84, 84, 84, 0.5) */\n  color: #0000ff80;      /* rgba(0, 0, 255, 0.5) */\n\n  color: hwb(90, 0%, 0%, 0.5);     /* like hsl() but easier for humans */\n  color: hsl(90deg 90% 70%);       /* hsl(180, 90%, 70%) -- supports deg */\n  color: hsl(90deg 90% 70% / 30%); /* hsla(180, 90%, 70%, 0.3) */\n  color: rgb(30 60 90 / 30%);      /* rgba(30, 60, 90, 0.3) */\n}\n
\n\n

Also see colorme.io.

\n\n

Mixins

\n\n
:root {\n  --centered: {\n    display: flex;\n    align-items: center;\n    justify-content: center;\n  };\n}\n\n.centered {\n  @apply --centered;\n}\n
\n\n

Selectors

\n\n

Nesting

\n\n
.class-name {\n  & .nesting { ··· }      /* direct nesting starts with & */\n  @nest span & { ··· }    /* complex nesting */\n  @media (min-width: 30em) { ··· }\n}\n
\n\n

Custom selectors

\n\n
@custom-selector :--button input[type='submit'], input[type='button'];\n@custom-selector :--enter :hover, :focus;\n
\n\n
:--button { ··· }\n:--button:--enter { ··· }\n
\n\n

Future selectors

\n\n
:any-link { ··· }         /* :link, :visited */\np:matches(.a, .b) { ··· } /* p.a, p.b */\np:not(.a, .b) { ··· }     /* p:not(.a), p:not(.b) */\na::before { ··· }         /* a:before -- for IE compatibility */\n[frame=hsides i] { ··· }  /* [frame=hsides] -- but case insensitive */\n
\n\n

Media queries

\n\n

Custom media queries

\n\n
@custom-media --viewport-medium (width <= 50rem);\n
\n\n
@media (--viewport-medium) { ··· }\n
\n\n

Media query ranges

\n\n
@media (width >= 500px) { ··· }    /* (min-width: 500px) */\n
\n\n

Properties

\n\n

Property fallbacks

\n\n
/* font-feature-settings fallback */\nh2 { font-variant-caps: small-caps; }\ntable { font-variant-numeric: lining-nums; }\n
\n\n
div { filter: blur(4px); }          /* svg filter fallback */\ndiv { overflow-wrap: break-word; }  /* word-wrap fallback */\n
\n\n

Autoprefixing

\n\n
div {\n  display: flex;\n}\n
\n\n
/*\n * display: -webkit-box;\n * display: -ms-flexbox;\n * display: flex;\n */\n
\n\n

Reset

\n\n
div {\n  all: initial;\n}\n
\n\n

Sets animation, background, margin, padding, and so on.

\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2017-10-30" },{ "id": "curl", "title": "Curl", "url": "/curl", "category": "CLI", "keywords": null, "content_html": "

Options

\n\n

Options

\n\n
-o <file>    # --output: write to file\n-u user:pass # --user: Authentication\n
\n\n
-v           # --verbose\n-vv          # Even more verbose\n-s           # --silent\n
\n\n
-i           # --include: Include the HTTP-header in the output\n-I           # --head: headers only\n
\n\n

Request

\n\n
-X POST          # --request\n-L               # follow link if page redirects \n
\n\n

Data

\n\n
-d 'data'    # --data: HTTP post data, URL encoded (eg, status=\"Hello\")\n-d @file     # --data via file\n-G           # --get: send -d data via get\n
\n\n

Headers

\n\n
-A <str>         # --user-agent\n-b name=val      # --cookie\n-b FILE          # --cookie\n-H \"X-Foo: y\"    # --header\n--compressed     # use deflate/gzip\n
\n\n

SSL

\n\n
    --cacert <file>\n    --capath <dir>\n
\n\n
-E, --cert <cert>     # --cert: Client cert file\n    --cert-type       # der/pem/eng\n-k, --insecure        # for self-signed certs\n
\n\n

Examples

\n\n
# Post data:\ncurl -d password=x http://x.com/y\n
\n\n
# Auth/data:\ncurl -u user:pass -d status=\"Hello\" http://twitter.com/statuses/update.xml\n
\n\n
# multipart file upload\ncurl -v -include --form key1=value1 --form upload=@localfilename URL\n
\n\n
# Use Curl to Check if a remote resource is available\n# details: https://matthewsetter.com/check-if-file-is-available-with-curl/\ncurl -o /dev/null --silent -Iw \"%{http_code}\" https://example.com/my.remote.tarball.gz\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-03-09" },{ "id": "datetime", "title": "Date & time formats", "url": "/datetime", "category": "Others", "keywords": null, "content_html": "

Common time formats

\n\n\n\n

strftime format

\n\n

Presets

\n\n

Date

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
%m/%d/%Y06/05/2013
%A, %B %e, %YSunday, June 5, 2013
%b %e %aJun 5 Sun
\n\n

Time

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
%H:%M23:05
%I:%M %p11:05 PM
\n\n

Used by Ruby, UNIX date, and many more.

\n\n

Date

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SymbolExampleArea
%aSunWeekday
%ASunday 
%w0..6 (Sunday is 0) 
%y13Year
%Y2013 
%bJanMonth
%BJanuary 
%m01..12 
%d01..31Day
%e1..31 
\n\n

Time

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SymbolExampleArea
%l1Hour
%H00..2324h Hour
%I01..1212h Hour
%M00..59Minute
%S00..60Second
%pAMAM or PM
%Z+08Time zone
%j001..366Day of the year
%%%Literal % character
\n\n

Moment.js format

\n\n

Examples

\n\n

Date

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
YYYY-MM-DD2014-01-01
dddd, MMMM Do YYYYFriday, May 16th 2014
\n\n

Time

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
hh:mm a12:30 pm
\n\n

Used by Moment.js and date-fns/format. Similar to Java SimpleDateFormat.

\n\n

Date

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SymbolExampleArea
d0..6Weekday
ddSu 
dddSun 
ddddSunday 
YY13Year
YYYY2013 
M1..12 (Jan is 1)Month
Mo1st..12th 
MM01..12 (Jan is 1) 
MMMJan 
MMMMJanuary 
Q1..4Quarter
Qo1st..4th 
D1..31Day
Do1st..31st 
DD01..31 
DDD1..365Day of year
DDDo1st..365th 
DDDD001..365 
w1..53Week of year
wo1st..53rd 
ww01..53 
\n\n

Time

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SymbolExampleArea
H0..2324h hour
HH00..23 
h1..1212h hour
hh01..12 
m0..59Minutes
mm00..59 
s0..59Seconds
ss00..59 
aamAM/PM
AAM 
Z+07:00Timezone offset
ZZ+0730 
S0..9Deciseconds
SS00..99Centiseconds
SSS000..999Milliseconds
X Unix timestamp
x Millisecond Unix timestamp
\n\n

Presets

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
LT8:30 PM
LTS8:30:25 PM
LLAugust 2 1985
llAug 2 1985
LLLAugust 2 1985 08:30 PM
lllAug 2 1985 08:30 PM
LLLLThursday, August 2 1985 08:30 PM
llllThu, Aug 2 1985 08:30 PM
", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2017-11-27" },{ "id": "deis", "title": "Deis", "url": "/deis", "category": "Devops", "keywords": null, "content_html": "

Deploy

\n\n
deis create app-name\ngit push deis master\ndeis open\n
\n\n

Deploy dockerfile

\n\n
$ deis create app-name\n$ deis pull redis:latest\n  Creating build...  done, v2\n# default process type is `cmd`\n
\n\n

Config

\n\n
deis config:list\ndeis config:set FOO=bar BAZ=foo\ndeis config:unset FOO\ndeis config:pull  # writes to .env\ndeis config:push  # reads from .env\n
\n\n

Managing instances

\n\n
deis logs\ndeis run rake db:migrate\ndeis ps\n
\n\n

Custom domains

\n\n
deis domains:list\ndeis domains:add www.myapp.com\ndeis domains:remove www.myapp.com\n
\n\n

Limits

\n\n
deis limits:set web=1G\ndeis limits:set web=1024 --cpu\n# (`web` is a process type)\n
\n\n

Sharing

\n\n
deis perms:create otheruser\n
\n\n

SSL

\n\n
deis certs:add server.crt server.key\n
\n\n

See: SSL

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "deku", "title": "Deku v2", "url": "/deku", "category": "JavaScript libraries", "keywords": null, "content_html": "

Components

\n\n
/** @jsx element */\nimport { element } from 'deku'\n\nfunction render ({ props, children, context, path }) {\n  // props    = properties object\n  // children = children array\n  // path     = path to current component (like 0.1.5.2)\n  // context  = common properties in all components\n  return (\n    <div class='App' hidden={props.hidden} color={context.theme.color}>\n      {children}\n    </div>\n  }\n}\n\nfunction onCreate ({ props, dispatch, path }) { ... }\nfunction onUpdate ({ props, dispatch, path }) { ... }\nfunction onRemove ({ props, dispatch, path }) { ... }\n// actually { children, props, path, context }\n\nexport default { render, onCreate, onRemove }\n
\n\n

Rendering

\n\n
import { createStore } from 'redux'\nimport { dom, element } from 'deku'\n\n// Create a Redux store to handle all UI actions and side-effects\nlet store = createStore(reducer)\n\n// Create a renderer that can turn vnodes into real DOM elements\nlet render = createRenderer(document.body, store.dispatch)\n\n// Update the page and add redux state to the context\nrender(<MyButton>Hello World!</MyButton>, store.getState())\n
", "intro_html": "

Quick reference for Deku, a minimal virtual DOM library.

", "description_html": "", "tags": null, "updated": null },{ "id": "deku@1", "title": "Deku v1", "url": "/deku@1", "category": "JavaScript libraries", "keywords": null, "content_html": "

Example

\n\n
/** @jsx element */\nimport element from 'virtual-element' // replacement for React.createElement\nimport { render, tree } from 'deku'\n\nvar app = <div class='my-app'>Hello World!</div>\n\nrender(tree(app), document.body)\n
\n\n

Components

\n\n
Button = {\n  render() {\n    return <button>Submit</button>\n  }\n}\n\nApp = {\n  render() {\n    return (\n      <div>\n        <Button />\n      </div>\n    )\n  }\n}\n\nrender(tree(<App />), document.body)\nrender(tree(element(App)), document.body)\n
\n\n

Component props/state

\n\n
App = {\n  render ({ props, state }) {\n    return <div>{ /*...use state.store here*/ }</div>\n  }\n\n  initialState (props) {\n    return { store: store.getState() }\n  },\n\n  afterMount (comp, el, setState) {\n    store.subscribe(() => setState({ store: store.getState() }))\n  }\n}\n\nrender(tree(<App />), document.body)\n
\n\n

Events

\n\n
<a onClick={onClick}>{props.text}</a>\n
\n\n

Magic virtual element

\n\n

Use magic-virtual-element to enable nice classnames.

\n\n
import element from 'magic-virtual-element'\n<div style={style} class={[ 'button', '-active' ]}>\n
\n\n

Reference

\n\n
name = 'MyComponent'\n\n// Defaults\ninitialState (props) {...} // return initial state\ndefaultProps = { hi: 'hello' }\n\n// Render\nrender ({props, state}, setState) {...}\n\n// Lifecycle\nbeforeUpdate  ({props, state, id}, nextProps, nextState) {}\nafterRender   ({props, state, id}, el) {}\nafterUpdate   ({props, state, id}, prevProps, prevState, setState) {}\nafterMount    ({props, state, id}, el, setState) {}\nbeforeUnmount ({props, state, id}, el) {}\n
\n\n

See: https://www.npmjs.com/package/deku

", "intro_html": "

Quick reference for Deku, a minimal virtual DOM library. Deprecated: This is for Deku v1. See deku for a more updated cheatsheet.

", "description_html": "", "tags": null, "updated": null },{ "id": "devise", "title": "Devise", "url": "/devise", "category": "Others", "keywords": null, "content_html": "

Devise is a flexible authentication \ngem.

\n\n

Installation

\n\n

Rails 3: Add the following to your Gemfile

\n\n
gem \"devise\"\ngem \"hpricot\"\ngem \"ruby_parser\"\n
\n\n

Install devise in your project

\n\n
$ rails generate devise:install\n
\n\n

Generate devise for your model

\n\n
$ rails generate devise MODEL\n$ rake db:migrate\n
\n\n

(Optional) Generate devise views

\n\n
$ rails generate devise:views\n
\n\n

Helpers

\n\n
user_signed_in?\ncurrent_user\nuser_session\ndestroy_user_session_path (Logout)\nnew_user_session_path (Login)\nedit_user_registration_path (Edit registration)\nnew_user_registration_path (Register new user)\n
\n\n

Controller stuff

\n\n
before_filter :authenticate_user!\n
\n\n

Model

\n\n

Model options

\n\n
class User < ActiveRecord::Base\n  devise :database_authenticatable,\n    :registerable,\n    :confirmable,\n    :recoverable,\n    :rememberable,\n    :trackable,\n    :validatable\nend\n
\n\n

Migration helpers

\n\n
create_table :users do |t|\n  t.database_authenticatable\n  t.confirmable\n  t.recoverable\n  t.rememberable\n  t.trackable\n  t.timestamps\nend\n
\n\n

Routing

\n\n

Authenticated and unauthenticated routes

\n\n
unauthenticated do\n   root :to => 'home#index'\nend\n\nauthenticated do\n  root :to => 'dashboard#index'\nend\n
\n\n

As

\n
as :user do\n  get 'sign_in', :to => 'devise/sessions#new'\nend\n
\n\n

Devise_for magic

\n\n
devise_for :users\n\n    # Session routes for Authenticatable (default)\n         new_user_session GET  /users/sign_in                    {:controller=>\"devise/sessions\", :action=>\"new\"}\n             user_session POST /users/sign_in                    {:controller=>\"devise/sessions\", :action=>\"create\"}\n     destroy_user_session GET  /users/sign_out                   {:controller=>\"devise/sessions\", :action=>\"destroy\"}\n   \n    # Password routes for Recoverable, if User model has :recoverable configured\n        new_user_password GET  /users/password/new(.:format)     {:controller=>\"devise/passwords\", :action=>\"new\"}\n       edit_user_password GET  /users/password/edit(.:format)    {:controller=>\"devise/passwords\", :action=>\"edit\"}\n            user_password PUT  /users/password(.:format)         {:controller=>\"devise/passwords\", :action=>\"update\"}\n                          POST /users/password(.:format)         {:controller=>\"devise/passwords\", :action=>\"create\"}\n   \n    # Confirmation routes for Confirmable, if User model has :confirmable configured\n    new_user_confirmation GET  /users/confirmation/new(.:format) {:controller=>\"devise/confirmations\", :action=>\"new\"}\n        user_confirmation GET  /users/confirmation(.:format)     {:controller=>\"devise/confirmations\", :action=>\"show\"}\n                          POST /users/confirmation(.:format)     {:controller=>\"devise/confirmations\", :action=>\"create\"}\n
\n\n

Customizing devise_for

\n\n
devise_for :users,\n  :path => \"usuarios\",\n  :path_names => {\n    :sign_in => 'login',\n    :sign_out => 'logout',\n    :password => 'secret',\n    :confirmation => 'verification',\n    :unlock => 'unblock',\n    :registration => 'register',\n    :sign_up => 'cmon_let_me_in' }\n
\n\n

Test helpers

\n\n
include Devise::TestHelpers\nhttps://github.com/plataformatec/devise/blob/1094ba65aac1d37713f2cba71f9edad76b5ca274/lib/devise/test_helpers.rb\n\nsign_in @user\nsign_out @user\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "divshot", "title": "Divshot", "url": "/divshot", "category": "Others", "keywords": null, "content_html": "

Getting started

\n\n

Install divshot-cli

\n\n
$ npm install -g divshot-cli\n$ divshot login\n
\n\n

Create divshot.json

\n\n
{\n  \"name\": \"yourapp\",\n  \"root\": \"./app\"\n}\n
\n\n

Push your app

\n\n
$ divshot push\n
\n\n

Configuration

\n\n

See configuration reference and routing guide.

\n\n
{\n  \"name\": \"yourapp\",\n  \"root\": \"./app\",\n  \"clean_urls\": true,\n  \"clean_urls\": [\"/app/**\", \"/!components/**\"],,\n  \"error_page\": \"error.html\",\n  \"exclude\": [ \"Gruntfile.js\" ],\n  \"cache_control\": {},\n  \"routes\": {\n    \"/*.html\": \"index.html\",\n    \"/app/**/*.html\": \"app.html\",\n    \"**\": \"index.html\"\n  },\n  \"redirects\": {\n    \"/old/:segment/path\": \"/new/path/:segment\",\n    \"/some/old/path\": {\n      \"status\": 302,\n      \"url\": \"/some/new/path\"\n    }\n  },\n  \"headers\": {\n    \"/cors-stuff/**\": {\n      \"Access-Control-Allow-Origin\": \"*\"\n    },\n    \"/scripts/**\": {\n      \"content-type\": \"text/javascript\"\n    }\n  }\n}\n
\n\n

CLI

\n\n
divshot s   # server\n\ndivshot push [staging|production|development]\ndivshot pull [staging|production|development]\ndivshot purge   # cleans cache\ndivshot files\n\ndivshot promote development production\n\ndivshot open [<env>]\n
\n\n

Config

\n

Edits divshot.json

\n\n
\ndivshot config:add name your-app-name\ndivshot config:remove name\n
\n\n

Environment vars

\n\n
divshot env:add <env> KEY=value\ndivshot env:remove <env> KEY\ndivshot env:pull <env>\n
\n\n

App management

\n\n
divshot create <appname>\ndivshot rename <newname>\ndivshot status\ndivshot destroy\n
\n\n

divshot apps\ndivshot account

\n
\n### Password protect\n\n```sh\ndivshot protect <env> <username:password>\n
\n\n

Custom domains

\n\n

See custom domains guide.

\n\n
divshot domains:add foo.bar.com\n
\n\n

In your DNS create a CNAME: (no apex domains are supported)

\n\n
www.    CNAME    yourname.divshot.io\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "do", "title": "Do gem", "url": "/do", "category": "Ruby libraries", "keywords": null, "content_html": "\n\n

Connection

\n\n
server = DO::Server.new('srv1', 'srv1.domain.local', 'root', :key => \n    %w[srv1.pem]\n
\n\n

Run

\n
server.run 'uname'\n# root@srv1 ~ # uname\n# Linux\n\nserver.run 'uname', '-a'\n# root@srv1 ~ # uname -a\n# Linux srv1.lipsiasoft.net 2.6.18-194.32.1.el5  x86_64 x86_64 x86_64 GNU/Linux\n\nserver.run 'mysqladmin -u root -p password \"oldone\"', 'newpassword'\n# root@srv1 ~ # mysqladmin -u root -p password 'oldone'\n# Enter password: oldone\n# mysqladmin: connect to server at 'localhost' failed\n# error: 'Access denied for user 'root'@'localhost' (using password: YES)'\n
\n\n

Files

\n\n
server.exist?('~/.ssh')\n# root@srv1 ~ # test -e ~/.ssh && echo True\n# => true\n\nserver.read('/etc/redhat-release')\n# root@srv1 ~ # cat /etc/redhat-release\n# => \"CentOS release 5.5 (Final)\"\n
\n\n

Upload/download

\n\n
server.upload '/tmp/file', '/tmp/foo'\n# root@srv1 ~ # upload from '/tmp/file' to '/tmp/foo'\n\nserver.download '/tmp/foo', '/tmp/file2'\n# root@srv1 ~ # download from '/tmp/foo' to '/tmp/file2'\n
\n\n

Replace

\n\n
server.replace :all, 'new content', '/tmp/file'\n# root@srv1 ~ # replace all in '/tmp/foo'\n\nserver.read('/tmp/foo')\n# root@srv1 ~ # cat /tmp/foo\n# => \"new content\"\n
\n\n

Replace via regex

\n\n
server.replace /content$/, 'changed content', '/tmp/foo'\n# root@srv1 ~ # replace /content$/ in '/tmp/foo'\n\nserver.read('/tmp/foo')\n# root@srv1 ~ # cat /tmp/foo\n# => \"new changed content\"\n
\n\n

Append

\n\n
server.append('appended', '/tmp/foo')\n# root@srv1 ~ # append to 'bottom' in '/tmp/foo'\n\nserver.read('/tmp/foo')\n# root@srv1 ~ # cat /tmp/foo\n# => \"new changed contentappended\"\n
\n\n

Append to top

\n\n
server.append('---', '/tmp/foo', :top)\n# root@srv1 ~ # append to 'top' in '/tmp/foo'\n\nserver.read('/tmp/foo')\n# root@srv1 ~ # cat /tmp/foo\n# => \"---new changed contentappended\"\n
\n\n

Prompt

\n\n
server.ask \"Please choose\"\n# root@srv1 ~ # Please choose: foo\n# => \"foo\"\n\nserver.yes? \"Do you want to proceed\"\n# root@srv1 ~ # Do you want to proceed? (y/n): y\n# => 0\n\nserver.wait\n# Press ENTER to continue...\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "docker-compose", "title": "docker-compose", "url": "/docker-compose", "category": "Devops", "keywords": null, "content_html": "

Basic example

\n\n
# docker-compose.yml\nversion: '2'\n\nservices:\n  web:\n    build: .\n    # build from Dockerfile\n    context: ./Path\n    dockerfile: Dockerfile\n    ports:\n     - \"5000:5000\"\n    volumes:\n     - .:/code\n  redis:\n    image: redis\n
\n\n

Commands

\n\n
docker-compose start\ndocker-compose stop\n
\n\n
docker-compose pause\ndocker-compose unpause\n
\n\n
docker-compose ps\ndocker-compose up\ndocker-compose down\n
\n\n

Reference

\n\n

Building

\n\n
web:\n  # build from Dockerfile\n  build: .\n  args:     # Add build arguments\n    APP_HOME: app\n
\n\n
  # build from custom Dockerfile\n  build:\n    context: ./dir\n    dockerfile: Dockerfile.dev\n
\n\n
  # build from image\n  image: ubuntu\n  image: ubuntu:14.04\n  image: tutum/influxdb\n  image: example-registry:4000/postgresql\n  image: a4bc65fd\n
\n\n

Ports

\n\n
  ports:\n    - \"3000\"\n    - \"8000:80\"  # host:container\n
\n\n
  # expose ports to linked services (not to host)\n  expose: [\"3000\"]\n
\n\n

Commands

\n\n
  # command to execute\n  command: bundle exec thin -p 3000\n  command: [bundle, exec, thin, -p, 3000]\n
\n\n
  # override the entrypoint\n  entrypoint: /app/start.sh\n  entrypoint: [php, -d, vendor/bin/phpunit]\n
\n\n

Environment variables

\n\n
  # environment vars\n  environment:\n    RACK_ENV: development\n  environment:\n    - RACK_ENV=development\n
\n\n
  # environment vars from file\n  env_file: .env\n  env_file: [.env, .development.env]\n
\n\n

Dependencies

\n\n
  # makes the `db` service available as the hostname `database`\n  # (implies depends_on)\n  links:\n    - db:database\n    - redis\n
\n\n
  # make sure `db` is alive before starting\n  depends_on:\n    - db\n
\n\n

Other options

\n\n
  # make this service extend another\n  extends:\n    file: common.yml  # optional\n    service: webapp\n
\n\n
  volumes:\n    - /var/lib/mysql\n    - ./_data:/var/lib/mysql\n
\n\n

Advanced features

\n\n

Labels

\n\n
services:\n  web:\n    labels:\n      com.example.description: \"Accounting web app\"\n
\n\n

DNS servers

\n\n
services:\n  web:\n    dns: 8.8.8.8\n    dns:\n      - 8.8.8.8\n      - 8.8.4.4\n
\n\n

Devices

\n\n
services:\n  web:\n    devices:\n    - \"/dev/ttyUSB0:/dev/ttyUSB0\"\n
\n\n

External links

\n\n
services:\n  web:\n    external_links:\n      - redis_1\n      - project_db_1:mysql\n
\n\n

Hosts

\n\n
services:\n  web:\n    extra_hosts:\n      - \"somehost:192.168.1.100\"\n
\n\n

Network

\n\n
# creates a custom network called `frontend`\nnetworks:\n  frontend:\n
\n\n

External network

\n\n
# join a pre-existing network\nnetworks:\n  default:\n    external:\n      name: frontend\n
\n\n

Volume

\n\n
# Mount host paths or named volumes, specified as sub-options to a service\n  db:\n    image: postgres:latest\n    volumes:\n      - \"/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock\"\n      - \"dbdata:/var/lib/postgresql/data\"\n\nvolumes:\n  dbdata:\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-01-01" },{ "id": "docker", "title": "Docker CLI", "url": "/docker", "category": "Devops", "keywords": null, "content_html": "

Manage images

\n\n

docker build

\n\n
docker build [options] .\n  -t \"app/container_name\"    # name\n  --build-arg APP_HOME=$APP_HOME    # Set build-time variables\n
\n\n

Create an image from a Dockerfile.

\n\n

docker run

\n\n
docker run [options] IMAGE\n  # see `docker create` for options\n
\n\n

Example

\n\n
$ docker run -it debian:buster /bin/bash\n
\n

Run a command in an image.

\n\n

Manage containers

\n\n

docker create

\n\n
docker create [options] IMAGE\n  -a, --attach               # attach stdout/err\n  -i, --interactive          # attach stdin (interactive)\n  -t, --tty                  # pseudo-tty\n      --name NAME            # name your image\n  -p, --publish 5000:5000    # port map\n      --expose 5432          # expose a port to linked containers\n  -P, --publish-all          # publish all ports\n      --link container:alias # linking\n  -v, --volume `pwd`:/app    # mount (absolute paths needed)\n  -e, --env NAME=hello       # env vars\n
\n\n

Example

\n\n
$ docker create --name app_redis_1 \\\n  --expose 6379 \\\n  redis:3.0.2\n
\n\n

Create a container from an image.

\n\n

docker exec

\n\n
docker exec [options] CONTAINER COMMAND\n  -d, --detach        # run in background\n  -i, --interactive   # stdin\n  -t, --tty           # interactive\n
\n\n

Example

\n\n
$ docker exec app_web_1 tail logs/development.log\n$ docker exec -t -i app_web_1 rails c\n
\n\n

Run commands in a container.

\n\n

docker start

\n\n
docker start [options] CONTAINER\n  -a, --attach        # attach stdout/err\n  -i, --interactive   # attach stdin\n\ndocker stop [options] CONTAINER\n
\n\n

Start/stop a container.

\n\n

docker ps

\n\n
$ docker ps\n$ docker ps -a\n$ docker kill $ID\n
\n\n

Manage containers using ps/kill.

\n\n

docker logs

\n\n
$ docker logs $ID\n$ docker logs $ID 2>&1 | less\n$ docker logs -f $ID # Follow log output\n
\n\n

See what’s being logged in an container.

\n\n

Images

\n\n

docker images

\n\n
$ docker images\n  REPOSITORY   TAG        ID\n  ubuntu       12.10      b750fe78269d\n  me/myapp     latest     7b2431a8d968\n
\n\n
$ docker images -a   # also show intermediate\n
\n\n

Manages images.

\n\n

docker rmi

\n\n
docker rmi b750fe78269d\n
\n\n

Deletes images.

\n\n

Clean up

\n\n

Clean all

\n\n
docker system prune\n
\n\n

Cleans up dangling images, containers, volumes, and networks (ie, not associated with a container)

\n\n
docker system prune -a\n
\n\n

Additionally remove any stopped containers and all unused images (not just dangling images)

\n\n

Containers

\n\n
# Stop all running containers\ndocker stop $(docker ps -a -q)\n\n# Delete stopped containers\ndocker container prune\n
\n\n

Images

\n\n
docker image prune [-a]\n
\n\n

Delete all the images

\n\n

Volumes

\n\n
docker volume prune\n
\n\n

Delete all the volumes

\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "dockerfile", "title": "Dockerfile", "url": "/dockerfile", "category": "Devops", "keywords": null, "content_html": "

Reference

\n\n

Inheritance

\n\n
FROM ruby:2.2.2\n
\n\n

Variables

\n\n
ENV APP_HOME /myapp\nRUN mkdir $APP_HOME\n
\n\n
ARG APP_HOME=\"\"\nRUN mkdir $APP_HOME\n
\n\n

Initialization

\n\n
RUN bundle install\n
\n\n
WORKDIR /myapp\n
\n\n
VOLUME [\"/data\"]\n# Specification for mount point\n
\n\n
ADD file.xyz /file.xyz\nCOPY --chown=user:group host_file.xyz /path/container_file.xyz\n
\n\n

Onbuild

\n\n
ONBUILD RUN bundle install\n# when used with another file\n
\n\n

Commands

\n\n
EXPOSE 5900\nCMD    [\"bundle\", \"exec\", \"rails\", \"server\"]\n
\n\n

Entrypoint

\n\n
ENTRYPOINT [\"executable\", \"param1\", \"param2\"]\nENTRYPOINT command param1 param2\n
\n\n

Configures a container that will run as an executable.

\n\n
ENTRYPOINT exec top -b\n
\n\n

This will use shell processing to substitute shell variables, and will ignore any CMD or docker run command line arguments.

\n\n

Metadata

\n\n
LABEL version=\"1.0\"\n
\n\n
LABEL \"com.example.vendor\"=\"ACME Incorporated\"\nLABEL com.example.label-with-value=\"foo\"\n
\n\n
LABEL description=\"This text illustrates \\\nthat label-values can span multiple lines.\"\n
\n\n

See also

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2019-10-20" },{ "id": "dom-range", "title": "DOM Range", "url": "/dom-range", "category": "JavaScript", "keywords": null, "content_html": "

Reference

\n\n

Creating ranges

\n\n
var range = document.createRange()\n
\n\n

See: https://devdocs.io/dom/document/createrange

\n\n

Methods

\n\n
range\n  .setStart(startNode, startOffset)\n  .setEnd(endNode, endOffset)\n\n  .setStartBefore(node)\n  .setStartAfter(node)\n  .setEndBefore(node)\n  .setEndAfter(node)\n\n  .selectNode(node)\n  .selectNodeContents(node)\n
\n\n

See: https://devdocs.io/dom/range

\n\n

Collapsing

\n\n
range.collapse() // to end (a single point)\nrange.collapse(true) // to start (a single point)\nrange.collapsed // true | false\n
\n\n

Operations

\n\n
range.cloneContents() // copy => DocumentFragment\nrange.extractContents() // cut  => DocumentFragment\nrange.deleteContents() // delete\n
\n\n
range.insertNode(node)\n
\n\n

String

\n\n
range.toString()\n
\n\n

Read-only attributes

\n\n
range.collapsed //       => true/false\nrange.startContainer //  => Node\nrange.startOffset\nrange.endContainer //    => Node\nrange.endOffset\nrange.commonAncestorContainer // closest of start and end containers\n
", "intro_html": "

Quick reference to the HTML DOM createRange API.

", "description_html": "", "tags": null, "updated": null },{ "id": "dom-selection", "title": "DOM Selection", "url": "/dom-selection", "category": "JavaScript", "keywords": null, "content_html": "

Reference

\n\n

Selection

\n\n
var sel = document.getSelection()\n
\n\n

See: https://devdocs.io/dom/selection

\n\n

Methods

\n\n
sel.removeAllRanges() //  deselects\nsel.addRange(range) //    sets a selection\nsel.removeRange(range) // remove a range\n
\n\n
sel.rangeCount\nsel.getRangeAt(0) // get the 0th range\n
\n\n

Collapsing

\n\n
sel.collapse(parent, offset)\nsel.collapseToEnd()\nsel.collapseToStart()\nsel.isCollapsed\n
\n\n
sel.containsNode(node)\n
\n\n

Deleting

\n\n
sel.deleteFromDocument()\n
\n\n

Events

\n\n
document.addEventListener('selectionchange', () => {})\n
", "intro_html": "

Quick introduction to the HTML DOM selection API.

", "description_html": "", "tags": null, "updated": null },{ "id": "editorconfig", "title": "editorconfig", "url": "/editorconfig", "category": "Apps", "keywords": null, "content_html": "

Short example

\n\n
# editorconfig.org\nroot = true\n\n[*]\nindent_style = space\nindent_size = 2\ntab_width = 2\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n
\n\n

This example should be fine for most projects indented by 2 spaces. See: animate.css editorconfig

\n\n

Properties

\n\n
indent_style = {space|tab}\nindent_size = {4|tab}\ntab_width = 2\nend_of_line = {cr|lf|crlf}\ncharset = {utf-8|utf-16be|utf-16le|latin1}\ntrim_trailing_whitespace = false\ninsert_final_newline = true\nmax_line_length = 80\n
\n\n

Full example

\n\n
# top-most EditorConfig file\nroot = true\n\n# Unix-style newlines with a newline ending every file\n[*]\nend_of_line = lf\ninsert_final_newline = true\n\n# 4 space indentation\n[*.py]\nindent_style = space\nindent_size = 4\n\n# Tab indentation (no size specified)\n[*.js]\nindent_style = tab\n\n# Indentation override for all JS under lib directory\n[lib/**.js]\nindent_style = space\nindent_size = 2\n\n# Matches the exact files either package.json or .travis.yml\n[{package.json,.travis.yml}]\nindent_style = space\nindent_size = 2\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2019-09-25" },{ "id": "elixir-metaprogramming", "title": "Elixir metaprogramming", "url": "/elixir-metaprogramming", "category": "Elixir", "keywords": null, "content_html": "

Kernel

\n\n

Most of these magic is defined in Kernel.SpecialForms.

\n\n

Pseudo-variables

\n\n
__DIR__     # current dir\n__MODULE__  # current module\n__CALLER__  # caller of the function\n
\n\n

__ENV__

\n\n
Map.keys(__ENV__)\n[:__struct__, :aliases, :context, :context_modules, :export_vars, :file,\n :function, :functions, :lexical_tracker, :line, :macro_aliases, :macros,\n :module, :requires, :vars]\n
\n\n
__CALLER__.module |> Module.definitions_in |> IO.inspect\n
\n\n
apply(Enum, :reverse, [[1, 2, 3]])\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "elixir", "title": "Elixir", "url": "/elixir", "category": "Elixir", "keywords": null, "content_html": "

Getting started

\n\n

Hello world

\n\n
# hello.exs\ndefmodule Greeter do\n  def greet(name) do\n    message = \"Hello, \" <> name <> \"!\"\n    IO.puts message\n  end\nend\n\nGreeter.greet(\"world\")\n
\n\n
elixir hello.exs\n# Hello, world!\n
\n\n

Variables

\n\n
age = 23\n
\n\n

Maps

\n\n
user = %{\n  name: \"John\",\n  city: \"Melbourne\"\n}\n
\n\n
IO.puts \"Hello, \" <> user.name\n
\n\n

Lists

\n\n
users = [ \"Tom\", \"Dick\", \"Harry\" ]\n
\n\n
Enum.map(users, fn user ->\n  IO.puts \"Hello \" <> user\nend)\n
\n\n

Piping

\n\n
source\n|> transform(:hello)\n|> print()\n
\n\n
# Same as:\nprint(transform(source, :hello))\n
\n\n

These two are equivalent.

\n\n

Pattern matching

\n\n
user = %{name: \"Tom\", age: 23}\n%{name: username} = user\n
\n\n

This sets username to \"Tom\".

\n\n

Pattern matching in functions

\n\n
def greet(%{name: username}) do\n  IO.puts \"Hello, \" <> username\nend\n\nuser = %{name: \"Tom\", age: 23}\n
\n\n

Pattern matching works in function parameters too.

\n\n

Control flow

\n\n

If

\n\n
if false do\n  \"This will never be seen\"\nelse\n  \"This will\"\nend\n
\n

Case

\n\n
case {1, 2, 3} do\n  {4, 5, 6} ->\n    \"This clause won't match\"\n  {1, x, 3} ->\n    \"This will match and bind x to 2\"\n  _ ->\n   \"This will match any value\"\nend\n
\n\n

Cond

\n\n
cond do\n  1 + 1 == 3 ->\n    \"I will never be seen\"\n  2 * 5 == 12 ->\n    \"Me neither\"\n  true ->\n    \"But I will (this is essentially an else)\"\nend\n
\n\n

Errors

\n\n
try do\n  throw(:hello)\ncatch\n  message -> \"Got #{message}.\"\nafter\n  IO.puts(\"I'm the after clause.\")\nend\n
\n\n

Types

\n\n

Primitives

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SampleType
nilNil/null
true / falseBoolean
?aInteger (ASCII)
23Integer
3.14Float
'hello'Charlist
<<2, 3>>Binary
\"hello\"Binary string
:helloAtom
[a, b]List
{a, b}Tuple
%{a: \"hello\"}Map
%MyStruct{a: \"hello\"}Struct
fn -> ... endFunction
\n\n

Type checks

\n\n
is_atom/1\nis_bitstring/1\nis_boolean/1\nis_function/1\nis_function/2\nis_integer/1\nis_float/1\n
\n\n
is_binary/1\nis_list/1\nis_map/1\nis_tuple/1\n
\n\n
is_nil/1\nis_number/1\nis_pid/1\nis_port/1\nis_reference/1\n
\n\n

Operators

\n\n
left != right   # equal\nleft !== right  # match\nleft ++ right   # concat lists\nleft <> right   # concat string/binary\nleft =~ right   # regexp\n
\n\n

Modules

\n\n

Importing

\n\n
require Redux   # compiles a module\nimport Redux    # compiles, and you can use without the `Redux.` prefix\n\nuse Redux       # compiles, and runs Redux.__using__/1\nuse Redux, async: true\n\nimport Redux, only: [duplicate: 2]\nimport Redux, only: :functions\nimport Redux, only: :macros\n\nimport Foo.{Bar, Baz}\n
\n\n

Aliases

\n\n
alias Foo.Bar, as: Bar\nalias Foo.Bar   # same as above\n\nalias Foo.{Bar, Baz}\n
\n\n

String

\n\n

Functions

\n\n
import String\n
\n\n
str = \"hello\"\nstr |> length()        # → 5\nstr |> codepoints()    # → [\"h\", \"e\", \"l\", \"l\", \"o\"]\nstr |> slice(2..-1)    # → \"llo\"\nstr |> split(\" \")      # → [\"hello\"]\nstr |> capitalize()    # → \"Hello\"\nstr |> match(regex)\n
\n\n

Inspecting objects

\n\n
inspect(object, opts \\\\ [])\n
\n
value |> IO.inspect()\n
\n
value |> IO.inspect(label: \"value\")\n
\n\n

Numbers

\n\n

Operations

\n\n
abs(n)\nround(n)\nrem(a, b)   # remainder (modulo)\ndiv(a, b)   # integer division\n
\n\n

Float

\n\n
import Float\n
\n\n
n = 10.3\n
\n\n
n |> ceil()            # → 11.0\nn |> ceil(2)           # → 11.30\nn |> to_string()       # → \"1.030000+e01\"\nn |> to_string([decimals: 2, compact: true])\n
\n\n
Float.parse(\"34\")  # → { 34.0, \"\" }\n
\n\n

Integer

\n\n
import Integer\n
\n\n
n = 12\n
\n\n
n |> digits()         # → [1, 2]\nn |> to_charlist()    # → '12'\nn |> to_string()      # → \"12\"\nn |> is_even()\nn |> is_odd()\n
\n\n
# Different base:\nn |> digits(2)        # → [1, 1, 0, 0]\nn |> to_charlist(2)   # → '1100'\nn |> to_string(2)     # → \"1100\"\n
\n\n
parse(\"12\")           # → {12, \"\"}\nundigits([1, 2])      # → 12\n
\n\n

Type casting

\n\n
Float.parse(\"34.1\")    # → {34.1, \"\"}\nInteger.parse(\"34\")    # → {34, \"\"}\n
\n\n
Float.to_string(34.1)  # → \"3.4100e+01\"\nFloat.to_string(34.1, [decimals: 2, compact: true])  # → \"34.1\"\n
\n\n

Map

\n\n

Defining

\n\n
m = %{name: \"hi\"}       # atom keys (:name)\nm = %{\"name\" => \"hi\"}   # string keys (\"name\")\n
\n\n

Updating

\n\n
import Map\n
\n\n
m = %{m | name: \"yo\"}  # key must exist\n
\n\n
m |> put(:id, 2)      # → %{id: 2, name: \"hi\"}\nm |> put_new(:id, 2)  # only if `id` doesn't exist (`||=`)\n
\n\n
m |> put(:b, \"Banana\")\nm |> merge(%{b: \"Banana\"})\nm |> update(:a, &(&1 + 1))\nm |> update(:a, fun a -> a + 1 end)\n
\n\n
m |> get_and_update(:a, &(&1 || \"default\"))\n# → {old, new}\n
\n\n

Deleting

\n\n
m |> delete(:name)  # → %{}\nm |> pop(:name)     # → {\"John\", %{}}\n
\n\n

Reading

\n\n
m |> get(:id)       # → 1\nm |> keys()         # → [:id, :name]\nm |> values()       # → [1, \"hi\"]\n
\n\n
m |> to_list()      # → [id: 1, name: \"hi\"]\n                    # → [{:id, 1}, {:name, \"hi\"}]\n
\n\n

Deep

\n\n
put_in(map, [:b, :c], \"Banana\")\nput_in(map[:b][:c], \"Banana\")    # via macros\n
\n\n
get_and_update_in(users, [\"john\", :age], &{&1, &1 + 1})\n
\n\n

Constructing from lists

\n\n
Map.new([{:b, 1}, {:a, 2}])\nMap.new([a: 1, b: 2])\nMap.new([:a, :b], fn x -> {x, x} end)  # → %{a: :a, b: :b}\n
\n\n

List

\n\n
import List\n
\n\n
l = [ 1, 2, 3, 4 ]\n
\n\n
l = l ++ [5]         # push (append)\nl = [ 0 | list ]     # unshift (prepend)\n
\n\n
l |> first()\nl |> last()\n
\n\n
l |> flatten()\nl |> flatten(tail)\n
\n\n

Also see Enum.

\n\n

Enum

\n\n

Usage

\n\n
import Enum\n
\n\n
list = [:a, :b, :c]\n
\n\n
list |> at(0)         # → :a\nlist |> count()       # → 3\nlist |> empty?()      # → false\nlist |> any?()        # → true\n
\n\n
list |> concat([:d])  # → [:a, :b, :c, :d]\n
\n\n

Also, consider streams instead.

\n\n

Map/reduce

\n\n
list |> reduce(fn)\nlist |> reduce(acc, fn)\nlist |> map(fn)\nlist |> reject(fn)\nlist |> any?(fn)\nlist |> empty?(fn)\n
\n\n
[1, 2, 3, 4]\n|> Enum.reduce(0, fn(x, acc) -> x + acc end)\n
\n\n

Tuple

\n\n

Tuples

\n\n
import Tuple\n
\n\n
t = { :a, :b }\n
\n\n
t |> elem(1)    # like tuple[1]\nt |> put_elem(index, value)\nt |> tuple_size()\n
\n\n

Keyword lists

\n\n
list = [{ :name, \"John\" }, { :age, 15 }]\nlist[:name]\n
\n\n
# For string-keyed keyword lists\nlist = [{\"size\", 2}, {\"type\", \"shoe\"}]\nList.keyfind(list, \"size\", 0)  # → {\"size\", 2}\n
\n\n

Functions

\n\n

Lambdas

\n\n
square = fn n -> n*n end\nsquare.(20)\n
\n\n

& syntax

\n\n
square = &(&1 * &1)\nsquare.(20)\n\nsquare = &Math.square/1\n
\n\n

Running

\n\n
fun.(args)\napply(fun, args)\napply(module, fun, args)\n
\n\n

Function heads

\n\n
def join(a, b \\\\ nil)\ndef join(a, b) when is_nil(b) do: a\ndef join(a, b) do: a <> b\n
\n\n

Structs

\n\n

Structs

\n\n
defmodule User do\n  defstruct name: \"\", age: nil\nend\n\n%User{name: \"John\", age: 20}\n\n%User{}.struct  # → User\n
\n\n

See: Structs

\n\n

Protocols

\n\n

Defining protocols

\n\n
defprotocol Blank do\n  @doc \"Returns true if data is considered blank/empty\"\n  def blank?(data)\nend\n
\n\n
defimpl Blank, for: List do\n  def blank?([]), do: true\n  def blank?(_), do: false\nend\n\nBlank.blank?([])  # → true\n
\n\n

Any

\n\n
defimpl Blank, for: Any do ... end\n\ndefmodule User do\n  @derive Blank     # Falls back to Any\n  defstruct name: \"\"\nend\n
\n\n

Examples

\n\n\n\n

Comprehensions

\n\n

For

\n\n
for n <- [1, 2, 3, 4], do: n * n\nfor n <- 1..4, do: n * n\n
\n\n
for {key, val} <- %{a: 10, b: 20}, do: val\n# → [10, 20]\n
\n\n
for {key, val} <- %{a: 10, b: 20}, into: %{}, do: {key, val*val}\n
\n\n

Conditions

\n\n
for n <- 1..10, rem(n, 2) == 0, do: n\n# → [2, 4, 6, 8, 10]\n
\n\n

Complex

\n\n
for dir <- dirs,\n    file <- File.ls!(dir),          # nested comprehension\n    path = Path.join(dir, file),    # invoked\n    File.regular?(path) do          # condition\n  IO.puts(file)\nend\n
\n\n

Misc

\n\n

Metaprogramming

\n\n
__MODULE__\n__MODULE__.__info__\n\n@after_compile __MODULE__\ndef __before_compile__(env)\ndef __after_compile__(env, _bytecode)\ndef __using__(opts)    # invoked on `use`\n\n@on_definition {__MODULE__, :on_def}\ndef on_def(_env, kind, name, args, guards, body)\n\n@on_load :load_check\ndef load_check\n
\n\n

Regexp

\n\n
exp = ~r/hello/\nexp = ~r/hello/i\n\"hello world\" =~ exp\n
\n\n

Sigils

\n\n
~r/regexp/\n~w(list of strings)\n~s|strings with #{interpolation} and \\x20 escape codes|\n~S|no interpolation and no escapes|\n~c(charlist)\n
\n\n

Allowed chars: / | \" ' ( [ { < \"\"\".\nSee: Sigils

\n\n

Type specs

\n\n
@spec round(number) :: integer\n\n@type number_with_remark :: {number, String.t}\n@spec add(number, number) :: number_with_remark\n
\n\n

Useful for dialyzer.\nSee: Typespecs

\n\n

Behaviours

\n\n
defmodule Parser do\n  @callback parse(String.t) :: any\n  @callback extensions() :: [String.t]\nend\n
\n\n
defmodule JSONParser do\n  @behaviour Parser\n\n  def parse(str), do: # ... parse JSON\n  def extensions, do: [\"json\"]\nend\n
\n\n

See: Module

\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": ["New"], "updated": "2018-07-04" },{ "id": "emacs", "title": "Emacs", "url": "/emacs", "category": "CLI", "keywords": null, "content_html": "

Movements

\n\n

^n ^p # up/down\n ^f ^b # left/right

\n\n

^v Mv # up/down page

\n\n

^a ^e # begin/end of line\n Ma Me # begin/end of sentence

\n\n

Basic

\n\n

^x ^f # find file\n ^x ^s # save file

\n\n

Command line

\n\n

Mx

\n\n

Packages

\n\n

Mx package-install RET evil RET

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ember", "title": "Ember.js", "url": "/ember", "category": "JavaScript libraries", "keywords": null, "content_html": "

Routes

\n\n
App.Router.map(function() {\n  this.resource('trips', function() {\n      this.route('item', { path: '/:trip_id' });\n  });\n\n  this.route('upcoming');\n  this.route('about', { path: '/about' });\n  this.route('schedules');\n  this.route('history');\n  this.route('post');\n});\n
\n\n

A route

\n\n
App.IndexRoute = Ember.Route.extend({\n  setupController: function(controller) {\n    controller.set('title', 'my app');\n    // <h1>{{title}}</h1>\n  },\n\n  setupController: function(controller, model) {\n    controller.set(\"model\", model);\n    this.controllerFor('topPost').set('model', model);\n  },\n\n  model: function(params) {\n    return this.store.find('posts');\n    return this.store.find('post', params.post_id);\n  },\n  \n  serialize: function(model) {\n    // this will make the URL `/posts/foo-post`\n    return { post_slug: model.get('slug') };\n  }\n});\n
\n\n

View

\n\n
App.InfoView = Ember.View.extend({\n  templateName: 'input',  /* optional */\n\n  fooName: \"Hello\"  /* {{ view.fooName }} */\n\n  click: function(e) {\n    \"I was clicked\";\n  }\n\n});\n
\n\n

markup

\n\n
<img {{bindAttr src=\"avatarURL\"}}>\n<button {{action follow}}>\n
\n\n

Value binding:

\n\n
{{view Ember.TextField class=\"input block\" valuebinding=\"emailAddresses\"}}\n
\n\n

Actions:

\n\n
<button {{action invite emailAddresses}}>Invite></button>\n\n<a href=\"#\" {{action set \"isEditingContacts\" true target=\"view\"}} \n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "emmet", "title": "Emmet", "url": "/emmet", "category": "Markup", "keywords": null, "content_html": "

Child: >

\n\n
nav>ul>li\n
\n

Expands to

\n
<nav>\n  <ul>\n    <li></li>\n  </ul>\n</nav>\n
\n\n

Sibling: +

\n\n
section>p+p+p\n
\n

Expands to

\n
<section>\n  <p></p>\n  <p></p>\n  <p></p>\n</section>\n
\n\n

Climb Up: ^

\n\n
section>header>h1^footer\n
\n

Expands to

\n
<section>\n  <header>\n    <h1></h1>\n  </header>\n  <footer></footer>\n</section>\n
\n\n

Grouping: ()

\n\n
section>(header>nav>ul>li)+footer>p\n
\n

Expands to

\n
<section>\n  <header>\n    <nav>\n      <ul>\n        <li></li>\n      </ul>\n    </nav>\n  </header>\n  <footer>\n    <p></p>\n  </footer>\n</section>\n
\n\n

Multiplication: *

\n\n
ul>li*3\n
\n

Expands to

\n
<ul>\n  <li></li>\n  <li></li>\n  <li></li>\n</ul>\n
\n\n

IDs and Classes: .

\n\n
ul.menu>li.menu__item+li#id_item+li.menu__item#id_2\n
\n

Expands to

\n
<ul>\n  <li class=\"menu__item\"></li>\n  <li id=\"id_item\"></li>\n  <li class=\"menu__item\" id=\"id_2\"></li>\n</ul>\n
\n\n

Numbering: $

\n\n
ul>li.item$*3\nul>li.item$$*3\nul>li.item$@-*3\nul>li.item$@3*5\n
\n

Expands to

\n
<ul>\n  <li class=\"item1\"></li>\n  <li class=\"item2\"></li>\n  <li class=\"item3\"></li>\n</ul>\n<ul>\n  <li class=\"item01\"></li>\n  <li class=\"item02\"></li>\n  <li class=\"item03\"></li>\n</ul>\n<ul>\n  <li class=\"item3\"></li>\n  <li class=\"item2\"></li>\n  <li class=\"item1\"></li>\n</ul>\n<ul>\n  <li class=\"item3\"></li>\n  <li class=\"item4\"></li>\n  <li class=\"item5\"></li>\n</ul>\n
\n\n

Attributes: []

\n\n
input[type=\"text\"]\ndiv[data-attr=\"test\"]\n
\n

Expands to

\n
<input type=\"text\" />\n<div data-attr=\"test\"></div>\n
\n\n

Text: {}

\n\n
p{Lorem ipsum}\n
\n

Expands to

\n
<p>Lorem ipsum</p>\n
\n\n

Implicit tags

\n\n
.default-block\nem>.default-inline\nul>.default-list\ntable>.default-table-row>.default-table-column\n
\n

Expands to

\n
<div class=\"default-block\"></div>\n<em><span class=\"default-inline\"></span></em>\n<ul>\n  <li class=\"default-list\"></li>\n</ul>\n<table>\n  <tr class=\"default-table-row\">\n    <td class=\"default-table-column\"></td>\n  </tr>\n</table>\n
", "intro_html": "

Emmet is a markup language for expanding CSS rules into HTML

", "description_html": "", "tags": null, "updated": "2020-07-03" },{ "id": "enzyme", "title": "Enzyme", "url": "/enzyme", "category": "React", "keywords": ["shallow()","mount()","wrap.setProps()","wrap.find().simulate('click')","wrap.contains(
)"], "content_html": "

Getting started

\n\n

Introduction

\n\n

Enzyme lets you write unit tests for React components. This guide covers Enzyme 3.x.

\n\n\n\n

Mounting

\n\n
import {shallow, mount} from 'enzyme'\n
\n\n
wrap = shallow(<MyComponent />)\n
\n\n
wrap = mount(<MyComponent />)\n
\n\n

Shallow wrapping doesn’t descend down to sub-components.\nA full mount also mounts sub-components.

\n\n

See: Shallow rendering,\nFull rendering

\n\n

Debugging

\n\n
console.log(wrap.debug())\n
\n\n

Shows HTML for debugging purposes.

\n\n

See: debug()

\n\n

Examples

\n\n

Basic example

\n\n
import { shallow } from 'enzyme'\nimport MyComponent from '../MyComponent'\n
\n\n
it('works', () => {\n  const wrap = shallow(\n    <MyComponent name='Groot' />\n  )\n\n  expect(wrap.text()).toEqual('I am Groot')\n})\n
\n\n

Props and state

\n\n

Setting

\n\n
wrap.setProps({ name: 'Moe' })\nwrap.setState({ show: true })\n
\n\n

Asserting

\n\n
expect(wrap.prop('name')).toEqual('Moe')\nexpect(wrap.state('show')).toEqual(true)\n
\n\n
expect('name' in wrap.props()).toEqual('Moe')\nexpect('show' in wrap.state()).toEqual(true)\n
\n\n

Matching elements

\n\n
expect(\n  wrap.containsMatchingElement(\n    <span>I am groot</span>\n  )\n).toBeTruthy()\n
\n\n

containsMatchingElement() is probably the most useful assertion in Jest.

\n\n

Snapshots

\n\n
expect(wrap).toMatchSnapshot()\n
\n\n

Be sure you’ve set up enzyme-to-json for snapshots (see Installing below).

\n\n

Traversions

\n\n
expect(\n  wrap.find('button').text()\n).toEqual('Submit')\n
\n\n

Use .find() to traverse down to nodes. It will return wrapper objects, too.

\n\n

Simulating events

\n\n
wrap.find('input').simulate('click')\n
\n\n

With event object props

\n\n
wrap.find('input').simulate('change', {\n  target: { value: 'hello' }\n})\n
\n\n

Installing

\n\n

Initial setup

\n\n
npm install --save-dev enzyme \\\n  enzyme-adapter-react-16 \\\n  react-test-renderer\n
\n\n

test/setup.js

\n\n
import Enzyme from 'enzyme'\nimport Adapter from 'enzyme-adapter-react-16'\n\nEnzyme.configure({ adapter: new Adapter() })\n
\n\n

package.json

\n\n
\"jest\": {\n  \"setupFiles\": [\n    \"test/setup.js\"\n  ]\n}\n
\n\n

This configures Enzyme for React v16, and Jest to automatically configure Enzyme for you. There are other adapters in Enzyme’s installation instructions.

\n\n

See: Installation

\n\n

Jest snapshots

\n\n
npm install --save-dev enzyme-to-json\n
\n\n

package.json

\n\n
\"jest\": {\n  \"snapshotSerializers\": [\n    \"enzyme-to-json/serializer\"\n  ]\n}\n
\n\n

Test

\n\n
it('works', () => {\n  wrap = mount(<MyComponent />)\n  expect(wrap).toMatchSnapshot()\n})\n
\n\n

Optional, but recommended: This allows you to use Enzyme wrappers with Jest snapshots.

\n\n

See: enzyme-to-json

\n\n

ReactWrapper

\n\n

Traversing

\n\n
wrap.find('button')   // → ReactWrapper\nwrap.filter('button') // → ReactWrapper\nwrap.not('span')      // → ReactWrapper (inverse of filter())\nwrap.children()       // → ReactWrapper\nwrap.parent()         // → ReactWrapper\nwrap.closest('div')   // → ReactWrapper\nwrap.childAt(0)       // → ReactWrapper\nwrap.at(0)            // → ReactWrapper\nwrap.first()          // → ReactWrapper\nwrap.last()           // → ReactWrapper\n
\n\n
wrap.get(0)           // → ReactElement\nwrap.getElement()     // → ReactElement\nwrap.getElements()    // → Array<ReactElement>\nwrap.getDOMNode()     // → DOMComponent\n
\n\n

See: Full rendering API

\n\n

Actions

\n\n
wrap.simulate('click')\n
\n\n

React components

\n\n
wrap.setState({ ··· })\nwrap.setProps({ ··· })\nwrap.setContext({ ··· })\n
\n\n
wrap.state()         // get full state\nwrap.props()         // get full props\nwrap.context()       // get full context\n
\n\n
wrap.state('key')    // → any\nwrap.prop('key')     // → any\nwrap.context('key')  // → any\n
\n\n
wrap.instance()      // → ReactComponent\n
\n\n

Mount

\n\n
wrap.mount()\nwrap.unmount()\nwrap.update()      // calls forceUpdate()\n
\n\n

Tests

\n\n
wrap.debug()               // → string\nwrap.html()                // → string\nwrap.text()                // → string\nwrap.type()                // → string | function\nwrap.name()                // → string\nwrap.is('.classname')      // → boolean\nwrap.hasClass('class')     // → boolean\nwrap.exists()              // → boolean\nwrap.contains(<div />)     // → boolean\nwrap.contains([ <div /> ]) // → boolean\nwrap.some('.child')        // → boolean\n\nwrap.someWhere(n => n.hasClass('foo'))\n\nwrap.containsMatchingElement(<div />)         // → boolean\nwrap.containsAllMatchingElements([ <div /> ]) // → boolean\nwrap.containsAnyMatchingElements([ <div /> ]) // → boolean\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": ["Featured"], "updated": "2020-02-12" },{ "id": "enzyme@2", "title": "Enzyme v2", "url": "/enzyme@2", "category": "React", "keywords": null, "content_html": "

Getting started

\n\n

Introduction

\n\n

(Deprecated) Enzyme lets you write unit tests for React components. This guide covers a previous version (v2.x).

\n\n

Mounting

\n\n
import {shallow, mount} from 'enzyme'\n
\n\n
wrap = shallow(<MyComponent />)\n
\n\n
wrap = mount(<MyComponent />)\n
\n\n

Shallow wrapping doesn’t descend down to sub-components.\nA full mount also mounts sub-components.\nSee: Shallow rendering,\nFull rendering

\n\n

Jest

\n\n
import toJson from 'enzyme-to-json'\n
\n\n
it('works', () => {\n  wrap = mount(<MyComponent />)\n  expect(toJson(wrap)).toMatchSnapshot()\n})\n
\n\n

Converts an Enzyme wrapper to a format compatible with Jest snapshots. See: enzyme-to-json

\n\n

Debugging

\n\n
console.log(wrap.debug())\n
\n\n

Shows HTML for debugging purposes. See: debug()

\n\n

ReactWrapper

\n\n

Traversing

\n\n
wrap.find('button')   // => ReactWrapper\nwrap.filter('button') // => ReactWrapper\nwrap.not('span')      // => ReactWrapper (inverse of filter())\nwrap.children()       // => ReactWrapper\nwrap.parent()         // => ReactWrapper\nwrap.closest('div')   // => ReactWrapper\nwrap.childAt(0)       // => ReactWrapper\nwrap.at(0)            // => ReactWrapper\nwrap.first()          // => ReactWrapper\nwrap.last()           // => ReactWrapper\n
\n\n
wrap.get(0)           // => ReactElement\nwrap.getNode()        // => ReactElement\nwrap.getNodes()       // => Array<ReactElement>\nwrap.getDOMNode()     // => DOMComponent\n
\n\n

See: Full rendering API

\n\n

Actions

\n\n
wrap.simulate('click')\n
\n\n

React components

\n\n
wrap.setState({ ... })\nwrap.setProps({ ... })\nwrap.setContext({ ... })\n\nwrap.state()            // => Any (get state)\nwrap.props()            // => object (get props)\nwrap.context()          // => Any (get context)\n\nwrap.instance()         // => ReactComponent\n
\n\n

Mount

\n\n
wrap.mount()\nwrap.unmount()\nwrap.update()      // calls forceUpdate()\n
\n\n

Tests

\n\n
wrap.debug()               // => string\nwrap.html()                // => string\nwrap.text()                // => string\nwrap.type()                // => string | function\nwrap.name()                // => string\nwrap.is('.classname')      // => boolean\nwrap.hasClass('class')     // => boolean\nwrap.exists()              // => boolean\nwrap.contains(<div />)     // => boolean\nwrap.contains([ <div /> ]) // => boolean\n\nwrap.containsMatchingElement(<div />)         // => boolean\nwrap.containsAllMatchingElements([ <div /> ]) // => boolean\nwrap.containsAnyMatchingElements([ <div /> ]) // => boolean\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-10-12" },{ "id": "es6", "title": "ES2015+", "url": "/es6", "category": "JavaScript", "keywords": null, "content_html": "

Block scoping

\n\n

Let

\n\n
function fn () {\n  let x = 0\n  if (true) {\n    let x = 1 // only inside this `if`\n  }\n}\n
\n\n

Const

\n\n
const a = 1\n
\n\n

let is the new var. Constants work just like let, but can’t be reassigned.\nSee: Let and const

\n\n

Backtick strings

\n\n

Interpolation

\n\n
const message = `Hello ${name}`\n
\n\n

Multiline strings

\n\n
const str = `\nhello\nworld\n`\n
\n\n

Templates and multiline strings.\nSee: Template strings

\n\n

Binary and octal literals

\n\n
let bin = 0b1010010\nlet oct = 0o755\n
\n\n

See: Binary and octal literals

\n\n

New methods

\n\n

New string methods

\n\n
\"hello\".repeat(3)\n\"hello\".includes(\"ll\")\n\"hello\".startsWith(\"he\")\n\"hello\".padStart(8) // \"   hello\"\n\"hello\".padEnd(8) // \"hello   \" \n\"hello\".padEnd(8, '!') // hello!!!\n\"\\u1E9B\\u0323\".normalize(\"NFC\")\n
\n\n

See: New methods

\n\n

Classes

\n\n
class Circle extends Shape {\n
\n\n

Constructor

\n\n
  constructor (radius) {\n    this.radius = radius\n  }\n
\n\n

Methods

\n\n
  getArea () {\n    return Math.PI * 2 * this.radius\n  }\n
\n\n

Calling superclass methods

\n\n
  expand (n) {\n    return super.expand(n) * Math.PI\n  }\n
\n\n

Static methods

\n\n
  static createFromDiameter(diameter) {\n    return new Circle(diameter / 2)\n  }\n}\n
\n\n

Syntactic sugar for prototypes.\nSee: Classes

\n\n

Exponent operator

\n\n
const byte = 2 ** 8\n// Same as: Math.pow(2, 8)\n
\n\n

Promises

\n\n

Making promises

\n\n
new Promise((resolve, reject) => {\n  if (ok) { resolve(result) }\n  else { reject(error) }\n})\n
\n\n

For asynchronous programming.\nSee: Promises

\n\n

Using promises

\n\n
promise\n  .then((result) => { ··· })\n  .catch((error) => { ··· })\n
\n\n

Using promises with finally

\n\n
promise\n  .then((result) => { ··· })\n  .catch((error) => { ··· })\n  .finally(() => { // logic independent of success/error })\n
\n\n

The handler is called when the promise is fulfilled or rejected.

\n\n

Promise functions

\n\n
Promise.all(···)\nPromise.race(···)\nPromise.reject(···)\nPromise.resolve(···)\n
\n\n

Async-await

\n\n
async function run () {\n  const user = await getUser()\n  const tweets = await getTweets(user)\n  return [user, tweets]\n}\n
\n\n

async functions are another way of using functions.

\n\n

See: async function

\n\n

Destructuring

\n\n

Destructuring assignment

\n\n

Arrays

\n\n
const [first, last] = ['Nikola', 'Tesla']\n
\n\n

Objects

\n\n
let {title, author} = {\n  title: 'The Silkworm',\n  author: 'R. Galbraith'\n}\n
\n\n

Supports for matching arrays and objects.\nSee: Destructuring

\n\n

Default values

\n\n
const scores = [22, 33]\nconst [math = 50, sci = 50, arts = 50] = scores\n
\n\n
// Result:\n// math === 22, sci === 33, arts === 50\n
\n\n

Default values can be assigned while destructuring arrays or objects.

\n\n

Function arguments

\n\n
function greet({ name, greeting }) {\n  console.log(`${greeting}, ${name}!`)\n}\n
\n\n
greet({ name: 'Larry', greeting: 'Ahoy' })\n
\n\n

Destructuring of objects and arrays can also be done in function arguments.

\n\n

Default values

\n\n
function greet({ name = 'Rauno' } = {}) {\n  console.log(`Hi ${name}!`);\n}\n
\n\n
greet() // Hi Rauno!\ngreet({ name: 'Larry' }) // Hi Larry!\n
\n\n

Reassigning keys

\n\n
function printCoordinates({ left: x, top: y }) {\n  console.log(`x: ${x}, y: ${y}`)\n}\n
\n\n
printCoordinates({ left: 25, top: 90 })\n
\n\n

This example assigns x to the value of the left key.

\n\n

Loops

\n\n
for (let {title, artist} of songs) {\n  ···\n}\n
\n\n

The assignment expressions work in loops, too.

\n\n

Object destructuring

\n\n
const { id, ...detail } = song;\n
\n\n

Extract some keys individually and remaining keys in the object using rest (…) operator

\n\n

Spread

\n\n

Object spread

\n\n

with Object spread

\n\n
const options = {\n  ...defaults,\n  visible: true\n}\n
\n\n

without Object spread

\n\n
const options = Object.assign(\n  {}, defaults,\n  { visible: true })\n
\n\n

The Object spread operator lets you build new objects from other objects.

\n\n

See: Object spread

\n\n

Array spread

\n\n

with Array spread

\n\n
const users = [\n  ...admins,\n  ...editors,\n  'rstacruz'\n]\n
\n\n

without Array spread

\n\n
const users = admins\n  .concat(editors)\n  .concat([ 'rstacruz' ])\n
\n\n

The spread operator lets you build new arrays in the same way.

\n\n

See: Spread operator

\n\n

Functions

\n\n

Function arguments

\n\n

Default arguments

\n\n
function greet (name = 'Jerry') {\n  return `Hello ${name}`\n}\n
\n\n

Rest arguments

\n\n
function fn(x, ...y) {\n  // y is an Array\n  return x * y.length\n}\n
\n\n

Spread

\n\n
fn(...[1, 2, 3])\n// same as fn(1, 2, 3)\n
\n\n

Default, rest, spread.\nSee: Function arguments

\n\n

Fat arrows

\n\n

Fat arrows

\n\n
setTimeout(() => {\n  ···\n})\n
\n\n

With arguments

\n\n
readFile('text.txt', (err, data) => {\n  ...\n})\n
\n\n

Implicit return

\n
numbers.map(n => n * 2)\n// No curly braces = implicit return\n// Same as: numbers.map(function (n) { return n * 2 })\nnumbers.map(n => ({\n  result: n * 2\n}))\n// Implicitly returning objects requires parentheses around the object\n
\n\n

Like functions but with this preserved.\nSee: Fat arrows

\n\n

Objects

\n\n

Shorthand syntax

\n\n
module.exports = { hello, bye }\n// Same as: module.exports = { hello: hello, bye: bye }\n
\n\n

See: Object literal enhancements

\n\n

Methods

\n\n
const App = {\n  start () {\n    console.log('running')\n  }\n}\n// Same as: App = { start: function () {···} }\n
\n\n

See: Object literal enhancements

\n\n

Getters and setters

\n\n
const App = {\n  get closed () {\n    return this.status === 'closed'\n  },\n  set closed (value) {\n    this.status = value ? 'closed' : 'open'\n  }\n}\n
\n\n

See: Object literal enhancements

\n\n

Computed property names

\n\n
let event = 'click'\nlet handlers = {\n  [`on${event}`]: true\n}\n// Same as: handlers = { 'onclick': true }\n
\n\n

See: Object literal enhancements

\n\n

Extract values

\n\n
const fatherJS = { age: 57, name: \"Brendan Eich\" }\n\nObject.values(fatherJS)\n// [57, \"Brendan Eich\"]\nObject.entries(fatherJS)\n// [[\"age\", 57], [\"name\", \"Brendan Eich\"]]\n
\n\n

Modules

\n\n

Imports

\n\n
import 'helpers'\n// aka: require('···')\n
\n\n
import Express from 'express'\n// aka: const Express = require('···').default || require('···')\n
\n\n
import { indent } from 'helpers'\n// aka: const indent = require('···').indent\n
\n\n
import * as Helpers from 'helpers'\n// aka: const Helpers = require('···')\n
\n\n
import { indentSpaces as indent } from 'helpers'\n// aka: const indent = require('···').indentSpaces\n
\n\n

import is the new require().\nSee: Module imports

\n\n

Exports

\n\n
export default function () { ··· }\n// aka: module.exports.default = ···\n
\n\n
export function mymethod () { ··· }\n// aka: module.exports.mymethod = ···\n
\n\n
export const pi = 3.14159\n// aka: module.exports.pi = ···\n
\n\n

export is the new module.exports.\nSee: Module exports

\n\n

Generators

\n\n

Generators

\n\n
function* idMaker () {\n  let id = 0\n  while (true) { yield id++ }\n}\n
\n\n
let gen = idMaker()\ngen.next().value  // → 0\ngen.next().value  // → 1\ngen.next().value  // → 2\n
\n\n

It’s complicated.\nSee: Generators

\n\n

For..of iteration

\n\n
for (let i of iterable) {\n  ···\n}\n
\n\n

For iterating through generators and arrays.\nSee: For..of iteration

", "intro_html": "

A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.

", "description_html": "", "tags": ["Featured"], "updated": "2019-11-14" },{ "id": "ets", "title": "Erlang ETS", "url": "/ets", "category": "Elixir", "keywords": null, "content_html": "

ETS

\n\n

Usage

\n\n
iex> table = :ets.new(:my_table, [])\n     8211\n
\n\n
iex> :ets.insert(table, {:fruit, \"Apple\"})\niex> :ets.lookup(table, :fruit)\n     [{:fruit, \"Apple\"}]\n
\n\n
iex> :ets.delete(table)\niex> :ets.delete_all_objects(table)\n
\n\n

Flags

\n\n
iex> table = :ets.new(:my_table, [:set, :protected])\n
\n\n\n \n \n \n \n \n \n \n \n \n \n
:setno duplicate keys (or: :ordered_set, :bag, :duplicate_bag)
:protectedonly this process can use it (or: :public, :private)
\n\n

Ordered sets

\n\n
:ets.first(table)\n:ets.last(table)\n:ets.next(table, key)\n:ets.prev(table, key)\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "expectjs", "title": "expect.js", "url": "/expectjs", "category": "JavaScript libraries", "keywords": null, "content_html": "

Using

\n\n
npm install --save-dev expect\n
\n\n
// using ES6 modules\nimport expect, { createSpy, spyOn, isSpy } from 'expect'\n
\n\n
// using CommonJS modules\nvar expect = require('expect')\nvar createSpy = expect.createSpy\nvar spyOn = expect.spyOn\nvar isSpy = expect.isSpy\n
\n\n

Expect is a library for assertions in tests.\nSee: mjackson/expect

\n\n

Assertions

\n\n
expect(x).toBe(y)\n  .toBe(val)\n  .toEqual(val)\n  .toThrow(err)\n  .toExist()          // aka: toBeTruthy()\n  .toNotExist()       // aka: toBeFalsy()\n  .toBeA(constructor)\n  .toBeA('string')\n  .toMatch(/expr/)\n  .toBeLessThan(n)\n  .toBeGreaterThan(n)\n  .toBeLessThanOrEqualTo(n)\n  .toBeGreaterThanOrEqualTo(n)\n  .toInclude(val)     // aka: toContain(val)\n  .toExclude(val)\n  .toIncludeKey(key)\n  .toExcludeKey(key)\n
\n\n

Also: toNotBe, toNotEqual, etc for negatives.

\n\n

Chaining assertions

\n\n
expect(3.14)\n  .toExist()\n  .toBeLessThan(4)\n  .toBeGreaterThan(3)\n
\n\n

Assertions can be chained.

\n\n

Spies

\n\n
const video = {\n  play: function () { ··· }\n}\n
\n\n
spy = expect.spyOn(video, 'play')\n
\n\n
spy = expect.spyOn(···)\n  .andCallThrough()      // pass through\n  .andCall(fn)\n  .andThrow(exception)\n  .andReturn(value)\n
\n\n

Assertions on spies

\n\n
expect(spy.calls.length).toEqual(1)\nexpect(spy.calls[0].context).toBe(video)\nexpect(spy.calls[0].arguments).toEqual([ 'some', 'args' ])\nexpect(spy.getLastCall().arguments).toEqual(...)\n
\n\n
expect(spy).toHaveBeenCalled()\nexpect(spy).toHaveBeenCalledWith('some', 'args')\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-02" },{ "id": "express", "title": "Express.js", "url": "/express", "category": "JavaScript libraries", "keywords": null, "content_html": "

Settings

\n\n
app.set('x', 'yyy')\napp.get('x') //=> 'yyy'\n\napp.enable('trust proxy')\napp.disable('trust proxy')\n\napp.enabled('trust proxy') //=> true\n
\n\n

Env

\n\n
app.get('env')\n
\n\n

Config

\n\n
app.configure('production', function() {\n  app.set...\n})\n
\n\n

Wares

\n\n
app.use(express.static(__dirname + '/public'))\napp.use(express.logger())\n
\n\n

Helpers

\n\n
app.locals({\n  title: \"MyApp\",\n})\n
\n\n

Request & response

\n\n

Request

\n\n
// GET  /user/tj\nreq.path         //=> \"/user/tj\"\nreq.url          //=> \"/user/tj\"\nreq.xhr          //=> true|false\nreq.method       //=> \"GET\"\nreq.params\nreq.params.name  //=> \"tj\"\nreq.params[0]\n
\n\n
// GET /search?q=tobi+ferret\nreq.query.q // => \"tobi ferret\"\n
\n\n
req.cookies\n
\n\n
req.accepted\n// [ { value: 'application/json', quality: 1, type: 'application', subtype: 'json' },\n//   { value: 'text/html', quality: 0.5, type: 'text',subtype: 'html' } ]\n
\n\n
req.is('html')\nreq.is('text/html')\n
\n\n
req.headers\nreq.headers['host']\nreq.headers['user-agent']\nreq.headers['accept-encoding']\nreq.headers['accept-language']\n
\n\n

Response

\n\n
res.redirect('/')\nres.redirect(301, '/')\n
\n\n
res.set('Content-Type', 'text/html')\n
\n\n
res.send('hi')\nres.send(200, 'hi')\n
\n\n
res.json({ a: 2 })\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "exunit", "title": "ExUnit", "url": "/exunit", "category": "Elixir", "keywords": null, "content_html": "

Test cases

\n\n
defmodule MyTest do\n  use ExUnit.Case\n  use ExUnit.Case, async: true  # for async\n\n  test \"the truth\" do\n    assert 1 + 1 == 2\n  end\nend\n
\n\n

Capture IO

\n\n
import ExUnit.CaptureIO\n\ntest \"capture io\" do\n  result = capture_io(fn ->\n    IO.puts \"sup\"\n  end)\n\n  assert result == \"sup\\n\"\nend\n
\n\n

Capture logs

\n\n
config :ex_unit, capture_logs: true\n
\n\n

Async

\n\n
defmodule AssertionTest do\n  # run concurrently with other test cases\n  use ExUnit.Case, async: true\nend\n
\n\n

Assertions

\n\n
assert x == y\nrefute x == y\n\nassert_raise ArithmeticError, fn ->\n  1 + \"test\"\nend\n\nassert_raise ArithmeticError, \"message\", fn -> ...\nassert_raise ArithmeticError, ~r/message/, fn -> ...\n\nflunk \"This should've been an error\"\n
\n\n

See: Assertions

\n\n

Setup

\n\n

Pattern matching

\n\n
setup do\n  {:ok, name: \"John\"}\nend\n
\n\n
test \"it works\", %{name: name} do\n  assert name == \"John\"\nend\n
\n\n

Setup

\n\n
defp my_hook(_context) do\n  # Invoked in every block in \"a block\"\n  {:ok, name: \"John\", age: 54}\nend\n\ndescribe \"a block\" do\n  setup [:my_hook]\n  \n  test \"John's age\", context do\n    assert context[:name] == \"John\"\n    assert context[:age] == 54\n  end\nend\n
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-11-19" },{ "id": "factory_bot", "title": "Factory Bot", "url": "/factory_bot", "category": "Ruby libraries", "keywords": ["FactoryBot.define do","factory :user","first_name 'John'","sequence(:username) { |n| \"user#{n}\" }"], "content_html": "

Factories

\n\n

Introduction

\n\n

Factory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl. For older versions, use FactoryGirl instead of FactoryBot.

\n\n\n\n

Defining factories

\n\n
FactoryBot.define do\n  factory :user do\n    first_name { 'John' }\n    last_name  { 'Doe' }\n    birthdate  { 21.years.ago }\n    admin { false }\n\n    sequence(:username) { |n| \"user#{n}\" }\n  end\nend\n
\n\n

See: Defining factories

\n\n

Extra options

\n\n

Custom class names

\n\n
factory :user, class: 'User' do\n  ···\nend\n
\n\n

Aliases

\n\n
factory :user, aliases: [:author] do\n  ···\nend\n
\n\n

Using

\n\n

Build a model

\n\n
FactoryBot.build(:user)\n
\n\n

Other ways

\n\n
build(:user)           # → model (not saved)\ncreate(:user)          # → model (saved)\nattributes_for(:user)  # → hash\nbuild_stubbed(:user)   # stubbed out attributes\n
\n\n

With options

\n\n
build(:user, name: 'John')\n
\n\n

Lists

\n\n
create_list(:user, 3)\nbuild_list(:user, 3)\n
\n\n

Associations

\n\n

Defining

\n\n
factory :post do\n  association :author, factory: :user\n  association :author, factory: [:user, :admin]\nend\n
\n\n

or

\n\n
factory :post do\n  author  # assumes there's a factory :author\nend\n
\n\n

After-create hooks

\n\n
factory :post do\n  after :create do |post|\n    create :theme, post: post             # has_one\n    create_list :comment, 3, post: post   # has_many\n  end\nend\n
\n\n

Other features

\n\n

Traits

\n\n
factory :user do\n  trait :admin do\n    admin { true }\n  end\nend\n
\n\n
create :user, :admin\n
\n\n

Traits allow you to group attributes together.\nSee: Traits

\n\n

Nested factories

\n\n
factory :user do\n  first_name { 'John' }\n\n  factory :sample_user do\n    first_name { FFaker::Name.first_name }\n  end\nend\n
\n\n
create :sample_user\n
\n\n

See: Inheritance

\n\n

Sub-factories

\n\n
factory :user do\n  ···\nend\n
\n\n
factory :sample_user, parent: :user do\n  first_name { FFaker::Name.first_name }\nend\n
\n\n
create :sample_user\n
\n\n

Works the same as nested factories.

\n\n

Options (transients)

\n\n
factory :user do\n  transient do\n    upcased { true }\n  end\n\n  after :create do |user, options|\n    user.name.upcase! if options.upcased\n  end\nend\n
\n\n
create(user, upcased: true)\n
\n\n

Transient attributes will not get passed to the model, but will be available in after-create hooks.\nSee: Transient attributes

\n\n

Paths

\n\n\n\n

Place your factories in these locations.

\n\n

See also

\n\n", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2020-07-06" },{ "id": "fastify", "title": "Fastify", "url": "/fastify", "category": "JavaScript libraries", "keywords": null, "content_html": "

Getting started

\n\n

Introduction

\n\n

Fastify lets you create HTTP servers in Node.js with good performance. This guide targets fastify v0.28.x.

\n\n\n\n

Hello world

\n\n
const fastify = require('fastify')()\n\nfastify.get('/', (req, reply) => {\n  reply.send({ hello: 'world' })\n})\n\nfastify.listen(3000, err => {\n  if (err) throw err\n  const port = fastify.server.address().port\n  console.log(`server listening on ${port}`)\n})\n
\n\n

Plugins

\n\n

app.js

\n\n
fastify.register(require('./route'))\n
\n\n

route.js

\n\n
function (fastify, opts, next) {\n  fastify.get('/', (req, reply) => {\n    reply.send({ hello: 'world' })\n  })\n\n  next()\n})\n
\n\n

Compose your app functionality into plugins. Plugins are simply functions.

\n\n

See: Plugins

\n\n

Routes

\n\n

Writing routes

\n\n
fastify.route({\n  method: 'GET',\n  url: '/',\n  schema: { ··· },\n  handler: (req, reply) => { ··· }\n  beforeHandler: (req, reply, done) => { ··· }\n})\n
\n\n

Shorthand declarations

\n\n
fastify.get(path, [options], handler)\nfastify.head(···)\nfastify.post(···)\nfastify.put(···)\nfastify.delete(···)\nfastify.options(···)\nfastify.patch(···)\n
\n\n

Async/await

\n\n
fastify.get('/', options, async (req, reply) => {\n  return data\n  // or\n  reply.send(data)\n})\n
\n\n

When using async functions, you can either return data or use reply.send.

\n\n

Request/reply

\n\n

Request

\n\n
request.query\nrequest.body\nrequest.params\nrequest.headers\nrequest.req  // Node.js core\nrequest.log.info('hello')\n
\n\n

See: Request

\n\n

Reply

\n\n

Response headers

\n\n
reply.code(404)\nreply.header('Content-Type', 'text/html')\nreply.type('text/html')\n
\n\n

Redirects

\n\n
reply.redirect('/foo')\nreply.redirect(302, '/foo')\n
\n\n

Sending

\n\n
reply.send(payload)\nreply.sent // → true|false\n
\n\n

See: Reply

\n\n

JSON schema

\n\n

Define a JSON schema

\n\n
const schema = {\n  querystring: {\n    name: { type: 'string' },\n    excitement: { type: 'integer' }\n  },\n  response: {\n    200: {\n      type: 'object',\n      properties: {\n        hello: { type: 'string' }\n      }\n    }\n  }\n}\n
\n\n

Pass it to the route

\n\n
fastify.get('/', { schema }, (req, reply) => {\n  ···\n})\n
\n\n

or (same as above)

\n\n
fastify.route({\n  method: 'GET',\n  url: '/',\n  schema,\n  handler: (req, reply) => { ··· }\n})\n
\n\n

By defining a JSON schema, you get validation and improved performance.

\n\n

See: Validation and serialization

\n\n

Plugins

\n\n

With function

\n\n
fastify.register(\n  require('./route'),\n  err => { if (err) throw err }\n)\n
\n\n

route.js

\n\n
module.exports = (fastify, options, next) => {\n  fastify.get('/', ···)\n  next()\n}\n
\n\n

See: Register

\n\n

Multiple

\n\n
fastify.register([\n  require('./another-route'),\n  require('./yet-another-route')\n], opts, (err) => {\n  if (err) throw err\n})\n
\n\n

You can pass arrays to register().

\n\n

Register with prefix

\n\n
fastify.register(\n  require('./route'),\n  { prefix: '/v1' }\n)\n
\n\n

This prefixes all routes in that module.

\n\n

Helmet

\n\n
const helmet = require('fastify-helmet')\n\nfastify.register(helmet)\n
\n\n

See: fastify-helmet

\n\n

fastify-plugin

\n\n
const fp = require('fastify-plugin')\n\nmodule.exports = fp((fastify, opts, next) => {\n  // your plugin code\n  fastify.decorate('utility', () => {})\n\n  next()\n}, '0.x')\n
\n\n

Allows you to limit Fastify versions via semver, and allows you not make a new Fastify scope.

\n\n

See: fastify-plugin

\n\n

Decorators

\n\n

Middleware

\n\n

Middleware

\n\n
fastify.use(require('cors')())\nfastify.use(require('dns-prefetch-control')())\nfastify.use(require('frameguard')())\nfastify.use(require('hide-powered-by')())\nfastify.use(require('hsts')())\nfastify.use(require('ienoopen')())\nfastify.use(require('x-xss-protection')())\n
\n\n

Compatible with Express and Restify middlewares. (Don’t use these middleware, these are covered by fastify-helmet.)

\n\n

See: Middlewares

\n\n

Template rendering

\n\n

point-of-view

\n\n
const fastify = require('fastify')()\n\nfastify.register(require('point-of-view'), {\n  engine: {\n    ejs: require('ejs')\n  }\n})\n
\n\n
fastify.get('/', (req, reply) => {\n  reply.view('/templates/index.ejs', { text: 'text' })\n})\n
\n\n

Support ejs, pug, handlebars and marko.

\n\n

See: point-of-view

\n\n

Options

\n\n
fastify.register(require('point-of-view'), {\n  engine: {\n    ejs: require('ejs')\n  },\n  templates: '/templates',\n  options: {}\n})\n
\n\n

templates lets you update the templates folder. options are options passed onto the template engines.

", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-23" },{ "id": "ffaker", "title": "FFaker", "url": "/ffaker", "category": "Ruby libraries", "keywords": null, "content_html": "

FFaker

\n\n

Installing

\n\n
# gem install ffaker\nrequire 'ffaker'\n
\n\n

Faker::Address

\n\n
Faker::Address.city                     #=> \"Autumnside\"\n                                        #=> \"South Brielleberg\"\n                                        #=> \"West Alvera\"\n
\n\n
Faker::Address.street_name              #=> \"Greyson Rapid\"\n                                        #=> \"Hoppe Grove\"\n                                        #=> \"Reichert Lights\"\n
\n\n
Faker::Address.street_address           #=> \"98786 Neal Motorway\"\n                                        #=> \"6619 Yvonne Dale\"\n                                        #=> \"6143 Bailey Plaza\"\n
\n\n
Faker::Address.secondary_address        #=> \"Suite 560\"\n                                        #=> \"Apt. 332\"\n                                        #=> \"Apt. 411\"\n
\n\n

Faker::Company

\n\n
Faker::Company.name                     #=> \"Pouros-Ondricka\"\n                                        #=> \"Ward Group\"\n                                        #=> \"Walter-Romaguera\"\n
\n\n
Faker::Company.suffix                   #=> \"and Sons\"\n                                        #=> \"LLC\"\n                                        #=> \"and Sons\"\n
\n\n
Faker::Company.catch_phrase             #=> \"Versatile mobile help-desk\"\n                                        #=> \"Extended fresh-thinking utilisation\"\n                                        #=> \"Reactive coherent flexibility\"\n
\n\n
Faker::Company.bs                       #=> \"extend one-to-one convergence\"\n                                        #=> \"architect 24/7 interfaces\"\n                                        #=> \"revolutionize viral vortals\"\n
\n\n
Faker::Company.position                 #=> \"General Corporate President\"\n                                        #=> \"Executive Department Consultant\"\n                                        #=> \"Associate Director\"\n
\n\n

Faker::Education

\n\n
Faker::Education.school                 #=> \"Larkwood Institution\"\n                                        #=> \"Whiteshire School\"\n                                        #=> \"California International College\"\n
\n\n
Faker::Education.degree                 #=> \"Bachelor of Science in Political Administration\"\n                                        #=> \"Doctor of Medicine in Marketing Economics\"\n                                        #=> \"Bachelor of Music in Marketing Development\"\n
\n\n
Faker::Education.degree_short           #=> \"MD in Industrial Arts\"\n                                        #=> \"DPhil in Social Management\"\n                                        #=> \"AB in Political Science\"\n
\n\n
Faker::Education.major                  #=> \"Financial Philosophy\"\n                                        #=> \"Social Arts\"\n                                        #=> \"Business Accountancy\"\n
\n\n
Faker::Education.school_name            #=> \"Larkfield\"\n                                        #=> \"Northshire\"\n                                        #=> \"Lakepoint\"\n
\n\n

Faker::Geolocation

\n\n
Faker::Geolocation.lat                  #=> 40.89505\n                                        #=> 41.77117\n                                        #=> 41.022921\n
\n\n
Faker::Geolocation.lng                  #=> -115.120716573\n                                        #=> -118.427610513239\n                                        #=> -72.204989\n
\n\n

Faker::Internet

\n\n
Faker::Internet.email                   #=> \"dayna@auer.name\"\n                                        #=> \"joy@nienowbradtke.info\"\n                                        #=> \"bernhard@wyman.ca\"\n
\n\n
Faker::Internet.user_name               #=> \"emory\"\n                                        #=> \"janelle_schamberger\"\n                                        #=> \"brigitte.dooley\"\n
\n\n
Faker::Internet.domain_name             #=> \"langworth.biz\"\n                                        #=> \"corkery.info\"\n                                        #=> \"schroeder.uk\"\n
\n\n
Faker::Internet.disposable_email        #=> \"barrett_schroeder@spamherelots.com\"\n                                        #=> \"nicholaus@suremail.info\"\n                                        #=> \"gladys@safetymail.info\"\n
\n\n
Faker::Internet.free_email              #=> \"lemuel@yahoo.com\"\n                                        #=> \"nickolas.gulgowski@gmail.com\"\n                                        #=> \"isaac_ankunding@gmail.com\"\n
\n\n
Faker::Internet.domain_word             #=> \"purdykutch\"\n                                        #=> \"sauer\"\n                                        #=> \"trantowmaggio\"\n
\n\n
Faker::Internet.domain_suffix           #=> \"us\"\n                                        #=> \"info\"\n                                        #=> \"biz\"\n
\n\n

Faker::Job

\n\n
Faker::Job.title                        #=> \"Future Data Assistant\"\n                                        #=> \"Product Division Technician\"\n                                        #=> \"Product Research Developer\"\n
\n\n

Faker::Lorem

\n\n
Faker::Lorem.word                       #=> \"sint\"\n                                        #=> \"sit\"\n                                        #=> \"omnis\"\n
\n\n
Faker::Lorem.sentence                   #=> \"Expedita et aspernatur eum sit ipsam culpa.\"\n                                        #=> \"Rem sunt voluptatem laborum dolores.\"\n                                        #=> \"Ad explicabo atque culpa.\"\n
\n\n
Faker::Lorem.paragraph                  #=> \"Quidem deserunt qui atque labore sunt quis laborum. Et iste\n                                        #    laudantium nobis adipisci delectus. Quod vero repudiandae m\n                                        #    agni repellat totam. Id ullam a aperiam et laboriosam. Volup\n                                        #    tas aut perspiciatis o...\"\n                                        #=> \"Dolor et quae quisquam placeat. Accusantium quidem totam no\n                                        #    n et deleniti accusamus hic. Iure quidem inventore molestiae\n                                        #    harum magni dolor. Deleniti ex a voluptas nihil temporibus.\n                                        #    \"\n                                        #=> \"Fugiat sapiente vero voluptatum natus assumenda quam beatae\n                                        #    in. Nemo velit incidunt dolor perspiciatis. Ipsum minima oc\n                                        #    caecati est laudantium ducimus libero. Et fugit et adipisci\n                                        #    molestias. Cupiditate ...\"\n
\n\n
Faker::Lorem.words(4)                   #=> [\"repellat\", \"quos\", \"amet\", \"voluptatem\"]\n                                        #=> [\"porro\", \"molestias\", \"ut\", \"qui\"]\n                                        #=> [\"blanditiis\", \"soluta\", \"enim\", \"fugit\"]\n
\n\n
Faker::Lorem.sentence(5)                #=> \"Laborum sint voluptate voluptatem rem doloremque et incidun\n                                        #    t itaque.\"\n                                        #=> \"Autem atque eum laborum alias perspiciatis debitis suscipit\n                                        #    deserunt sint.\"\n                                        #=> \"Quaerat nam consectetur eum dolor deleniti tempore doloremq\n                                        #    ue et aspernatur.\"\n
\n\n
Faker::Lorem.sentences(3)               #=> [\"Culpa debitis architecto est.\", \"Quo et voluptatem distinc\n                                        #    tio repellendus qui cupiditate.\", \"Quo repellendus ut eius.\"\n                                        #    ]\n                                        #=> [\"Quos nihil dolorem quidem maxime.\", \"Expedita ab veniam do\n                                        #    lorum at et placeat iure.\", \"In perspiciatis cupiditate amet\n                                        #    non saepe consequatur molestias minus.\"]\n                                        #=> [\"Quasi velit et voluptas est.\", \"Dolores ut dolor aut repel\n                                        #    lat fuga minima sed quia.\", \"Eum id minus atque ex modi.\"]\n
\n\n
Faker::Lorem.paragraphs(3)              #=> [\"Iusto mollitia sequi nam perspiciatis fuga aut. Modi moles\n                                        #    tiae consectetur architecto et dolorem aut perferendis. Cumq\n                                        #    ue rerum aliquam sapiente. Dolorum quo reiciendis nemo vero.\n                                        #    Quo earum explicabo pariatur.\", \"Possimus omnis accusamus f\n                                        #    uga. Harum sint facere sed dolor itaque quia. Ullam optio at\n                                        #    que vel nihil facilis quidem accusantium sint.\", \"Itaque per\n                                        #    ferendis saepe pariatur maxime expedita laborum qui. Ea nemo\n                                        #    dolor aut. In sed sit minus itaque sit.\"]\n                                        #=> [\"Ducimus non quo qui doloremque aperiam aspernatur. Consequ\n                                        #    atur id qui sit occaecati. Incidunt tempora quia et. Esse vo\n                                        #    luptatem debitis similique ab totam sit. Illo neque vel face\n                                        #    re maxime voluptatum non voluptatem.\", \"Aut eveniet consequa\n                                        #    tur laudantium veniam qui dolores. Provident pariatur perspi\n                                        #    ciatis id. Eum iste id quasi. Esse nihil quis rerum laudanti\n                                        #    um aliquam molestiae eum tempora.\", \"Quia porro sint numquam\n                                        #    qui. Ut sint reiciendis quis pariatur veniam nesciunt optio\n                                        #    . Officia unde fugit distinctio dolorem voluptatem incidunt.\n                                        #    Ex omnis sit et non aut.\"]\n                                        #=> [\"Dicta consequatur sapiente saepe fugiat ut. Necessitatibus\n                                        #    enim explicabo qui fugiat occaecati expedita quis. Quo iust\n                                        #    o magnam facere nihil earum.\", \"In deleniti explicabo veniam\n                                        #    dolorem temporibus enim. Delectus exercitationem ipsum dolo\n                                        #    r modi. Aut quia voluptas velit sint aperiam sed eveniet.\",\n                                        #    \"Quo doloribus explicabo ut magnam quasi. Voluptatem debitis\n                                        #    quaerat aperiam. Accusantium quis voluptatem dolorem.\"]\n
\n\n

Faker::HipsterIpsum

\n\n
Faker::HipsterIpsum.paragraph           #=> \"Wayfarers mustache thundercats pitchfork messenger bag high\n                                        #    life. Beard messenger bag wayfarers squid vinyl letterpress\n                                        #    party iphone jean shorts. Lomo irony before they sold out e\n                                        #    thical wayfarers scene...\"\n                                        #=> \"Tofu stumptown cliche sartorial vhs letterpress keffiyeh wi\n                                        #    lliamsburg. Whatever jean shorts williamsburg lomo salvia fo\n                                        #    od truck 8-bit. Cosby sweater portland artisan wayfarers vhs\n                                        #    photo booth.\"\n                                        #=> \"Skateboard fanny pack wes anderson sartorial cred gluten-fr\n                                        #    ee vinyl marfa locavore. Messenger bag master cleanse mlkshk\n                                        #    vegan thundercats beard wes anderson brunch. Helvetica mess\n                                        #    enger bag lo-fi four l...\"\n
\n\n

Faker::HTMLIpsum

\n\n
Faker::HTMLIpsum.body                   #=> \"<h1>Exercitationem et</h1><table><thead><tr><th>Eligendi</t\n                                        #    h><th>Vel</th><th>Sed</th><th>At</th></tr></thead><tbody><tr\n                                        #    ><...\"\n                                        #=> \"<h1>Excepturi sequi</h1><table><thead><tr><th>Quam</th><th>\n                                        #    Eius</th><th>Quibusdam</th><th>Totam</th></tr></thead><tbody\n                                        #    ><tr>...\"\n                                        #=> \"<h1>Iusto voluptatem</h1><p>Laborum velit ducimus eius. Mol\n                                        #    estiae id vel ipsam a accusantium et ut. Sunt et fugiat qui\n                                        #    sint ab quia. Eum ut molestiae cumque molestiae error volupt\n                                        #    ates. Ipsum molestiae ...\"\n
\n\n
Faker::HTMLIpsum.table                  #=> \"<table><thead><tr><th>Voluptatem</th><th>Porro</th><th>Tene\n                                        #    tur</th><th>Facilis</th></tr></thead><tbody><tr><td>Numquam<\n                                        #    /t...\"\n                                        #=> \"<table><thead><tr><th>Impedit</th><th>Voluptatem</th><th>Qu\n                                        #    i</th><th>Est</th></tr></thead><tbody><tr><td>Nihil</td>...\"\n                                        #=> \"<table><thead><tr><th>Iste</th><th>Et</th><th>Sequi</th><th\n                                        #    >Et</th></tr></thead><tbody><tr><td>Blanditiis</td>...\"\n
\n\n
Faker::HTMLIpsum.fancy_string           #=> \"<a href=\\\"#distinctio\\\" title=\\\"Tenetur explicabo\\\">Velit e\n                                        #    st</a> <code>aperiam reiciendis</code> Consectetur aut hic e\n                                        #    um quisquam. Dolore aut rerum dolor accusantium ab repellend\n                                        #    us magni. Deserunt optio o...\"\n                                        #=> \"Et vel similique ullam accusantium laboriosam. Sit ut ea to\n                                        #    tam. Iusto praesentium ut molestiae. Voluptatem laudantium a\n                                        #    ut qui adipisci. Est saepe repellendus qui blanditiis volupt\n                                        #    ates sed odit ullam. <...\"\n                                        #=> \"Neque et omnis ipsam ad culpa maiores inventore. Laborum cu\n                                        #    m est fugit libero repellendus vero. Modi pariatur sunt tene\n                                        #    tur soluta inventore ratione. Iste consequuntur quia omnis n\n                                        #    umquam excepturi quod ...\"\n
\n\n

Faker::Name

\n\n
Faker::Name.name                        #=> \"Trevion Herman V\"\n                                        #=> \"Aracely Balistreri\"\n                                        #=> \"Daphnee Terry Sr.\"\n
\n\n
Faker::Name.first_name                  #=> \"Aliza\"\n                                        #=> \"Joseph\"\n                                        #=> \"Orland\"\n
\n\n
Faker::Name.last_name                   #=> \"Hand\"\n                                        #=> \"Macejkovic\"\n                                        #=> \"Heller\"\n
\n\n
Faker::Name.prefix                      #=> \"Dr.\"\n                                        #=> \"Ms.\"\n                                        #=> \"Mr.\"\n
\n\n
Faker::Name.suffix                      #=> \"I\"\n                                        #=> \"III\"\n                                        #=> \"DDS\"\n
\n\n

Faker::PhoneNumber

\n\n
Faker::PhoneNumber.phone_number         #=> \"335-364-4549 x430\"\n                                        #=> \"040-278-4021 x753\"\n                                        #=> \"420.645.4382\"\n
\n\n
Faker::PhoneNumber.short_phone_number   #=> \"473-412-3192\"\n                                        #=> \"353-084-1297\"\n                                        #=> \"080-546-2356\"\n
\n\n

Faker::Product

\n\n
Faker::Product.brand                    #=> \"Trouffeforge\"\n                                        #=> \"VIG\"\n                                        #=> \"NDZ\"\n
\n\n
Faker::Product.product_name             #=> \"Air HD Viewer\"\n                                        #=> \"HD Kit\"\n                                        #=> \"Air HD Bridge\"\n
\n\n
Faker::Product.product                  #=> \"Amnix Air HD Tuner\"\n                                        #=> \"Panapod Audible Filter\"\n                                        #=> \"Phuffe Disc Receiver\"\n
\n\n
Faker::Product.model                    #=> \"I-422\"\n                                        #=> \"J89\"\n                                        #=> \"L6\"\n
\n\n

Faker::NameCN

\n\n
Faker::NameCN.name                      #=> \"姵书虞\"\n                                        #=> \"修男嵇\"\n                                        #=> \"瑜人军\"\n
\n\n
Faker::NameCN.last_first                #=> \"向坚舜\"\n                                        #=> \"疏骏哲\"\n                                        #=> \"秘合雪\"\n
\n\n
Faker::NameCN.first_name                #=> \"佑淑\"\n                                        #=> \"燕谦\"\n                                        #=> \"重生\"\n
\n\n
Faker::NameCN.last_name                 #=> \"释\"\n                                        #=> \"巩\"\n                                        #=> \"麻\"\n
\n\n

Faker::NameDE

\n\n
Faker::NameDE.name                      #=> \"Noelle Schuster\"\n                                        #=> \"Bendix Schmid\"\n                                        #=> \"Azra Neumann\"\n
\n\n
Faker::NameDE.first_name                #=> \"Victoria\"\n                                        #=> \"Lotta\"\n                                        #=> \"Mads\"\n
\n\n
Faker::NameDE.last_name                 #=> \"Martin\"\n                                        #=> \"Klein\"\n                                        #=> \"Walter\"\n
\n\n
Faker::NameDE.prefix                    #=> \"Frau\"\n                                        #=> \"Prof.\"\n                                        #=> \"Prof.\"\n
\n\n

Faker::NameJA

\n\n
Faker::NameJA.name                      #=> \"飛鳥田部\"\n                                        #=> \"未杉浦\"\n                                        #=> \"功本間\"\n
\n\n
Faker::NameJA.last_first                #=> \"青木杏子\"\n                                        #=> \"棚原大貴\"\n                                        #=> \"知名翔\"\n
\n\n
Faker::NameJA.first_name                #=> \"巴\"\n                                        #=> \"浩子\"\n                                        #=> \"沙耶\"\n
\n\n
Faker::NameJA.last_name                 #=> \"小栗\"\n                                        #=> \"高江洲\"\n                                        #=> \"友寄\"\n
\n\n

Faker::NameRU

\n\n
Faker::NameRU.name                      #=> \"Стелла Карнилина\"\n                                        #=> \"Евгения Мазовская\"\n                                        #=> \"Кузьма Ваиренко\"\n
\n\n
Faker::NameRU.last_name                 #=> \"Манишева\"\n                                        #=> \"Тюлева\"\n                                        #=> \"Понченко\"\n
\n\n
Faker::NameRU.first_name                #=> \"Артур\"\n                                        #=> \"Руслана\"\n                                        #=> \"Зинаида\"\n
\n\n
Faker::NameRU.patronymic                #=> \"Мечеславович\"\n                                        #=> \"Ионович\"\n                                        #=> \"Исаевич\"\n
\n\n
Faker::NameRU.name(:male)               #=> \"Слежиков Роман Всеволодович\"\n                                        #=> \"Осип Мугрузин\"\n                                        #=> \"Джиджаев Гавриил Леванович\"\n
\n\n
Faker::NameRU.name(:female)             #=> \"Зиядтдинова Полина Людвиговна\"\n                                        #=> \"Андреева Тереза Арсеновна\"\n                                        #=> \"Дарина Минхазова\"\n
\n\n

Faker::NameSN

\n\n
Faker::NameSN.name_sn                   #=> \"mame Djaly Mbodj\"\n                                        #=> \"Hatab Samy\"\n                                        #=> \"Niouma Dramé\"\n
\n\n
Faker::NameSN.name_male                 #=> \"serigne Yakou Diagne\"\n                                        #=> \"serigne Sécouba Diagne\"\n                                        #=> \"Sihalébé Badji\"\n
\n\n
Faker::NameSN.name_female               #=> \"Thiomba Niang\"\n                                        #=> \"adjaratou Kiné Panduppy\"\n                                        #=> \"Nini Gakou\"\n
\n\n
Faker::NameSN.first_name_male           #=> \"Khoudia\"\n                                        #=> \"Sanokho\"\n                                        #=> \"Diomaye\"\n
\n\n
Faker::NameSN.first_name_female         #=> \"Assa\"\n                                        #=> \"Sahaba\"\n                                        #=> \"Manthita\"\n
\n\n
Faker::NameSN.prefix_male               #=> \"eladji\"\n                                        #=> \"eladji\"\n                                        #=> \"serigne\"\n
\n\n
Faker::NameSN.prefix_female             #=> \"adjaratou\"\n                                        #=> \"adja\"\n                                        #=> \"adja\"\n
\n\n

Faker::PhoneNumberAU

\n\n
Faker::PhoneNumberAU.phone_number       #=> \"0495 539 191\"\n                                        #=> \"(05) 6838 2406\"\n                                        #=> \"0496 013 652\"\n
\n\n

Faker::PhoneNumberSN

\n\n
Faker::PhoneNumberSN.phone_number       #=> \"77-356-93-09\"\n                                        #=> \"33-891-67-75\"\n                                        #=> \"33-886-02-02\"\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-12" },{ "id": "ffmpeg", "title": "ffmpeg", "url": "/ffmpeg", "category": "CLI", "keywords": null, "content_html": "

Common switches

\n\n
-codecs          # list codecs\n-c:v             # video codec (-vcodec) - 'copy' to copy stream\n-c:a             # audio codec (-acodec)\n
\n\n
-fs SIZE         # limit file size (bytes)\n
\n\n

Bitrate

\n\n
-b:v 1M          # video bitrate (1M = 1Mbit/s)\n-b:a 1M          # audio bitrate\n
\n\n

Video

\n\n
-aspect RATIO    # aspect ratio (4:3, 16:9, or 1.25)\n-r RATE          # frame rate per sec\n-s WIDTHxHEIGHT  # frame size\n-vn              # no video\n
\n\n

Audio

\n\n
-aq QUALITY      # audio quality (codec-specific)\n-ar 44100        # audio sample rate (hz)\n-ac 1            # audio channels (1=mono, 2=stereo)\n-an              # no audio\n-vol N           # volume (256=normal)\n
\n\n

Example

\n\n

Ringtone conversion using ffmpeg

\n\n
ffmpeg -i foo.mp3 -ac 1 -ab 128000 -f mp4 -acodec libfaac -y target.m4r\n
\n\n

To web

\n\n
# no audio\nffmpeg -i input.mov -vcodec h264   -an -strict -2 output.mp4\nffmpeg -i input.mov -vcodec libvpx -an output.webm\n
\n\n
ffmpeg -i input.mov -vcodec h264 -acodec aac -strict -2 output.mp4\nffmpeg -i input.mov -vcodec libvpx -acodec libvorbis output.webm\n
\n\n
<video width=\"320\" height=\"240\" controls>\n  <source src=\"movie.mp4\" type='video/mp4'></source>\n  <source src=\"movie.webm\" type='video/ogg'></source>\n</video>\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "figlet", "title": "Figlet", "url": "/figlet", "category": "Others", "keywords": null, "content_html": "

Usage

\n\n
echo \"Hamburger\" | figlet -f cybermedium\n
\n\n
_  _ ____ _  _ ___  _  _ ____ ____ ____ ____ \n|__| |__| |\\/| |__] |  | |__/ | __ |___ |__/ \n|  | |  | |  | |__] |__| |  \\ |__] |___ |  \\ \n
\n\n

Run figlet with -f <font> to use a font.

\n\n

Toilet fonts

\n\n
echo \"Hello\" | \\\n  figlet -f smmono12 -d /usr/local/share/figlet\n
\n\n

Figlet comes with support for Toilet fonts, which are in {share}/figlet. This is not the default font dir, so you’ll have to use -d <path> to access it.

\n\n

Rico’s favorites

\n\n

wideterm

\n\n
Hamburger\n
\n\n

stampatello

\n\n
,-_/,.           .                       \n' |_|/ ,-. ,-,-. |-. . . ,-. ,-. ,-. ,-. \n /| |  ,-| | | | | | | | |   | | |-' |   \n `' `' `-^ ' ' ' ^-' `-^ '   `-| `-' '   \n                              ,|         \n                              `'         \n
\n\n

cybermedium

\n\n
_  _ ____ _  _ ___  _  _ ____ ____ ____ ____ \n|__| |__| |\\/| |__] |  | |__/ | __ |___ |__/ \n|  | |  | |  | |__] |__| |  \\ |__] |___ |  \\ \n
\n\n

cyberlarge

\n\n
 _     _ _______ _______ ______  _     _  ______  ______ _______  ______\n |_____| |_____| |  |  | |_____] |     | |_____/ |  ____ |______ |_____/\n |     | |     | |  |  | |_____] |_____| |    \\_ |_____| |______ |    \\_\n
\n\n

thin

\n\n
|   |          |                             \n|---|,---.,-.-.|---..   .,---.,---.,---.,---.\n|   |,---|| | ||   ||   ||    |   ||---'|    \n`   '`---^` ' '`---'`---'`    `---|`---'`    \n                              `---'          \n
\n\n

smbraille

\n\n
 ⣇⣸ ⢀⣀ ⣀⣀  ⣇⡀ ⡀⢀ ⡀⣀ ⢀⡀ ⢀⡀ ⡀⣀\n ⠇⠸ ⠣⠼ ⠇⠇⠇ ⠧⠜ ⠣⠼ ⠏  ⣑⡺ ⠣⠭ ⠏ \n
\n\n

rectangles

\n\n
 _____           _                       \n|  |  |___ _____| |_ _ _ ___ ___ ___ ___ \n|     | .'|     | . | | |  _| . | -_|  _|\n|__|__|__,|_|_|_|___|___|_| |_  |___|_|  \n                            |___|        \n
\n\n

bell

\n\n
 __  __                  _                                     \n |   |    ___  , _ , _   \\ ___  ,   . .___    ___.   ___  .___ \n |___|   /   ` |' `|' `. |/   \\ |   | /   \\ .'   ` .'   ` /   \\\n |   |  |    | |   |   | |    ` |   | |   ' |    | |----' |   '\n /   /  `.__/| /   '   / `___,' `._/| /      `---| `.___, /    \n                                             \\___/             \n
\n\n

Figlet fonts

\n\n

3-d

\n\n
 **      **                       **                                           \n/**     /**                      /**                      *****                \n/**     /**  ******   ********** /**      **   ** ****** **///**  *****  ******\n/********** //////** //**//**//**/****** /**  /**//**//*/**  /** **///**//**//*\n/**//////**  *******  /** /** /**/**///**/**  /** /** / //******/******* /** / \n/**     /** **////**  /** /** /**/**  /**/**  /** /**    /////**/**////  /**   \n/**     /**//******** *** /** /**/****** //******/***     ***** //******/***   \n//      //  //////// ///  //  // /////    ////// ///     /////   ////// ///    \n
\n\n

3x5

\n\n
# #         #                       \n# #  ## ### ### # # ### ### ### ### \n### # # ### # # # # #   # # ##  #   \n# # ### # # ### ### #    ## ### #   \n# #                     ###         \n
\n\n

5lineoblique

\n\n
    //    / /                                                                        \n   //___ / /  ___      _   __     / __               __      ___      ___      __    \n  / ___   / //   ) ) // ) )  ) ) //   ) ) //   / / //  ) ) //   ) ) //___) ) //  ) ) \n //    / / //   / / // / /  / / //   / / //   / / //      ((___/ / //       //       \n//    / / ((___( ( // / /  / / ((___/ / ((___( ( //        //__   ((____   //        \n
\n\n

acrobatic

\n\n
  o         o                                  o                                                                      \n <|>       <|>                                <|>                                                                     \n < >       < >                                / >                                                                     \n  |         |      o__ __o/  \\o__ __o__ __o   \\o__ __o      o       o   \\o__ __o     o__ __o/    o__  __o   \\o__ __o  \n  o__/_ _\\__o     /v     |    |     |     |>   |     v\\    <|>     <|>   |     |>   /v     |    /v      |>   |     |> \n  |         |    />     / \\  / \\   / \\   / \\  / \\     <\\   < >     < >  / \\   < >  />     / \\  />      //   / \\   < > \n <o>       <o>   \\      \\o/  \\o/   \\o/   \\o/  \\o/      /    |       |   \\o/        \\      \\o/  \\o    o/     \\o/       \n  |         |     o      |    |     |     |    |      o     o       o    |          o      |    v\\  /v __o   |        \n / \\       / \\    <\\__  / \\  / \\   / \\   / \\  / \\  __/>     <\\__ __/>   / \\         <\\__  < >    <\\/> __/>  / \\       \n                                                                                           |                          \n                                                                                   o__     o                          \n                                                                                   <\\__ __/>                          \n
\n\n

alligator

\n\n
      :::    :::    :::      :::   :::  ::::::::: :::    ::::::::::::  :::::::: ::::::::::::::::::: \n     :+:    :+:  :+: :+:   :+:+: :+:+: :+:    :+::+:    :+::+:    :+::+:    :+::+:       :+:    :+: \n    +:+    +:+ +:+   +:+ +:+ +:+:+ +:++:+    +:++:+    +:++:+    +:++:+       +:+       +:+    +:+  \n   +#++:++#+++#++:++#++:+#+  +:+  +#++#++:++#+ +#+    +:++#++:++#: :#:       +#++:++#  +#++:++#:    \n  +#+    +#++#+     +#++#+       +#++#+    +#++#+    +#++#+    +#++#+   +#+#+#+       +#+    +#+    \n #+#    #+##+#     #+##+#       #+##+#    #+##+#    #+##+#    #+##+#    #+##+#       #+#    #+#     \n###    ######     ######       ############  ######## ###    ### ######## #############    ###      \n
\n\n

alligator2

\n\n
:::    :::    :::    ::::    :::: ::::::::: :::    ::::::::::::  :::::::: :::::::::::::::::::  \n:+:    :+:  :+: :+:  +:+:+: :+:+:+:+:    :+::+:    :+::+:    :+::+:    :+::+:       :+:    :+: \n+:+    +:+ +:+   +:+ +:+ +:+:+ +:++:+    +:++:+    +:++:+    +:++:+       +:+       +:+    +:+ \n+#++:++#+++#++:++#++:+#+  +:+  +#++#++:++#+ +#+    +:++#++:++#: :#:       +#++:++#  +#++:++#:  \n+#+    +#++#+     +#++#+       +#++#+    +#++#+    +#++#+    +#++#+   +#+#+#+       +#+    +#+ \n#+#    #+##+#     #+##+#       #+##+#    #+##+#    #+##+#    #+##+#    #+##+#       #+#    #+# \n###    ######     ######       ############  ######## ###    ### ######## #############    ### \n
\n\n

alphabet

\n\n
H  H           b                         \nH  H           b                         \nHHHH  aa mmmm  bbb  u  u rrr ggg eee rrr \nH  H a a m m m b  b u  u r   g g e e r   \nH  H aaa m m m bbb   uuu r   ggg ee  r   \n                               g         \n                             ggg         \n
\n\n

avatar

\n\n
 _     ____  _      ____  _     ____  _____ _____ ____ \n/ \\ /|/  _ \\/ \\__/|/  _ \\/ \\ /\\/  __\\/  __//  __//  __\\\n| |_||| / \\|| |\\/||| | //| | |||  \\/|| |  _|  \\  |  \\/|\n| | ||| |-||| |  ||| |_\\\\| \\_/||    /| |_//|  /_ |    /\n\\_/ \\|\\_/ \\|\\_/  \\|\\____/\\____/\\_/\\_\\\\____\\\\____\\\\_/\\_\\\n
\n\n

banner

\n\n
#     #                                                         \n#     #   ##   #    # #####  #    # #####   ####  ###### #####  \n#     #  #  #  ##  ## #    # #    # #    # #    # #      #    # \n####### #    # # ## # #####  #    # #    # #      #####  #    # \n#     # ###### #    # #    # #    # #####  #  ### #      #####  \n#     # #    # #    # #    # #    # #   #  #    # #      #   #  \n#     # #    # #    # #####   ####  #    #  ####  ###### #    # \n
\n\n

banner3-D

\n\n
'##::::'##::::'###::::'##::::'##:'########::'##::::'##:'########:::'######:::'########:'########::\n ##:::: ##:::'## ##::: ###::'###: ##.... ##: ##:::: ##: ##.... ##:'##... ##:: ##.....:: ##.... ##:\n ##:::: ##::'##:. ##:: ####'####: ##:::: ##: ##:::: ##: ##:::: ##: ##:::..::: ##::::::: ##:::: ##:\n #########:'##:::. ##: ## ### ##: ########:: ##:::: ##: ########:: ##::'####: ######::: ########::\n ##.... ##: #########: ##. #: ##: ##.... ##: ##:::: ##: ##.. ##::: ##::: ##:: ##...:::: ##.. ##:::\n ##:::: ##: ##.... ##: ##:.:: ##: ##:::: ##: ##:::: ##: ##::. ##:: ##::: ##:: ##::::::: ##::. ##::\n ##:::: ##: ##:::: ##: ##:::: ##: ########::. #######:: ##:::. ##:. ######::: ########: ##:::. ##:\n..:::::..::..:::::..::..:::::..::........::::.......:::..:::::..:::......::::........::..:::::..::\n
\n\n

banner3

\n\n
##     ##    ###    ##     ## ########  ##     ## ########   ######   ######## ########  \n##     ##   ## ##   ###   ### ##     ## ##     ## ##     ## ##    ##  ##       ##     ## \n##     ##  ##   ##  #### #### ##     ## ##     ## ##     ## ##        ##       ##     ## \n######### ##     ## ## ### ## ########  ##     ## ########  ##   #### ######   ########  \n##     ## ######### ##     ## ##     ## ##     ## ##   ##   ##    ##  ##       ##   ##   \n##     ## ##     ## ##     ## ##     ## ##     ## ##    ##  ##    ##  ##       ##    ##  \n##     ## ##     ## ##     ## ########   #######  ##     ##  ######   ######## ##     ## \n
\n\n

banner4

\n\n
.##.....##....###....##.....##.########..##.....##.########...######...########.########.\n.##.....##...##.##...###...###.##.....##.##.....##.##.....##.##....##..##.......##.....##\n.##.....##..##...##..####.####.##.....##.##.....##.##.....##.##........##.......##.....##\n.#########.##.....##.##.###.##.########..##.....##.########..##...####.######...########.\n.##.....##.#########.##.....##.##.....##.##.....##.##...##...##....##..##.......##...##..\n.##.....##.##.....##.##.....##.##.....##.##.....##.##....##..##....##..##.......##....##.\n.##.....##.##.....##.##.....##.########...#######..##.....##..######...########.##.....##\n
\n\n

barbwire

\n\n
><<     ><<                       ><<                                               \n><<     ><<                       ><<                                               \n><<     ><<   ><<    ><<< ><< ><< ><<      ><<  ><<>< ><<<   ><<      ><<    >< ><<<\n><<<<<< ><< ><<  ><<  ><<  ><  ><<><< ><<  ><<  ><< ><<    ><<  ><< ><   ><<  ><<   \n><<     ><<><<   ><<  ><<  ><  ><<><<   ><<><<  ><< ><<   ><<   ><<><<<<< ><< ><<   \n><<     ><<><<   ><<  ><<  ><  ><<><<   ><<><<  ><< ><<    ><<  ><<><         ><<   \n><<     ><<  ><< ><<<><<<  ><  ><<><< ><<    ><<><<><<<        ><<   ><<<<   ><<<   \n                                                            ><<                     \n
\n\n

basic

\n\n
db   db  .d8b.  .88b  d88. d8888b. db    db d8888b.  d888b  d88888b d8888b. \n88   88 d8' `8b 88'YbdP`88 88  `8D 88    88 88  `8D 88' Y8b 88'     88  `8D \n88ooo88 88ooo88 88  88  88 88oooY' 88    88 88oobY' 88      88ooooo 88oobY' \n88~~~88 88~~~88 88  88  88 88~~~b. 88    88 88`8b   88  ooo 88~~~~~ 88`8b   \n88   88 88   88 88  88  88 88   8D 88b  d88 88 `88. 88. ~8~ 88.     88 `88. \nYP   YP YP   YP YP  YP  YP Y8888P' ~Y8888P' 88   YD  Y888P  Y88888P 88   YD \n
\n\n

bell

\n\n
 __  __                  _                                     \n |   |    ___  , _ , _   \\ ___  ,   . .___    ___.   ___  .___ \n |___|   /   ` |' `|' `. |/   \\ |   | /   \\ .'   ` .'   ` /   \\\n |   |  |    | |   |   | |    ` |   | |   ' |    | |----' |   '\n /   /  `.__/| /   '   / `___,' `._/| /      `---| `.___, /    \n                                             \\___/             \n
\n\n

big

\n\n
 _    _                 _                               \n| |  | |               | |                              \n| |__| | __ _ _ __ ___ | |__  _   _ _ __ __ _  ___ _ __ \n|  __  |/ _` | '_ ` _ \\| '_ \\| | | | '__/ _` |/ _ \\ '__|\n| |  | | (_| | | | | | | |_) | |_| | | | (_| |  __/ |   \n|_|  |_|\\__,_|_| |_| |_|_.__/ \\__,_|_|  \\__, |\\___|_|   \n                                         __/ |          \n                                        |___/           \n
\n\n

bigchief

\n\n
_____________________________________________________________\n    _     _                                                  \n    /    /                 /                                 \n---/___ /-----__---_--_---/__----------)__----__----__---)__-\n  /    /    /   ) / /  ) /   ) /   /  /   ) /   ) /___) /   )\n_/____/____(___(_/_/__/_(___/_(___(__/_____(___/_(___ _/_____\n                                              /              \n                                          (_ /               \n
\n\n

binary

\n\n
01001000 01100001 01101101 01100010 01110101 01110010 01100111 01100101 01110010 \n
\n\n

block

\n\n
_|    _|                            _|                                                          \n_|    _|    _|_|_|  _|_|_|  _|_|    _|_|_|    _|    _|  _|  _|_|    _|_|_|    _|_|    _|  _|_|  \n_|_|_|_|  _|    _|  _|    _|    _|  _|    _|  _|    _|  _|_|      _|    _|  _|_|_|_|  _|_|      \n_|    _|  _|    _|  _|    _|    _|  _|    _|  _|    _|  _|        _|    _|  _|        _|        \n_|    _|    _|_|_|  _|    _|    _|  _|_|_|      _|_|_|  _|          _|_|_|    _|_|_|  _|        \n                                                                        _|                      \n                                                                    _|_|                        \n
\n\n

broadway

\n\n
                                                .         .                                                                                                         \n8 8888        8          .8.                   ,8.       ,8.          8 888888888o   8 8888      88 8 888888888o.      ,o888888o.    8 8888888888   8 888888888o.   \n8 8888        8         .888.                 ,888.     ,888.         8 8888    `88. 8 8888      88 8 8888    `88.    8888     `88.  8 8888         8 8888    `88.  \n8 8888        8        :88888.               .`8888.   .`8888.        8 8888     `88 8 8888      88 8 8888     `88 ,8 8888       `8. 8 8888         8 8888     `88  \n8 8888        8       . `88888.             ,8.`8888. ,8.`8888.       8 8888     ,88 8 8888      88 8 8888     ,88 88 8888           8 8888         8 8888     ,88  \n8 8888        8      .8. `88888.           ,8'8.`8888,8^8.`8888.      8 8888.   ,88' 8 8888      88 8 8888.   ,88' 88 8888           8 888888888888 8 8888.   ,88'  \n8 8888        8     .8`8. `88888.         ,8' `8.`8888' `8.`8888.     8 8888888888   8 8888      88 8 888888888P'  88 8888           8 8888         8 888888888P'   \n8 8888888888888    .8' `8. `88888.       ,8'   `8.`88'   `8.`8888.    8 8888    `88. 8 8888      88 8 8888`8b      88 8888   8888888 8 8888         8 8888`8b       \n8 8888        8   .8'   `8. `88888.     ,8'     `8.`'     `8.`8888.   8 8888      88 ` 8888     ,8P 8 8888 `8b.    `8 8888       .8' 8 8888         8 8888 `8b.     \n8 8888        8  .888888888. `88888.   ,8'       `8        `8.`8888.  8 8888    ,88'   8888   ,d8P  8 8888   `8b.     8888     ,88'  8 8888         8 8888   `8b.   \n8 8888        8 .8'       `8. `88888. ,8'         `         `8.`8888. 8 888888888P      `Y88888P'   8 8888     `88.    `8888888P'    8 888888888888 8 8888     `88. \n
\n\n

bubble

\n\n
  _   _   _   _   _   _   _   _   _  \n / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ \n( H | a | m | b | u | r | g | e | r )\n \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \n
\n\n

bulbhead

\n\n
 _   _    __    __  __  ____  __  __  ____   ___  ____  ____ \n( )_( )  /__\\  (  \\/  )(  _ \\(  )(  )(  _ \\ / __)( ___)(  _ \\\n ) _ (  /(__)\\  )    (  ) _ < )(__)(  )   /( (_-. )__)  )   /\n(_) (_)(__)(__)(_/\\/\\_)(____/(______)(_)\\_) \\___/(____)(_)\\_)\n
\n\n

calgphy2

\n\n
     #####    ##                              /                                                              \n  ######  /  #### /                         #/                                                               \n /#   /  /   ####/                          ##                                                               \n/    /  /    # #                            ##                                                               \n    /  /     #                              ##                                                               \n   ## ##     #      /###   ### /### /###    ## /###   ##   ####    ###  /###     /###      /##  ###  /###    \n   ## ##     #     / ###  / ##/ ###/ /##  / ##/ ###  / ##    ###  / ###/ #### / /  ###  / / ###  ###/ #### / \n   ## ########    /   ###/   ##  ###/ ###/  ##   ###/  ##     ###/   ##   ###/ /    ###/ /   ###  ##   ###/  \n   ## ##     #   ##    ##    ##   ##   ##   ##    ##   ##      ##    ##       ##     ## ##    ### ##         \n   ## ##     ##  ##    ##    ##   ##   ##   ##    ##   ##      ##    ##       ##     ## ########  ##         \n   #  ##     ##  ##    ##    ##   ##   ##   ##    ##   ##      ##    ##       ##     ## #######   ##         \n      /       ## ##    ##    ##   ##   ##   ##    ##   ##      ##    ##       ##     ## ##        ##         \n  /##/        ## ##    /#    ##   ##   ##   ##    /#   ##      /#    ##       ##     ## ####    / ##         \n /  #####      ## ####/ ##   ###  ###  ###   ####/      ######/ ##   ###       ########  ######/  ###        \n/     ##           ###   ##   ###  ###  ###   ###        #####   ##   ###        ### ###  #####    ###       \n#                                                                                     ###                    \n ##                                                                             ####   ###                   \n                                                                              /######  /#                    \n                                                                             /     ###/                      \n
\n\n

calligraphy

\n\n
     *****    **                                  *                                                                        \n  ******  *  **** *                             **                                                                         \n **   *  *   *****                              **                                                                         \n*    *  *    * *                                **                                                                         \n    *  *     *                                  **         **   ****     ***  ****                            ***  ****    \n   ** **     *         ****    *** **** ****    ** ****     **    ***  *  **** **** *     ****         ***     **** **** * \n   ** **     *        * ***  *  *** **** ***  * *** ***  *  **     ****    **   ****     *  ***  *    * ***     **   ****  \n   ** ********       *   ****    **  **** ****  **   ****   **      **     **           *    ****    *   ***    **         \n   ** **     *      **    **     **   **   **   **    **    **      **     **          **     **    **    ***   **         \n   ** **     **     **    **     **   **   **   **    **    **      **     **          **     **    ********    **         \n   *  **     **     **    **     **   **   **   **    **    **      **     **          **     **    *******     **         \n      *       **    **    **     **   **   **   **    **    **      **     **          **     **    **          **         \n  ****        **    **    **     **   **   **   **    **     ******* **    ***         **     **    ****    *   ***        \n *  *****      **    ***** **    ***  ***  ***   *****        *****   **    ***         ********     *******     ***       \n*     **              ***   **    ***  ***  ***   ***                                     *** ***     *****                \n*                                                                                              ***                         \n **                                                                                      ****   ***                        \n                                                                                       *******  **                         \n                                                                                      *     ****                           \n
\n\n

catwalk

\n\n
_//     _//                       _//                                               \n_//     _//                       _//                                               \n_//     _//   _//    _/// _// _// _//      _//  _//_/ _///   _//      _//    _/ _///\n_////// _// _//  _//  _//  _/  _//_// _//  _//  _// _//    _//  _// _/   _//  _//   \n_//     _//_//   _//  _//  _/  _//_//   _//_//  _// _//   _//   _//_///// _// _//   \n_//     _//_//   _//  _//  _/  _//_//   _//_//  _// _//    _//  _//_/         _//   \n_//     _//  _// _///_///  _/  _//_// _//    _//_//_///        _//   _////   _///   \n                                                            _//                     \n
\n\n

chunky

\n\n
 _______                  __                                \n|   |   |.---.-.--------.|  |--.--.--.----.-----.-----.----.\n|       ||  _  |        ||  _  |  |  |   _|  _  |  -__|   _|\n|___|___||___._|__|__|__||_____|_____|__| |___  |_____|__|  \n                                          |_____|           \n
\n\n

coinstak

\n\n
O))     O))                       O))                                               \nO))     O))                       O))                                               \nO))     O))   O))    O))) O)) O)) O))      O))  O))O) O)))   O))      O))    O) O)))\nO)))))) O)) O))  O))  O))  O)  O))O)) O))  O))  O)) O))    O))  O)) O)   O))  O))   \nO))     O))O))   O))  O))  O)  O))O))   O))O))  O)) O))   O))   O))O))))) O)) O))   \nO))     O))O))   O))  O))  O)  O))O))   O))O))  O)) O))    O))  O))O)         O))   \nO))     O))  O)) O)))O)))  O)  O))O)) O))    O))O))O)))        O))   O))))   O)))   \n                                                            O))                     \n
\n\n

colossal

\n\n
888    888                     888                                            \n888    888                     888                                            \n888    888                     888                                            \n8888888888 8888b. 88888b.d88b. 88888b. 888  888888d888 .d88b.  .d88b. 888d888 \n888    888    \"88b888 \"888 \"88b888 \"88b888  888888P\"  d88P\"88bd8P  Y8b888P\"   \n888    888.d888888888  888  888888  888888  888888    888  88888888888888     \n888    888888  888888  888  888888 d88PY88b 888888    Y88b 888Y8b.    888     \n888    888\"Y888888888  888  88888888P\"  \"Y88888888     \"Y88888 \"Y8888 888     \n                                                           888                \n                                                      Y8b d88P                \n                                                       \"Y88P\"                 \n
\n\n

computer

\n\n
8   8                                                     \n8   8 eeeee eeeeeee eeeee  e   e eeeee  eeeee eeee eeeee  \n8eee8 8   8 8  8  8 8   8  8   8 8   8  8   8 8    8   8  \n88  8 8eee8 8e 8  8 8eee8e 8e  8 8eee8e 8e    8eee 8eee8e \n88  8 88  8 88 8  8 88   8 88  8 88   8 88 \"8 88   88   8 \n88  8 88  8 88 8  8 88eee8 88ee8 88   8 88ee8 88ee 88   8 \n
\n\n

contessa

\n\n
.  .        .                 \n|__| _.._ _ |_ . .._. _  _ ._.\n|  |(_][ | )[_)(_|[  (_](/,[  \n                     ._|      \n
\n\n

contrast

\n\n
.%%..%%...%%%%...%%...%%..%%%%%...%%..%%..%%%%%....%%%%...%%%%%%..%%%%%..\n.%%..%%..%%..%%..%%%.%%%..%%..%%..%%..%%..%%..%%..%%......%%......%%..%%.\n.%%%%%%..%%%%%%..%%.%.%%..%%%%%...%%..%%..%%%%%...%%.%%%..%%%%....%%%%%..\n.%%..%%..%%..%%..%%...%%..%%..%%..%%..%%..%%..%%..%%..%%..%%......%%..%%.\n.%%..%%..%%..%%..%%...%%..%%%%%....%%%%...%%..%%...%%%%...%%%%%%..%%..%%.\n.........................................................................\n
\n\n

cosmic

\n\n
  ::   .:   :::.     .        :   :::::::.   ...    ::::::::::..    .,-:::::/ .,:::::: :::::::..   \n ,;;   ;;,  ;;`;;    ;;,.    ;;;   ;;;'';;'  ;;     ;;;;;;;``;;;; ,;;-'````'  ;;;;'''' ;;;;``;;;;  \n,[[[,,,[[[ ,[[ '[[,  [[[[, ,[[[[,  [[[__[[\\.[['     [[[ [[[,/[[[' [[[   [[[[[[/[[cccc   [[[,/[[['  \n\"$$$\"\"\"$$$c$$$cc$$$c $$$$$$$$\"$$$  $$\"\"\"\"Y$$$$      $$$ $$$$$$c   \"$$c.    \"$$ $$\"\"\"\"   $$$$$$c    \n 888   \"88o888   888,888 Y88\" 888o_88o,,od8P88    .d888 888b \"88bo,`Y8bo,,,o88o888oo,__ 888b \"88bo,\n MMM    YMMYMM   \"\"` MMM  M'  \"MMM\"\"YUMMMP\"  \"YmmMMMM\"\" MMMM   \"W\"   `'YMUP\"YMM\"\"\"\"YUMMMMMMM   \"W\" \n
\n\n

cosmike

\n\n
  ::   .:   :::.     .        :   :::::::.   ...    ::::::::::..    .,-:::::/ .,:::::: :::::::..   \n ,;;   ;;,  ;;`;;    ;;,.    ;;;   ;;;'';;'  ;;     ;;;;;;;``;;;; ,;;-'````'  ;;;;'''' ;;;;``;;;;  \n,[[[,,,[[[ ,[[ '[[,  [[[[, ,[[[[,  [[[__[[\\.[['     [[[ [[[,/[[[' [[[   [[[[[[/[[cccc   [[[,/[[['  \n\"$$$\"\"\"$$$c$$$cc$$$c $$$$$$$$\"$$$  $$\"\"\"\"Y$$$$      $$$ $$$$$$c   \"$$c.    \"$$ $$\"\"\"\"   $$$$$$c    \n 888   \"88o888   888,888 Y88\" 888o_88o,,od8P88    .d888 888b \"88bo,`Y8bo,,,o88o888oo,__ 888b \"88bo,\n MMM    YMMYMM   \"\"` MMM  M'  \"MMM\"\"YUMMMP\"  \"YmmMMMM\"\" MMMM   \"W\"   `'YMUP\"YMM\"\"\"\"YUMMMMMMM   \"W\" \n
\n\n

crawford

\n\n
 __ __   ____  ___ ___  ____   __ __  ____    ____    ___  ____  \n|  T  T /    T|   T   T|    \\ |  T  T|    \\  /    T  /  _]|    \\ \n|  l  |Y  o  || _   _ ||  o  )|  |  ||  D  )Y   __j /  [_ |  D  )\n|  _  ||     ||  \\_/  ||     T|  |  ||    / |  T  |Y    _]|    / \n|  |  ||  _  ||   |   ||  O  ||  :  ||    \\ |  l_ ||   [_ |    \\ \n|  |  ||  |  ||   |   ||     |l     ||  .  Y|     ||     T|  .  Y\nl__j__jl__j__jl___j___jl_____j \\__,_jl__j\\_jl___,_jl_____jl__j\\_j\n
\n\n

cricket

\n\n
 ___ ___                __                                \n|   Y   .---.-.--------|  |--.--.--.----.-----.-----.----.\n|.  1   |  _  |        |  _  |  |  |   _|  _  |  -__|   _|\n|.  _   |___._|__|__|__|_____|_____|__| |___  |_____|__|  \n|:  |   |                               |_____|           \n|::.|:. |                                                 \n`--- ---'                                                 \n
\n\n

cursive

\n\n
 _    ,                                 \n' )  /              /                   \n /--/ __.  ______  /__. . __  _,  _  __ \n/  (_(_/|_/ / / <_/_)(_/_/ (_(_)_</_/ (_\n                              /|        \n                             |/         \n
\n\n

cyberlarge

\n\n
 _     _ _______ _______ ______  _     _  ______  ______ _______  ______\n |_____| |_____| |  |  | |_____] |     | |_____/ |  ____ |______ |_____/\n |     | |     | |  |  | |_____] |_____| |    \\_ |_____| |______ |    \\_\n
\n\n

cybermedium

\n\n
_  _ ____ _  _ ___  _  _ ____ ____ ____ ____ \n|__| |__| |\\/| |__] |  | |__/ | __ |___ |__/ \n|  | |  | |  | |__] |__| |  \\ |__] |___ |  \\ \n
\n\n

cybersmall

\n\n
 _  _ ____ _  _ ___  _  _ ____ ____ ____ ____\n |--| |--| |\\/| |==] |__| |--< |__, |=== |--<\n
\n\n

decimal

\n\n
72 97 109 98 117 114 103 101 114 \n
\n\n

diamond

\n\n
/\\\\     /\\\\                       /\\\\                                               \n/\\\\     /\\\\                       /\\\\                                               \n/\\\\     /\\\\   /\\\\    /\\\\\\ /\\\\ /\\\\ /\\\\      /\\\\  /\\\\/\\ /\\\\\\   /\\\\      /\\\\    /\\ /\\\\\\\n/\\\\\\\\\\\\ /\\\\ /\\\\  /\\\\  /\\\\  /\\  /\\\\/\\\\ /\\\\  /\\\\  /\\\\ /\\\\    /\\\\  /\\\\ /\\   /\\\\  /\\\\   \n/\\\\     /\\\\/\\\\   /\\\\  /\\\\  /\\  /\\\\/\\\\   /\\\\/\\\\  /\\\\ /\\\\   /\\\\   /\\\\/\\\\\\\\\\ /\\\\ /\\\\   \n/\\\\     /\\\\/\\\\   /\\\\  /\\\\  /\\  /\\\\/\\\\   /\\\\/\\\\  /\\\\ /\\\\    /\\\\  /\\\\/\\         /\\\\   \n/\\\\     /\\\\  /\\\\ /\\\\\\/\\\\\\  /\\  /\\\\/\\\\ /\\\\    /\\\\/\\\\/\\\\\\        /\\\\   /\\\\\\\\   /\\\\\\   \n                                                            /\\\\                     \n
\n\n

digital

\n\n
+-+-+-+-+-+-+-+-+-+\n|H|a|m|b|u|r|g|e|r|\n+-+-+-+-+-+-+-+-+-+\n
\n\n

doh

\n\n
                                                                bbbbbbbb                                                                                                             \nHHHHHHHHH     HHHHHHHHH                                         b::::::b                                                                                                             \nH:::::::H     H:::::::H                                         b::::::b                                                                                                             \nH:::::::H     H:::::::H                                         b::::::b                                                                                                             \nHH::::::H     H::::::HH                                          b:::::b                                                                                                             \n  H:::::H     H:::::H    aaaaaaaaaaaaa      mmmmmmm    mmmmmmm   b:::::bbbbbbbbb    uuuuuu    uuuuuu rrrrr   rrrrrrrrr      ggggggggg   ggggg    eeeeeeeeeeee    rrrrr   rrrrrrrrr   \n  H:::::H     H:::::H    a::::::::::::a   mm:::::::m  m:::::::mm b::::::::::::::bb  u::::u    u::::u r::::rrr:::::::::r    g:::::::::ggg::::g  ee::::::::::::ee  r::::rrr:::::::::r  \n  H::::::HHHHH::::::H    aaaaaaaaa:::::a m::::::::::mm::::::::::mb::::::::::::::::b u::::u    u::::u r:::::::::::::::::r  g:::::::::::::::::g e::::::eeeee:::::eer:::::::::::::::::r \n  H:::::::::::::::::H             a::::a m::::::::::::::::::::::mb:::::bbbbb:::::::bu::::u    u::::u rr::::::rrrrr::::::rg::::::ggggg::::::gge::::::e     e:::::err::::::rrrrr::::::r\n  H:::::::::::::::::H      aaaaaaa:::::a m:::::mmm::::::mmm:::::mb:::::b    b::::::bu::::u    u::::u  r:::::r     r:::::rg:::::g     g:::::g e:::::::eeeee::::::e r:::::r     r:::::r\n  H::::::HHHHH::::::H    aa::::::::::::a m::::m   m::::m   m::::mb:::::b     b:::::bu::::u    u::::u  r:::::r     rrrrrrrg:::::g     g:::::g e:::::::::::::::::e  r:::::r     rrrrrrr\n  H:::::H     H:::::H   a::::aaaa::::::a m::::m   m::::m   m::::mb:::::b     b:::::bu::::u    u::::u  r:::::r            g:::::g     g:::::g e::::::eeeeeeeeeee   r:::::r            \n  H:::::H     H:::::H  a::::a    a:::::a m::::m   m::::m   m::::mb:::::b     b:::::bu:::::uuuu:::::u  r:::::r            g::::::g    g:::::g e:::::::e            r:::::r            \nHH::::::H     H::::::HHa::::a    a:::::a m::::m   m::::m   m::::mb:::::bbbbbb::::::bu:::::::::::::::uur:::::r            g:::::::ggggg:::::g e::::::::e           r:::::r            \nH:::::::H     H:::::::Ha:::::aaaa::::::a m::::m   m::::m   m::::mb::::::::::::::::b  u:::::::::::::::ur:::::r             g::::::::::::::::g  e::::::::eeeeeeee   r:::::r            \nH:::::::H     H:::::::H a::::::::::aa:::am::::m   m::::m   m::::mb:::::::::::::::b    uu::::::::uu:::ur:::::r              gg::::::::::::::g   ee:::::::::::::e   r:::::r            \nHHHHHHHHH     HHHHHHHHH  aaaaaaaaaa  aaaammmmmm   mmmmmm   mmmmmmbbbbbbbbbbbbbbbb       uuuuuuuu  uuuurrrrrrr                gggggggg::::::g     eeeeeeeeeeeeee   rrrrrrr            \n                                                                                                                                     g:::::g                                         \n                                                                                                                         gggggg      g:::::g                                         \n                                                                                                                         g:::::gg   gg:::::g                                         \n                                                                                                                          g::::::ggg:::::::g                                         \n                                                                                                                           gg:::::::::::::g                                          \n                                                                                                                             ggg::::::ggg                                            \n                                                                                                                                gggggg                                               \n
\n\n

doom

\n\n
 _   _                 _                               \n| | | |               | |                              \n| |_| | __ _ _ __ ___ | |__  _   _ _ __ __ _  ___ _ __ \n|  _  |/ _` | '_ ` _ \\| '_ \\| | | | '__/ _` |/ _ \\ '__|\n| | | | (_| | | | | | | |_) | |_| | | | (_| |  __/ |   \n\\_| |_/\\__,_|_| |_| |_|_.__/ \\__,_|_|  \\__, |\\___|_|   \n                                        __/ |          \n                                       |___/           \n
\n\n

dotmatrix

\n\n
 _           _                                 _                                                                                    \n(_)         (_)                               (_)                                                                                   \n(_)         (_)   _  _  _        _  _   _  _  (_) _  _  _    _         _  _       _  _   _  _  _  _   _  _  _  _   _       _  _     \n(_) _  _  _ (_)  (_)(_)(_) _    (_)(_)_(_)(_) (_)(_)(_)(_)_ (_)       (_)(_)_  _ (_)(_)_(_)(_)(_)(_) (_)(_)(_)(_)_(_)_  _ (_)(_)    \n(_)(_)(_)(_)(_)   _  _  _ (_)  (_)   (_)   (_)(_)        (_)(_)       (_)  (_)(_)     (_)        (_)(_) _  _  _ (_) (_)(_)          \n(_)         (_) _(_)(_)(_)(_)  (_)   (_)   (_)(_)        (_)(_)       (_)  (_)        (_)        (_)(_)(_)(_)(_)(_) (_)             \n(_)         (_)(_)_  _  _ (_)_ (_)   (_)   (_)(_) _  _  _(_)(_)_  _  _(_)_ (_)        (_)_  _  _ (_)(_)_  _  _  _   (_)             \n(_)         (_)  (_)(_)(_)  (_)(_)   (_)   (_)(_)(_)(_)(_)    (_)(_)(_) (_)(_)          (_)(_)(_)(_)  (_)(_)(_)(_)  (_)             \n                                                                                         _  _  _ (_)                                \n                                                                                        (_)(_)(_)                                   \n
\n\n

double

\n\n
__  __ ___ ___  _______ __ ______   ___  ________ \n||  ||// \\\\||\\\\//|||| ))|| |||| \\\\ // \\\\||   || \\\\\n||==||||=|||| \\/ ||||=) || ||||_//(( ___||== ||_//\n||  |||| ||||    ||||_))\\\\_//|| \\\\ \\\\_||||___|| \\\\\n
\n\n

drpepper

\n\n
 _ _              _                            \n| | | ___ ._ _ _ | |_  _ _  _ _  ___  ___  _ _ \n|   |<_> || ' ' || . \\| | || '_>/ . |/ ._>| '_>\n|_|_|<___||_|_|_||___/`___||_|  \\_. |\\___.|_|  \n                                <___'          \n
\n\n

dwhistled

\n\n
H m ur  r\n X X  XX \n X .  XX \n . .  XX \n . .  .X \n . .  .X \n . .  .. \nHamburger\n
\n\n

eftichess

\n\n
         #########         #########         #########         ####################################\n  [`'`'] ##\\`.'/##  ':v:`  ##/\\:/\\##  |:+:|  ##':v:`##  \\`.'/  ##[`'`']###'\\v/`####[`'`']###[`'`']#\n   |::|  ##(o:o)##  (o:0)  #/(o:o)\\#  (o:o)  ##(o:0)##  (o:o)  ###|::|####(o 0)#####|  |#####|  |##\n   |::|  ###\\:/:\\#   (:)   ###(:)###   (:)   ###(:)###   \\:/:\\ ###|::|#####(_)######|__|#####|__|##\n         ####\"####         #########         #########    \"    ####################################\n
\n\n

eftifont

\n\n
 _ _                         \n| U |_    _ _ ||    _  _ _ _ \n|   /o\\ |/ \\ \\|o\\U|/_|/oYoY_|\n|_n_\\_,]L_n_n||_|_/L| \\_|(L| \n                       _)    \n
\n\n

eftipiti

\n\n
[]-|amburger\n
\n\n

eftirobot

\n\n
 _  _               _                         \n( )( )             ( )                        \n| L| | ___  __  __ | |_  _ _  __  __  ___  __ \n( __ )( o )( _`'_ )( o \\( U )( _)/o )( o_)( _)\n/_\\/_\\/_^_\\/_\\`'/_\\/___//___\\/_\\ \\__\\ \\(  /_\\ \n                                  _|/         \n
\n\n

eftitalic

\n\n
   _ __                                \n  /// / _   _     /7      _   _   __ _ \n / ` /,'o| / \\'\\ /o\\ /7/7//7,'o|,'o///7\n/_n_/ |_,7/_nn_//_,'/__///  |_,'|_(//  \n                            _//        \n
\n\n

eftiwall

\n\n
                 |                ___         ( ( (           o            !!!                         |\"|           !!!      \n     ***         |.===.          /_\\ `*     '. ___ .'      ` /_\\ '      `  _ _  '      __MMM__        _|_|_       `  _ _  '   \n    (o o)        {}o o{}        (o o)      '  (> <) '     - (o o) -    -  (OXO)  -      (o o)         (o o)      -  (OXO)  -  \nooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-\n
\n\n

eftiwater

\n\n
 _ _             _                       \n )L`) ___  _  _  ))  _    __  ___  __ __ \n(( ( ((_( ((`1( ((_)((_( (|  ((_( (('(|  \n                               _))       \n
\n\n

epic

\n\n
          _______  _______  ______            _______  _______  _______  _______ \n|\\     /|(  ___  )(       )(  ___ \\ |\\     /|(  ____ )(  ____ \\(  ____ \\(  ____ )\n| )   ( || (   ) || () () || (   ) )| )   ( || (    )|| (    \\/| (    \\/| (    )|\n| (___) || (___) || || || || (__/ / | |   | || (____)|| |      | (__    | (____)|\n|  ___  ||  ___  || |(_)| ||  __ (  | |   | ||     __)| | ____ |  __)   |     __)\n| (   ) || (   ) || |   | || (  \\ \\ | |   | || (\\ (   | | \\_  )| (      | (\\ (   \n| )   ( || )   ( || )   ( || )___) )| (___) || ) \\ \\__| (___) || (____/\\| ) \\ \\__\n|/     \\||/     \\||/     \\||/ \\___/ (_______)|/   \\__/(_______)(_______/|/   \\__/\n
\n\n

fender

\n\n
'||  ||`                    '||                                          \n ||  ||                      ||                                          \n ||''||   '''|.  '||),,(|,   ||''|, '||  ||` '||''| .|''|, .|''|, '||''| \n ||  ||  .|''||   || || ||   ||  ||  ||  ||   ||    ||  || ||..||  ||    \n.||  ||. `|..||. .||    ||. .||..|'  `|..'|. .||.   `|..|| `|...  .||.   \n                                                        ||               \n                                                     `..|'               \n
\n\n

fourtops

\n\n
|  |             |                       \n|--|/~~||/~\\ /~\\ |~~\\|   ||/~\\/~~|/~/|/~\\\n|  |\\__||   |   ||__/ \\_/||   \\__|\\/_|   \n                              \\__|       \n
\n\n

fraktur

\n\n
                                                            ..                                                                    \n         .xHL                                         . uW8\"                                                                      \n      .-`8888hxxx~                   ..    .     :    `t888          x.    .        .u    .                             .u    .   \n   .H8X  `%888*\"            u      .888: x888  x888.   8888   .    .@88k  z88u    .d88B :@8c       uL          .u     .d88B :@8c  \n   888X     ..x..        us888u.  ~`8888~'888X`?888f`  9888.z88N  ~\"8888 ^8888   =\"8888f8888r  .ue888Nc..   ud8888.  =\"8888f8888r \n  '8888k .x8888888x   .@88 \"8888\"   X888  888X '888>   9888  888E   8888  888R     4888>'88\"  d88E`\"888E` :888'8888.   4888>'88\"  \n   ?8888X    \"88888X  9888  9888    X888  888X '888>   9888  888E   8888  888R     4888> '    888E  888E  d888 '88%\"   4888> '    \n    ?8888X    '88888> 9888  9888    X888  888X '888>   9888  888E   8888  888R     4888>      888E  888E  8888.+\"      4888>      \n H8H %8888     `8888> 9888  9888    X888  888X '888>   9888  888E   8888 ,888B .  .d888L .+   888E  888E  8888L       .d888L .+   \n'888> 888\"      8888  9888  9888   \"*88%\"\"*88\" '888!` .8888  888\"  \"8888Y 8888\"   ^\"8888*\"    888& .888E  '8888c. .+  ^\"8888*\"    \n \"8` .8\" ..     88*   \"888*\"\"888\"    `~    \"    `\"`    `%888*%\"     `Y\"   'YP        \"Y\"      *888\" 888&   \"88888%       \"Y\"      \n    `  x8888h. d*\"     ^Y\"   ^Y'                          \"`                                   `\"   \"888E    \"YP'                 \n      !\"\"*888%~                                                                               .dWi   `88E                         \n      !   `\"  .                                                                               4888~  J8%                          \n      '-....:~                                                                                 ^\"===*\"`                           \n
\n\n

fuzzy

\n\n
.-..-.                .-.                               \n: :; :                : :                               \n:    : .--.  ,-.,-.,-.: `-. .-..-..--.  .--.  .--. .--. \n: :: :' .; ; : ,. ,. :' .; :: :; :: ..'' .; :' '_.': ..'\n:_;:_;`.__,_;:_;:_;:_;`.__.'`.__.':_;  `._. ;`.__.':_;  \n                                        .-. :           \n                                        `._.'           \n
\n\n

goofy

\n\n
    ___    _____  _____          _      ___    ___    _     _____       ___        __     ___\n\\  |   |  /    /  \\    |        | \\     \\  |  |   |  | |    \\    )  ____)  \\    ___) |    \\  \n |  \\_/  |    /    \\   |  |\\/|  |  |     ) |  |   |  | |     )  /  /  __    |  (__   |     ) \n |   _   |   /  ()  \\  |  |  |  |  |    <  |  |   |  | |    /  (  (  (  \\   |   __)  |    /  \n |  / \\  |  |   __   | |  |  |  |  |     ) |   \\_/   | | |\\ \\   \\  \\__)  )  |  (___  | |\\ \\  \n/  |___|  \\_|  (__)  |_|  |__|  |_/     /___\\       /__| |_\\ \\___)      (__/       )_| |_\\ \\_\n
\n\n

gothic

\n\n
_-_-                     ,,                                  \n  /,        _            ||                  _               \n  || __    < \\, \\\\/\\\\/\\\\ ||/|, \\\\ \\\\ ,._-_  / \\\\  _-_  ,._-_ \n ~||-  -   /-|| || || || || || || ||  ||   || || || \\\\  ||   \n  ||===|| (( || || || || || |' || ||  ||   || || ||/    ||   \n ( \\_, |   \\/\\\\ \\\\ \\\\ \\\\ \\\\/   \\\\/\\\\  \\\\,  \\\\_-| \\\\,/   \\\\,  \n       `                                    /  \\             \n                                           '----`            \n
\n\n

graceful

\n\n
 _  _   __   _  _  ____  _  _  ____   ___  ____  ____ \n/ )( \\ / _\\ ( \\/ )(  _ \\/ )( \\(  _ \\ / __)(  __)(  _ \\\n) __ (/    \\/ \\/ \\ ) _ () \\/ ( )   /( (_ \\ ) _)  )   /\n\\_)(_/\\_/\\_/\\_)(_/(____/\\____/(__\\_) \\___/(____)(__\\_)\n
\n\n

gradient

\n\n
eee..eee..eeeeee..eee......eee.eeeeeee..eee..eee.eeeeeee...eeeeee..eeeeee.eeeeeee..\n@@@::@@@:@@@@@@@@:@@@@::::@@@@:@@@@@@@@:@@@::@@@:@@@@@@@@:@@@@@@@@:@@@@@@:@@@@@@@@:\n%%%--%%%-%%%--%%%-%%%%%--%%%%%-%%%--%%%-%%%--%%%-%%%--%%%-%%%------%%%----%%%--%%%-\n&&&&&&&&+&&&&&&&&+&&&&&&&&&&&&+&&&&&&&++&&&++&&&+&&&&&&&++&&&++++++&&&&&++&&&&&&&++\n||||||||*||||||||*|||*||||*|||*||||||||*|||**|||*||||||***|||*||||*|||||**||||||***\n!!!==!!!=!!!==!!!=!!!==!!==!!!=!!!==!!!=!!!==!!!=!!!=!!!==!!!==!!!=!!!====!!!=!!!==\n:::##:::#:::##:::#:::######:::#::::::::#::::::::#:::##:::#::::::::#::::::#:::##:::#\n...@@...@...@@...@...@@@@@@...@.......@@@......@@...@@...@@......@@......@...@@...@\n
\n\n

graffiti

\n\n
  ___ ___               ___.                                     \n /   |   \\_____    _____\\_ |__  __ _________  ____   ___________ \n/    ~    \\__  \\  /     \\| __ \\|  |  \\_  __ \\/ ___\\_/ __ \\_  __ \\\n\\    Y    // __ \\|  Y Y  \\ \\_\\ \\  |  /|  | \\/ /_/  >  ___/|  | \\/\n \\___|_  /(____  /__|_|  /___  /____/ |__|  \\___  / \\___  >__|   \n       \\/      \\/      \\/    \\/            /_____/      \\/       \n
\n\n

hex

\n\n
48 61 6D 62 75 72 67 65 72 \n
\n\n

hollywood

\n\n
           _                                                                                    \n          ' )     )                           /'                                                \n          /'    /'                          /'                                                  \n       ,/'    /' ____     ,__________     /'__               ____     ____     ____      ____   \n      /`---,/' /'    )   /'    )     )  /'    )  /'    /   )'    )--/'    )  /'    )   )'    )--\n    /'    /' /'    /'  /'    /'    /' /'    /' /'    /'  /'       /'    /' /(___,/'  /'         \n(,/'     (_,(___,/(__/'    /'    /(__(___,/(__(___,/(__/'        (___,/(__(________/'           \n                                                                    /'                          \n                                                            /     /'                            \n                                                           (___,/'                              \n
\n\n

invita

\n\n
   ____  ___)                              \n  (, /   /           /)                    \n    /---/  _  ___   (/_     __  _    _  __ \n ) /   (__(_(_// (_/_) (_(_/ (_(_/__(/_/ (_\n(_/                           .-/          \n                             (_/           \n
\n\n

isometric1

\n\n
      ___           ___           ___           ___           ___           ___           ___           ___           ___     \n     /\\__\\         /\\  \\         /\\__\\         /\\  \\         /\\__\\         /\\  \\         /\\  \\         /\\  \\         /\\  \\    \n    /:/  /        /::\\  \\       /::|  |       /::\\  \\       /:/  /        /::\\  \\       /::\\  \\       /::\\  \\       /::\\  \\   \n   /:/__/        /:/\\:\\  \\     /:|:|  |      /:/\\:\\  \\     /:/  /        /:/\\:\\  \\     /:/\\:\\  \\     /:/\\:\\  \\     /:/\\:\\  \\  \n  /::\\  \\ ___   /::\\~\\:\\  \\   /:/|:|__|__   /::\\~\\:\\__\\   /:/  /  ___   /::\\~\\:\\  \\   /:/  \\:\\  \\   /::\\~\\:\\  \\   /::\\~\\:\\  \\ \n /:/\\:\\  /\\__\\ /:/\\:\\ \\:\\__\\ /:/ |::::\\__\\ /:/\\:\\ \\:|__| /:/__/  /\\__\\ /:/\\:\\ \\:\\__\\ /:/__/_\\:\\__\\ /:/\\:\\ \\:\\__\\ /:/\\:\\ \\:\\__\\\n \\/__\\:\\/:/  / \\/__\\:\\/:/  / \\/__/~~/:/  / \\:\\~\\:\\/:/  / \\:\\  \\ /:/  / \\/_|::\\/:/  / \\:\\  /\\ \\/__/ \\:\\~\\:\\ \\/__/ \\/_|::\\/:/  /\n      \\::/  /       \\::/  /        /:/  /   \\:\\ \\::/  /   \\:\\  /:/  /     |:|::/  /   \\:\\ \\:\\__\\    \\:\\ \\:\\__\\      |:|::/  / \n      /:/  /        /:/  /        /:/  /     \\:\\/:/  /     \\:\\/:/  /      |:|\\/__/     \\:\\/:/  /     \\:\\ \\/__/      |:|\\/__/  \n     /:/  /        /:/  /        /:/  /       \\::/__/       \\::/  /       |:|  |        \\::/  /       \\:\\__\\        |:|  |    \n     \\/__/         \\/__/         \\/__/         ~~            \\/__/         \\|__|         \\/__/         \\/__/         \\|__|    \n
\n\n

isometric2

\n\n
      ___           ___           ___                         ___           ___           ___           ___           ___     \n     /\\  \\         /\\  \\         /\\  \\         _____         /\\  \\         /\\  \\         /\\__\\         /\\__\\         /\\  \\    \n     \\:\\  \\       /::\\  \\       |::\\  \\       /::\\  \\        \\:\\  \\       /::\\  \\       /:/ _/_       /:/ _/_       /::\\  \\   \n      \\:\\  \\     /:/\\:\\  \\      |:|:\\  \\     /:/\\:\\  \\        \\:\\  \\     /:/\\:\\__\\     /:/ /\\  \\     /:/ /\\__\\     /:/\\:\\__\\  \n  ___ /::\\  \\   /:/ /::\\  \\   __|:|\\:\\  \\   /:/ /::\\__\\   ___  \\:\\  \\   /:/ /:/  /    /:/ /::\\  \\   /:/ /:/ _/_   /:/ /:/  /  \n /\\  /:/\\:\\__\\ /:/_/:/\\:\\__\\ /::::|_\\:\\__\\ /:/_/:/\\:|__| /\\  \\  \\:\\__\\ /:/_/:/__/___ /:/__\\/\\:\\__\\ /:/_/:/ /\\__\\ /:/_/:/__/___\n \\:\\/:/  \\/__/ \\:\\/:/  \\/__/ \\:\\~~\\  \\/__/ \\:\\/:/ /:/  / \\:\\  \\ /:/  / \\:\\/:::::/  / \\:\\  \\ /:/  / \\:\\/:/ /:/  / \\:\\/:::::/  /\n  \\::/__/       \\::/__/       \\:\\  \\        \\::/_/:/  /   \\:\\  /:/  /   \\::/~~/~~~~   \\:\\  /:/  /   \\::/_/:/  /   \\::/~~/~~~~ \n   \\:\\  \\        \\:\\  \\        \\:\\  \\        \\:\\/:/  /     \\:\\/:/  /     \\:\\~~\\        \\:\\/:/  /     \\:\\/:/  /     \\:\\~~\\     \n    \\:\\__\\        \\:\\__\\        \\:\\__\\        \\::/  /       \\::/  /       \\:\\__\\        \\::/  /       \\::/  /       \\:\\__\\    \n     \\/__/         \\/__/         \\/__/         \\/__/         \\/__/         \\/__/         \\/__/         \\/__/         \\/__/    \n
\n\n

isometric3

\n\n
      ___           ___           ___                         ___           ___           ___           ___           ___     \n     /__/\\         /  /\\         /__/\\         _____         /__/\\         /  /\\         /  /\\         /  /\\         /  /\\    \n     \\  \\:\\       /  /::\\       |  |::\\       /  /::\\        \\  \\:\\       /  /::\\       /  /:/_       /  /:/_       /  /::\\   \n      \\__\\:\\     /  /:/\\:\\      |  |:|:\\     /  /:/\\:\\        \\  \\:\\     /  /:/\\:\\     /  /:/ /\\     /  /:/ /\\     /  /:/\\:\\  \n  ___ /  /::\\   /  /:/~/::\\   __|__|:|\\:\\   /  /:/~/::\\   ___  \\  \\:\\   /  /:/~/:/    /  /:/_/::\\   /  /:/ /:/_   /  /:/~/:/  \n /__/\\  /:/\\:\\ /__/:/ /:/\\:\\ /__/::::| \\:\\ /__/:/ /:/\\:| /__/\\  \\__\\:\\ /__/:/ /:/___ /__/:/__\\/\\:\\ /__/:/ /:/ /\\ /__/:/ /:/___\n \\  \\:\\/:/__\\/ \\  \\:\\/:/__\\/ \\  \\:\\~~\\__\\/ \\  \\:\\/:/~/:/ \\  \\:\\ /  /:/ \\  \\:\\/:::::/ \\  \\:\\ /~~/:/ \\  \\:\\/:/ /:/ \\  \\:\\/:::::/\n  \\  \\::/       \\  \\::/       \\  \\:\\        \\  \\::/ /:/   \\  \\:\\  /:/   \\  \\::/~~~~   \\  \\:\\  /:/   \\  \\::/ /:/   \\  \\::/~~~~ \n   \\  \\:\\        \\  \\:\\        \\  \\:\\        \\  \\:\\/:/     \\  \\:\\/:/     \\  \\:\\        \\  \\:\\/:/     \\  \\:\\/:/     \\  \\:\\     \n    \\  \\:\\        \\  \\:\\        \\  \\:\\        \\  \\::/       \\  \\::/       \\  \\:\\        \\  \\::/       \\  \\::/       \\  \\:\\    \n     \\__\\/         \\__\\/         \\__\\/         \\__\\/         \\__\\/         \\__\\/         \\__\\/         \\__\\/         \\__\\/    \n
\n\n

isometric4

\n\n
      ___           ___           ___           ___           ___           ___           ___           ___           ___     \n     /  /\\         /  /\\         /  /\\         /  /\\         /  /\\         /  /\\         /  /\\         /  /\\         /  /\\    \n    /  /:/        /  /::\\       /  /::|       /  /::\\       /  /:/        /  /::\\       /  /::\\       /  /::\\       /  /::\\   \n   /  /:/        /  /:/\\:\\     /  /:|:|      /  /:/\\:\\     /  /:/        /  /:/\\:\\     /  /:/\\:\\     /  /:/\\:\\     /  /:/\\:\\  \n  /  /::\\ ___   /  /::\\ \\:\\   /  /:/|:|__   /  /::\\ \\:\\   /  /:/        /  /::\\ \\:\\   /  /:/  \\:\\   /  /::\\ \\:\\   /  /::\\ \\:\\ \n /__/:/\\:\\  /\\ /__/:/\\:\\_\\:\\ /__/:/_|::::\\ /__/:/\\:\\_\\:| /__/:/     /\\ /__/:/\\:\\_\\:\\ /__/:/_\\_ \\:\\ /__/:/\\:\\ \\:\\ /__/:/\\:\\_\\:\\\n \\__\\/  \\:\\/:/ \\__\\/  \\:\\/:/ \\__\\/  /~~/:/ \\  \\:\\ \\:\\/:/ \\  \\:\\    /:/ \\__\\/~|::\\/:/ \\  \\:\\__/\\_\\/ \\  \\:\\ \\:\\_\\/ \\__\\/~|::\\/:/\n      \\__\\::/       \\__\\::/        /  /:/   \\  \\:\\_\\::/   \\  \\:\\  /:/     |  |:|::/   \\  \\:\\ \\:\\    \\  \\:\\ \\:\\      |  |:|::/ \n      /  /:/        /  /:/        /  /:/     \\  \\:\\/:/     \\  \\:\\/:/      |  |:|\\/     \\  \\:\\/:/     \\  \\:\\_\\/      |  |:|\\/  \n     /__/:/        /__/:/        /__/:/       \\__\\::/       \\  \\::/       |__|:|~       \\  \\::/       \\  \\:\\        |__|:|~   \n     \\__\\/         \\__\\/         \\__\\/            ~~         \\__\\/         \\__\\|         \\__\\/         \\__\\/         \\__\\|    \n
\n\n

italic

\n\n
 )__/_ _  /   _ _ _ _ \n/  /(///)()(// (/(-/  \n              _/      \n
\n\n

ivrit

\n\n
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   _                     _   _ \n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         _ __ ___  __ _ _ __ _   _| |__  _ __ ___   __ _| | | |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | '__/ _ \\/ _` | '__| | | | '_ \\| '_ ` _ \\ / _` | |_| |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | | |  __/ (_| | |  | |_| | |_) | | | | | | (_| |  _  |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |_|  \\___|\\__, |_|   \\__,_|_.__/|_| |_| |_|\\__,_|_| |_|\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |___/                                        \n
\n\n

jazmine

\n\n
 o    o                8                                       \n 8    8                8                                       \no8oooo8 .oPYo. ooYoYo. 8oPYo. o    o oPYo. .oPYo. .oPYo. oPYo. \n 8    8 .oooo8 8' 8  8 8    8 8    8 8  `' 8    8 8oooo8 8  `' \n 8    8 8    8 8  8  8 8    8 8    8 8     8    8 8.     8     \n 8    8 `YooP8 8  8  8 `YooP' `YooP' 8     `YooP8 `Yooo' 8     \n:..:::..:.....:..:..:..:.....::.....:..:::::....8 :.....:..::::\n:::::::::::::::::::::::::::::::::::::::::::::ooP'.:::::::::::::\n:::::::::::::::::::::::::::::::::::::::::::::...:::::::::::::::\n
\n\n

jerusalem

\n\n
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ______ ________   _ ______ ___  ___  __   __._   _   _ _   _ \n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |____  |____  \\ \\ | |____  |_  ||_  | \\ \\ / /| | | | | | | | |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | | _  | |\\ \\| |    | | | |  | |  \\ V / | | | | | | |_| |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | || | |_|_\\ ` |    | | | |__| |___\\  \\ | |/ /_/ /|  _  |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |_|| |  |______|    |_| |_|____|______| |_______/ |_| |_|\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |_|                                                   \n
\n\n

katakana

\n\n
   #       #        ######### ######## ##########                #                          \n  ######## #   ###          #        #          # #########     #      ########## ######### \n #       # ####             #        #         #  #       #    #               #  #       # \n#      ##  #        ########        #  ########   #       #   #               #   #       # \n     ##    #               #      ##       ##     #       #  #     #       # #    #       # \n   ##      #               #    ##       ##       ######### #########       #     ######### \n ##         ####### ########  ##       ##                            #       #              \n
\n\n

kban

\n\n
'||'  '||'                    '||                                               \n ||    ||   ....   .. .. ..    || ...  ... ...  ... ..    ... .   ....  ... ..  \n ||''''||  '' .||   || || ||   ||'  ||  ||  ||   ||' ''  || ||  .|...||  ||' '' \n ||    ||  .|' ||   || || ||   ||    |  ||  ||   ||       |''   ||       ||     \n.||.  .||. '|..'|' .|| || ||.  '|...'   '|..'|. .||.     '||||.  '|...' .||.    \n                                                        .|....'                 \n
\n\n

l4me

\n\n
|-|4mbvrg3r\n
\n\n

larry3d

\n\n
 __  __                       __                                           \n/\\ \\/\\ \\                     /\\ \\                                          \n\\ \\ \\_\\ \\     __      ___ ___\\ \\ \\____  __  __  _ __    __      __   _ __  \n \\ \\  _  \\  /'__`\\  /' __` __`\\ \\ '__`\\/\\ \\/\\ \\/\\`'__\\/'_ `\\  /'__`\\/\\`'__\\\n  \\ \\ \\ \\ \\/\\ \\L\\.\\_/\\ \\/\\ \\/\\ \\ \\ \\L\\ \\ \\ \\_\\ \\ \\ \\//\\ \\L\\ \\/\\  __/\\ \\ \\/ \n   \\ \\_\\ \\_\\ \\__/.\\_\\ \\_\\ \\_\\ \\_\\ \\_,__/\\ \\____/\\ \\_\\\\ \\____ \\ \\____\\\\ \\_\\ \n    \\/_/\\/_/\\/__/\\/_/\\/_/\\/_/\\/_/\\/___/  \\/___/  \\/_/ \\/___L\\ \\/____/ \\/_/ \n                                                        /\\____/            \n                                                        \\_/__/             \n
\n\n

lcd

\n\n
                                       _              \n|   |             |                   | |             \n|-+-|  -    |- -  |-          |-       -|  -    |-    \n|   | | |   | | | | |   | |   |         | |/    |     \n       --          -     --            -   --         \n
\n\n

lean

\n\n
    _/    _/                            _/                                                          \n   _/    _/    _/_/_/  _/_/_/  _/_/    _/_/_/    _/    _/  _/  _/_/    _/_/_/    _/_/    _/  _/_/   \n  _/_/_/_/  _/    _/  _/    _/    _/  _/    _/  _/    _/  _/_/      _/    _/  _/_/_/_/  _/_/        \n _/    _/  _/    _/  _/    _/    _/  _/    _/  _/    _/  _/        _/    _/  _/        _/           \n_/    _/    _/_/_/  _/    _/    _/  _/_/_/      _/_/_/  _/          _/_/_/    _/_/_/  _/            \n                                                                       _/                           \n                                                                  _/_/                              \n
\n\n

letters

\n\n
HH   HH                     bb                                           \nHH   HH   aa aa mm mm mmmm  bb      uu   uu rr rr   gggggg   eee  rr rr  \nHHHHHHH  aa aaa mmm  mm  mm bbbbbb  uu   uu rrr  r gg   gg ee   e rrr  r \nHH   HH aa  aaa mmm  mm  mm bb   bb uu   uu rr     ggggggg eeeee  rr     \nHH   HH  aaa aa mmm  mm  mm bbbbbb   uuuu u rr          gg  eeeee rr     \n                                                    ggggg                \n
\n\n

linux

\n\n
.-. .-..---..-.-.-..--..-..-..---. .---..---..---. \n| |=| || | || | | ||-< | || || |-< | |'_| |- | |-< \n`-' `-'`-^-'`-'-'-'`--'`----'`-'`-'`-'-/`---'`-'`-'\n
\n\n

lockergnome

\n\n
::| ::|          :|                            \n::::::|.::\\ :\\/| ::'| :\\:| :::| /::| :~~/ :::| \n::| ::|`::| :::| :::| `::| :|   \\::| :::, :|   \n                                ,.:/           \n
\n\n

madrid

\n\n
/ \\           |                     \n|=| /=| /=\\=\\ |=\\ | | /= /=| /=\\ /= \n\\ / \\=| | | | |=/ \\=/ |  \\=| \\=  |  \n                         \\=|        \n
\n\n

marquee

\n\n
.::     .::                       .::                                               \n.::     .::                       .::                                               \n.::     .::   .::    .::: .:: .:: .::      .::  .::.: .:::   .::      .::    .: .:::\n.:::::: .:: .::  .::  .::  .:  .::.:: .::  .::  .:: .::    .::  .:: .:   .::  .::   \n.::     .::.::   .::  .::  .:  .::.::   .::.::  .:: .::   .::   .::.::::: .:: .::   \n.::     .::.::   .::  .::  .:  .::.::   .::.::  .:: .::    .::  .::.:         .::   \n.::     .::  .:: .:::.:::  .:  .::.:: .::    .::.::.:::        .::   .::::   .:::   \n                                                            .::                     \n
\n\n

maxfour

\n\n
|  |             |                       \n|--|/~~||/~\\ /~\\ |~~\\|   ||/~\\/~~|/~/|/~\\\n|  |\\__||   |   ||__/ \\_/||   \\__|\\/_|   \n                              \\__|       \n
\n\n

mike

\n\n
 |          |       _     _  _\n |\\ //| ||\\ |/ |/| |  /| |/ | \n                       |      \n
\n\n

mini

\n\n
|_| _.._ _ |_    .__  _ ._ \n| |(_|| | ||_)|_||(_|(/_|  \n                   _|      \n
\n\n

mirror

\n\n
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       _                 _   _ \n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         __ _ ___  _ __ __ _ _   _  __| | ___ __ _ _ __ | | | |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |__` / _ \\| '_ \\__` | | | |/ _` |/ _ ' _` | '_ \\| |_| |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | \\__  | |_) | | | |_| | (_| | | | | | | |_) |  _  |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |_|___/| .__/  |_|_.__/ \\__,_|_| |_| |_|_.__/|_| |_|\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   \\___|                                       \n
\n\n

mnemonic

\n\n
Hamburger\n
\n\n

morse

\n\n
.... .- -- -... ..- .-. --. . .-. \n
\n\n

moscow

\n\n
#   #   #   #   # ####  #   # ####  ##### ##### ####  \n # #   # #  ## ##  #     # #  #   # #   # #     #   # \n  #   ##### # # #  ####   #   ####  #     ####  ####  \n # #  #   # #   #  #  #  #    #     #     #     #     \n#   # #   # #   # ##### #     #     #     ##### #     \n
\n\n

mshebrew210

\n\n
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         \"\"|\"\"|\\  |\"\"|| |\\/|/ |\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           || ' \\/   ||_|_\\|_/ \n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |  -'              \n
\n\n

nancyj-fancy

\n\n
M\"\"MMMMM\"\"MM                     dP                                                    \nM  MMMMM  MM                     88                                                    \nM         `M .d8888b. 88d8b.d8b. 88d888b. dP    dP 88d888b. .d8888b. .d8888b. 88d888b. \nM  MMMMM  MM 88'  `88 88'`88'`88 88'  `88 88    88 88'  `88 88'  `88 88ooood8 88'  `88 \nM  MMMMM  MM 88.  .88 88  88  88 88.  .88 88.  .88 88       88.  .88 88.  ... 88       \nM  MMMMM  MM `88888P8 dP  dP  dP 88Y8888' `88888P' dP       `8888P88 `88888P' dP       \nMMMMMMMMMMMM                                                     .88                   \n                                                             d8888P                    \n
\n\n

nancyj-underlined

\n\n
dP     dP                      dP                                                    \n88     88                      88                                                    \n88aaaaa88a .d8888b. 88d8b.d8b. 88d888b. dP    dP 88d888b. .d8888b. .d8888b. 88d888b. \n88     88  88'  `88 88'`88'`88 88'  `88 88    88 88'  `88 88'  `88 88ooood8 88'  `88 \n88     88  88.  .88 88  88  88 88.  .88 88.  .88 88       88.  .88 88.  ... 88       \ndP     dP  `88888P8 dP  dP  dP 88Y8888' `88888P' dP       `8888P88 `88888P' dP       \nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo~~~~.88~oooooooooooooooooo\n                                                           d8888P                    \n
\n\n

nancyj

\n\n
dP     dP                      dP                                                    \n88     88                      88                                                    \n88aaaaa88a .d8888b. 88d8b.d8b. 88d888b. dP    dP 88d888b. .d8888b. .d8888b. 88d888b. \n88     88  88'  `88 88'`88'`88 88'  `88 88    88 88'  `88 88'  `88 88ooood8 88'  `88 \n88     88  88.  .88 88  88  88 88.  .88 88.  .88 88       88.  .88 88.  ... 88       \ndP     dP  `88888P8 dP  dP  dP 88Y8888' `88888P' dP       `8888P88 `88888P' dP       \n                                                               .88                   \n                                                           d8888P                    \n
\n\n

nipples

\n\n
{__     {__                       {__                                               \n{__     {__                       {__                                               \n{__     {__   {__    {___ {__ {__ {__      {__  {__{_ {___   {__      {__    {_ {___\n{______ {__ {__  {__  {__  {_  {__{__ {__  {__  {__ {__    {__  {__ {_   {__  {__   \n{__     {__{__   {__  {__  {_  {__{__   {__{__  {__ {__   {__   {__{_____ {__ {__   \n{__     {__{__   {__  {__  {_  {__{__   {__{__  {__ {__    {__  {__{_         {__   \n{__     {__  {__ {___{___  {_  {__{__ {__    {__{__{___        {__   {____   {___   \n                                                            {__                     \n
\n\n

ntgreek

\n\n
 _   _               ___                             \n| | | |             / _ \\                            \n| |_| | __  ___   _| |_) )_   _  ___ _   _ ___  ___  \n|  _  |/  \\/ / | | |  _ <| | | |/ _ ( \\ / ) __)/ _ \\ \n| | | ( ()  <| |_| | |_) ) |_| | |_) ) v /> _)| |_) )\n|_| |_|\\__/\\_\\ ._,_|  __/ \\___/|  __/ | | \\___)  __/ \n             | |   | |         | |    | |     | |    \n             |_|   |_|         |_|    |_|     |_|    \n
\n\n

nvscript

\n\n
 ,ggg,        gg                                                                                                  \ndP\"\"Y8b       88                                 ,dPYb,                                                           \nYb, `88       88                                 IP'`Yb                                                           \n `\"  88       88                                 I8  8I                                                           \n     88aaaaaaa88                                 I8  8'                                                           \n     88\"\"\"\"\"\"\"88    ,gggg,gg   ,ggg,,ggg,,ggg,   I8 dP      gg      gg   ,gggggg,    ,gggg,gg   ,ggg,    ,gggggg, \n     88       88   dP\"  \"Y8I  ,8\" \"8P\" \"8P\" \"8,  I8dP   88ggI8      8I   dP\"\"\"\"8I   dP\"  \"Y8I  i8\" \"8i   dP\"\"\"\"8I \n     88       88  i8'    ,8I  I8   8I   8I   8I  I8P    8I  I8,    ,8I  ,8'    8I  i8'    ,8I  I8, ,8I  ,8'    8I \n     88       Y8,,d8,   ,d8b,,dP   8I   8I   Yb,,d8b,  ,8I ,d8b,  ,d8b,,dP     Y8,,d8,   ,d8I  `YbadP' ,dP     Y8,\n     88       `Y8P\"Y8888P\"`Y88P'   8I   8I   `Y88P'\"Y88P\"' 8P'\"Y88P\"`Y88P      `Y8P\"Y8888P\"888888P\"Y8888P      `Y8\n                                                                                         ,d8I'                    \n                                                                                       ,dP'8I                     \n                                                                                      ,8\"  8I                     \n                                                                                      I8   8I                     \n                                                                                      `8, ,8I                     \n                                                                                       `Y8P\"                      \n
\n\n

o8

\n\n
ooooo ooooo                          oooo                                                                  \n 888   888   ooooooo   oo ooo oooo    888ooooo  oooo  oooo  oo oooooo     oooooooo8 ooooooooo8 oo oooooo   \n 888ooo888   ooooo888   888 888 888   888    888 888   888   888    888 888    88o 888oooooo8   888    888 \n 888   888 888    888   888 888 888   888    888 888   888   888         888oo888o 888          888        \no888o o888o 88ooo88 8o o888o888o888o o888ooo88    888o88 8o o888o       888     888  88oooo888 o888o       \n                                                                         888ooo888                         \n
\n\n

octal

\n\n
110 141 155 142 165 162 147 145 162 \n
\n\n

ogre

\n\n
                       _                               \n  /\\  /\\__ _ _ __ ___ | |__  _   _ _ __ __ _  ___ _ __ \n / /_/ / _` | '_ ` _ \\| '_ \\| | | | '__/ _` |/ _ \\ '__|\n/ __  / (_| | | | | | | |_) | |_| | | | (_| |  __/ |   \n\\/ /_/ \\__,_|_| |_| |_|_.__/ \\__,_|_|  \\__, |\\___|_|   \n                                       |___/           \n
\n\n

os2

\n\n
oo____oo___________________oo______________________________________________\noo____oo__ooooo__oo_oo_oo__oooooo__oo____o_oo_ooo___oooo____ooooo__oo_ooo__\noo____oo_oo___oo_ooo_oo__o_oo___oo_oo____o_ooo___o_oo__oo__oo____o_ooo___o_\noooooooo_oo___oo_oo__oo__o_oo___oo_oo____o_oo______oo___o__ooooooo_oo______\noo____oo_oo___oo_oo__oo__o_oo___oo_ooo___o_oo_______oooooo_oo______oo______\noo____oo__oooo_o_oo______o_oooooo__oo_ooo__oo______o____oo__ooooo__oo______\n____________________________________________________ooooo__________________\n
\n\n

pawp

\n\n
 _     _                    _                                     \n(_)   (_)                  (_)            _            ____  _    \n(_)___(_)  ____   __   __  (_)_    _   _ (_)__  ____  (____)(_)__ \n(_______) (____) (__)_(__) (___)_ (_) (_)(____)(____)(_)_(_)(____)\n(_)   (_)( )_( )(_) (_) (_)(_)_(_)(_)_(_)(_)  ( )_(_)(__)__ (_)   \n(_)   (_) (__)_)(_) (_) (_)(____)  (___) (_)   (____) (____)(_)   \n                                              (_)_(_)             \n                                               (___)              \n
\n\n

peaks

\n\n
/^^     /^^                       /^^                                               \n/^^     /^^                       /^^                                               \n/^^     /^^   /^^    /^^^ /^^ /^^ /^^      /^^  /^^/^ /^^^   /^^      /^^    /^ /^^^\n/^^^^^^ /^^ /^^  /^^  /^^  /^  /^^/^^ /^^  /^^  /^^ /^^    /^^  /^^ /^   /^^  /^^   \n/^^     /^^/^^   /^^  /^^  /^  /^^/^^   /^^/^^  /^^ /^^   /^^   /^^/^^^^^ /^^ /^^   \n/^^     /^^/^^   /^^  /^^  /^  /^^/^^   /^^/^^  /^^ /^^    /^^  /^^/^         /^^   \n/^^     /^^  /^^ /^^^/^^^  /^  /^^/^^ /^^    /^^/^^/^^^        /^^   /^^^^   /^^^   \n                                                            /^^                     \n
\n\n

pebbles

\n\n
o      O                  o                                     \nO      o                 O                                      \no      O                 O                                      \nOoOooOOo                 o                                      \no      O .oOoO' `oOOoOO. OoOo. O   o  `OoOo. .oOoO .oOo. `OoOo. \nO      o O   o   O  o  o O   o o   O   o     o   O OooO'  o     \no      o o   O   o  O  O o   O O   o   O     O   o O      O     \no      O `OoO'o  O  o  o `OoO' `OoO'o  o     `OoOo `OoO'  o     \n                                                 O              \n                                              OoO'              \n
\n\n

pepper

\n\n
 /_/_  _ _  /_    __  _  _\n/ //_|/ / //_//_///_//_'/ \n                  _/      \n
\n\n

poison

\n\n
@@@  @@@   @@@@@@   @@@@@@@@@@   @@@@@@@   @@@  @@@  @@@@@@@    @@@@@@@@  @@@@@@@@  @@@@@@@   \n@@@  @@@  @@@@@@@@  @@@@@@@@@@@  @@@@@@@@  @@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@  @@@@@@@@  \n@@!  @@@  @@!  @@@  @@! @@! @@!  @@!  @@@  @@!  @@@  @@!  @@@  !@@        @@!       @@!  @@@  \n!@!  @!@  !@!  @!@  !@! !@! !@!  !@   @!@  !@!  @!@  !@!  @!@  !@!        !@!       !@!  @!@  \n@!@!@!@!  @!@!@!@!  @!! !!@ @!@  @!@!@!@   @!@  !@!  @!@!!@!   !@! @!@!@  @!!!:!    @!@!!@!   \n!!!@!!!!  !!!@!!!!  !@!   ! !@!  !!!@!!!!  !@!  !!!  !!@!@!    !!! !!@!!  !!!!!:    !!@!@!    \n!!:  !!!  !!:  !!!  !!:     !!:  !!:  !!!  !!:  !!!  !!: :!!   :!!   !!:  !!:       !!: :!!   \n:!:  !:!  :!:  !:!  :!:     :!:  :!:  !:!  :!:  !:!  :!:  !:!  :!:   !::  :!:       :!:  !:!  \n::   :::  ::   :::  :::     ::    :: ::::  ::::: ::  ::   :::   ::: ::::   :: ::::  ::   :::  \n :   : :   :   : :   :      :    :: : ::    : :  :    :   : :   :: :: :   : :: ::    :   : :  \n
\n\n

puffy

\n\n
 _   _                    _                                     \n( ) ( )                  ( )                                    \n| |_| |   _ _   ___ ___  | |_    _   _  _ __   __     __   _ __ \n|  _  | /'_` )/' _ ` _ `\\| '_`\\ ( ) ( )( '__)/'_ `\\ /'__`\\( '__)\n| | | |( (_| || ( ) ( ) || |_) )| (_) || |  ( (_) |(  ___/| |   \n(_) (_)`\\__,_)(_) (_) (_)(_,__/'`\\___/'(_)  `\\__  |`\\____)(_)   \n                                            ( )_) |             \n                                             \\___/'             \n
\n\n

pyramid

\n\n
  ^    ^    ^    ^    ^    ^    ^    ^    ^  \n /H\\  /a\\  /m\\  /b\\  /u\\  /r\\  /g\\  /e\\  /r\\ \n<___><___><___><___><___><___><___><___><___>\n
\n\n

rectangles

\n\n
 _____           _                       \n|  |  |___ _____| |_ _ _ ___ ___ ___ ___ \n|     | .'|     | . | | |  _| . | -_|  _|\n|__|__|__,|_|_|_|___|___|_| |_  |___|_|  \n                            |___|        \n
\n\n

relief

\n\n
___________________________________________________________________________________________________\n/~~\\__/~~\\__/~~~~~~\\__/~~\\__/~~\\_/~~~~~~~\\__/~~\\__/~~\\_/~~~~~~~\\___/~~~~~~\\__/~~~~~~~~\\_/~~~~~~~\\__\n/~~\\__/~~\\_/~~\\__/~~\\_/~~~\\/~~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\_______/~~\\__/~~\\_\n/~~~~~~~~\\_/~~~~~~~~\\_/~~~~~~~~\\_/~~~~~~~\\__/~~\\__/~~\\_/~~~~~~~\\__/~~\\_______/~~~~~~\\___/~~~~~~~\\__\n/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\_______/~~\\__/~~\\_\n/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~~~~~~\\___/~~~~~~\\__/~~\\__/~~\\__/~~~~~~~\\_/~~~~~~~~\\_/~~\\__/~~\\_\n________________________________________________________________________/~~\\_______________________\n
\n\n

relief2

\n\n
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n/// \\\\/// \\\\/////// \\\\/// \\\\/// \\//////// \\\\/// \\\\/// \\//////// \\\\\\/////// \\\\///////// \\//////// \\\\\n/// \\\\/// \\/// \\\\/// \\//// //// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\\\\\\\\\\\/// \\\\/// \\\n///////// \\///////// \\/// / /// \\//////// \\\\/// \\\\/// \\//////// \\\\/// \\\\\\\\\\\\\\/////// \\\\\\//////// \\\\\n/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\\\\\\\\\\\/// \\\\/// \\\n/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\//////// \\\\\\/////// \\\\/// \\\\/// \\\\//////// \\///////// \\/// \\\\/// \\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n
\n\n

rev

\n\n
=========================================================================\n=  ====  ===================  ===========================================\n=  ====  ===================  ===========================================\n=  ====  ===================  ===========================================\n=  ====  ===   ===  =  = ===  =====  =  ==  =   ====   ====   ===  =   ==\n=        ==  =  ==        ==    ===  =  ==    =  ==  =  ==  =  ==    =  =\n=  ====  =====  ==  =  =  ==  =  ==  =  ==  ========    ==     ==  ======\n=  ====  ===    ==  =  =  ==  =  ==  =  ==  ==========  ==  =====  ======\n=  ====  ==  =  ==  =  =  ==  =  ==  =  ==  =======  =  ==  =  ==  ======\n=  ====  ===    ==  =  =  ==    ====    ==  ========   ====   ===  ======\n=========================================================================\n
\n\n

roman

\n\n
ooooo   ooooo                              .o8                                                          \n`888'   `888'                             \"888                                                          \n 888     888   .oooo.   ooo. .oo.  .oo.    888oooo.  oooo  oooo  oooo d8b  .oooooooo  .ooooo.  oooo d8b \n 888ooooo888  `P  )88b  `888P\"Y88bP\"Y88b   d88' `88b `888  `888  `888\"\"8P 888' `88b  d88' `88b `888\"\"8P \n 888     888   .oP\"888   888   888   888   888   888  888   888   888     888   888  888ooo888  888     \n 888     888  d8(  888   888   888   888   888   888  888   888   888     `88bod8P'  888    .o  888     \no888o   o888o `Y888\"\"8o o888o o888o o888o  `Y8bod8P'  `V88V\"V8P' d888b    `8oooooo.  `Y8bod8P' d888b    \n                                                                          d\"     YD                     \n                                                                          \"Y88888P'                     \n
\n\n

rot13

\n\n
Unzohetre\n
\n\n

rounded

\n\n
 _     _             _                                  \n(_)   (_)           | |                                 \n _______ _____ ____ | |__  _   _  ____ ____ _____  ____ \n|  ___  (____ |    \\|  _ \\| | | |/ ___) _  | ___ |/ ___)\n| |   | / ___ | | | | |_) ) |_| | |  ( (_| | ____| |    \n|_|   |_\\_____|_|_|_|____/|____/|_|   \\___ |_____)_|    \n                                     (_____|            \n
\n\n

rowancap

\n\n
    dMP dMP .aMMMb  dMMMMMMMMb dMMMMb  dMP dMP dMMMMb  .aMMMMP dMMMMMP dMMMMb \n   dMP dMP dMP\"dMP dMP\"dMP\"dMPdMP\"dMP dMP dMP dMP.dMP dMP\"    dMP     dMP.dMP \n  dMMMMMP dMMMMMP dMP dMP dMPdMMMMK\" dMP dMP dMMMMK\" dMP MMP\"dMMMP   dMMMMK\"  \n dMP dMP dMP dMP dMP dMP dMPdMP.aMF dMP.aMP dMP\"AMF dMP.dMP dMP     dMP\"AMF   \ndMP dMP dMP dMP dMP dMP dMPdMMMMP\"  VMMMP\" dMP dMP  VMMMP\" dMMMMMP dMP dMP    \n
\n\n

rozzo

\n\n
888 888                     888                                               \n888 888  ,\"Y88b 888 888 8e  888 88e  8888 8888 888,8,  e88 888  ,e e,  888,8, \n8888888 \"8\" 888 888 888 88b 888 888b 8888 8888 888 \"  d888 888 d88 88b 888 \"  \n888 888 ,ee 888 888 888 888 888 888P Y888 888P 888    Y888 888 888   , 888    \n888 888 \"88 888 888 888 888 888 88\"   \"88 88\"  888     \"88 888  \"YeeP\" 888    \n                                                        ,  88P                \n                                                       \"8\",P\"                 \n
\n\n

runic

\n\n
|    | \n|\\   | \n| \\  | \n|  \\ | \n|   \\| \n|    | \n
\n\n

runyc

\n\n
|    |                               \n|\\   |                               \n| \\  |                               \n|  \\ | |\\ |\\/| |\\ |\\  |\\ \\ / |\\/| |\\ \n|   \\| |\\ |/\\| |< | | |/  X  |  | |/ \n|    | |  |  | |/ | | |\\ / \\ |  | |\\ \n
\n\n

sblood

\n\n
 @@@  @@@  @@@@@@  @@@@@@@@@@  @@@@@@@  @@@  @@@ @@@@@@@   @@@@@@@  @@@@@@@@ @@@@@@@ \n @@!  @@@ @@!  @@@ @@! @@! @@! @@!  @@@ @@!  @@@ @@!  @@@ !@@       @@!      @@!  @@@\n @!@!@!@! @!@!@!@! @!! !!@ @!@ @!@!@!@  @!@  !@! @!@!!@!  !@! @!@!@ @!!!:!   @!@!!@! \n !!:  !!! !!:  !!! !!:     !!: !!:  !!! !!:  !!! !!: :!!  :!!   !!: !!:      !!: :!! \n  :   : :  :   : :  :      :   :: : ::   :.:: :   :   : :  :: :: :  : :: :::  :   : :\n
\n\n

script

\n\n
 ,                      _                               \n/|   |                 | |                              \n |___|  __,   _  _  _  | |          ,_    __,  _   ,_   \n |   |\\/  |  / |/ |/ | |/ \\_|   |  /  |  /  | |/  /  |  \n |   |/\\_/|_/  |  |  |_/\\_/  \\_/|_/   |_/\\_/|/|__/   |_/\n                                           /|           \n                                           \\|           \n
\n\n

serifcap

\n\n
 _  _   __   __  __  ___  _  _  ___   __  ___  ___  \n( )( ) (  ) (  \\/  )(  ,)( )( )(  ,) / _)(  _)(  ,) \n )__(  /__\\  )    (  ) ,\\ )()(  )  \\( (/\\ ) _) )  \\ \n(_)(_)(_)(_)(_/\\/\\_)(___/ \\__/ (_)\\_)\\__/(___)(_)\\_)\n
\n\n

shadow

\n\n
 |   |                 |                               \n |   |  _` | __ `__ \\  __ \\  |   |  __| _` |  _ \\  __| \n ___ | (   | |   |   | |   | |   | |   (   |  __/ |    \n_|  _|\\__,_|_|  _|  _|_.__/ \\__,_|_|  \\__, |\\___|_|    \n                                      |___/            \n
\n\n

short

\n\n
|_|  ,_ |        _   \n| |(|||||)L||`(|(/_|`\n              _|     \n
\n\n

slant

\n\n
    __  __                __                              \n   / / / /___ _____ ___  / /_  __  ___________ ____  _____\n  / /_/ / __ `/ __ `__ \\/ __ \\/ / / / ___/ __ `/ _ \\/ ___/\n / __  / /_/ / / / / / / /_/ / /_/ / /  / /_/ /  __/ /    \n/_/ /_/\\__,_/_/ /_/ /_/_.___/\\__,_/_/   \\__, /\\___/_/     \n                                       /____/             \n
\n\n

slide

\n\n
##  ||            ##                            \n##  ||##|  ##H H| ##   ## H|## H|#HH| #H| ## H| \n##HH||  H| ### HH|##H| ## H|##H|## H|##HH|##H|  \n##  ||##H| ## H H|## H|## H|##   #HH|##   ##    \n##  ||##HH|##   H|##H|  #HH|##     H| #HH|##    \n                                ##H|            \n
\n\n

slscript

\n\n
 _    ,                                 \n' )  /              /                   \n /--/ __.  ______  /__. . __  _,  _  __ \n/  (_(_/|_/ / / <_/_)(_/_/ (_(_)_</_/ (_\n                              /|        \n                             |/         \n
\n\n

small

\n\n
 _  _            _                          \n| || |__ _ _ __ | |__ _  _ _ _ __ _ ___ _ _ \n| __ / _` | '  \\| '_ \\ || | '_/ _` / -_) '_|\n|_||_\\__,_|_|_|_|_.__/\\_,_|_| \\__, \\___|_|  \n                              |___/         \n
\n\n

smisome1

\n\n
    ___       ___       ___       ___       ___       ___       ___       ___       ___   \n   /\\__\\     /\\  \\     /\\__\\     /\\  \\     /\\__\\     /\\  \\     /\\  \\     /\\  \\     /\\  \\  \n  /:/__/_   /::\\  \\   /::L_L_   /::\\  \\   /:/ _/_   /::\\  \\   /::\\  \\   /::\\  \\   /::\\  \\ \n /::\\/\\__\\ /::\\:\\__\\ /:/L:\\__\\ /::\\:\\__\\ /:/_/\\__\\ /::\\:\\__\\ /:/\\:\\__\\ /::\\:\\__\\ /::\\:\\__\\\n \\/\\::/  / \\/\\::/  / \\/_/:/  / \\:\\::/  / \\:\\/:/  / \\;:::/  / \\:\\:\\/__/ \\:\\:\\/  / \\;:::/  /\n   /:/  /    /:/  /    /:/  /   \\::/  /   \\::/  /   |:\\/__/   \\::/  /   \\:\\/  /   |:\\/__/ \n   \\/__/     \\/__/     \\/__/     \\/__/     \\/__/     \\|__|     \\/__/     \\/__/     \\|__|  \n
\n\n

smkeyboard

\n\n
 ____ ____ ____ ____ ____ ____ ____ ____ ____ \n||H |||a |||m |||b |||u |||r |||g |||e |||r ||\n||__|||__|||__|||__|||__|||__|||__|||__|||__||\n|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|\n
\n\n

smscript

\n\n
 ,                                           \n/|  |  _,         |)         ,_   _,  _  ,_  \n |--| / |  /|/|/| |/\\_|  |  /  | / | |/ /  | \n |  |)\\/|_/ | | |_/\\/  \\/|_/   |/\\/|/|_/   |/\n                                  (|         \n
\n\n

smshadow

\n\n
 |  |             |                          \n __ |  _` |  ` \\   _ \\ |  |  _|_` |  -_)  _| \n_| _|\\__,_|_|_|_|_.__/\\_,_|_|\\__, |\\___|_|   \n                             ____/           \n
\n\n

smslant

\n\n
   __ __           __                        \n  / // /__ ___ _  / /  __ _________ ____ ____\n / _  / _ `/  ' \\/ _ \\/ // / __/ _ `/ -_) __/\n/_//_/\\_,_/_/_/_/_.__/\\_,_/_/  \\_, /\\__/_/   \n                              /___/          \n
\n\n

smtengwar

\n\n
\\  .',  _ _   _ _  ?    _____ ,'    \n/\\  |  |_)_) |_)_) | \\/ (_(_|  | \\/ \n             |       (,     |    (, \n
\n\n

speed

\n\n
______  __                 ______                                    \n___  / / /_____ _______ ______  /_____  _______________ _____________\n__  /_/ /_  __ `/_  __ `__ \\_  __ \\  / / /_  ___/_  __ `/  _ \\_  ___/\n_  __  / / /_/ /_  / / / / /  /_/ / /_/ /_  /   _  /_/ //  __/  /    \n/_/ /_/  \\__,_/ /_/ /_/ /_//_.___/\\__,_/ /_/    _\\__, / \\___//_/     \n                                                /____/               \n
\n\n

stacey

\n\n
__________________________________________________________________\n7  7  77  _  77        77  _  77  7  77  _  77     77     77  _  7\n|  !  ||  _  ||  _  _  ||   __||  |  ||    _||   __!|  ___!|    _|\n|     ||  7  ||  7  7  ||  _  ||  |  ||  _ \\ |  !  7|  __|_|  _ \\ \n|  7  ||  |  ||  |  |  ||  7  ||  !  ||  7  ||     ||     7|  7  |\n!__!__!!__!__!!__!__!__!!_____!!_____!!__!__!!_____!!_____!!__!__!\n
\n\n

stampatello

\n\n
,-_/,.           .                       \n' |_|/ ,-. ,-,-. |-. . . ,-. ,-. ,-. ,-. \n /| |  ,-| | | | | | | | |   | | |-' |   \n `' `' `-^ ' ' ' ^-' `-^ '   `-| `-' '   \n                              ,|         \n                              `'         \n
\n\n

standard

\n\n
 _   _                 _                               \n| | | | __ _ _ __ ___ | |__  _   _ _ __ __ _  ___ _ __ \n| |_| |/ _` | '_ ` _ \\| '_ \\| | | | '__/ _` |/ _ \\ '__|\n|  _  | (_| | | | | | | |_) | |_| | | | (_| |  __/ |   \n|_| |_|\\__,_|_| |_| |_|_.__/ \\__,_|_|  \\__, |\\___|_|   \n                                       |___/           \n
\n\n

starwars

\n\n
 __    __       ___      .___  ___. .______    __    __  .______        _______  _______ .______      \n|  |  |  |     /   \\     |   \\/   | |   _  \\  |  |  |  | |   _  \\      /  _____||   ____||   _  \\     \n|  |__|  |    /  ^  \\    |  \\  /  | |  |_)  | |  |  |  | |  |_)  |    |  |  __  |  |__   |  |_)  |    \n|   __   |   /  /_\\  \\   |  |\\/|  | |   _  <  |  |  |  | |      /     |  | |_ | |   __|  |      /     \n|  |  |  |  /  _____  \\  |  |  |  | |  |_)  | |  `--'  | |  |\\  \\----.|  |__| | |  |____ |  |\\  \\----.\n|__|  |__| /__/     \\__\\ |__|  |__| |______/   \\______/  | _| `._____| \\______| |_______|| _| `._____|\n
\n\n

stellar

\n\n
`..     `..                       `..                                               \n`..     `..                       `..                                               \n`..     `..   `..    `... `.. `.. `..      `..  `..`. `...   `..      `..    `. `...\n`...... `.. `..  `..  `..  `.  `..`.. `..  `..  `.. `..    `..  `.. `.   `..  `..   \n`..     `..`..   `..  `..  `.  `..`..   `..`..  `.. `..   `..   `..`..... `.. `..   \n`..     `..`..   `..  `..  `.  `..`..   `..`..  `.. `..    `..  `..`.         `..   \n`..     `..  `.. `...`...  `.  `..`.. `..    `..`..`...        `..   `....   `...   \n                                                            `..                     \n
\n\n

stop

\n\n
 _     _             _                                  \n| |   | |           | |                                 \n| |__ | | ____ ____ | | _  _   _  ____ ____  ____  ____ \n|  __)| |/ _  |    \\| || \\| | | |/ ___) _  |/ _  )/ ___)\n| |   | ( ( | | | | | |_) ) |_| | |  ( ( | ( (/ /| |    \n|_|   |_|\\_||_|_|_|_|____/ \\____|_|   \\_|| |\\____)_|    \n                                     (_____|            \n
\n\n

straight

\n\n
|__| _  _ |_     _ _  _ _ \n|  |(_|||||_)|_|| (_)(-|  \n                  _/      \n
\n\n

tanja

\n\n
H)    hh                    b)                                              \nH)    hh                    b)                                              \nH)hhhhhh a)AAAA   m)MM MMM  b)BBBB  u)   UU  r)RRR   g)GGG  e)EEEEE  r)RRR  \nH)    hh  a)AAA  m)  MM  MM b)   BB u)   UU r)   RR g)   GG e)EEEE  r)   RR \nH)    hh a)   A  m)  MM  MM b)   BB u)   UU r)      g)   GG e)      r)      \nH)    hh  a)AAAA m)      MM b)BBBB   u)UUU  r)       g)GGGG  e)EEEE r)      \n                                                         GG                 \n                                                    g)GGGG                  \n
\n\n

tengwar

\n\n
`Yb.            db                                    dP\"Yb.                                .dP'            \n  `Yb        db    db                                 `b   'Yb                            dP'               \n    Yb                                                                    \"Ybaaaaaaaaad8'                   \n     Yb        'Yb    `Yb d88b d88b   `Yb d88b d88b      'Yb   `Yb    dP'  .dP'  dP'  88   'Yb   `Yb    dP' \n    dPYb        88     88P   88   8b   88P   8Y   8b      88     Yb  dP    88   88    88    88     Yb  dP   \n  ,dP  Yb       88     88    8P   88   88    8P   88      88      YbdP     Y8   Y8   .88    88      YbdP    \n.dP'    `Yb.   .8P     88  .dP  .dP    88  .dP' .dP'     .8P      .8P      `Y88P`Y88P'88   .8P      .8P     \n                      .888888888888b.  888888888888b.           dP'  b                88          dP'  b    \n                                       88                       Y.  ,P                88          Y.  ,P    \n                                      .8P                        `\"\"'                 Y8.          `\"\"'     \n
\n\n

term

\n\n
Hamburger\n
\n\n

thick

\n\n
8   8                8                               \n8www8 .d88 8d8b.d8b. 88b. 8   8 8d8b .d88 .d88b 8d8b \n8   8 8  8 8P Y8P Y8 8  8 8b d8 8P   8  8 8.dP' 8P   \n8   8 `Y88 8   8   8 88P' `Y8P8 8    `Y88 `Y88P 8    \n                                     wwdP            \n
\n\n

thin

\n\n
|   |          |                             \n|---|,---.,-.-.|---..   .,---.,---.,---.,---.\n|   |,---|| | ||   ||   ||    |   ||---'|    \n`   '`---^` ' '`---'`---'`    `---|`---'`    \n                              `---'          \n
\n\n

threepoint

\n\n
|_| _  _ _ |_     _ _  _  _\n| |(_|| | ||_)|_|| (_|(/_| \n                    _|     \n
\n\n

ticks

\n\n
_/\\/\\____/\\/\\______________________________/\\/\\___________________________________________________________________\n_/\\/\\____/\\/\\__/\\/\\/\\______/\\/\\/\\__/\\/\\____/\\/\\________/\\/\\__/\\/\\__/\\/\\__/\\/\\____/\\/\\/\\/\\____/\\/\\/\\____/\\/\\__/\\/\\_\n_/\\/\\/\\/\\/\\/\\______/\\/\\____/\\/\\/\\/\\/\\/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\/\\__/\\/\\/\\/\\/\\__/\\/\\/\\/\\___\n_/\\/\\____/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__________/\\/\\/\\/\\__/\\/\\________/\\/\\_______\n_/\\/\\____/\\/\\__/\\/\\/\\/\\/\\__/\\/\\______/\\/\\__/\\/\\/\\/\\______/\\/\\/\\/\\__/\\/\\______________/\\/\\____/\\/\\/\\/\\__/\\/\\_______\n_______________________________________________________________________________/\\/\\/\\/\\___________________________\n
\n\n

ticksslant

\n\n
     _/\\/\\____/\\/\\______________________________/\\/\\___________________________________________________________________\n    _/\\/\\____/\\/\\__/\\/\\/\\______/\\/\\/\\__/\\/\\____/\\/\\________/\\/\\__/\\/\\__/\\/\\__/\\/\\____/\\/\\/\\/\\____/\\/\\/\\____/\\/\\__/\\/\\_ \n   _/\\/\\/\\/\\/\\/\\______/\\/\\____/\\/\\/\\/\\/\\/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\/\\__/\\/\\/\\/\\/\\__/\\/\\/\\/\\___  \n  _/\\/\\____/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__________/\\/\\/\\/\\__/\\/\\________/\\/\\_______   \n _/\\/\\____/\\/\\__/\\/\\/\\/\\/\\__/\\/\\______/\\/\\__/\\/\\/\\/\\______/\\/\\/\\/\\__/\\/\\______________/\\/\\____/\\/\\/\\/\\__/\\/\\_______    \n_______________________________________________________________________________/\\/\\/\\/\\___________________________     \n
\n\n

tinker-toy

\n\n
o  o           o                          \n|  |           |                          \nO--O  oo o-O-o O-o  o  o o-o o--o o-o o-o \n|  | | | | | | |  | |  | |   |  | |-' |   \no  o o-o-o o o o-o  o--o o   o--O o-o o   \n                                |         \n                             o--o         \n
\n\n

tombstone

\n\n
 _,_  _, _, _ __, _,_ __,  _, __, __,\n |_| /_\\ |\\/| |_) | | |_) / _ |_  |_)\n | | | | |  | |_) | | | \\ \\ / |   | \\\n ~ ~ ~ ~ ~  ~ ~   `~' ~ ~  ~  ~~~ ~ ~\n
\n\n

trek

\n\n
     dBP dBP dBBBBBb     dBBBBBBb dBBBBb   dBP dBP dBBBBBb    dBBBBb  dBBBP dBBBBBb\n                  BB          dBP    dBP               dBP                      dBP\n   dBBBBBP    dBP BB   dBPdBPdBP dBBBK'  dBP dBP   dBBBBK   dBBBB   dBBP    dBBBBK \n  dBP dBP    dBP  BB  dBPdBPdBP dB' db  dBP_dBP   dBP  BB  dB' BB  dBP     dBP  BB \n dBP dBP    dBBBBBBB dBPdBPdBP dBBBBP' dBBBBBP   dBP  dB' dBBBBBB dBBBBP  dBP  dB' \n
\n\n

tsalagi

\n\n
 __      __   -|-       __           __     ___   ___     __   \n/  '    |  \\   |       `  \\  ,  |~, /  '     |_-_  |     /  '  \n\\_      |   \\  |        _  |@|  |  | ,_   `\\/\\     |_,  | ,_   \n/  _    |   /  | _   |  |  | |  /  | ' |   |  |    | '  | ' |  \n\\__,    |__/    _|    \\_|_/   \\/    \\__/    \\/    _|_    \\__/  \n
\n\n

twopoint

\n\n
|_| _ ._ _ |_    ._(~| _._\n| |(_|| | ||_)|_||  _|}_| \n
\n\n

univers

\n\n
88        88                               88                                                                    \n88        88                               88                                                                    \n88        88                               88                                                                    \n88aaaaaaaa88 ,adPPYYba, 88,dPYba,,adPYba,  88,dPPYba,  88       88 8b,dPPYba,  ,adPPYb,d8  ,adPPYba, 8b,dPPYba,  \n88\"\"\"\"\"\"\"\"88 \"\"     `Y8 88P'   \"88\"    \"8a 88P'    \"8a 88       88 88P'   \"Y8 a8\"    `Y88 a8P_____88 88P'   \"Y8  \n88        88 ,adPPPPP88 88      88      88 88       d8 88       88 88         8b       88 8PP\"\"\"\"\"\"\" 88          \n88        88 88,    ,88 88      88      88 88b,   ,a8\" \"8a,   ,a88 88         \"8a,   ,d88 \"8b,   ,aa 88          \n88        88 `\"8bbdP\"Y8 88      88      88 8Y\"Ybbd8\"'   `\"YbbdP'Y8 88          `\"YbbdP\"Y8  `\"Ybbd8\"' 88          \n                                                                               aa,    ,88                        \n                                                                                \"Y8bbdP\"                         \n
\n\n

usaflag

\n\n
 :::  === :::====  :::=======  :::====  :::  === :::====  :::=====  :::===== :::==== \n :::  === :::  === ::: === === :::  === :::  === :::  === :::       :::      :::  ===\n ======== ======== === === === =======  ===  === =======  === ===== ======   ======= \n ===  === ===  === ===     === ===  === ===  === === ===  ===   === ===      === === \n ===  === ===  === ===     === =======   ======  ===  ===  =======  ======== ===  ===\n
\n\n

weird

\n\n
 /  |           /                            \n(___| ___  _ _ (___       ___  ___  ___  ___ \n|   )|   )| | )|   )|   )|   )|   )|___)|   )\n|  / |__/||  / |__/ |__/ |    |__/ |__  |    \n                              __/            \n
\n\n

whimsy

\n\n
 d8b                               d8b                                                  \n ?88                               ?88                                                  \n  88b                               88b                                                 \n  888888b  d888b8b    88bd8b,d88b   888888b ?88   d8P  88bd88b d888b8b   d8888b  88bd88b\n  88P `?8bd8P' ?88    88P'`?8P'?8b  88P `?8bd88   88   88P'  `d8P' ?88  d8b_,dP  88P'  `\n d88   88P88b  ,88b  d88  d88  88P d88,  d88?8(  d88  d88     88b  ,88b 88b     d88     \nd88'   88b`?88P'`88bd88' d88'  88bd88'`?88P'`?88P'?8bd88'     `?88P'`88b`?888P'd88'     \n                                                                     )88                \n                                                                    ,88P                \n                                                                `?8888P                 \n
\n\n

Toilet fonts

\n\n

ascii12

\n\n
 mm    mm                      mm                                                         \n ##    ##                      ##                                                         \n ##    ##   m#####m  ####m##m  ##m###m   ##    ##   ##m####   m###m##   m####m    ##m#### \n ########   \" mmm##  ## ## ##  ##\"  \"##  ##    ##   ##\"      ##\"  \"##  ##mmmm##   ##\"     \n ##    ##  m##\"\"\"##  ## ## ##  ##    ##  ##    ##   ##       ##    ##  ##\"\"\"\"\"\"   ##      \n ##    ##  ##mmm###  ## ## ##  ###mm##\"  ##mmm###   ##       \"##mm###  \"##mmmm#   ##      \n \"\"    \"\"   \"\"\"\" \"\"  \"\" \"\" \"\"  \"\" \"\"\"     \"\"\"\" \"\"   \"\"        m\"\"\" ##    \"\"\"\"\"    \"\"      \n                                                              \"####\"\"                     \n
\n\n

ascii9

\n\n
 m    m               #                                        \n #    #  mmm   mmmmm  #mmm   m   m   m mm   mmmm   mmm    m mm \n #mmmm# \"   #  # # #  #\" \"#  #   #   #\"  \" #\" \"#  #\"  #   #\"  \"\n #    # m\"\"\"#  # # #  #   #  #   #   #     #   #  #\"\"\"\"   #    \n #    # \"mm\"#  # # #  ##m#\"  \"mm\"#   #     \"#m\"#  \"#mm\"   #    \n                                            m  #               \n                                             \"\"                \n
\n\n

bigascii12

\n\n
 ##    ##                      ##                                                         \n ##    ##                      ##                                                         \n ##    ##                      ##                                                         \n ##    ##   :####    ## #:##:  ##.###:   ##    ##   ##.####   :###:##   .####:    ##.#### \n ##    ##   ######   ########  #######:  ##    ##   #######  .#######  .######:   ####### \n ########   #:  :##  ##.##.##  ###  ###  ##    ##   ###.     ###  ###  ##:  :##   ###.    \n ########    :#####  ## ## ##  ##.  .##  ##    ##   ##       ##.  .##  ########   ##      \n ##    ##  .#######  ## ## ##  ##    ##  ##    ##   ##       ##    ##  ########   ##      \n ##    ##  ## .  ##  ## ## ##  ##.  .##  ##    ##   ##       ##.  .##  ##         ##      \n ##    ##  ##:  ###  ## ## ##  ###  ###  ##:  ###   ##       ###  ###  ###.  :#   ##      \n ##    ##  ########  ## ## ##  #######:   #######   ##       .#######  .#######   ##      \n ##    ##    ###.##  ## ## ##  ##.###:     ###.##   ##        :###:##   .#####:   ##      \n                                                              #.  :##                     \n                                                              ######                      \n                                                              :####:                      \n
\n\n

bigascii9

\n\n
                      #                                        \n #    #               #                                        \n #    #               #                                        \n #    # .###.  ## #   # ##   #   #   #:##:  ## #   ###    #:##:\n #    # #: :#  #:#:#  #   #  #   #   ##  # #   #     :#   ##  #\n ######     #  # # #  #   #  #   #   #     #   #  #   #   #    \n #    # :####  # # #  #   #  #   #   #     #   #  #####   #    \n #    # #:  #  # # #  #   #  #   #   #     #   #  #       #    \n #    # #.  #  # # #  #   #  #:  #   #     #   #      #   #    \n #    # :##:#  # # #  # ##   :##:#   #      ##:#   ###:   #    \n                                               #               \n                                              :#               \n                                            :##.               \n
\n\n

bigmono12

\n\n
 ██    ██                      ██                                                         \n ██    ██                      ██                                                         \n ██    ██                      ██                                                         \n ██    ██   ▒████▓   ██▓█▒██▒  ██░███▒   ██    ██   ██░████   ▒███▒██   ░████▒    ██░████ \n ██    ██   ██████▓  ████████  ███████▒  ██    ██   ███████  ░███████  ░██████▒   ███████ \n ████████   █▒  ▒██  ██░██░██  ███  ███  ██    ██   ███░     ███  ███  ██▒  ▒██   ███░    \n ████████    ▒█████  ██ ██ ██  ██░  ░██  ██    ██   ██       ██░  ░██  ████████   ██      \n ██    ██  ░███████  ██ ██ ██  ██    ██  ██    ██   ██       ██    ██  ████████   ██      \n ██    ██  ██▓░  ██  ██ ██ ██  ██░  ░██  ██    ██   ██       ██░  ░██  ██         ██      \n ██    ██  ██▒  ███  ██ ██ ██  ███  ███  ██▒  ███   ██       ███  ███  ███░  ▒█   ██      \n ██    ██  ████████  ██ ██ ██  ███████▒  ▓███████   ██       ░███████  ░███████   ██      \n ██    ██   ▓███░██  ██ ██ ██  ██░███▒    ▓███░██   ██        ▒███▒██   ░█████▒   ██      \n                                                              █░  ▒██                     \n                                                              ██████▓                     \n                                                              ▒████▒                      \n
\n\n

bigmono9

\n\n
                      █                                        \n █    █               █                                        \n █    █               █                                        \n █    █ ░███░  ██▓█▓  █▓██   █   █   █▒██▒  ██▓█   ███    █▒██▒\n █    █ █▒ ▒█  █▒█▒█  █▓ ▓█  █   █   ██  █ █▓ ▓█  ▓▓ ▒█   ██  █\n ██████     █  █ █ █  █   █  █   █   █     █   █  █   █   █    \n █    █ ▒████  █ █ █  █   █  █   █   █     █   █  █████   █    \n █    █ █▒  █  █ █ █  █   █  █   █   █     █   █  █       █    \n █    █ █░ ▓█  █ █ █  █▓ ▓█  █▒ ▓█   █     █▓ ▓█  ▓▓  █   █    \n █    █ ▒██▒█  █ █ █  █▓██   ▒██▒█   █      ██▒█   ███▒   █    \n                                               █               \n                                            ▓ ▒█               \n                                            ▒██░               \n
\n\n

circle

\n\n
Ⓗⓐⓜⓑⓤⓡⓖⓔⓡ\n
\n\n

emboss

\n\n
┃ ┃┏━┃┏┏ ┏━ ┃ ┃┏━┃┏━┛┏━┛┏━┃\n┏━┃┏━┃┃┃┃┏━┃┃ ┃┏┏┛┃ ┃┏━┛┏┏┛\n┛ ┛┛ ┛┛┛┛━━ ━━┛┛ ┛━━┛━━┛┛ ┛\n
\n\n

emboss2

\n\n
║ ║╔═║╔╔ ╔═ ║ ║╔═║╔═╝╔═╝╔═║\n╔═║╔═║║║║╔═║║ ║╔╔╝║ ║╔═╝╔╔╝\n╝ ╝╝ ╝╝╝╝══ ══╝╝ ╝══╝══╝╝ ╝\n
\n\n

future

\n\n
╻ ╻┏━┓┏┳┓┏┓ ╻ ╻┏━┓┏━╸┏━╸┏━┓\n┣━┫┣━┫┃┃┃┣┻┓┃ ┃┣┳┛┃╺┓┣╸ ┣┳┛\n╹ ╹╹ ╹╹ ╹┗━┛┗━┛╹┗╸┗━┛┗━╸╹┗╸\n
\n\n

letter

\n\n
H   H   A   M   M BBBB  U   U RRRR   GGG  EEEEE RRRR  \nH   H  A A  MM MM B   B U   U R   R G     E     R   R \nHHHHH AAAAA M M M BBBB  U   U RRRR  G GG  EEEE  RRRR  \nH   H A   A M   M B   B U   U R  R  G   G E     R  R  \nH   H A   A M   M BBBB   UUU  R   R  GGG  EEEEE R   R \n
\n\n

mono12

\n\n
 ▄▄    ▄▄                      ▄▄                                                         \n ██    ██                      ██                                                         \n ██    ██   ▄█████▄  ████▄██▄  ██▄███▄   ██    ██   ██▄████   ▄███▄██   ▄████▄    ██▄████ \n ████████   ▀ ▄▄▄██  ██ ██ ██  ██▀  ▀██  ██    ██   ██▀      ██▀  ▀██  ██▄▄▄▄██   ██▀     \n ██    ██  ▄██▀▀▀██  ██ ██ ██  ██    ██  ██    ██   ██       ██    ██  ██▀▀▀▀▀▀   ██      \n ██    ██  ██▄▄▄███  ██ ██ ██  ███▄▄██▀  ██▄▄▄███   ██       ▀██▄▄███  ▀██▄▄▄▄█   ██      \n ▀▀    ▀▀   ▀▀▀▀ ▀▀  ▀▀ ▀▀ ▀▀  ▀▀ ▀▀▀     ▀▀▀▀ ▀▀   ▀▀        ▄▀▀▀ ██    ▀▀▀▀▀    ▀▀      \n                                                              ▀████▀▀                     \n
\n\n

mono9

\n\n
 ▄    ▄               █                                        \n █    █  ▄▄▄   ▄▄▄▄▄  █▄▄▄   ▄   ▄   ▄ ▄▄   ▄▄▄▄   ▄▄▄    ▄ ▄▄ \n █▄▄▄▄█ ▀   █  █ █ █  █▀ ▀█  █   █   █▀  ▀ █▀ ▀█  █▀  █   █▀  ▀\n █    █ ▄▀▀▀█  █ █ █  █   █  █   █   █     █   █  █▀▀▀▀   █    \n █    █ ▀▄▄▀█  █ █ █  ██▄█▀  ▀▄▄▀█   █     ▀█▄▀█  ▀█▄▄▀   █    \n                                            ▄  █               \n                                             ▀▀                \n
\n\n

pagga

\n\n
░█░█░█▀█░█▄█░█▀▄░█░█░█▀▄░█▀▀░█▀▀░█▀▄\n░█▀█░█▀█░█░█░█▀▄░█░█░█▀▄░█░█░█▀▀░█▀▄\n░▀░▀░▀░▀░▀░▀░▀▀░░▀▀▀░▀░▀░▀▀▀░▀▀▀░▀░▀\n
\n\n

smascii12

\n\n
., .,          .,                            \n][ ][          ][                            \n][ ][ dWW,]WbW,]bWb ][ ][ WdW[ dWd[ dWb  WdW[\n]WWW[ `md[][W][]P T[][ ][ W`  ]P T[]bmd[ W`  \n][ ][.W\"T[][W][][ ][][ ][ W   ][ ][]P\"\"` W   \n][ ][]bmW[][W][]WmW`]bmW[ W   'WmW['Wmm[ W   \n'` '` \"\"'`'`\"'`'`\"`  \"\"'` \"    /\"][ '\"\"  \"   \n                               TWP`          \n
\n\n

smascii9

\n\n
.  ,        ]                       \n]  [ m, .mm ]m, . .  ,m  mm  m,  ,m \n]mm[' ] ]]] ]`T ] ]  P `]`T ]`]  P `\n]  [.\"T ]]] ] ] ] ]  [  ] ] ]\"\"  [  \n]  ['mT ]]] ]bP 'mT  [  'bT 'b/  [  \n                         ,]         \n                         '`         \n
\n\n

smblock

\n\n
▌ ▌       ▌                 \n▙▄▌▝▀▖▛▚▀▖▛▀▖▌ ▌▙▀▖▞▀▌▞▀▖▙▀▖\n▌ ▌▞▀▌▌▐ ▌▌ ▌▌ ▌▌  ▚▄▌▛▀ ▌  \n▘ ▘▝▀▘▘▝ ▘▀▀ ▝▀▘▘  ▗▄▘▝▀▘▘  \n
\n\n

smbraille

\n\n
 ⣇⣸ ⢀⣀ ⣀⣀  ⣇⡀ ⡀⢀ ⡀⣀ ⢀⡀ ⢀⡀ ⡀⣀\n ⠇⠸ ⠣⠼ ⠇⠇⠇ ⠧⠜ ⠣⠼ ⠏  ⣑⡺ ⠣⠭ ⠏ \n
\n\n

smmono12

\n\n
▗▖ ▗▖          ▗▖                            \n▐▌ ▐▌          ▐▌                            \n▐▌ ▐▌ ▟██▖▐█▙█▖▐▙█▙ ▐▌ ▐▌ █▟█▌ ▟█▟▌ ▟█▙  █▟█▌\n▐███▌ ▘▄▟▌▐▌█▐▌▐▛ ▜▌▐▌ ▐▌ █▘  ▐▛ ▜▌▐▙▄▟▌ █▘  \n▐▌ ▐▌▗█▀▜▌▐▌█▐▌▐▌ ▐▌▐▌ ▐▌ █   ▐▌ ▐▌▐▛▀▀▘ █   \n▐▌ ▐▌▐▙▄█▌▐▌█▐▌▐█▄█▘▐▙▄█▌ █   ▝█▄█▌▝█▄▄▌ █   \n▝▘ ▝▘ ▀▀▝▘▝▘▀▝▘▝▘▀▘  ▀▀▝▘ ▀    ▞▀▐▌ ▝▀▀  ▀   \n                               ▜█▛▘          \n
\n\n

smmono9

\n\n
▗  ▖        ▐                       \n▐  ▌ ▄▖ ▗▄▄ ▐▄▖ ▗ ▗  ▖▄  ▄▄  ▄▖  ▖▄ \n▐▄▄▌▝ ▐ ▐▐▐ ▐▘▜ ▐ ▐  ▛ ▘▐▘▜ ▐▘▐  ▛ ▘\n▐  ▌▗▀▜ ▐▐▐ ▐ ▐ ▐ ▐  ▌  ▐ ▐ ▐▀▀  ▌  \n▐  ▌▝▄▜ ▐▐▐ ▐▙▛ ▝▄▜  ▌  ▝▙▜ ▝▙▞  ▌  \n                         ▖▐         \n                         ▝▘         \n
\n\n

wideterm

\n\n
Hamburger\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-06-14" },{ "id": "find", "title": "Find", "url": "/find", "category": "CLI", "keywords": null, "content_html": "

Usage

\n\n
find <path> <conditions> <actions>\n
\n\n

Conditions

\n\n
-name \"*.c\"\n
\n\n
-user jonathan\n-nouser\n
\n\n
-type f            # File\n-type d            # Directory\n-type l            # Symlink\n
\n\n
-depth 2           # At least 3 levels deep\n-regex PATTERN\n
\n\n
-size 8            # Exactly 8 512-bit blocks \n-size -128c        # Smaller than 128 bytes\n-size 1440k        # Exactly 1440KiB\n-size +10M         # Larger than 10MiB\n-size +2G          # Larger than 2GiB\n
\n\n
-newer   file.txt\n-newerm  file.txt        # modified newer than file.txt\n-newerX  file.txt        # [c]hange, [m]odified, [B]create\n-newerXt \"1 hour ago\"    # [t]imestamp\n
\n\n

Access time conditions

\n\n
-atime 0           # Last accessed between now and 24 hours ago\n-atime +0          # Accessed more than 24 hours ago\n-atime 1           # Accessed between 24 and 48 hours ago\n-atime +1          # Accessed more than 48 hours ago\n-atime -1          # Accessed less than 24 hours ago (same a 0)\n-ctime -6h30m      # File status changed within the last 6 hours and 30 minutes\n-mtime +1w         # Last modified more than 1 week ago\n
\n\n

These conditions only work in MacOS and BSD-like systems (no GNU/Linux support).

\n\n

Condition flow

\n\n
\\! -name \"*.c\"\n\\( x -or y \\)\n
\n\n

Actions

\n\n
-exec rm {} \\;\n-print\n-delete\n
\n\n

Examples

\n\n
find . -name '*.jpg'\nfind . -name '*.jpg' -exec rm {} \\;\n
\n\n
find . -newerBt \"24 hours ago\"\n
\n\n
find . -type f -mtime +29 # find files modified more than 30 days ago\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2019-11-17" },{ "id": "firebase", "title": "Firebase", "url": "/firebase", "category": "Others", "keywords": null, "content_html": "

Authenticating

\n\n
FB = new Firebase('https://xxx.firebase.io')\nFB.auth(TOKEN, (err, result) => { ···})\n
\n\n
FB.authAnonymously(···)\nFB.authWithPassword(···)\nFB.authWithOAuthPopup(···)\nFB.authWithOAuthToken(···)\n
\n\n

Using

\n\n
Users = FB.child('users')\n
\n\n
// Create\nuser = Users.push(first: \"Frank\", last: \"Sinatra\")\n
\n\n
// Retrieve\nuser = Users.child('alan')  // gets `users/alan`\n
\n\n
// Update\nuser.set(first: \"Miles\", last: \"Davis\")\nuser.update(first: \"Miles\")\nuser.setWithPriority({ ··· }, priority)\n
\n\n
// Destroy\nuser.remove()\n
\n\n
// Getting\nuser.name()  // primary id\n\nuser.once('value', (snap) => {\n  snap.name()  // primary id\n  snap.val()   // value\n}, (err) => {\n  ···\n})\n
\n\n
// traversal\nuser.parent()\n
\n\n

Querying

\n\n
Users = FB.child('users')\nUsers\n  .startAt(1000)\n  .limit(50)\n  .equalTo(priority, [name])\n  .on 'child_added', (snap) -> ···\n
\n

Lists

\n\n
Posts = FB.child('posts')\npost = Posts.push({ title: \"How to do things\", author: \"alan\" })\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "firefox", "title": "Firefox", "url": "/firefox", "category": "Others", "keywords": null, "content_html": "

Firefox 31 (July 2014)

\n\n\n\n

Firefox 30 (June 2014)

\n\n\n\n

Firefox 29 (April 2014)

\n\n\n\n

Firefox 18 (Jan 2013)

\n\n\n\n

Firefox 17 (Nov 2012)

\n\n\n\n

Firefox 16 (Oct 2012)

\n\n\n\n

Firefox 15 (Aug 2012)

\n\n\n\n

Firefox 14 (Jul 2012)

\n\n\n\n

Firefox 13 (Jun 2012)

\n\n\n\n

Firefox 12 (Apr 2012)

\n\n\n\n

Firefox 11 (Mar 2012)

\n\n\n\n

Firefox 10 (Jan 2012)

\n\n\n\n

Firefox 9 (Dec 2011)

\n\n\n\n

Firefox 8 (Nov 2011)

\n\n

Firefox 7 (Sep 2011)

\n\n\n\n

Firefox 6 (Aug 2011)

\n\n\n\n

Firefox 5 (Jun 2011)

\n\n\n\n

Firefox 4 (Mar 2011)

\n\n\n\n

Firefox 3.6 (Jan 2010)

\n\n\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "fish-shell", "title": "Fish shell", "url": "/fish-shell", "category": "CLI", "keywords": null, "content_html": "

Keys

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
Alt ← / Alt →Move word
^UDelete to beginning
^WDelete to previous /
^DDelete next character
Alt DDelete next word
^CCancel line
Alt PPage output
Alt ↑ / Alt ↓Previous / next arguments
Alt E / Alt VOpen in external editor
^LRepaint screen
\n\n

Help

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Alt HHelp on word (man)
Alt WHelp on word (short descriptions)
Alt LList directory on cursor
\n\n

Function

\n\n

Writing functions

\n\n
function my_function --description \"My description\"\n  ···\nend\n
\n\n

Conditional

\n\n
if test -f foo.txt\n  ···\nelse if test -f bar.txt\n  ···\nelse\n  ···\nend\n
\n\n

Combining tests

\n\n
if test -f foo.txt && test -f bar.txt\n
\n\n
if test -f foo.txt -a -f bar.txt\n
\n\n
if test \\( -f foo.txt \\) -a -f \\( bar.txt \\)\n
\n\n

Events

\n\n

Emitting

\n\n
emit my_event\n
\n\n

Listening

\n\n
function myhook --on-event my_event\n  ···\nend\n
\n\n

This lets you hook onto events, such as fish_prompt.

\n\n

Completions

\n\n

Creating completions

\n\n

~/.fish/completions/mycommand.fish

\n\n
complete -c mycommand ...\ncomplete -c mycommand ...\ncomplete -c mycommand ...\n
\n\n

Options

\n\n
complete \\\n  -c                         # command\n  -s                         # short option\n  -l                         # long option\n  -r, --require-parameter\n  -f, --no-files\n  -x                         # exclusive (-r -f)\n  -n '__fish_use_subcommand' # condition\n  --description \"..\"\n
\n\n

Example

\n\n
  complete -c $cmd \\\n-n '__fish_use_subcommand' \\\n-x -a hello \\\n--description 'lol'\n
\n\n

Conditions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConditionDescription
-n __fish_complete_directories STRING DESCRIPTIONperforms path completion on STRING, allowing only directories, and giving them the description DESCRIPTION.
-n __fish_complete_path STRING DESCRIPTIONperforms path completion on STRING, giving them the description DESCRIPTION.
-n __fish_complete_groupsprints a list of all user groups with the groups members as description.
-n __fish_complete_pidsprints a list of all processes IDs with the command name as description.
-n __fish_complete_suffix SUFFIXperforms file completion allowing only files ending in SUFFIX. The mimetype database is used to find a suitable description.
-n __fish_complete_usersprints a list of all users with their full name as description.
-n __fish_print_filesystemsprints a list of all known file systems. Currently, this is a static list, and not dependent on what file systems the host operating system actually understands.
-n __fish_print_hostnamesprints a list of all known hostnames. This functions searches the fstab for nfs servers, ssh for known hosts and checks the /etc/hosts file.
-n __fish_print_interfacesprints a list of all known network interfaces.
-n __fish_print_packagesprints a list of all installed packages. This function currently handles Debian, rpm and Gentoo packages.
-n __fish_use_subcommand 
-n __fish_seen_subcommand_from init 
\n\n

Example

\n\n
complete -c ruby -s X -x -a '(__fish_complete_directories (commandline -ct))' --description 'Directory'\n
\n\n

Examples

\n\n

Start each example with complete -c cmdname

\n\n
-x\n  # no filename completion\n
\n\n
-s d -x -a \"read skip\"\n  # -d {read|skip}\n
\n\n
-s d -x\n  # -d <something>\n
\n\n
-s f -r\n  # -f FILE\n
\n\n
-s f -l force\n  # -f, --force\n
\n\n
-a \"(cat /etc/passwd | cut -d : -f 1)\"\n  # first argument as filename\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-01-31" },{ "id": "flashlight", "title": "Flashlight", "url": "/flashlight", "category": "Apps", "keywords": null, "content_html": "

Commands

\n\n

Events and reminders

\n\n\n\n

DuckDuckGo

\n\n\n\n

System

\n\n\n\n

Emoji

\n\n\n\n

Web search

\n\n\n\n

Prefix with / to do a web search.

\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "flow", "title": "Flow", "url": "/flow", "category": "JavaScript libraries", "keywords": null, "content_html": "

Getting started

\n\n

Simple example

\n\n
/* @flow */\nfunction square (n: number) {\n  return n * n\n}\n\nconst four = square(2)\n
\n\n

Most of what you need to do is to simply add annotations to function arguments!

\n\n

See: flow.org docs

\n\n

Type inference

\n\n
function square (n: number) {\n  const result = n * n\n}\n
\n\n

result is inferred to be a number because number * number will result in a number. There’s no need to give it annotations.

\n\n

Type aliases

\n\n
type Person = {\n  name: string,\n  age: number,\n  isAdmin: boolean,\n  likes: Array<string>\n}\n
\n\n
function greet(user: Person) {\n  console.log('hello', user.name)\n}\n
\n\n
greet({ name: 'Miles Davis', ··· })\n
\n\n

This is the typical way to define the shape of complex objects.

\n\n

Variables

\n\n
const count: number = 200\n
\n\n

You typically don’t need to do this, function args are often enough.

\n\n

See: Variable types

\n\n

Importing and exporting

\n\n
import type { Person } from './types'\n
\n\n
export type Person = {\n  ···\n}\n
\n\n

See: Module types

\n\n

Union types

\n\n
type Action = number | string\n
\n\n
type Direction = 'left' | 'right'\n
\n\n

See: Unions

\n\n

Optionals

\n\n

Maybe types

\n\n
type Album = {\n  name: ?string\n}\n
\n\n
const a: Album = { }                 // ✗ Error\nconst a: Album = { name: 'Blue' }    // ✓ OK\nconst a: Album = { name: null }      // ✓ OK\nconst a: Album = { name: undefined } // ✓ OK\n
\n\n

This makes name either a string or null.

\n\n

See: Maybe types

\n\n

Optional properties

\n\n
type Album = {\n  name?: string\n}\n
\n\n
const a: Album = { } // ✓ OK\na.name = 'Blue'      // ✓ OK\na.name = null        // ✗ Error\na.name = undefined   // ✓ OK\n
\n\n

This makes an Album valid even if name is not part of the keys. This is different from “maybe” types.

\n\n

See: Optional properties

\n\n

Objects

\n\n

Width subtyping

\n\n
type Artist = {\n  name: string,\n  label: string\n}\n
\n\n
const a: Artist = {\n  name: 'Miguel Migs',\n  label: 'Naked Music',\n  genre: 'House' // ✓ OK\n}\n
\n\n

A type with more properties is “wider” and is a subtype of a “narrower” type.

\n\n

See: Width subtyping

\n\n

Exact object types

\n\n
type Artist = {|\n  name: string,\n  label: string\n|}\n
\n\n
const a: Artist = {\n  name: 'Miguel Migs',\n  label: 'Naked Music',\n  genre: 'House' // ✗ Error\n}\n
\n\n

Exact object types prevent extra properties from being added to an object.

\n\n

See: Exact object types

\n\n

Dynamic keys

\n\n
type Items = {\n  [key: string]: Item\n}\n
\n\n

See: Dynamic object keys

\n\n

Advanced features

\n\n

Primitives

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TypeDescription
any 
boolean 
mixed 
number 
string 
voidundefined
nullnull (but not undefined)
{a: Number}Object with a shape
[any, number]Tuples (fixed-length arrays)
Array<T> 
Class<T> 
Function 
Object 
?numberMaybe (number, void, null)
a | bUnion types
\n\n

Enums

\n\n
type Suit = \"Diamonds\" | \"Clubs\" | \"Hearts\" | \"Spades\"\n\nconst countries = {\n  US: \"United States\",\n  IT: \"Italy\",\n  FR: \"France\"\n}\n\ntype Country = $Keys<typeof countries>\n
\n\n

See: Enums

\n\n

Type aliases

\n\n
type Tree = {\n  foo: string,\n  bar: number,\n  qux: (foo: string, bar: number) => boolean\n}\n\ntype Generic<T> = {\n  foo: T\n}\n
\n\n

See: Type aliases

\n\n

Generic classes

\n\n
class GenericClass<T> {\n  x: T\n  constructor (x: T) { ... }\n}\n\nvar n: GenericClass<number> = new GenericClass(0)\n
\n\n

See: Generic classes

\n\n

Interfaces

\n\n
interface Jsonable {\n  toJSON(): string\n}\n\nclass Foo {\n  toJSON() { return '{}' }\n}\n\n(new Foo: Jsonable)\n
\n\n

See: Interfaces

\n\n

Functions

\n\n
const callback: () => void = function () {}\n
\n\n
function filter<T> (\n  list: Array<T>,\n  callback: (item: T) => boolean\n): Array<T> {\n  ···\n}\n
\n\n

See: Functions

\n\n

Imports

\n\n
import type { Person } from '../person'\nimport typeof Config from '../config'\n
\n\n
export type Person = { id: string }\n
\n\n

Comment syntax

\n\n
/*::\n  export type Foo = { ... }\n*/\n\nfunction add(n /*: number */) { ... }\n
\n\n

React

\n\n
type Props = {\n  bar: number,\n}\n\ntype State = {\n  open: boolean,\n}\n\nclass Foo extends React.Component<Props, State> {\n  // Component code\n}\n
\n\n

Examples

\n\n

Examples

\n\n
var myNumbers: Array<number> = [42]\nfunction foo(): any { return 42 }\nvar b: boolean = false\nvar b: ?boolean = false  /* maybe */\nvar b: string | boolean = false\n\nvar a: Class<MyClass> = MyClass\nvar b: MyClass = new a()\n
\n\n

Function signature

\n\n
type Callback = (?Error, string) => any\n\nfunction fetch (callback: Callback) {\n  ···\n}\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2020-07-05" },{ "id": "flux", "title": "Flux architecture", "url": "/flux", "category": "React", "keywords": null, "content_html": "

Architecture

\n\n\n\n
\n\n

Dispatcher

\n\n

Pub-sub

\n

A dispatcher emits events (.dispatch()) to its listeners (.register(fn)).

\n\n
var Dispatcher = require('flux').Dispatcher;\n\nd = new Dispatcher();\n\n// send\nd.dispatch({ action: 'edit', ... };\n\n// receive\ntoken = d.register(function (payload) {\n  payload.action === 'edit'\n})\n
\n\n

Ensuring proper order

\n\n

With multiple listeners, you can ensure one is fired after another using .waitFor().

\n\n
token1 = d.register(...);\n\ntoken2 = d.register(function (payload) {\n\n  // ensure receiver 1 is fired before this\n  d.waitFor([ token1 ]);\n  \n  // process here\n})\n
\n\n

Subclassing

\n\n

Object.assign is the preferred way to subclass Dispatcher (think $.extend).
\nYou can also make action creators, which are shortcuts for dispatch().

\n\n
var Dispatcher = require('flux').Dispatcher;\nvar assign = require('object-assign');\n\nvar AppDispatcher = assign({}, Dispatcher.prototype, {\n\n  // action creator\n  handleViewAction(action) {\n    this.dispatch({\n      source: 'VIEW_ACTION',\n      action: action\n    })\n  } \n\n})\n
\n\n
\n\n

Stores

\n\n

Plain objects

\n

Stores are just like objects.

\n\n
var TodoStore = { list: [] };\n
\n\n

Events

\n

Sometimes they’re eventemitters, too. Usually it’s used to emit change events for views to pick up.

\n\n
var TodoStore = assign({}, EventEmitter.prototype, {\n  ...\n});\n\nTodoStore.emit('change');\nTodoStore.on('change', function () { ... });\n
\n\n

Model logic

\n

Logic can sometimes belong in stores.

\n\n
{\n  isAllActive() {\n    return this.list.every(item => item.active);\n  }\n}\n
\n\n
\n\n

Stores and dispatchers

\n\n

Instantiate

\n

Make a Dispatcher and Stores.

\n\n
d = new Dispatcher();\nTabStore = { tab: 'home' };\n
\n\n

Updating data

\n

Dispatch events to alter the store.

\n\n
d.dispatch({ action: 'tab.change', tab: 'timeline' });\n\nd.register(function (data) {\n  if (data.action === 'tab.change') {\n    TabStore.tab = data.tab;\n  }\n});\n
\n\n
\n\n

With Views

\n\n

Listen to dispatchers

\n

Views (React Components) can listen to Dispatchers.

\n\n
var TodoApp = React.createClass({\n\n  componentDidMount() {\n    this.token = AppDispatcher.register((payload) => {\n      switch (payload.action) {\n        case 'tab.change':\n          this.render();\n          // ...\n      }\n    });\n  },\n  \n  componentDidUnmount() {\n    AppDispatcher.unregister(this.token);\n  }\n  \n});\n
\n\n

Listen to Stores

\n

Or to Stores’s change events.

\n\n
{\n  componentDidMount() {\n    TodoStore.on('change', this.onChange);\n  },\n  \n  componentDidUnmount() {\n    TodoState.removeListener('change', this.onChange);\n  },\n  \n  onChange(data) {\n    // ...\n  }\n}\n
\n\n
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "flynn", "title": "Flynn", "url": "/flynn", "category": "Devops", "keywords": null, "content_html": "

General workflow

\n\n\n\n

Creating a cluster (AWS)

\n\n
flynn install  # (provisions AWS EC2 stuff)\nflynn key add  # (adds your pubkey to AWS)\n
\n\n

What it does

\n\n\n\n

Using a flynn cluster

\n\n

Managed in ~/.flynnrc:

\n\n
flynn cluster\nflynn cluster add [-g githost] [-p pin] NAME URL KEY\nflynn cluster remove NAME\nflynn cluster default NAME # use this current\n
\n\n

Setting up a new app

\n\n
cd ~/project\nflynn create example # adds the `flynn` remote\nflynn route # prints http routes\ngit push flynn master\n
\n\n

Commands

\n\n

Environment vars

\n\n
flynn env\nflynn env set FOO=bar BAZ=foobar\nflynn env unset FOO\n
\n\n

Scale

\n\n
flynn ps\nflynn scale web=3\n
\n\n

Logs

\n\n
flynn log\nflynn log flynn-d55c7a...\n
\n\n

Running commands

\n\n
flynn run rake db:migrate\n
\n\n

Manage routes

\n\n
flynn route\nflynn route add http example.com\n# then make a CNAME from example.com to myapp.xxxx.flynnhub.com\n
\n\n

More

\n\n
flynn ps\nflynn kill <job>\n\nflynn meta\nflynn meta set foo=baz\n
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "freenode", "title": "Freenode", "url": "/freenode", "category": "Others", "keywords": null, "content_html": "

IRC server

\n\n
irc.freenode.net\n
\n\n

NickServ commands

\n\n
/msg nickserv identify [nick] <password>\n/msg nickserv info <nick>\n
\n\n

Add a nick

\n\n
/nick newnick\n/msg nickserv identify <oldnick> <password>\n/msg nickserv group\n
", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "frequency-separation-retouching", "title": "Frequency separation retouching", "url": "/frequency-separation-retouching", "category": "Others", "keywords": null, "content_html": "

Frequency separation retouching in Photoshop

\n\n

Duplicate the layer twice. Perform these in each layer:

\n\n

Lower layer

\n\n\n\n

Upper layer

\n\n\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "fitness/general", "title": "General fitness notes", "url": "/fitness/general", "category": "Fitness", "keywords": null, "content_html": "

Target heart rate

\n\n
max heart rate = (220 - age)\n
\n\n

“The target heart rate method is a simple formula: take 220 and minus your age.\nThen take that number and multiply it by .75 - .85, which will give you your\npercentages of 75% – 85% of your Max. HR.”

\n\n

See: http://www.bodybuilding.com/fun/mike1.htm

\n\n

Warmup sets

\n\n\n\n

See: http://corw.in/warmup/

\n\n

Bench

\n\n

Jennifer Thompson video: http://www.youtube.com/watch?v=34XRmd3a8_0

\n\n

Metabolism

\n\n\n\n

See: Substrates (exrx.net)

\n\n

Deloads on a cut

\n\n\n\n

See: Link (facebook.com)

\n\n

Conditioning with 5/3/1

\n\n\n\n

See: 531 and Bodybuilding (jimwendler.com)

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "gh-pages", "title": "GitHub pages", "url": "/gh-pages", "category": "Jekyll", "keywords": null, "content_html": "

Custom domains

\n\n

Custom domains

\n\n
$ echo \"foobar.com\" > CNAME\n$ git commit && git push\n
\n\n

Create a CNAME file with your domain on it.

\n\n

See: Setting up a custom domain (github.com)

\n\n

Set up your domain

\n\n

Subdomain (like www):

\n\n
 CNAME => username.github.io\n
\n\n

Apex domains:

\n\n
 ALIAS => username.github.io\n
\n\n

Apex domains (alternative):

\n\n
A => 192.30.252.153\nA => 192.30.252.154\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "git-branch", "title": "Git branches", "url": "/git-branch", "category": "Git", "keywords": null, "content_html": "

Working with branches

\n\n

Creating

\n\n
git checkout -b $branchname\ngit push origin $branchname --set-upstream\n
\n\n

Creates a new branch locally then pushes it.

\n\n

Getting from remote

\n\n
git fetch origin\ngit checkout --track origin/$branchname\n
\n\n

Gets a branch in a remote.

\n\n

Delete local remote-tracking branches

\n\n
git remote prune origin\n
\n\n

Deletes origin/* branches in your local copy. Doesn’t affect the remote.

\n\n

List existing branches

\n\n
git branch --list\n
\n\n

Existing branches are listed. Current branch will be highlighted with an asterisk.

\n\n

List merged branches

\n\n
git branch -a --merged\n
\n\n

List outdated branches that have been merged into the current one.

\n\n

Delete a local branch

\n\n
git branch -d $branchname\n
\n\n

Deletes the branch only if the changes have been pushed and merged with remote.

\n\n

Delete branch forcefully

\n\n
git branch -D $branchname\n
\n\n
git branch -d $branchname\n
\n\n
\n

Note: You can also use the -D flag which is synonymous with –delete –force instead of -d. This will delete the branch regardless of its merge status.\nDelete a branch irrespective of its merged status.

\n
\n\n

Delete remote branch

\n\n
git push origin --delete :$branchname\n
\n\n

Works for tags, too!

\n\n

Get current sha1

\n\n
git show-ref HEAD -s\n
\n

Reset branch and remove all changes

\n\n
git reset --hard\n
\n\n

Undo commits to a specific commit

\n\n
git reset --hard $commit_id\n\n# Now push to your branch\ngit push --force\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-02-13" },{ "id": "git-extras", "title": "Git extras", "url": "/git-extras", "category": "Git", "keywords": null, "content_html": "

References

\n\n

Git-flow

\n\n
$ git feature myfeature\n  switched to branch 'feature/rofl'\n\n$ ...\n$ git checkout develop\n$ git feature finish myfeature\n  merging 'feature/rofl' into develop\n  deleted branch 'feature/rofl'\n
\n\n

Also git-bug and git-refactor.

\n\n

Branches

\n\n
$ git delete-merged-branches\n  # hint: do `git remote prune origin` after\n\n$ git create-branch development\n$ git delete-branch development\n\n$ git fresh-branch gh-pages\n
\n\n

Inspecting

\n\n
$ git summary   # repo age, commits, active days, etc\n$ git impact    # impact graph\n$ git effort    # commits per file\n
\n\n

Github

\n\n
$ git fork strongloop/express\n# sync your fork with the original repository:\n$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git\n$ git fetch upstream; git merge upstream/master\n
\n\n

Tags

\n\n
$ git release v1.0.0           # commit, tag, push-tags\n$ git delete-tag v1.0.0\n
\n\n

Conveniences

\n\n
$ git ignore \"*.log\"\n
\n\n

Locking

\n\n

Assumes that changes will not be committed.

\n\n
$ git lock config/database.yml\n$ git unlock config/database.yml\n
\n\n

Etc

\n\n
$ git obliterate secret.yml   # remove all references to it\n
\n\n

References

\n\n", "intro_html": "

Quick reference to some utilities in the git-extras utilities.

", "description_html": "", "tags": null, "updated": null },{ "id": "git-log-format", "title": "Git log format string", "url": "/git-log-format", "category": "Git", "keywords": ["git log --pretty=format:%H","%H - Commit hash","%an - Author","%aD - Author date"], "content_html": "

Log format

\n\n

Pretty format

\n\n
git log --pretty=\"format:%H\"\n
\n\n

See the next tables on format variables.

\n\n

Hash

\n\n

Commit

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%Hcommit hash
%h(abbrev) commit hash
\n\n

Tree

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%Ttree hash
%t(abbrev) tree hash
\n\n

Parent

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%Pparent hash
%p(abbrev) parent hash
\n\n

Commit

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%scommit subject
%fcommit subject, filename style
%bcommit body
%dref names
%eencoding
\n\n

Author and committer

\n\n

Author

\n\n

Name

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%anauthor
%aNauthor, respecting mailmap
\n\n

Email

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%aeauthor email
%aEauthor email, respecting mailmap
\n\n

Date

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%aDauthor date (rfc2882)
%arauthor date (relative)
%atauthor date (unix timestamp)
%aiauthor date (iso8601)
\n\n

Committer

\n\n

Name

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%cncommitter name
%cNcommitter name, respecting mailmap
\n\n

Email

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%cecommitter email
%cEcommitter email, respecting mailmap
\n\n

Date

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
VariableDescription
%cDcommitter date (rfc2882)
%crcommitter date (relative)
%ctcommitter date (unix timestamp)
%cicommitter date (iso8601)
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-10-18" },{ "id": "git-log", "title": "git log", "url": "/git-log", "category": "Git", "keywords": null, "content_html": "

Revision ranges

\n\n
git log master             # branch\ngit log origin/master      # branch, remote\ngit log v1.0.0             # tag\n\ngit log master develop\n\ngit log v2.0..master       # reachable from *master* but not *v2.0*\ngit log v2.0...master      # reachable from *master* and *v2.0*, but not both\n
\n\n

See gitrevisions.

\n\n

Basic filters

\n\n
-n, --max-count=2\n    --skip=2\n
\n\n
    --since=\"1 week ago\"\n    --until=\"yesterday\"\n
\n\n
    --author=\"Rico\"\n    --committer=\"Rico\"\n
\n\n

Search

\n\n
    --grep=\"Merge pull request\"   # in commit messages\n    -S\"console.log\"               # in code\n    -G\"foo.*\"                     # in code (regex)\n
\n\n
    --invert-grep\n    --all-match                   # AND in multi --grep\n
\n\n

Limiting

\n\n
    --merges\n    --no-merges\n
\n\n
    --first-parent          # no stuff from merged branches\n
\n\n
    --branches=\"feature/*\"\n    --tags=\"v*\"\n    --remotes=\"origin\"\n
\n\n

Simplification

\n\n
git log -- app/file.rb          # only file\n    --simplify-by-decoration    # tags and branches\n
\n\n

Ordering

\n\n
    --date-order\n    --author-date-order\n    --topo-order              # \"smart\" ordering\n    --reverse\n
\n\n

Formatting

\n\n
    --abbrev-commit\n    --oneline\n    --graph\n
\n\n

Custom formats

\n\n
    --pretty=\"format:%H\"\n
\n\n

See: Git log format cheatsheet

\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "git-revisions", "title": "Git revisions", "url": "/git-revisions", "category": "Git", "keywords": null, "content_html": "

Example usages

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
git log master...developinspect differences in branches
git rebase -i HEAD~3rebase last 3 commits
git reset --hard HEAD@{2}undo last operation that changed HEAD
git checkout v2^{}checkout the v2 tag (not v2 branch)
\n\n

The 3rd argument in each of these commands is a gitrevision. These gitrevisions can be passed to many Git commands.

\n\n

Common git revisions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ReferenceDescription
git show dae68e1sha1
git show HEADreference
git show v1.0.0tag
git show masterlocal branch
git show origin/masterremote branch
git show master~22 commits back from master
git show master..fixreachable from fix but not master
git show master...fixreachable from fix and master, but not both
\n\n

These are just the common ones, there’s a lot more below! (These work in many other commands, not just git show.)

\n\n

Reference

\n\n

Commits

\n\n\n \n \n \n \n \n \n
git checkout dae68e1sha1
\n\n

References

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleDescription
git checkout HEADreference
git checkout masterbranch
git checkout v1.0.0tag
git checkout origin/masteraka, refs/remotes/origin/master
git checkout heads/masteraka, refs/heads/master
\n\n

Searching back

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleDescription
git checkout master@{yesterday}also 1 day ago, etc
git checkout master@{2}2nd prior value
git checkout master@{push}where master would push to
git checkout master^parent commit
git checkout master^22nd parent, eg, what it merged
git checkout master~55 parents back
git checkout master^0this commit; disambiguates from tags
git checkout v0.99.8^{tag}can be commit, tag, tree, object
git checkout v0.99.8^{}defaults to {tag}
git checkout \":/fix bug\"searches commit messages
\n\n

Other

\n\n\n \n \n \n \n \n \n \n \n \n \n
HEAD:README
0:README(0 to 3) …
\n\n

Ranges

\n\n

Ranges

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
git log masterreachable parents from master
git log ^masterexclude reachable parents from master
git log master..fixreachable from fix but not master
git log master...fixreachable from fix and master, but not both
git log HEAD^@parents of HEAD
git log HEAD^!HEAD, then excluding parents’s ancestors
git log HEAD^{:/fix}search previous HEADs matching criteria
\n\n

Ranges illustration

\n\n
A ─┬─ E ── F ── G   master\n   │\n   └─ B ── C ── D   fix\n
\n\n\n \n \n \n \n \n \n \n \n \n \n
git log master..fixBCD
git log master...fixBCD and EFG
\n\n

References

\n\n", "intro_html": "

A list of revision specifications you can use with git log and many other Git commands. Summarized from gitrevisions(7) man page.

", "description_html": "", "tags": null, "updated": "2017-10-11" },{ "id": "git-tricks", "title": "Git tricks", "url": "/git-tricks", "category": "Git", "keywords": null, "content_html": "

Refs

\n\n
HEAD^       # 1 commit before head\nHEAD^^      # 2 commits before head\nHEAD~5      # 5 commits before head\n
\n\n

Branches

\n\n
# create a new branch\n  git checkout -b $branchname\n  git push origin $branchname --set-upstream\n\n# get a remote branch\n  git fetch origin\n  git checkout --track origin/$branchname\n\n# delete local remote-tracking branches (lol)\n  git remote prune origin\n\n# list merged branches\n  git branch -a --merged\n\n# delete remote branch\n  git push origin :$branchname\n  \n# go back to previous branch\n  git checkout -\n
\n\n

Collaboration

\n\n
# Rebase your changes on top of the remote master\n  git pull --rebase upstream master\n  \n# Squash multiple commits into one for a cleaner git log\n# (on the following screen change the word pick to either 'f' or 's')\n  git rebase -i $commit_ref\n
\n\n

Submodules

\n\n
# Import .gitmodules\n  git submodule init\n\n# Clone missing submodules, and checkout commits\n  git submodule update --init --recursive\n\n# Update remote URLs in .gitmodules\n# (Use when you changed remotes in submodules)\n  git submodule sync\n
\n\n

Diff

\n\n

Diff with stats

\n\n
git diff --stat\napp/a.txt    | 2 +-\napp/b.txt    | 8 ++----\n2 files changed, 10 insertions(+), 84 deletions(-)\n
\n\n

Just filenames

\n\n
git diff --summary\n
\n\n

Log options

\n\n
--oneline\n  e11e9f9 Commit message here\n\n--decorate\n  shows \"(origin/master)\"\n\n--graph\n  shows graph lines\n\n--date=relative\n  \"2 hours ago\"\n
\n\n

Misc

\n\n

Cherry pick

\n\n
git rebase 76acada^\n
\n\n

Misc

\n\n
# get current sha1 (?)\n  git show-ref HEAD -s\n\n# show single commit info\n  git log -1 f5a960b5\n\n# Go back up to root directory\n  cd \"$(git rev-parse --show-top-level)\"\n
\n\n

Short log

\n\n
 $ git shortlog\n $ git shortlog HEAD~20..    # last 20 commits\n\n James Dean (1):\n     Commit here\n     Commit there\n\n Frank Sinatra (5):\n     Another commit\n     This other commit\n
\n\n

Bisect

\n\n
git bisect start HEAD HEAD~6\ngit bisect run npm test\ngit checkout refs/bisect/bad   # this is where it screwed up\ngit bisect reset\n
\n\n

Manual bisection

\n\n
git bisect start\ngit bisect good   # current version is good\n\ngit checkout HEAD~8\nnpm test          # see if it's good\ngit bisect bad    # current version is bad\n\ngit bisect reset  # abort\n
\n\n

Searching

\n\n
git log --grep=\"fixes things\"  # search in commit messages\ngit log -S\"window.alert\"       # search in code\ngit log -G\"foo.*\"              # search in code (regex)\n
\n\n

GPG Signing

\n\n
git config set user.signingkey <GPG KEY ID>       # Sets GPG key to use for signing\n\ngit commit -m \"Implement feature Y\" --gpg-sign    # Or -S, GPG signs commit\n\ngit config set commit.gpgsign true                # Sign commits by default\ngit commit -m \"Implement feature Y\" --no-gpg-sign # Do not sign\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "gnupg", "title": "GnuPG", "url": "/gnupg", "category": "CLI", "keywords": null, "content_html": "

Basics

\n\n

Exporting keys

\n\n
gpg -o key.gpg --export <KEY ID>\n
\n\n

Export key in ASCII:

\n\n
gpg -o key.asc --armor --export <KEY ID>\n
\n\n

Note: Omitting the -o|--output option will print the key to stdout.

\n\n

Importing keys

\n\n
gpg --import key.gpg\ngpg --import key.asc\n
\n\n

Only merge updates for keys already in key-ring:

\n\n
gpg --import key.asc --merge-options merge-only\n
\n\n

Managing your keyring

\n\n

Generate a new key:

\n\n
gpg --gen-key\n# or, generate a new key with dialogs for all options\ngpg --full-gen-key\n
\n\n

List public keys:

\n\n
gpg -k\ngpg --list-keys\n
\n\n

List secret keys:

\n\n
gpg -K\ngpg --list-secret-keys\n
\n\n

Using a keyserver

\n\n

Import keys from keyserver:

\n\n
gpg --receive-keys <KEY IDS>\n
\n\n

Upload keys to keyserver:

\n\n
gpg --send-keys <KEY IDS>\n
\n\n

Request updates from keyserver for keys already in your keyring:

\n\n
gpg --refresh-keys\n
\n\n

Search keys from keyserver:

\n\n
gpg --search-keys \"<SEARCH STRING>\"\n
\n\n

Override keyserver from ~/.gnupg/gpg.conf

\n\n
gpg --keyserver <URL> ...\n
\n\n

Trusting a key

\n\n
gpg --edit-key <KEY ID>\n# In the interactive prompt:\ngpg> sign\ngpg> save\n
\n\n

NOTE: You can use the owner’s email or name (or part thereof) instead of the key ID for --edit-key

\n\n

Encrypting

\n\n

Public key encryption

\n

This will produce an encrypted file, secret.txt.gpg, that can only be decrypted by the recipient:

\n\n
gpg -e -o secret.txt.gpg -r <RECIPIENT> secret.txt\n
\n\n

For <RECIPIENT> you can use their key ID, their email, or their name (or part thereof).

\n\n
gpg -e -r <KEY ID> ...\ngpg -e -r \"Bez\" ...\ngpg -e -r \"bezalelhermoso@gmail.com\" ...\n
\n\n

Specifying multiple recipients

\n\n
gpg -e -r <RECIPIENT> -r <ANOTHER RECIPIENT> ... secret.txt\n
\n\n

NOTE: Omitting -o|--output will produce an encrypted file named <ORIGINAL FILENAME>.gpg by default.

\n\n

Symmetric encryption

\n\n

Encrypt file using a shared key. You will be prompted for a passphrase.

\n\n
gpg --symmetric secret.txt\n# or\ngpg -c secret.txt\n
\n\n

Decrypting

\n\n

Decrypting a file

\n\n
gpg -d -o secret.txt secret.txt.gpg\n
\n\n

If the file is encrypted via symmetric encryption, you will be prompted for the passphrase.

\n\n

NOTE: Omitting -o|--output will print the unencrypted contents to stdout

\n\n

Signing & Verifying

\n\n

Signing

\n\n
gpg -o signed-file.txt.gpg -s file.txt\n
\n\n

This can be used during encryption to also sign encrypted files:

\n\n
gpg -s -o secret.txt.gpg \\\n  -r <RECIPIENT> secret.txt\n
\n\n

Verifying a signature

\n\n
gpg --verify file.txt.gpg\n
\n\n

Viewing content of signed file

\n\n
gpg -d signed-file.txt.gpg\n
\n\n

Miscellaneous

\n\n

Components

\n\n

List all components:

\n\n
gpgconf --list-components\n
\n\n

Kill a component:

\n\n
gpgconf --kill <COMPONENT> # i.e. gpgconf --kill dirmngr\n
\n\n

Kill all components:

\n
gpgconf --kill all\n
\n\n

Parsing keyring data

\n\n

Use --with-colons to produce an output that can easily be parsed i.e. with awk, grep. Fields are colon-separated.

\n\n
gpg -k --with-colons\n
\n\n

Field Quick Reference:

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Field #Description
1Record type
2Validity
3Key length in bits
4Public key algorithm
5Key ID
6Creation date
7Expiry date
8Certificate S/N, UID hash, trust signature info
9Ownertrust
10User ID
11Signature class
12Key capabilities
13Issuer fingerprint
14Flag field
15S/N of token
16Hash algorithm
17Curve name
18Compliance flags
19Last update timestamp
20Origin
\n\n

See GnuPG Details for more details.

", "intro_html": "

GnuPG is a complete and free implementation of the OpenPGP standard.

", "description_html": "", "tags": [], "updated": "2017-10-22" },{ "id": "go", "title": "Go", "url": "/go", "category": "C-like", "keywords": null, "content_html": "

Getting started

\n\n

Introduction

\n\n\n\n

Hello world

\n\n

hello.go

\n\n
package main\n\nimport \"fmt\"\n\nfunc main() {\n  message := greetMe(\"world\")\n  fmt.Println(message)\n}\n\nfunc greetMe(name string) string {\n  return \"Hello, \" + name + \"!\"\n}\n
\n\n
$ go build\n
\n\n

Or try it out in the Go repl, or A Tour of Go.

\n\n

Variables

\n\n

Variable declaration

\n\n
var msg string\nmsg = \"Hello\"\n
\n\n

Shortcut of above (Infers type)

\n\n
msg := \"Hello\"\n
\n\n

Constants

\n\n
const Phi = 1.618\n
\n\n

Constants can be character, string, boolean, or numeric values.

\n\n

See: Constants

\n\n

Basic types

\n\n

Strings

\n\n
str := \"Hello\"\n
\n\n
str := `Multiline\nstring`\n
\n\n

Strings are of type string.

\n\n

Numbers

\n\n

Typical types

\n\n
num := 3          // int\nnum := 3.         // float64\nnum := 3 + 4i     // complex128\nnum := byte('a')  // byte (alias for uint8)\n
\n\n

Other types

\n\n
var u uint = 7        // uint (unsigned)\nvar p float32 = 22.7  // 32-bit float\n
\n\n

Arrays

\n\n
// var numbers [5]int\nnumbers := [...]int{0, 0, 0, 0, 0}\n
\n\n

Arrays have a fixed size.

\n\n

Slices

\n\n
slice := []int{2, 3, 4}\n
\n\n
slice := []byte(\"Hello\")\n
\n\n

Slices have a dynamic size, unlike arrays.

\n\n

Pointers

\n\n
func main () {\n  b := *getPointer()\n  fmt.Println(\"Value is\", b)\n}\n
\n\n
func getPointer () (myPointer *int) {\n  a := 234\n  return &a\n}\n
\n\n
a := new(int)\n*a = 234\n
\n\n

Pointers point to a memory location of a variable. Go is fully garbage-collected.

\n\n

See: Pointers

\n\n

Type conversions

\n\n
i := 2\nf := float64(i)\nu := uint(i)\n
\n\n

See: Type conversions

\n\n

Flow control

\n\n

Conditional

\n\n
if day == \"sunday\" || day == \"saturday\" {\n  rest()\n} else if day == \"monday\" && isTired() {\n  groan()\n} else {\n  work()\n}\n
\n\n

See: If

\n\n

Statements in if

\n\n
if _, err := doThing(); err != nil {\n  fmt.Println(\"Uh oh\")\n}\n
\n\n

A condition in an if statement can be preceded with a statement before a ;. Variables declared by the statement are only in scope until the end of the if.

\n\n

See: If with a short statement

\n\n

Switch

\n\n
switch day {\n  case \"sunday\":\n    // cases don't \"fall through\" by default!\n    fallthrough\n\n  case \"saturday\":\n    rest()\n\n  default:\n    work()\n}\n
\n\n

See: Switch

\n\n

For loop

\n\n
for count := 0; count <= 10; count++ {\n  fmt.Println(\"My counter is at\", count)\n}\n
\n\n

See: For loops

\n\n

For-Range loop

\n\n
entry := []string{\"Jack\",\"John\",\"Jones\"}\nfor i, val := range entry {\n  fmt.Printf(\"At position %d, the character %s is present\\n\", i, val)\n}\n
\n\n

See: For-Range loops

\n\n

Functions

\n\n

Lambdas

\n\n
myfunc := func() bool {\n  return x > 10000\n}\n
\n\n

Functions are first class objects.

\n\n

Multiple return types

\n\n
a, b := getMessage()\n
\n\n
func getMessage() (a string, b string) {\n  return \"Hello\", \"World\"\n}\n
\n\n

Named return values

\n\n
func split(sum int) (x, y int) {\n  x = sum * 4 / 9\n  y = sum - x\n  return\n}\n
\n\n

By defining the return value names in the signature, a return (no args) will return variables with those names.

\n\n

See: Named return values

\n\n

Packages

\n\n

Importing

\n\n
import \"fmt\"\nimport \"math/rand\"\n
\n\n
import (\n  \"fmt\"        // gives fmt.Println\n  \"math/rand\"  // gives rand.Intn\n)\n
\n\n

Both are the same.

\n\n

See: Importing

\n\n

Aliases

\n\n
import r \"math/rand\"\n
\n\n
r.Intn()\n
\n\n

Exporting names

\n\n
func Hello () {\n  ···\n}\n
\n\n

Exported names begin with capital letters.

\n\n

See: Exported names

\n\n

Packages

\n\n
package hello\n
\n\n

Every package file has to start with package.

\n\n

Concurrency

\n\n

Goroutines

\n\n
func main() {\n  // A \"channel\"\n  ch := make(chan string)\n\n  // Start concurrent routines\n  go push(\"Moe\", ch)\n  go push(\"Larry\", ch)\n  go push(\"Curly\", ch)\n\n  // Read 3 results\n  // (Since our goroutines are concurrent,\n  // the order isn't guaranteed!)\n  fmt.Println(<-ch, <-ch, <-ch)\n}\n
\n\n
func push(name string, ch chan string) {\n  msg := \"Hey, \" + name\n  ch <- msg\n}\n
\n\n

Channels are concurrency-safe communication objects, used in goroutines.

\n\n

See: Goroutines, Channels

\n\n

Buffered channels

\n\n
ch := make(chan int, 2)\nch <- 1\nch <- 2\nch <- 3\n// fatal error:\n// all goroutines are asleep - deadlock!\n
\n\n

Buffered channels limit the amount of messages it can keep.

\n\n

See: Buffered channels

\n\n

Closing channels

\n\n

Closes a channel

\n\n
ch <- 1\nch <- 2\nch <- 3\nclose(ch)\n
\n\n

Iterates across a channel until its closed

\n\n
for i := range ch {\n  ···\n}\n
\n\n

Closed if ok == false

\n\n
v, ok := <- ch\n
\n\n

See: Range and close

\n\n

WaitGroup

\n\n
import \"sync\"\n\nfunc main() {\n  var wg sync.WaitGroup\n  \n  for _, item := range itemList {\n    // Increment WaitGroup Counter\n    wg.Add(1)\n    go doOperation(item)\n  }\n  // Wait for goroutines to finish\n  wg.Wait()\n  \n}\n
\n\n
func doOperation(item string) {\n  defer wg.Done()\n  // do operation on item\n  // ...\n}\n
\n\n

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. The goroutine calls wg.Done() when it finishes.\nSee: WaitGroup

\n\n

Error control

\n\n

Defer

\n\n
func main() {\n  defer fmt.Println(\"Done\")\n  fmt.Println(\"Working...\")\n}\n
\n\n

Defers running a function until the surrounding function returns.\nThe arguments are evaluated immediately, but the function call is not ran until later.

\n\n

See: Defer, panic and recover

\n\n

Deferring functions

\n\n
func main() {\n  defer func() {\n    fmt.Println(\"Done\")\n  }()\n  fmt.Println(\"Working...\")\n}\n
\n\n

Lambdas are better suited for defer blocks.

\n\n
func main() {\n  var d = int64(0)\n  defer func(d *int64) {\n    fmt.Printf(\"& %v Unix Sec\\n\", *d)\n  }(&d)\n  fmt.Print(\"Done \")\n  d = time.Now().Unix()\n}\n
\n

The defer func uses current value of d, unless we use a pointer to get final value at end of main.

\n\n

Structs

\n\n

Defining

\n\n
type Vertex struct {\n  X int\n  Y int\n}\n
\n\n
func main() {\n  v := Vertex{1, 2}\n  v.X = 4\n  fmt.Println(v.X, v.Y)\n}\n
\n\n

See: Structs

\n\n

Literals

\n\n
v := Vertex{X: 1, Y: 2}\n
\n\n
// Field names can be omitted\nv := Vertex{1, 2}\n
\n\n
// Y is implicit\nv := Vertex{X: 1}\n
\n\n

You can also put field names.

\n\n

Pointers to structs

\n\n
v := &Vertex{1, 2}\nv.X = 2\n
\n\n

Doing v.X is the same as doing (*v).X, when v is a pointer.

\n\n

Methods

\n\n

Receivers

\n\n
type Vertex struct {\n  X, Y float64\n}\n
\n\n
func (v Vertex) Abs() float64 {\n  return math.Sqrt(v.X * v.X + v.Y * v.Y)\n}\n
\n\n
v := Vertex{1, 2}\nv.Abs()\n
\n\n

There are no classes, but you can define functions with receivers.

\n\n

See: Methods

\n\n

Mutation

\n\n
func (v *Vertex) Scale(f float64) {\n  v.X = v.X * f\n  v.Y = v.Y * f\n}\n
\n\n
v := Vertex{6, 12}\nv.Scale(0.5)\n// `v` is updated\n
\n\n

By defining your receiver as a pointer (*Vertex), you can do mutations.

\n\n

See: Pointer receivers

\n\n

References

\n\n

Official resources

\n\n\n\n

Other links

\n\n", "intro_html": "", "description_html": "", "tags": ["Featured"], "updated": "2020-06-21" },{ "id": "goby", "title": "Goby", "url": "/goby", "category": "Ruby", "keywords": null, "content_html": "

Getting started

\n\n

Hello world

\n\n

hello.gb

\n\n
class Greet\n  attr_accessor :audience, :head, :tail\n  \n  def initialize\n    @head = \"Hello, \"\n    @tail = \"!\"\n  end\n\n  def name\n    audience.name\n  end\n\n  def say\n    puts head + name + tail\n  end\nend\n\nmodule MyName\n  attr_reader :name\n\n  def initialize\n    @name = self.class.to_s\n  end\nend\n\nclass World\n  include MyName\nend\n\ngreet = Greet.new\ngreet.audience = World.new\ngreet.say\n
\n\n

Then run:

\n\n
$ goby hello.gb\n#=> Hello, World!\n
\n\n

REPL (igb)

\n\n
$ goby -i\n
\n\n\n\n

See igb manual & test script. You can use readline features such as command history by arrow keys.

\n\n

Variables

\n\n

Local variable

\n\n
zip101 = \"233-7383\"\nmagic_number = 42\n
\n\n

Should be “[a-z][a-z0-9_]+“(snake_case).

\n\n

Instance variable

\n\n
module State\n  def initialize(state)\n    @state = state      # declaring an instance variable by assignment\n  end\n  def show\n    @state              # accessible from other instance methods\n  end\nend\n\nstate = State.new \"success\"\nstate.show\n#=> success\n
\n\n

Should be “@[a-z][a-z0-9_]+“(snake_case).

\n\n

Multiple assignment

\n\n
# array literal\na, b, c = [1, 2, 3]\n\n# array with '*'\na = [1, 2, 3]\nx, y, z = *a\n\n# array literal with '*'\na, b, c = *[1, 2, 3]\n\n# bare assignment: unsupported\na, b, c = 1, 2, 3  #=> unexpected 3 Line: 0\n
\n\n

Black hole variable

\n\n
# '_' is write-only\na, _ = [1, 2]\n
\n\n

Class variable

\n\n

Unsupported.

\n\n

Global variable

\n\n

Unsupported.

\n\n

Method definition

\n\n

Method definition and calling

\n\n
def foo_bar?(baz)\n  if baz == \"Hi, Goby!\"\n    true\n  else\n    false\n  end\nend\n\nfoo_bar? \"Hi, Goby!\" #=> true\n
\n\n

Method name should be “[a-z][a-z0-9_]+\\??” (snake_case). You can omit the trailing “()” only if no parameters are taken. Trailing using “!” is unsupported.

\n\n

Order of method parameter

\n\n
def foo(normal, default=\"value\", hash={}, ary=[], keyword:, keyword_default:\"key\", *sprat)\nend\n
\n\n

If a default value is provided to a parameter, the parameter can be omitted when calling. () can be omitted. The order of parameters in method definition is restricted as follows:

\n\n
    \n
  1. normal parameters (like a)
  2. \n
  3. normal parameters with default value (like a=1)
  4. \n
  5. optional parameters (array or hash, like ary=[] or hs={})
  6. \n
  7. keyword parameters (like kwd:)
  8. \n
  9. keyword parameters with default value (like kwd: 1 or ary: [1,2,3] or hsh: {key: \"value\"})
  10. \n
  11. splat parameters (like *sp)
  12. \n
\n\n

Or you will receive an error.

\n\n

Keyword parameter (WIP)

\n\n
def foo(process:, verb: :GET, opt:{ csp: :enabled }, ary: [1, 2, 3])\nend\n
\n\n

Returning value

\n\n
PI = 3.14\ndef area(radius)\n  radius * PI      # returns the result of evaluation\nend\n\narea 6             #=> 18.84\n
\n\n

Returning multiple value

\n\n
def my_array\n  [1, 2, 3]\nend\n\nmy_array   #=> [1, 2, 3]\n
\n\n

Instance method

\n\n
module Foo\n  def bar       # defining instance method\n    puts \"bar\"\n  end\n  \n  def baz(count, email: \"goby@example.com\")\n    count.times do\n      puts email\n    end\n  end\nend\n\nfoo = Foo.new\nfoo.bar     #=> bar\nfoo.baz(3)  #↓\ngoby@example.com\ngoby@example.com\ngoby@example.com\n
\n\n

Singleton method #1

\n\n
str = \"Goby\"\ndef str.foo     #1 singleton method on the object\n  self * 2\nend\n\nstr.foo\n#=> GobyGoby\n
\n\n

Singleton method #2

\n\n
module Foo\n  def self.bar  #2 singleton method with `self.`\n    92\n  end\nend\n
\n\n

Singleton method #3

\n\n
module Foo  \n  def Foo.bar   #3 singleton method with a class name (unrecommended)\n    88\n  end\nend\n
\n\n

Singleton method #4

\n\n
module Foo end\n\ndef Foo.bar     #4 singleton methods outside the Foo\n  9999\nend\n\nFoo.bar #=> 9999\n
\n\n

Attribute accessor method

\n\n
class Foo\n  attr_accessor :bar, :baz\n\n  def initialize\n    @bar = 42\n    @baz = 99\n  end\nend\n\nfoo = Foo.new\n\nfoo.bar = 77\nfoo.baz = 88\n
\n\n

You can use the following shorthands to declare attribute accessor methods in classes/modules:

\n\n\n\n

Private method (to be implemented)

\n\n
class Foo\n  def bar\n    42\n  end\n  \n  def _baz  # leading '_' means private method\n    99\n  end\nend\n
\n\n

Module/Class definition

\n\n

Module definition and include

\n\n
module Foo\n  def foo\n    \"Foo's instance method\"\n  end\nend\n\nclass Bar\n  include Foo   # to include Foo\nend\n\nBar.new.foo     #=> Foo's instance method\n
\n\n

Module names should be “[A-Z][A-Za-z0-9_]+” (UpperCamelCase). Modules cannot be inherited.

\n\n

Module definition and extend

\n\n
module Foo\n  def foo\n    \"Foo's instance method will be a singleton method\"\n  end\nend\n\nclass Bar\n  extend Foo   # to extend Foo  \nend\n\nBar.foo        #=> Foo's instance method will be a singleton method\n
\n\n

extend is to use the instance methods in the specified modules as singleton methods in your class or module.

\n\n

Module instantiation

\n\n
module Foo   #module definition\n  def foo   \n    99\n  end\nend\n\nFoo.new.foo  #=> 99\n
\n\n

Actually, Goby’s module can be even instantiated via “new” like “Foo.new”.

\n\n

Class definition and inheritance

\n\n
class Foo       # class definition\n  def bar\n    99\n  end\nend\n\nclass Baz < Foo # inheritance\nend\n\nBaz.new.bar  #=> 99\n
\n\n

Class names should be “[A-Z][A-Za-z0-9]+” (UpperCamelCase). Inheritance with “<” is supported.

\n\n

Constants

\n\n
HTTP_ERROR_404 = 404\nHTTP_ERROR_404 = 500    # error\n
\n\n

Constants should be “[A-Z][A-Za-z0-9_]+” (UPPER_SNAKECASE). Constants are not reentrant and the scope is global.

\n\n

Redefining class/modules

\n\n
class Foo\n  def bar\n    99\n  end\nend\n\nclass Foo\n  def bar  # redefining is possible\n    77\n  end\nend\n
\n\n

Namespaces

\n\n
class Foo\n  module Bar\n    MAGIC = 99\n    def baz\n      99\n    end\n  end\nend\n\nFoo::Bar.new.baz     # Use '::' for namespacing\nFoo::Bar::MAGIC      # Use '::' for namespacing\n
\n\n

Load library

\n\n

require

\n\n
require(\"uri\")   # to activate URL class\n\nu = URI.parse(\"http://example.com\")\nu.scheme   #=> \"http\"\n
\n\n

require_relative

\n\n
require_relative(\"bar\")  # loading the local bar.gb\n\nclass Foo\n  def self.bar(x)\n    Bar.foo do |ten|\n      x * ten\n    end\n  end\n\n  def self.baz\n    yield(100)\n  end\nend\n
\n\n

Literal

\n\n

Keyword

\n\n

def, true, false, nil, if, elsif, else, case, when, return, self, end, while, do, yield, get_block, next, class, module, break

\n\n

String literal

\n\n
\"double quote\"\n'single quote'\n
\n\n

Double and single quotation can be used.

\n\n

Symbol literal

\n\n
:symbol           # equivalent to \"symbol\"\n{ symbol: \"value\" }\n
\n\n

Goby’s symbol (using :) is always String class.

\n\n

Numeric literal

\n\n
year   =  2018   # Integer\noffset = -42     # Integer\nPI     = 3.14    # Float\nG      = -9.8    # Float\n
\n\n

Array literal

\n\n
[1, 2, 3, \"hello\", :goby, { key: \"value\"}]\n[1, 2, [3, 4], 5, 6]\n
\n\n

Hash literal

\n\n
h = { key: \"value\", key2: \"value2\" }\nh[:key2]   #=> value2\n
\n\n

Hash literal’s keys should always be symbol literals.

\n\n

Range literal

\n\n
(1..10).each do |x|    # '..' represents a range\n  puts x*x\nend\n
\n\n

Boolean and nil

\n\n
true       # Boolean class\nfalse      # Boolean class\nnil        # Null class\n\n!nil  #=> true\n
\n\n

Any objects except nil and false will be treated as true on conditionals.

\n\n

Operator

\n\n

Arithmetic/logical/assignment operators

\n\n
+           # unary\n**          # power\n-           # unary\n* / %       # multiplication, division, modulus\n+ -         # addition, subtraction\n!           # logical inversion\n> >= < <=   # inequality comparison\n== !=       # equality comparison, negative comparison\n&&          # logical AND\n||          # logical OR\n+= -=       # shorthand of addition/subtraction\n=           # assignment\n
\n\n

*Priority of operators are TBD

\n\n

Other operators

\n\n
()          # chaning priority of interpretation\n[]          # array literal\n*           # multiple assignment\n..          # range\n
\n\n

*Priority of operators are TBD

\n\n

Delimiter

\n\n
class Foo; end   # ';' to delimit\n\nclass Bar end    # recommended\n
\n\n

String interpolation (to be implemented)

\n\n
puts \"Error: #{error_message}\"  # double quotation is required\n
\n\n

Comment

\n\n
puts \"Goby\"    # comments\n
\n\n

Use the annotations to keep the comments concise.

\n\n\n\n

I/O

\n\n\n\n

Flow control

\n\n

if, else, elsif

\n\n
def foo(str)\n  if str.size > 10\n    puts \"too big!\"\n  elsif str.size < 3\n    puts \"too short!\"\n  else\n    puts \"moderate\"\n  end\nend\n
\n\n

then is not supported.

\n\n

Break

\n\n
def foo(tail)\n  (5..tail).each do |t|\n    if t % 2 == 0 && t % 5 == 0\n      puts \"ouch!\"\n      break       # finish the block\n    else\n      puts t\n    end\n  end\n  puts \"out of the block\"\nend\n\nfoo 20\n#=> 5 6 7 8 9\n#=> ouch!\n#=> out of the block\n
\n\n

Case

\n\n
def foo(str)\n  case str\n  when \"Elf\"\n    puts \"You might be Aragorn II!\"\n  when \"Aragorn\"\n    puts \"Long time no see, Aragorn!\"\n  when \"Frodo\", \"Sam\", \"Gandalf\"\n    puts \"One of us!\"\n  else\n    puts \"You're not yourself\"\n  end\nend\n
\n\n

While

\n\n
decr = 10\nwhile decr do\n  if decr < 1\n    break\n  end\n  puts decr\n  decr -= 1\nend\n
\n\n

while, conditional and a do/end block can be used for a loop.

\n\n

Rescue

\n\n

Under construction. Join #605.

\n\n

Block

\n\n

Block

\n\n
def foo(ary: [1, 2, 3])\n  ary.each do |s|      # start of the block with |block variable|\n    puts s\n  end                  # end of the block\nend\n
\n\n

{ } cannot be used for forming a block.

\n\n

yield

\n\n
def foo\n  yield(10)  # executes the block given\nend\n\nfoo do |ten|\n  ten + 20\nend\n
\n\n

Block object and call

\n\n
b = Block.new do\n  100\nend\n\nb.call  #=> 100\n
\n\n

Block.new can take a block and then call.

\n\n

Passing a block

\n\n
def baz\n  1000\nend\n\nclass Foo\n  def exec_block(block)\n\tblock.call\n  end\n\n  def baz\n    100\n  end\nend\n\nb = Block.new do\n  baz\nend\n\nf = Foo.new\nf.exec_block(b)\n
\n\n

Passing a block with block arguments

\n\n
b = Block.new do |arg, offset|\n  arg + 1000 - offset\nend\n\nb.call(49, 500) #=> 549\n
\n\n

Special get_block keyword

\n\n
def bar(block)\n  # runs the block object and the block arg simultaneously\n  block.call + get_block.call\nend\n\ndef foo\n  bar(get_block) do # passes two blocks to `bar`\n    20\n  end\nend\n\nfoo do\n  10\nend\n
\n\n

get_block is not a method but a keyword to retrive a given block argument as a block object. By this, you can pass around or call the given block arguments as block objects.

\n\n

Closure

\n\n
count = 0          # the declaration is used\nb = Block.new do\n  count += 1       # the block looks preserving the `count`\nend\n\nclass Foo\n  def bar(blk)\n    count = 9      # (does not affect)\n    puts blk.call  # local variable is resolved to the one above\n  end\nend\n\nFoo.new.bar b  #=> 1\nFoo.new.bar b  #=> 2\nFoo.new.bar b  #=> 3\n
\n\n

Native class (Primary)

\n\n

Goby’s most “native” classes cannot instantiate with new in principle.

\n\n

Object

\n\n
Bar.ancestors\n#» [Bar, Foo, Object]\nBar.singleton_class.ancestors\n#» [#<Class:Bar>, #<Class:Object>, Class, Object]\n
\n\n

Object is actually just for creating singleton classes. See Class.

\n\n\n\n

Class

\n\n
String.ancestors      #=> [String, Object]\n
\n\n

Class and Objectcan actually be regarded as the same and you don’t need to distinguish them in almost all the cases.

\n\n\n\n

String

\n\n
puts \"Hello\" + ' ' + 'world'  #=> Hello world\n
\n\n

Fixed to UTF-8 with mb4 support.

\n\n\n\n

Integer

\n\n
37037 * 27      #=> 999999\n
\n\n\n\n

Array

\n\n
[1, \"2\", :card, [4, 5], { john: \"doe\" }]\n
\n\n\n\n

Hash

\n\n
h = { key: \"value\" }\nh = { \"key\": \"value\" }  #=> error\n\nh[\"key\"]  #=> value\nh[:key]   #=> value\n
\n\n

Keys in hash literals should be symbol literals, while Hash index can be either string or symbol literals.

\n\n\n\n

Range

\n\n
(1..10).each do |i|\n  puts i ** 2\nend\n
\n\n\n\n

Block

\n\n
b = Block.new do\n  100\nend\n\nb.call  #=> 100\n
\n\n\n\n

Native class (secondary)

\n\n

Float

\n\n
1.1 + 1.1   # => -2.2\n2.1 * -2.1  # => -4.41\n
\n\n

Float literals like 3.14 or -273.15. Float class is based on Golang’s float64 type.

\n\n\n\n

Decimal

\n\n
\"3.14\".to_d            # => 3.14\n\"-0.7238943\".to_d      # => -0.7238943\n\"355/113\".to_d         \n# => 3.1415929203539823008849557522123893805309734513274336283185840\n\na = \"16.1\".to_d\nb = \"1.1\".to_d\ne = \"17.2\".to_d\na + b # => 0.1\na + b == e # => true\n\n('16.1'.to_d  + \"1.1\".to_d).to_s #=> 17.2\n('16.1'.to_f  + \"1.1\".to_f).to_s #=> 17.200000000000003\n
\n\n

Experimental: the size is arbitrary and internally a fraction from Golang’s big.Rat type. Decimal literal is TBD for now and you can get Decimal number via to_d method from Integer/Float/String.

\n\n\n\n

Regexp

\n\n
a = Regexp.new(\"orl\")\na.match?(\"Hello World\")   #=> true\na.match?(\"Hello Regexp\")  #=> false\n\nb = Regexp.new(\"😏\")\nb.match?(\"🤡 😏 😐\")    #=> true\nb.match?(\"😝 😍 😊\")    #=> false\n\nc = Regexp.new(\"居(ら(?=れ)|さ(?=せ)|る|ろ|れ(?=[ばる])|よ|(?=な[いかくけそ]|ま[しすせ]|そう|た|て))\")\nc.match?(\"居られればいいのに\")  #=> true\nc.match?(\"居ずまいを正す\")      #=> false\n
\n\n

Using / / is to be implemented.

\n\n\n\n

MatchData

\n\n
# numbered capture\n'abcd'.match(Regexp.new('(b.)'))\n#=> #<MatchData 0:\"bc\" 1:\"bc\">\n\n# named capture\n'abcd'.match(Regexp.new('a(?<first>b)(?<second>c)'))\n#=> #<MatchData 0:\"abc\" first:\"b\" second:\"c\">\n\n# converting to hash\n» 'abcd'.match(Regexp.new('a(?<first>b)(?<second>c)')).to_h\n#» { 0: \"abc\", first: \"b\", second: \"c\" }\n
\n\n

The number keys in the captures are actually String class.The key 0 is the mached string.

\n\n\n\n

File

\n\n
f = File.new(\"../test_fixtures/file_test/size.gb\")\nf.name  #=> \"../test_fixtures/file_test/size.gb\"\n
\n\n\n\n

Native class (Golang-oriented)

\n\n

GoMap

\n\n
h = { foo: \"bar\" }\nm = GoMap.new(h)    # to pass values to Golang's code\nh2 = m.to_hash\nh2[:foo]   #=> \"bar\"\n
\n\n\n\n

Channel

\n\n
c = Channel.new\n\n1001.times do |i| # i start from 0 to 1000\n  thread do\n  \tc.deliver(i)\n  end\nend\n\nr = 0\n1001.times do\n  r = r + c.receive\nend\n\nr #=> 500500\n
\n\n

Channel class is to hold channels to work with #thread. See thread.

\n\n\n\n

Enumerator & lazy

\n\n

Pretty new experimental library.

\n\n

LazyEnumerator

\n\n
# creating a lazy enumerator\nenumerator = LazyEnumerator.new(ArrayEnumerator.new([1, 2, 3])) do |value|\n\t2 * value\nend\nresult = []\n\nenumerator.each do |value|\n\tresult.push(value)\nend\n\nresult   #=> [2, 4, 6]\n
\n\n

A shorthand #lazy method is also provided in Array and Range by now. See “Tips & tricks” below.

\n\n\n\n

ArrayEnumerator

\n\n
iterated_values = []\n\nenumerator = ArrayEnumerator.new([1, 2, 4])\n\nwhile enumerator.has_next? do\n\titerated_values.push(enumerator.next)\nend\n\niterated_values   #=> [1, 2, 4]\n
\n\n\n\n

RangeEnumerator

\n\n
iterated_values = []\n\nenumerator = RangeEnumerator.new((1..4))\n\nwhile enumerator.has_next? do\n\titerated_values.push(enumerator.next)\nend\n\niterated_values   #=> [1, 2, 3, 4]\n
\n\n\n\n

Special class

\n\n

Boolean

\n\n
true.class  #=> Boolean\nfalse.class #=> Boolean\n
\n\n

A special class that just to hold true and false. Cannot be instantiate.

\n\n

Null

\n\n
nil.class   #=> Null\n
\n\n

A special class that just to hold nil. Cannot be instantiate.

\n\n

Method

\n\n

(A special dummy class that just holds methods defined by Goby code.)

\n\n

Diggable

\n\n

Provides #dig method. Currently. Array and Hash classes’ instance can be Diggable.

\n\n
[1, 2].dig(0, 1)  #=> TypeError: Expect target to be Diggable, got Integer\n
\n\n

Testing framework

\n\n

Spec

\n\n
require \"spec\"\n\nSpec.describe Spec do\n  it \"fails and exit with code 1\" do\n\texpect(1).to eq(2)\n  end\nend\n\nSpec.run\n
\n\n\n\n

Tips & tricks

\n\n

Showing methods

\n\n
» \"string\".methods\n#» [\"!=\", \"*\", \"+\", \"<\", \"<=>\", \"==\", \"=~\", \">\", \"[]\", \"[]=\", \"capitalize\", \"chop\", \"concat\", \"count\", \"delete\", \"downcase\", \"each_byte\", \"each_char\", \"each_line\", \"empty?\", \"end_with?\", \"eql?\", \"fmt\", \"include?\", \"insert\", \"length\", \"ljust\", \"match\", \"new\", \"replace\", \"replace_once\", \"reverse\", \"rjust\", \"size\", \"slice\", \"split\", \"start_with\", \"strip\", \"to_a\", \"to_bytes\", \"to_d\", \"to_f\", \"to_i\", \"to_s\", \"upcase\", \"!\", \"block_given?\", \"class\", \"exit\", \"instance_eval\", \"instance_variable_get\", \"instance_variable_set\", \"is_a?\", \"methods\", \"nil?\", \"object_id\", \"puts\", \"raise\", \"require\", \"require_relative\", \"send\", \"singleton_class\", \"sleep\", \"thread\"]\n
\n\n

Showing class

\n\n
» \"string\".class\n#» String\n
\n\n

Showing singleton class

\n\n
» \"moji\".singleton_class\n#» #<Class:#<String:842352325152>>\n\n» \"moji\".class.singleton_class\n#» #<Class:String>\n
\n\n

Showing ancestors

\n\n
» Integer.ancestors\n#» [Integer, Object]\n\n» \"moji\".class.ancestors\n#» [String, Object]\n
\n\n

Showing singleton classes’ ancestors

\n\n
» \"moji\".class.singleton_class.ancestors\n#» [#<Class:String>, #<Class:Object>, Class, Object]\n
\n\n

Showing object’s id

\n\n
» \"moji\".object_id\n#» 842352977920\n
\n\n

#to_json

\n\n
h = { a: 1, b: [1, \"2\", [4, 5, nil]]}\nh.to_json         # converts hash to JSON\n#=> {\"a\":1, \"b\":[1, \"2\", [4, 5, null]]}\n
\n\n

Customize #to_json

\n\n

Overwrite the #to_json in your class:

\n\n
class JobTitle\n  def initialize(name)\n    @name = name\n  end\n\n  def to_json\n    { title: @name }.to_json\n  end\nend\n\nclass Person\n  def initialize(name, age)\n    @name = name\n    @age = age\n    @job = JobTitle.new(\"software engineer\")\n  end\n\n  def to_json\n    { name: @name, age: @age, job: @job }.to_json\n  end\nend\n\nstan = Person.new(\"Stan\", 23)\nh = { person: stan }\nh.to_json #=> {\"person\":{\"name\":\"Stan\",\"job\":{\"title\":\"software engineer\"},\"age\":23}}\n
\n\n

Lazy enumeration

\n\n

To avoid N + 1 query.

\n\n
enumerator = [1, 2, 3].lazy.map do |value|\n\t2 * value\nend\nresult = []\n\nenumerator.each do |value|\n\tresult.push(value)\nend\n\nresult  #=> [2, 4, 6]\n
\n\n

You can call #lazy.map on Array, Range, or JSON objects.

\n\n

Styling

\n\n

Quick style guide

\n\n\n\n

Document notation

\n\n\n\n

Syntax highlighting

\n\n

Ready for Vim and Sublime text. You can also use Ruby’s syntax highlighting so far.

\n\n

References

\n\n

Official

\n\n\n\n

Readings for Goby developers

\n\n\n\n

JP resource

\n\n", "intro_html": "

Goby’s language design is based on Ruby language’s, slim and shaped up. Differences in syntax between them is very small.

", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "google-webfonts", "title": "Google Webfonts", "url": "/google-webfonts", "category": "Others", "keywords": null, "content_html": "\n\n\n
<link href=\"http://fonts.googleapis.com/css?family=Open+Sans\" rel=\"stylesheet\" type=\"text/css\" />\n
\n\n

CSS import

\n\n\n
/* One font */\n@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');\n\n/* Combining multiple fonts */\n@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,400italic|Montserrat:400,700'');\n
\n\n

Great for using with Codepen.io or similar websites!

", "intro_html": "

Short snippets on using Google Webfonts in a web page.

", "description_html": "", "tags": null, "updated": null },{ "id": "google_analytics", "title": "Google Analytics", "url": "/google_analytics", "category": "Others", "keywords": null, "content_html": "

Pageview

\n\n
// Analytics.js\nga('create', 'UA-XXXX-Y', 'auto');\nga('send', 'pageview');\n
\n\n

Track events

\n\n
// ga.js\n// [..., category, action, label, value (int), noninteraction (bool)]\n_gaq.push(['_trackEvent', 'Videos', 'Play', 'Birthday video', true])\n_gaq.push(['_trackEvent', 'Projects', 'Donate', 'Project name'])\n_gaq.push(['_trackEvent', 'Accounts', 'Login'])\n\n// Analytics.js\n//       ,        ,  category,  action,  label,         value (int)\nga('send', 'event', 'button',   'click', 'nav buttons', 4);\n
\n\n

Variables

\n\n
// [..., index, name, value, scope (optional)]\n_gaq.push(['_setCustomVar', 1, 'Logged in', 'Yes', 2]);\n\n// Scope = 1 (visitor), 2 (session), 3 (page, default)\n
\n\n

https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables\nhttps://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "graphql", "title": "GraphQL", "url": "/graphql", "category": "API", "keywords": null, "content_html": "

Intro

\n\n

Queries

\n\n

Basic query

\n\n
{ status }\n
\n\n

\n\n
{ status: 'available' }\n
\n\n

Nesting

\n\n
{ hero { name height } }\n
\n\n

\n\n
{ hero:\n    { name: \"Luke Skywalker\",\n      height: 1.74 } }\n
\n\n

Lists

\n\n
{ friends { name } }\n
\n\n

\n\n
{ friends:\n    [ { name: \"Luke Skywalker\" },\n      { name: \"Han Solo\" },\n      { name: \"R2D2\" } ] }\n
\n\n

GraphQL queries look the same for both single items or lists of items.

\n\n

Lookups

\n\n
{\n  hero(id: \"1000\") { id name }\n}\n
\n\n

\n\n
{ hero:\n    { id: \"1000\",\n    { name: \"Luke Skywalker\" } }\n
\n\n

Aliases

\n\n
{\n  luke: hero(id: \"1000\") { name }\n  han: hero(id: \"1001\") { name }\n}\n
\n\n

\n\n
{ luke:\n    { name: \"Luke Skywalker\" },\n    han:\n    { name: \"Han Solo\" } }\n
\n\n

Operation names and variables

\n\n

Query

\n
query FindHero($id: String!) {\n  hero(id: $id) { name }\n}\n
\n\n

Just to make things less ambiguous. Also, to use variables, you need an operation name.

\n\n

Variables

\n\n
{ id: '1000' }\n
\n\n

Mutations

\n\n

Query

\n\n
{ createReview($review) { id } }\n
\n\n

Variables

\n\n
{ review: { stars: 5 } }\n
\n\n

\n\n
{ createReview: { id: 5291 } }\n
\n\n

Mutations are just fields that do something when queried.

\n\n

Multiple types

\n\n
{\n  search(q: \"john\") {\n    id\n    ... on User { name }\n    ... on Comment { body author { name } }\n  }\n}\n
\n\n

Great for searching.

\n\n

Over HTTP

\n\n

GET

\n\n
fetch('http://myapi/graphql?query={ me { name } }')\n
\n\n

POST

\n\n
fetch('http://myapi/graphql', {\n  body: JSON.stringify({\n    query: '...',\n    operationName: '...',\n    variables: { ... }\n  })\n})\n
\n\n

Schema

\n\n

Basic schemas

\n\n
type Query {\n  me: User\n  users(limit: Int): [User]\n}\n\ntype User {\n  id: ID!\n  name: String\n}\n
\n\n

See: sogko/graphql-shorthand-notation-cheat-sheet

\n\n

Built in types

\n\n

Scalar types

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
IntInteger
FloatFloat
StringString
BooleanBoolean
IDID
\n\n

Type definitions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
scalarScalar type
typeObject type
interfaceInterface type
unionUnion type
enumEnumerable type
inputInput object type
\n\n

Type modifiers

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
StringNullable string
String!Required string
[String]List of strings
[String]!Required list of strings
[String!]!Required list of required strings
\n\n

Mutations

\n\n
type Mutation {\n  users(params: ListUsersInput) [User]!\n}\n
\n\n

Interfaces

\n\n
interface Entity {\n  id: ID!\n}\n\ntype User implements Entity {\n  id: ID!\n  name: String\n}\n
\n\n

Enums

\n\n
enum DIRECTION {\n  LEFT\n  RIGHT\n}\n\ntype Root {\n  direction: DIRECTION!\n}\n
\n\n

Unions

\n\n
type Artist { ··· }\ntype Album { ··· }\n\nunion Result = Artist | Album\n\ntype Query {\n  search(q: String) [Result]\n}\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2019-07-07" },{ "id": "gremlins", "title": "Gremlins.js", "url": "/gremlins", "category": "JavaScript libraries", "keywords": null, "content_html": "

Example

\n\n

Simple example

\n\n
<script src='https://cdn.jsdelivr.net/npm/gremlins/dist/gremlins.js'></script>\n<script>\ngremlins.createHorde().unleash()\n</script>\n
\n\n

\"\"

\n\n

Custom gremlins

\n\n
gremlins.createHorde()\n  .allGremlins()\n  .gremlin(function () {\n    document.activeElement.blur()\n  })\n
\n\n

Runs the given function at regular intervals.

\n\n

Full example

\n\n
gremlins.createHorde()\n  .gremlin(gremlins.species.formFiller())\n  .gremlin(gremlins.species.clicker()\n    .clickTypes(['click'])\n    .canClick(element => { ··· })\n    .showAction((x, y) => { ··· }))\n  .gremlin(gremlins.species.scroller())\n  .mogwai(gremlins.mogwais.alert())\n  .mogwai(gremlins.mogwais.fps())\n  .mogwai(gremlins.mogwais.gizmo().maxErrors(2))\n  .unleash()\n
\n\n

By default, all gremlins and mogwais species are added to the horde. Do it this way to customize gremlins.

\n\n

See: Specifying gremlins

\n\n

Hooks

\n\n

Before and after

\n\n
gremlins.createHorde()\n  .before(function () {\n    this.log('sync')\n    console.profile('gremlins')\n  })\n  .after(function () {\n    this.log('done')\n    console.profileEnd()\n  })\n
\n\n

Asynchronous

\n\n
gremlins.createHorde()\n  .before(function (done) {\n    setTimeout(() => {\n      this.log('async')\n      done()\n    }, 500)\n  })\n
\n\n

References

\n\n", "intro_html": "

Gremlins is a JavaScript library to do “monkey-testing” by providing random user input (clicks, scrolls, and so on).

", "description_html": "", "tags": null, "updated": "2017-10-22" },{ "id": "gulp", "title": "Gulp", "url": "/gulp", "category": "JavaScript libraries", "keywords": null, "content_html": "\n\n

Example

\n\n
// gulpfile.js\n// Load plugins\nvar gulp = require('gulp'),\n    sass = require('gulp-ruby-sass'),\n    autoprefixer = require('gulp-autoprefixer'),\n    minifycss = require('gulp-minify-css'),\n    jshint = require('gulp-jshint'),\n    uglify = require('gulp-uglify'),\n    imagemin = require('gulp-imagemin'),\n    rename = require('gulp-rename'),\n    clean = require('gulp-clean'),\n    concat = require('gulp-concat'),\n    notify = require('gulp-notify'),\n    cache = require('gulp-cache'),\n    livereload = require('gulp-livereload'),\n    lr = require('tiny-lr'),\n    server = lr();\n\n// Styles\ngulp.task('styles', function() {\n  return gulp.src('src/styles/main.scss')\n    .pipe(sass({ style: 'expanded', }))\n    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))\n    .pipe(gulp.dest('dist/styles'))\n    .pipe(rename({ suffix: '.min' }))\n    .pipe(minifycss())\n    .pipe(livereload(server))\n    .pipe(gulp.dest('dist/styles'))\n    .pipe(notify({ message: 'Styles task complete' }));\n});\n\n// Scripts\ngulp.task('scripts', function() {\n  return gulp.src('src/scripts/**/*.js')\n    .pipe(jshint('.jshintrc'))\n    .pipe(jshint.reporter('default'))\n    .pipe(concat('main.js'))\n    .pipe(gulp.dest('dist/scripts'))\n    .pipe(rename({ suffix: '.min' }))\n    .pipe(uglify())\n    .pipe(livereload(server))\n    .pipe(gulp.dest('dist/scripts'))\n    .pipe(notify({ message: 'Scripts task complete' }));\n});\n\n// Images\ngulp.task('images', function() {\n  return gulp.src('src/images/**/*')\n    .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))\n    .pipe(livereload(server))\n    .pipe(gulp.dest('dist/images'))\n    .pipe(notify({ message: 'Images task complete' }));\n});\n\n// Clean\ngulp.task('clean', function() {\n  return gulp.src(['dist/styles', 'dist/scripts', 'dist/images'], {read: false})\n    .pipe(clean());\n});\n\n// Default task\ngulp.task('default', ['clean'], function() {\n    gulp.start('styles', 'scripts', 'images');\n});\n\n// Watch\ngulp.task('watch', function() {\n\n  // Listen on port 35729\n  server.listen(35729, function (err) {\n    if (err) {\n      return console.log(err)\n    };\n\n    // Watch .scss files\n    gulp.watch('src/styles/**/*.scss', ['styles']);\n\n    // Watch .js files\n    gulp.watch('src/scripts/**/*.js', ['scripts']);\n\n    // Watch image files\n    gulp.watch('src/images/**/*', ['images']);\n\n  });\n\n});\n
\n\n

References

\n\n

https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md#getting-started

\n\n

Livereload

\n\n
var lr = require('tiny-lr')();\n\nfunction notify (lr, root) {\n  return function (event) {\n    var fname = require('path').relative(root, event.path);\n    lr.changed({ body: { files: [ fname ] }});\n  };\n}\n\ngulp.task('livereload', function () {\n  lr.listen(35729)\n  gulp.watch('public/**/*', notify(lr, __dirname+'/public'));\n});\n\n// Express\napp.use(require('connect-livereload')())\n<!-- livereload --><script>document.write('<script src=\"'+(location.protocol||'http:')+'//'+(location.hostname||'localhost')+':35729/livereload.js?snipver=1\"><\\/scr'+'ipt>')</script>\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "haml", "title": "Haml", "url": "/haml", "category": "Markup", "keywords": null, "content_html": "

Doctype

\n\n
!!! 5\n
\n\n

Tags

\n\n
%html\n  %head\n    %title\n  %body\n    %h1 Hello World\n    %br/\n
\n\n

Classes and ID’s

\n\n
%p.class-example\n.no-tag-defaults-to-div\n%div#butItCanBeIncluded\n
\n\n

Inline Attributes

\n\n

Either hash syntax works

\n\n
%meta{ name: \"viewport\", content: \"width=device-width, initial-scale=1.0\" }\n%input{ :type => \"text\", :required => true }\n
\n\n

Ruby

\n\n
-# This is a comment\n-# Anything starting with a hyphen signals to Haml that Ruby is coming\n- @arr = [1, 2, 3]\n- @str = \"test\"\n-# Equal signals output\n= render partial: \"shared/header\"\n= yield\n= link_to page_url\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "handlebars.js", "title": "Handlebars.js", "url": "/handlebars.js", "category": "JavaScript libraries", "keywords": null, "content_html": "

Helpers

\n\n
Handlebars.registerHelper('link_to', function() {\n  return \"<a href='\" + this.url + \"'>\" + this.body + \"</a>\";\n})\n
\n\n
var context = { posts: [{url: \"/hello-world\", body: \"Hello World!\"}] }\nvar source = \"<ul>{{#posts}}<li>{{{link_to}}}</li>{{/posts}}</ul>\"\n
\n\n
var template = Handlebars.compile(source)\ntemplate(context)\n
\n\n

Would render:

\n\n
<ul>\n  <li><a href='/hello-world'>Hello World!</a></li>\n</ul>\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "harvey.js", "title": "Harvey.js", "url": "/harvey.js", "category": "JavaScript libraries", "keywords": null, "content_html": "

Usage

\n\n
Harvey.attach('(min-width: 600px)', {\n  setup: function () {\n    // Called on first enter\n  },\n  on: function () {\n    // Called on every enter\n  },\n  off: function () {\n    // Called on every exit\n  }\n})\n
\n\n

Deprecated

\n\n

Harvey.js hasn’t been updated in a while, as of time of writing. Consider enquire.js instead.

\n\n

References

\n\n", "intro_html": "

Harvey.js helps you build responsive interfaces.

", "description_html": "", "tags": null, "updated": null },{ "id": "heroku", "title": "Heroku", "url": "/heroku", "category": "Devops", "keywords": null, "content_html": "

create - Create an app

\n\n
heroku create sushi\n
\n\n
git push heroku master\n
\n\n

access - Collaboration

\n\n

Manage collaborators

\n\n
heroku access                     # List\nheroku access:add me@xy.com\nheroku access:remove me@xy.com\n
\n\n

Transfer to another owner

\n\n
heroku apps:transfer new@owner.com\n
\n\n

logs - Show logs

\n\n
heroku logs\nheroku logs -t      # --tail (stream)\nheroku logs -s app  # --source (only on app logs)\n
\n\n

releases

\n\n
heroku releases\nheroku releases:info v25\nheroku rollback\n
\n\n

pg - PostgreSQL

\n\n

Start a database

\n\n
heroku addons:add heroku-postgresql\n
\n\n

Enable backups

\n\n
heroku addons:add pgbackups:auto-month\n
\n\n

See: Heroku PostgreSQL (devcenter.heroku.com)

\n\n

config - Environment var configuration

\n\n

Listing

\n\n
heroku config        # List\nheroku config -s     # List in shell format\n
\n\n

Getting

\n\n
heroku config:get KEY\n
\n\n

Setting

\n\n
heroku config:set KEY=val\nheroku config:set KEY1=val KEY2=val ...\n
\n\n
heroku config:unset KEY1\n
\n\n

apps - Applications

\n\n
heroku apps                  # list\nheroku apps:create [NAME]\nheroku apps:destroy --app APP\nheroku apps:info\nheroku apps:open             # open in browser\nheroku apps:rename NEWNAME\n
\n\n

maintenance

\n\n
heroku maintenance:on\n
\n\n
heroku maintenance:off\n
\n\n

Processes

\n\n

ps - Managing processes

\n\n
heroku ps              # list\nheroku ps:scale web=1  # spawn more dynos\n
\n\n

restart

\n\n
heroku restart\n
\n\n

run - Running tasks

\n\n
heroku run bash\nheroku run console                  # Rails console\nheroku run rake assets:precompile\n
\n\n

Domains

\n\n

domains - Custom domains

\n\n

Add both!

\n\n
heroku domains:add example.com\nheroku domains:add www.example.com\n
\n\n

Removing

\n\n
heroku domains:clear\nheroku domains:remove example.com\n
\n\n

See: Custom domains (devcenter.heroku.com)

\n\n

Wildcard domains

\n\n
heroku addons:add wildcard_domains\n
\n\n
*.yourdomain.com => heroku.com\n
\n\n

Other tricks

\n\n

htpasswd (for PHP apps)

\n\n

Create an .htaccess file in the webroot:

\n\n
AuthUserFile /app/www/.htpasswd\nAuthType Basic\nAuthName \"Restricted Access\"\nRequire valid-user\n
\n\n

Create a .htpasswd file:

\n\n
$ htpasswd -c .htpasswd [username]\n
\n\n

See: gist.github.com

\n\n

References

\n\n", "intro_html": "

Heroku is a web hosting platform supporting many languages, and this guide is a reference to Heroku’s command-line interface.

", "description_html": "

A one-page reference to common Heroku-CLI commands.

", "tags": null, "updated": "2017-10-11" },{ "id": "hledger", "title": "Hledger", "url": "/hledger", "category": "Ledger", "keywords": null, "content_html": "

Reporting

\n\n
hledger bal {query}\nhledger reg {query}\n
\n\n

Query

\n\n

Queries are used on all commands (bal, reg, etc). (docs)

\n\n
Assets           # An account (regex)\nacct:Assets      # same\n^Assets          # Starting with Assets (eg, not 'Expenses:Assets')\n\nacctonly:A       # no subaccounts\n\namt:2000         # amount (in absolute value)\namt:<200         # amount comparison (in absolute value)\namt:<+200        # amount comparison\n                 # also: <=, >, >=\n\ndesc:REGEX      # description\ncode:REGEX      # transaction code (check number?)\ntag:REGEX\ncur:'\\$'\n\nreal:            # real posts\nreal:0           # virtual posts\n\ndepth:N          # --depth 2\nnot:...          # eg, not:status:!\n
\n\n

Filter by status/type

\n\n
real:1           # -R, --real, no virtuals\nstatus:!         #     --pending\nstatus:*         # -C, --cleared\nstatus:          #     --uncleared\n
\n\n

Periods

\n

For dates and intervals (see above).

\n\n
date:2015/01/01\ndate:2015/01/01-    # -b, --begin\ndate:-2015/01/01    # -e, --end\ndate2:PERIODEXPR\n
\n\n
-p, --period=...\n  -p \"2009/01/01\"\n  -p \"2009/01/01 to 2009/12/31\"\n  -p \"2009/01/01to2009/12/31\"      # spaces optional\n  -p \"1/1 to 12/31\"\n  -p \"to 2009\"\n  -p \"weekly\"                      # -W, --weekly\n  -p \"weekly 2009/01/01 to 2009/12/31\"\n
\n\n

Intervals

\n

Used on all commands (bal, reg, etc). Displays in multi-column mode. In ledger-cli, only reg is supported. Can also specified via -p (period).

\n\n
-D, --daily\n-W, --weekly\n-M, --monthly\n-Q, --quarterly\n-Y, --yearly\n
\n\n

Smart dates

\n

Used for --period, --begin and --end (-p -b -e).

\n\n
-p 2015/01/01\n-p 2015/01\n-p 2015\n-p january\n-p jan\n-p 05/25\n
\n\n
-b today\n-b yesterday\n-e tomorrow\n
\n\n
-p this week\n-p last month\n-p this year\n
\n\n

Display formats

\n\n
    --tree          # only in bal\n    --flat\n\n    --depth 2       # collapse those under this depth\n    --drop 1        # drop top-level accounts\n-B, --cost          # convert to default currency\n-E, --empty         # don't strip out $0 accounts\n    --date2         # use date2 when available\n
\n\n

Multi-column mode

\n

When used with intervals (like --weekly):

\n\n
-T, --row-total\n-N, --no-total\n
\n\n

Also: (only in bal)

\n\n
    --cumulative    # show ending balance per period\n-I, --historical    # like --cumulative but only for --begin\n-A, --average\n
\n\n

Accounts

\n\n
hledger accounts [--tree]\n
\n\n

Other commands

\n\n
hledger balancesheet       # bs\nhledger incomestatement    # is\nhledger cashflow           # cf\nhledger print\nhledger activity\nhledger stats\n
\n\n

Examples

\n\n
# Current balance\n  hledger bal Assets\n  hledger balancesheet\n\n  hledger balancesheet Assets [--cleared --cost --empty -e tomorrow]\n  # ...discard future stuff; convert foreign currencies\n\n# Monthly changes in assets\n  hledger bal Assets Liabilities --monthly --tree --historical [--cleared --cost --empty -e tomorrow]\n\n# Weekly expenses\n  hledger bal Expenses --weekly --average --tree -b 'last month' [--cleared --cost --empty -e tomorrow]\n
\n\n

See also

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "homebrew", "title": "Homebrew", "url": "/homebrew", "category": "CLI", "keywords": null, "content_html": "

Commands

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
brew install gitInstall a package
brew uninstall gitRemove/Uninstall a package
brew upgrade gitUpgrade a package
brew unlink gitUnlink
brew link gitLink
brew switch git 2.5.0Change versions
brew list --versions gitSee what versions you have
\n\n

More package commands

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
brew info gitList versions, caveats, etc
brew cleanup gitRemove old versions
brew edit gitEdit this formula
brew cat gitPrint this formula
brew home gitOpen homepage
brew search gitSearch for formulas
\n\n

Global commands

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
brew updateUpdate brew and cask
brew upgradeUpgrade all packages
brew listList installed
brew outdatedWhat’s due for upgrades?
brew doctorDiagnose brew issues
\n\n

Brew Cask commands

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
brew cask install firefoxInstall the Firefox browser
brew cask listList installed applications
\n\n

Cask commands are used for interacting with graphical applications.

\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "html-email", "title": "HTML emails", "url": "/html-email", "category": "HTML", "keywords": null, "content_html": "

Properties to avoid

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PropertyWhere
position(Outlook, Gmail, Yahoo)
display(Outlook, Gmail)
float(Outlook)
height(Outlook)
width in p/div(Outlook)
padding in p/div(Outlook)
background(Outlook, Gmail)
min-width(Outlook)
max-width(Outlook)
opacity(Outlook, Gmail, Yahoo)
box-shadow(Outlook, Gmail, Yahoo)
rgba()(Outlook)
data-uri(all webmail)
\n\n

Selectors to avoid

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
E[attr](Outlook, Gmail)
E:nth-child(n)(Outlook, Gmail)
::before and ::after(Outlook, Yahoo, Gmail)
E F(Gmail)
E + F, E > F etc(Outlook, Gmail)
\n\n

Inline your CSS as much as possible.

\n\n

Basic layout

\n\n
<table cellpadding=\"0\" cellspacing=\"0\">\n  <tr>\n    <td width=\"auto\"></td>\n    <td width=\"600\" background=\"#ffffff\">\n      ···\n    </td>\n    <td width=\"auto\"></td>\n  </tr>\n</table>\n
\n\n

Responsive

\n\n
<style>\n@media only screen and (max-device-width: 480px)\n</style>\n
\n\n

<style> is supported in the head and body by everything except Gmail. Only use them for responsive styles.

\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-08-30" },{ "id": "html-input", "title": "Input tag", "url": "/html-input", "category": "HTML", "keywords": null, "content_html": "

Input

\n\n
 <input ...\n   disabled\n   required\n   checked\n
\n\n
   autofocus\n
\n\n
   autocomplete='off'        <!-- autocomplete -->\n   autocompletetype='cc-exp'\n   autocapitalize='off'      <!-- for mobiles -->\n   pattern='\\d*'             <!-- force numeric input in iOS -->\n
\n\n

Input types

\n\n

Text

\n\n\n\n

Time

\n\n\n\n

Time (not widely supported)

\n\n\n\n

Etc

\n\n\n\n

Buttons

\n\n\n\n

Numeric

\n\n\n\n

Examples

\n\n

Dates

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TypeExample
type='date'
type='time'
\n\n

Datetime

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TypeExample
type='datetime'
type='datetime-local'
\n\n

datetime and datetime-local fields are not widely supported.

\n\n

Numbers

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TypeExample
type='number'
type='range'
\n\n

Text

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TypeExample
type='text'
type='password'
type='search'
type='tel'
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-10-30" },{ "id": "html-meta", "title": "HTML meta tags", "url": "/html-meta", "category": "HTML", "keywords": null, "content_html": "

Meta tags

\n\n
<meta charset='utf-8'>\n
\n\n
<!-- title -->\n<title>···</title>\n<meta property='og:title'  content='···'>\n<meta name='twitter:title' content='···'>\n
\n\n
<!-- url -->\n<link rel='canonical'       href='http://···'>\n<meta property='og:url'  content='http://···'>\n<meta name='twitter:url' content='http://···'>\n
\n\n
<!-- description -->\n<meta name='description'         content='···'>\n<meta property='og:description'  content='···'>\n<meta name='twitter:description' content='···'>\n
\n\n
<!-- image -->\n<meta property=\"og:image\"  content=\"http://···\">\n<meta name=\"twitter:image\" content=\"http://···\">\n
\n\n
<!-- ua -->\n<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>\n
\n\n
<!-- viewport -->\n<meta name='viewport' content='width=device-width'>\n<meta name='viewport' content='width=1024'>\n
\n\n

More opengraph

\n\n
<meta property='og:site_name' content='···'>\n<meta property='og:type' content='website'>\n
\n\n
<meta property='fb:app_id' content='···'>\n<meta property='fb:admins' content='UID1,UID2'>\n<!-- ···unless there's app_id -->\n
\n\n
<meta property='og:audio' content='http://···/theme.mp3'>\n<meta property='og:video' content='http://···/trailer.swf'>\n
\n\n

See: OpenGraph protocol (developers.facebook.com)

\n\n

Opengraph for articles

\n\n\n\n

Apple-only

\n\n
<meta name='format-detection' content='telephone=no'>\n
\n\n

Progressive web apps

\n\n

Add to homescreen

\n\n
<meta name='mobile-web-app-capable' content='yes'>\n<meta name='apple-mobile-web-app-capable' content='yes'>\n
\n\n
<meta name='apple-mobile-web-app-status-bar-style' content='black'>\n<!-- black | black-translucent | default -->\n
\n\n

Theme color

\n\n
<meta name='theme-color' content='#ff00ff'>\n
\n\n

Android-only.\nSee: Theme color

\n\n

Manifest

\n\n
<link rel='manifest' href='/manifest.json'>\n
\n\n

Android-only.\nSee: Manifest

\n\n

Icons

\n\n
<!-- Minimal -->\n<link rel='icon' type='image/png' href='favicon@32.png'>\n<link rel='icon' sizes='192x192' href='icon@192.png'>\n<link rel='apple-touch-icon' href='icon@152.png'>\n<meta name='msapplication-square310x310logo' content='icon@310.png'>\n
\n\n
<!-- Apple -->\n<link rel='apple-touch-icon' href='touch-icon-iphone.png'>\n<link rel='apple-touch-icon' sizes='76x76' href='touch-icon-ipad.png'>\n<link rel='apple-touch-icon' sizes='120x120' href='touch-icon-iphone-retina.png'>\n<link rel='apple-touch-icon' sizes='152x152' href='touch-icon-ipad-retina.png'>\n
\n\n
<!-- Microsoft -->\n<meta name='msapplication-square70x70logo' content='icon_smalltile.png'>\n<meta name='msapplication-square150x150logo' content='icon_mediumtile.png'>\n<meta name='msapplication-wide310x150logo' content='icon_widetile.png'>\n
\n\n

Chrome on Android recommends 192x192.\nSee: Icons

\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-03-20" },{ "id": "html-microformats", "title": "Microformats", "url": "/html-microformats", "category": "HTML", "keywords": null, "content_html": "

Author

\n\n
<span class=\"entry-author\" itemprop=\"author\" itemscope=\"itemscope\" itemtype=\"http://schema.org/Person\">\n  <a href=\"http://AUTHORPAGE\" class=\"entry-author-link\" itemprop=\"url\" rel=\"author\">\n    <span class=\"entry-author-name\" itemprop=\"name\">AUTHORNAME</span>\n  </a>\n</span>\n
\n\n

Time

\n\n
<time class=\"entry-time\" itemprop=\"datePublished\" datetime=\"2009-02-09T20:04:00+00:00\">February 9, 2009</time>\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "html-share", "title": "Share links", "url": "/html-share", "category": "HTML", "keywords": null, "content_html": "

Share links

\n\n

Facebook:

\n\n
<a href='https://www.facebook.com/sharer/sharer.php?u=URL' target='share'>\n
\n\n

Twitter:

\n\n
<a href='https://twitter.com/intent/tweet?text=DESCRIPTION+URL' target='share'>\n
\n\n

Google Plus:

\n\n
<a href='https://plus.google.com/share?url=URL' target='share'>\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-04" },{ "id": "html", "title": "HTML", "url": "/html", "category": "HTML", "keywords": null, "content_html": "

Head stuff

\n\n
<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/favicon.ico\">\n<link rel=\"shortcut icon\" type=\"image/png\" href=\"/favicon.png\">\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n
\n\n

iPhone viewport

\n\n
<meta name=\"viewport\" content=\"initial-scale=1.0, maximum-scale=1.0\">\n<meta name=\"viewport\" content=\"width=device-width\">\n<meta name=\"viewport\" content=\"width=320, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\"/> <!-- full example -->\n
\n\n

Default OpenGraph meta tags

\n\n
<meta content=\"...\" name=\"description\">\n<meta content=\"...\" property=\"og:description\">\n<meta content=\"http://.../preview.jpg\" property=\"og:image\">\n<meta content=\"Hello There\" property=\"og:title\">\n<meta content=\"Hello There\" property=\"og:site_name\">\n<meta content=\"hellothere\" property=\"fb:admins\">\n<meta content=\"website\" property=\"og:type\">\n
\n\n

Webfonts

\n\n
<script>WebFontConfig={    },function(a,b){var c=a.createElement(b);c.src=\"//ajax.googleapis.com/ajax/libs/webfont/1/webfont.js\",c.async=1;var d=a.getElementsByTagName(b)[0];d.parentNode.insertBefore(c,d)}(document,\"script\")</script>\n\n// {typekit{id:\"...\"}}\n// {google:{families:['Exo:400']}}\n
\n\n

Google Analytics

\n\n
<script>location.hostname.match(/helloworld\\.com/)&&(_gaq=[[\"_setAccount\",\"UA-XXXXX-1\"],[\"_trackPageview\"]],function(a,b){var c=a.createElement(b),d=a.getElementsByTagName(b)[0];c.async=1,c.src=(\"https:\"==location.protocol?\"//ssl\":\"//www\")+\".google-analytics.com/ga.js\",d.parentNode.insertBefore(c,d)}(document,\"script\"))</script>\n
\n\n

FB/Twitter

\n\n
<div id=\"fb-root\"></div><script>fbAsyncInit=function(){FB.init({\"appId\":\"___APPIDGOESHERE___\",\"status\":true,\"cookie\":true,\"xfbml\":true})};!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.async=1;js.src='//connect.facebook.net/en_US/all.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','facebook-jssdk');</script>\n\n<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.async=1;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");</script>\n
\n\n

HTML5 Shiv for IE8

\n\n
<!--[if lte IE 8]><script src='//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.6.1/html5shiv.js'></script><![endif]-->\n
\n\n

H5BP HTML tag (IE8 and IE9 only)

\n\n
<!--[if lte IE 8]><html class=\"ie8\"><![endif]--><!--[if IE 9]><html class=\"ie9\"><![endif]--><!--[if gt IE 9]><!-->\n<html><!--<![endif]-->\n
\n\n

Touch icons

\n\n\n\n

Icons

\n\n
<link rel=\"shortcut icon\" type=\"image/png\" href=\"favicon.png\">\n<link href=\"apple-touch-icon-precomposed.png\" rel=\"apple-touch-icon\">\n<link href=\"apple-touch-icon-57x57-precomposed.png\" size=\"57x57\" rel=\"apple-touch-icon\">\n<link href=\"apple-touch-icon-72x72-precomposed.png\" size=\"72x72\" rel=\"apple-touch-icon\">\n<link href=\"apple-touch-icon-114x114-precomposed.png\" size=\"114x114\" rel=\"apple-touch-icon\">\n<link href=\"apple-touch-icon-144x144-precomposed.png\" size=\"144x144\" rel=\"apple-touch-icon\">\n
\n\n

Only do this if you’re not placing the site in the root!

\n\n

H5BP HTML tag

\n\n
<!--[if lt IE 7 ]> <html class=\"ie6\"> <![endif]-->\n<!--[if IE 7 ]>    <html class=\"ie7\"> <![endif]-->\n<!--[if IE 8 ]>    <html class=\"ie8\"> <![endif]-->\n<!--[if IE 9 ]>    <html class=\"ie9\"> <![endif]-->\n<!--[if (gt IE 9)|!(IE)]><!--> <html class=\"\"> <!--<![endif]-->\n
\n\n

Google jQuery

\n\n
<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"></script>\n
\n\n

Unsupported message

\n\n
<!--[if lt IE 8]>\n<div class=\"unsupported-browser\">\n  <strong>\n    You are using an outdated browser.\n  </strong>\n  <span>\n    Please <a class=\"upgrade-browser\"\n    href=\"http://browsehappy.com/\">\n    upgrade your browser</a> or <a  class=\"chrome-frame\"\n    href=\"http://www.google.com/chromeframe/?redirect=true\">activate Google \n    Chrome Frame</a> to improve your experience.\n  </span>\n</div>\n<![endif]-->\n
\n\n

HTML Compatibility inspector

\n\n
<script src=\"http://ie.microsoft.com/testdrive/HTML5/CompatInspector/inspector.js\"></script>\n
\n\n

More info here: microsoft.com

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "http-status", "title": "HTTP Status", "url": "/http-status", "category": "API", "keywords": null, "content_html": "

Informational Responses

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeName?
100Continue?
101Switching Protocols?
\n\n

Success Responses

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeName?
200OK?
201Created?
202Accepted?
203Non-Authoritive Information?
204No Content?
205Reset Content?
206Partial Content?
226IM Used?
\n\n

Redirection Responses

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeName?
300Multiple Choices?
301Moved Permanently?
302Found?
303See Other?
304Not Modified?
305Use Proxy?
306Switch Proxy?
307Temporary Redirect?
308Permanent Redirect?
\n\n

Client Error Responses

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeName?
400Bad Request?
401Unauthorized?
402Payment Required?
403Forbidden?
404Not Found?
405Method Not Allowed?
406Not Acceptable?
407Proxy Authentication Required?
408Request Timeout?
409Conflict?
410Gone?
411Length Required?
412Precondition Failed?
413Payload Too Large?
414URI Too Long?
415Unsupported Media Type?
416Range Not Satisfiable?
417Expectation Failed?
418I’m a teapot?
421Misdirected Request?
426Upgrade Required?
428Precondition Required?
429Too Many Requests?
431Request Header Fields Too Large?
451Unavailable For Legal Reasons?
\n\n

Server Error Responses

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeName?
500Internal Server Error?
501Not Implemented?
502Bad Gateway?
503Service Unavailable?
504Gateway Timeout?
505HTTP Version Not Supported?
506Variant Also Negotiates?
510Not Extended?
511Network Authentication Required?
\n\n

WebDAV Status Codes

\n\n

WebDAV is an extension of HTTP that allows clients to perform remote Web content authoring operations. It provides a framework for users to create, change and move documents on a server. It adds the following status codes on top of HTTP.

\n\n

Read more.

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeName?
102Processing?
207Multi-Status?
208Already Reported?
422Unprocessable Entity?
423Locked?
424Failed Dependency?
507Insufficient Storage?
508Loop Detected?
\n\n

Also see

\n\n", "intro_html": "", "description_html": "

List of HTTP Status codes and links to description.

", "tags": null, "updated": null },{ "id": "httpie", "title": "httpie", "url": "/httpie", "category": "CLI", "keywords": null, "content_html": "

Intorduction

\n\n

HTTPie is a command-line HTTP client.

\n\n\n\n

Parameters

\n\n
$ http POST http://example.com/posts/3 \\\n    Origin:example.com \\  # :   HTTP headers\n    name=\"John Doe\" \\     # =   string\n    q==\"search\" \\         # ==  URL parameters (?q=search)\n    age:=29 \\             # :=  for non-strings\n    list:='[1,3,4]' \\     # :=  json\n    file@file.bin \\       # @   attach file\n    token=@token.txt \\    # =@  read from file (text)\n    user:=@user.json      # :=@ read from file (json)\n
\n\n

Forms

\n\n
$ http --form POST example.com \\\n    name=\"John Smith\" \\\n    cv=@document.txt\n
\n\n

Raw JSON

\n\n
$ echo '{\"hello\": \"world\"}' | http POST example.com/post\n
\n\n

Options

\n\n

Printing options

\n\n
-v, --verbose            # same as --print=HhBb --all\n-h, --headers            # same as --print=h\n-b, --body               # same as --print=b\n    --all                # print intermediate requests\n    --print=HhBb         # H: request headers\n                         # B: request body\n                         # h: response headers\n                         # b: response body\n    --pretty=none        # all | colors | format\n    --json | -j          # Response is serialized as a JSON object.\n
\n\n

Authentication

\n\n
    --session NAME\n-a, --auth USER:PASS\n    --auth-type basic\n    --auth-type digest\n
\n\n

Session

\n\n
    --session NAME       # store auth and cookies\n    --session-read-only NAME\n
\n\n

Downloading

\n\n
-d, --download           # like wget\n-c, --continue\n-o, --output FILE\n
\n\n

Others

\n\n
-F, --follow             # follow redirects\n    --max-redirects N    # maximum for --follow\n    --timeout SECONDS\n    --verify no          # skip SSL verification\n    --proxy http:http://foo.bar:3128\n
\n\n

References

\n\n", "intro_html": "", "description_html": "

$ http POST http://example.com name=”John” Host:example.com — JSON, cookies, files, auth, and other httpie examples.

", "tags": null, "updated": "2020-07-05" },{ "id": "ie", "title": "Internet Explorer", "url": "/ie", "category": "HTML", "keywords": null, "content_html": "

Support table

\n\n

CSS Selectors

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FeatureIE6IE7IE8IE9IE10
> (descendant) 7 ✓
[attr] (attribute) 7 ✓
.class1.class2 (multiple classes) 7 ✓
~ (sibling) 7 ✓
+ (adjacent) 7 ✓
:first-child *  8 ✓
:focus  8 ✓
:before :after (single colon only)  8 ✓
:lang  8 ✓
:first-of-type, :last-of-type   9 ✓
:last-child   9 ✓
:empty   9 ✓
:enabled :disabled :checked   9 ✓
:not()   9 ✓
:nth-child() :nth-last-child()   9 ✓
:nth-of-type() :nth-last-of-type() :only-of-type()   9 ✓
:only-child()   9 ✓
:target   9 ✓
::selection   9 ✓
:root   9 ✓
\n\n

first-child: doesn’t work for elements inserted via JS.

\n\n

CSS properties

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FeatureIE6IE7IE8IE9IE10IE11
max-width 7 ✓
position: fixed 7 ✓
outline  8 ✓
display: inline-block *  8 ✓
display: table  8 ✓
border-collapse, border-spacing, table-layout, …  8 ✓
whitespace: pre-wrap  8 ✓
whitespace: pre-line  8 ✓
box-sizing  8 ✓
background-clip   9 ✓
background-origin   9 ✓
background-size   9 ✓
background: x, y, z (multiple backgrounds)   9 ✓
opacity   9 ✓
border-radius   9 ✓
box-shadow   9 ✓
rgba()   9 ✓
transform   9 ✓
animation    10 ✓
transition    10 ✓
linear-gradient()    10 ✓
text-shadowpolyfill    10 ✓
border-image     11 ✓
\n\n

inline-block: IE6/7 can only support inline-block for elements that are naturally inline, like span

\n\n

Features

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FeatureIE6IE7IE8IE9IE10IE11
PNG alpha transparency 7 ✓
data URI   8 ✓
JS: JSON parsing   8 ✓
JS: Cross-origin resource sharing   8 ✓
JS: Local storage   8 ✓
CSS: @media queries — polyfill   9 ✓
HTML: new HTML5 elements - polyfill   9 ✓
HTML: <canvas>   9 ✓
HTML: <svg>   9 ✓
HTML: <img src='image.svg'>   9 ✓
CSS: flexbox *    10 ✓
HTML: <input placeholder='..'>     10 ✓
HTML: <input type='range'>    10 ✓
HTML: <input required>     10 ✓
JS: Web sockets    10 ✓
JS: Fullscreen mode     11 ✓
\n\n

flexbox: IE10 only supports the 2012 syntax with -ms- prefix.

\n\n

Polyfills

\n\n

IE polyfills

\n\n

Always install these in almost every project:

\n\n\n\n
<!--[if lt IE 9]>\n<script src='https://cdnjs.cloudflare.com/ajax/libs/nwmatcher/1.2.5/nwmatcher.min.js'></script>\n<script src='https://cdnjs.cloudflare.com/ajax/libs/json2/20140204/json2.min.js'>\n<script src='https://cdn.rawgit.com/gisu/selectivizr/1.0.3/selectivizr.js'></script>\n<script src='https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js'>\n<script src='https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.js'>\n<![endif]--> \n
\n\n

You may also need

\n\n\n\n

for CSS3 decorations

\n\n\n\n

See: Cross-browser polyfills list

\n\n

Misc

\n\n

IE Conditional comment HTML

\n\n
<!--[if lt IE 7 ]> <html class=\"ie6\"> <![endif]-->\n<!--[if IE 7 ]>    <html class=\"ie7\"> <![endif]-->\n<!--[if IE 8 ]>    <html class=\"ie8\"> <![endif]-->\n<!--[if IE 9 ]>    <html class=\"ie9\"> <![endif]-->\n<!--[if (gt IE 9)|!(IE)]><!--> <html class=\"\"> <!--<![endif]-->\n
\n\n

IE conditionals

\n\n
<!--[if IE]>      I'm IE      <![endif]-->\n<!--[if !IE]> --> Not IE <!-- <![endif]-->\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-03-06" },{ "id": "ie_bugs", "title": "Legacy IE bugs", "url": "/ie_bugs", "category": "HTML", "keywords": null, "content_html": "

IE8: ‘change’ event

\n\n

The ‘change’ event doesn’t always fire. Not for checkboxes, radios, multi-select lists. Use the click handler instead.

\n\n\n\n

IE8: label with input

\n\n

Clicking label with input inside doesn’t focus the input.

\n\n\n\n

IE8: Opacity propagation

\n\n

An element’s ‘opacity’ value isn’t propagated to its positioned descendants.

\n\n", "intro_html": "

A bunch of bugs to take care of if you’re going to target legacy IE browsers.

", "description_html": "", "tags": null, "updated": "2018-03-06" },{ "id": "imagemagick", "title": "Imagemagick", "url": "/imagemagick", "category": "Others", "keywords": null, "content_html": "

Common options

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
OptionDescription
-resize 100x40Resize to a dimension
-crop 40x30+10+10(width)x(height)+(x)+y
-crop 40x30-10-10(width)x(height)+(x)+y
-flipVertical
-flopHorizontal
-transposeFlip vertical + rotate 90deg
-transverseFlip horizontal + rotate 270deg
-trimTrim image edges
-rotate 90Rotate 90 degrees
\n\n

Resize to fit

\n\n
convert input.jpg -resize 80x80^ -gravity center -extent 80x80 icon.png\n
\n\n

Convert all images to another format

\n\n
mogrify -format jpg -quality 85 *.png\n
\n\n

Make a pdf

\n\n
convert *.jpg hello.pdf\n
\n\n

References

\n\n", "intro_html": "

A quick reference for common Imagemagick commands and switches.

", "description_html": "", "tags": null, "updated": null },{ "id": "immutable.js", "title": "Immutable.js", "url": "/immutable.js", "category": "JavaScript libraries", "keywords": null, "content_html": "

Maps

\n\n
var map = Immutable.Map({ a: 1, b: 2, c: 3 })\n
\n\n
map\n  .set('b', 50)\n  .get('b') // 50\n
\n\n

Lists

\n\n
var list = Immutable.List.of(1, 2)\n\nlist\n  .push(3, 4, 5)\n  .unshift(0)\n  .concat(list2, list3)\n  .get(0)\n  .size\n
\n\n

Nested maps

\n\n
var nested = Immutable.fromJS({ user: { profile: { name: 'John' } } })\n\nnested\n  // Update\n  .mergeDeep({ user: { profile: { age: 90 } } })\n  .setIn([ 'user', 'profile', 'name' ], 'Jack')\n  .updateIn([ 'user', 'profile', 'name' ], (s) => s.toUpperCase())\n\n  // Get\n  .getIn(['user', 'profile', 'name']) // 'JACK'\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "inkscape", "title": "Inkscape", "url": "/inkscape", "category": "Apps", "keywords": null, "content_html": "

All

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
- / =Zoom in/out
3 / 4Zoom to selection / drawing
5 / 6Zoom to page / page width
\n\n

Select tool (F1)

\n\n\n \n \n \n \n \n \n
[ ]Rotate
\n\n

Edit path (F2)

\n\n\n \n \n \n \n \n \n
Ctrlconstraint
\n\n

Dragging an anchor handle

\n\n\n \n \n \n \n \n \n \n \n \n \n
Ctrlsnap to 15 degrees
Alt?
\n\n

Bezier (Shift F6)

", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "wip/intl-datetime", "title": "Intl.DateTimeFormat", "url": "/wip/intl-datetime", "category": "Hidden", "keywords": null, "content_html": "

Parsing

\n\n

As local time

\n\n
const date = new Date(2012, 11, 20, 3, 0, 0)\n
\n\n

As UTC time

\n\n
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0))\n
\n\n

From ISO strings

\n\n
const date = new Date('2018-04-20T12:00:00Z')\n
\n\n

Note that JavaScript doesn’t “store” timezones in a date object. All these date objects, when expressed via .toString() or similar, will show the local timezone of the browser, regardless if you parsed UTC dates.

\n\n

Formatting dates

\n\n

Default formatting

\n\n
console.log(new Intl.DateTimeFormat().format(date))\n// → '12/19/2012' (assuming America/Los_Angeles)\n
\n\n

Custom locale

\n\n
console.log(new Intl.DateTimeFormat('en-GB').format(date))\n// → '19/12/2012' (date-first)\n
\n\n

Custom timezone

\n\n
console.log(new Intl.DateTimeFormat('en-AU', {\n  timeZone: 'Australia/Sydney'\n}).format(date))\n// → '19/12/2012'\n
\n\n

Custom formats

\n\n

Time

\n\n
console.log(new Intl.DateTimeFormat('default', {\n  hour: 'numeric',\n  minute: 'numeric',\n  second: 'numeric'\n}).format(date))\n// → '2:00:00 pm'\n
\n\n

Date

\n\n
console.log(new Intl.DateTimeFormat('en-US', {\n  year: 'numeric',\n  month: 'numeric',\n  day: 'numeric'\n}).format(date))\n// → '12/19/2012'\n
\n\n

To specify options without a locale, use 'default' as a locale.

\n\n

All options

\n\n
{\n  weekday: 'narrow' | 'short' | 'long',\n  era: 'narrow' | 'short' | 'long',\n  year: 'numeric' | '2-digit',\n  month: 'numeric' | '2-digit' | 'narrow' | 'short' | 'long',\n  day: 'numeric' | '2-digit',\n  hour: 'numeric' | '2-digit',\n  minute: 'numeric' | '2-digit',\n  second: 'numeric' | '2-digit',\n  timeZoneName: 'short' | 'long',\n\n  // Time zone to express it in\n  timeZone: 'Asia/Shanghai',\n  // Force 12-hour or 24-hour\n  hour12: true | false,\n\n  // Rarely-used options\n  hourCycle: 'h11' | 'h12' | 'h23' | 'h24',\n  formatMatcher: 'basic' | 'best fit'\n}\n
\n\n

References

\n\n", "intro_html": "

Intl.DateTimeFormat is used to format date strings in JavaScript.

", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "ios-provision", "title": "iOS Provisioning Profiles", "url": "/ios-provision", "category": "Others", "keywords": null, "content_html": "

Types of profiles

\n\n\n\n

Requirements

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
WhatDevAdhocAppstore
CSR file 
Device UDIDs 
Developers list  
\n\n

Obtaining a CSR file

\n\n

Needed for Adhoc & Appstore builds.

\n\n\n\n

Get the .cer files

\n\n

Needed for Adhoc & Appstore builds.

\n\n\n\n

Obtaining device UDIDs

\n\n

Needed for Dev and Adhoc builds.

\n\n\n\n

For developers

\n\n

Don’t ever ask Xcode to Fix issue… for you.

\n\n

Using a provisioning profile

\n\n

No need to use .mobileprovision files since XCode 5.

\n\n\n\n

Building an .ipa (Adhoc or Appstore)

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "jade", "title": "Jade", "url": "/jade", "category": "JavaScript libraries", "keywords": null, "content_html": "", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "jasmine", "title": "Jasmine", "url": "/jasmine", "category": "JavaScript libraries", "keywords": null, "content_html": "

Tests

\n\n

Writing tests

\n\n
describe('A suite', () => {\n  it('works', () => {\n    expect(true).toBe(true)\n  })\n})\n
\n\n

Note: This cheatsheet may be a little outdated. Also see the Jest cheatsheet. Jest uses Jasmine, and therefore has similar API.

\n\n

Expectations

\n\n
expect(true).toBe(true)\nexpect(true).not.toBe(true)\n
\n\n
expect(a).toEqual(bar)\n
\n\n
expect(message).toMatch(/bar/)\nexpect(message).toMatch('bar')\n
\n\n
expect(a.foo).toBeDefined()\nexpect(a.foo).toBeUndefined()\nexpect(a.foo).toBeNull()\n
\n\n
expect(a.foo).toBeTruthy()\nexpect(a.foo).toBeFalsy()\n
\n\n
expect(message).toContain('hello')\n
\n\n
expect(pi).toBeGreaterThan(3)\nexpect(pi).toBeLessThan(4)\nexpect(pi).toBeCloseTo(3.1415, 0.1)\n
\n\n
expect(func).toThrow()\n
\n\n

Hooks

\n\n
beforeEach(() => {\n  ···\n})\n
\n\n
afterEach(() => {\n  ···\n})\n
\n\n

Pending

\n\n
xit('this is a pending test', () => {\n  ···\n})\n
\n\n
xdescribe('this is a pending block', () => {\n  ···\n})\n
\n\n

Spies

\n\n
spyOn(foo, 'setBar')\nspyOn(foo, 'setBar').andReturn(123)\nspyOn(foo, 'getBar').andCallFake(function() { return 1001; })\nfoo.setBar(123)\n
\n\n
expect(foo.setBar).toHaveBeenCalled()\nexpect(foo.setBar).toHaveBeenCalledWith(123)\nexpect(foo.setBar.calls.length).toEqual(2)\nexpect(foo.setBar.calls[0].args[0]).toEqual(123)\n
\n\n

Creating spies

\n\n
stub = jasmine.createSpy('stub')\nstub('hello')\n
\n\n
expect(stub.identity).toEqual('stub')\nexpect(stub).toHaveBeenCalled()\n
\n\n

Async

\n\n
test('works with promises', () => {\n  return new Promise((resolve, reject) => {\n    ···\n  })\n})\n
\n\n

Make your test return a promise.

\n\n

HTML runner

\n\n
var jasmineEnv = jasmine.getEnv()\njasmineEnv.updateInterval = 250\n\nvar htmlReporter = new jasmine.HtmlReporter()\njasmineEnv.addReporter(htmlReporter)\n\n$(function() { jasmineEnv.execute() })\n
\n\n

Jasmine jQuery

\n\n

Expectations

\n\n
expect($('#id')).toBe('div')\nexpect($('input[type=checkbox]')).toBeChecked()\nexpect($('input[type=checkbox]')).toBeDisabled()\nexpect($('input[type=checkbox]')).toBeFocused()\nexpect($('#menu ul')).toBeEmpty()\n
\n\n
expect($('#toolbar')).toBeHidden()\nexpect($('#toolbar')).toBeVisible()\n
\n\n
expect($('#popup')).toHaveCss({ margin: \"10px\" })\nexpect($('option')).toBeSelected()\n
\n\n
expect($('.foo')).toExist()\n
\n\n
expect($('a')).toHaveAttr('rel')\nexpect($('a')).toHaveAttr('rel', 'nofollow')\n
\n\n
expect($('a')).toHaveClass('rel')\nexpect($('a')).toHaveId('home')\n
\n\n
expect($('a')).toHaveHtml('<span></span>')\nexpect($('a')).toContainHtml('<span></span>')\nexpect($('a')).toHaveText('hi')\n
\n\n
expect($form).toHandle('submit') // event\nexpect($form).toHandleWith('submit', onSumbit)\n
\n\n

See: jasmine-jquery

\n\n

Event spies

\n\n
spyOnEvent($('#some_element'), 'click')\n$('#some_element').click()\nexpect('click').toHaveBeenPreventedOn($('#some_element'))\nexpect('click').toHaveBeenTriggeredOn($('#some_element'))\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "jekyll-github", "title": "Jekyll for GitHub pages", "url": "/jekyll-github", "category": "Jekyll", "keywords": null, "content_html": "

Jekyll

\n\n\n\n

As of github-pages v156. For an updated list, see: Dependency versions (pages.github.com)

\n\n

GitHub Metadata

\n\n

Configuration

\n\n
plugins:\n  - jekyll-github-metadata\n\nrepository: username/project\n
\n\n

Put this in your _config.yml.\nSee: Repository metadata on GitHub pages

\n\n

Listing repos

\n\n
{% for repository in site.github.public_repositories %}\n  <a href='{{ repository.html_url }}'>\n    {{ repository.name }}\n  </a>\n{% endfor %}\n
\n\n\n\n
<a href='{{ site.github.repository_url }}'>\n  {{ site.github.project_title }}\n</a>\n
\n\n

Gists

\n\n

Configuration

\n\n
plugins:\n  - jekyll-gist\n
\n\n

See: jekyll-gist

\n\n

Usage

\n\n
{% gist parkr/c08ee0f2726fd0e3909d %}\n
\n\n

This places a Gist in your page.

\n\n

Mentions

\n\n

Configuration

\n\n
plugins:\n  - jekyll-mentions\n
\n\n

See: jekyll-mentions

\n\n

Usage

\n\n
Hey @rstacruz, what do you think of this?\n
\n\n

Just mention anyone in any page. Their names will be turned into links.

\n\n

Redirects

\n\n

Configuration

\n\n
plugins:\n    - jekyll-redirect-from\n
\n\n

See: jekyll-redirect-from

\n\n

Usage

\n\n
---\nredirect_from:\n  - /foo\n---\n
\n\n

Place on any page.

\n\n

Redirecting

\n\n
---\nredirect_to:\n  - /foo\n---\n
\n\n

Place on any page.\nSee: redirect to

", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": "2017-11-17" },{ "id": "jekyll", "title": "Jekyll", "url": "/jekyll", "category": "Jekyll", "keywords": null, "content_html": "

Installation

\n\n
# Install the gems\ngem install jekyll bundler\n
\n\n
# Create a new site at `./myblog`\njekyll new myblog\ncd myblog\n
\n\n
# Optional: if you're targeting github-pages,\n# use this Gemfile instead.\ncat > Gemfile <<-END\nsource 'https://rubygems.org'\ngem 'github-pages', group: :jekyll_plugins\nEND\n
\n\n
bundle exec jekyll serve\n
\n\n

See: Jekyll quickstart
\nSee: github/pages-gem

\n\n

Directories

\n\n
./\n├── _config.yml\n│\n├── _data/\n│   └── ...\n│\n├── _drafts/\n│   └── ...\n│\n├── _posts/\n│   └── 2014-01-01-hello.md\n│\n├── _layouts/\n│   ├── default.html\n│   └── post.html\n│\n├── _includes/             - partials\n│   ├── header.html\n│   └── footer.html\n│\n└── _site/\n    └── ...\n
\n\n

Front-matter

\n\n

Basic frontmatter

\n\n
---\nlayout: post\ntitle: Hello\n---\nHello! this is my post.\n
\n\n

Attach metadata to a page by adding them on top of the page, delimited by ---.\nSee: Front-matter

\n\n

Other frontmatter stuff

\n\n
permalink: '/hello'\npublished: false\ncategory: apple\ncategories: ['html', 'css']\ntags: ['html', 'css']\n
\n\n

Configuration

\n\n

In _config.yml:

\n\n
source: .\ndestination: _site\nexclude:\n- Gemfile\n- Gemfile.lock\ninclude: ['.htaccess']\n
\n\n

All config keys are optional.\nSee: Configuration

\n\n

Markup

\n\n

Page variables

\n\n
<title>\n  {{ page.title }}\n</title>\n
\n\n

Filters

\n\n
<p>\n  {{ page.description | truncate_words: 20 }}\n</p>\n
\n\n

Loops

\n\n
{% for post in site.posts %}\n  <a href=\"{{ post.url }}\">\n    <h2>{{ post.title }}</h2>\n    <p>{{ post.date | date_to_string }}</p>\n  </a>\n{% endfor %}\n
\n\n

Dates

\n\n
{{ page.date | date: \"%b %d, %Y\" }}\n
\n\n

Conditionals

\n\n
{% if page.image.feature %}\n  ...\n{% elsif xyz %}\n  ...\n{% else %}\n  ...\n{% endif %}\n
\n\n
{% if page.category == 'React' %}\n{% if page.category == 'React' or page.featured %}\n{% if page.tags contains 'Featured' %}\n
\n\n

Case

\n\n
{% case shipping.title %}\n  {% when 'international' %}\n     Arriving in 2-3 weeks\n  {% when 'Domestic' %}\n     Arriving in 2-3 days\n  {% else %}\n     Thank you for your order!\n{% endcase %}\n
\n\n

Includes (partials)

\n\n
{% include header.html %}\n
\n\n
<!-- Including local vars -->\n{% include header.html page=page %}\n
\n\n

Comments

\n\n
{% comment %}\n  This is a comment!\n{% endcomment %}\n
\n\n

Variables

\n\n

Top-level variables

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
{{ site }}Data from config.yml
{{ page }}From frontmatter, and page-specific info
{{ content }}HTML content (use in layouts)
{{ paginator }}Paginator
\n\n

See: Variables

\n\n

Site

\n\n
{{ site.time }}\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
site.timeCurrent time
site.pagesList of pages
site.postsList of blog posts
site.related_postsList of posts related to current
site.categories.CATEGORYList
site.tags.TAGList
site.static_filesList
\n\n

Page

\n\n
{{ page.content }}  - un-rendered content\n{{ page.title }}\n{{ page.excerpt }}  - un-rendered excerpt\n{{ page.url }}\n{{ page.date }}\n{{ page.id }}       - unique id for RSS feeds\n{{ page.categories }}\n{{ page.tags }}\n{{ page.path }}\n{{ page.dir }}\n{{ page.excerpt | remove: '<p>' | remove: '</p>' }}\n{{ page.excerpt | strip_html }}\n
\n\n
<!-- blog pagination: -->\n{{ page.next }}\n{{ page.previous }}\n
\n\n

Filters

\n\n

Dates

\n\n
{{ site.time | date: \"%Y %m %d\" }}\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
date_to_xmlschema2008-11-07T13:07:54-08:00
date_to_rfc822Mon, 07 Nov 2008 13:07:54 -0800
date_to_string07 Nov 2008
date_to_long_string07 November 2008
date: ‘%Y %m %d’2017 Nov 7
\n\n

Preprocessors

\n\n
{{ page.description | markdownify }}\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FilterDescription
textilizeTextile
markdownifyMarkdown
jsonifyJSON
sassifySass
scssifySCSS
smartifySmartypants
\n\n

Array filters

\n\n
{{ site.pages | where: \"year\", \"2014\" }}\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FilterDescription
where: “year”, “2014” 
where_exp: “item”, “item.year >= 2014” 
group_by: “genre”{name, items}
group_by_exp: “item”, “item.genre”{name, items}
sort 
sort: ‘author’ 
uniq 
first 
last 
join: ’,’ 
array_to_sentence_string\"X, Y and Z\"
map: ‘post’Works like ‘pluck’
size 
push: ‘xxx’Adds an item
\n\n

String filters

\n\n
{{ page.title | default: \"xxx\" }}\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FilterDescription
default: ‘xxx’ 
upcase 
downcase 
remove: ‘p’ 
replace: ‘super’, ‘mega’ 
remove_first: ‘p’ 
replace_first: ‘super’, ‘mega’ 
truncate: 5 
truncatewords: 20 
prepend: ‘Mr. ‘ 
append: ‘Jr.’ 
camelize 
capitalize 
strip_html 
strip_newlines 
newlines_to_br 
split: ’,’ 
escape 
escape_once 
slice: -3, 3 
\n\n

See: String filters

\n\n

String filters (Jekyll-only)

\n\n
{{ page.excerpt | number_of_words }}\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FilterDescription
number_of_words 
slugify 
xml_escapeCDATA
cgi_escapefoo%2Cbar
uri_escapefoo,%20bar
\n\n

Numbers

\n\n
{{ site.posts.size | minus: 2 }}\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FilterDescription
minus: 2 
plus: 2 
times: 2 
divided_by: 2 
modulo: 2 
ceil 
floor 
round 
\n\n

Paginator

\n\n

Paginator setup

\n\n

Add this to _config.yml:

\n\n
paginate: 5\npaginate_path: \"blog/:num\"\n
\n\n

See: Paginator

\n\n

Numbers

\n\n
{{ paginator.page }}         - page number\n{{ paginator.total_posts }}\n{{ paginator.total_pages }}\n{{ paginator.per_page }}\n
\n\n

Iterating through posts

\n\n
{% for post in paginator.posts %} ... {% endfor %}\n
\n\n

Previous button

\n\n
{% if paginator.total_pages > 1 %}\n  {% if paginator.previous_page %}\n    <a href=\"{{ paginator.previous_page_path }}\">Previous</a>\n  {% else %}\n  {% endif %}\n{% endif %}\n
\n\n
{{ paginator.next_page }}     - page number\n{{ paginator.next_page_path }}\n
\n\n

Blogging

\n\n

Paths

\n\n
_posts/YEAR-MONTH-DAY-title.md\n
\n\n

See: Blogging

\n\n

Image paths

\n\n
![My helpful screenshot]({{ site.url }}/assets/screenshot.jpg)\n
\n\n

See: Image paths

\n\n

Drafts

\n\n
vi _drafts/a-draft-post.md\njekyll build --drafts\n
\n\n

Posts in _drafts only show up in development, but not production.\nSee: Drafts

\n\n

Defining excerpts

\n\n
---\ntitle: My blog post\nexcerpt: This post is about cats\n---\n\nHello, let's talk about cats. (···)\n
\n\n

Put a key excerpt in the frontmatter.\nSee: Excerpts

\n\n

Displaying excerpts

\n\n
{{ post.excerpt }}\n
\n\n
{{ post.excerpt | remove: '<p>' | remove: '</p>' }}\n{{ post.excerpt | strip_html }}\n
\n\n

Excerpt separator

\n\n
---\nexcerpt_separator: <!--more-->\n---\n\nExcerpt here\n<!--more-->\nMore post body here\n
\n\n

Alternatively, you can put excerpts inline in your post by defining excerpt_separator.

\n\n

Permalinks

\n\n
# _config.yml\npermalink: date   # /:categories/:year/:month/:day/:title.html\npermalink: pretty # /:categories/:year/:month/:day/:title/\npermalink: none   # /:categories/:title.html\npermalink: \"/:title\"\n
\n\n

See: Permalinks

\n\n

More features

\n\n

Data

\n\n
_data/members.yml\n
\n\n
{% for member in site.data.members %}\n  ...\n{% endfor %}\n
\n\n

See: Data

\n\n

Collections

\n\n
# _config.yml\ncollections:\n  - authors\n
\n\n
# _/authors/a-n-roquelaire.md\n---\nname: A. N. Roquelaire\nreal_name: Anne Rice\n---\n
\n\n
{% for author in site.authors %}\n
\n\n

See: Collections

\n\n

Code highlighter

\n\n
{% highlight ruby linenos %}\ndef show\n  ...\nend\n{% endhighlight %}\n
\n\n

Integration

\n\n

Bundler

\n\n

In _plugins/bundler.rb:

\n\n
require \"bunder/setup\"\nBundler.require :default\n
\n\n

Compass

\n\n\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-08-25" },{ "id": "jest", "title": "Jest", "url": "/jest", "category": "JavaScript libraries", "keywords": null, "content_html": "

Testing

\n\n

Quick start

\n\n
npm install --save-dev jest babel-jest\n
\n\n
/* Add to package.json */\n\"scripts\": {\n  \"test\": \"jest\"\n}\n
\n\n
# Run your tests\nnpm test -- --watch\n
\n\n

See: Getting started

\n\n

Writing tests

\n\n
describe('My work', () => {\n  test('works', () => {\n    expect(2).toEqual(2)\n  })\n})\n
\n\n

See: describe(), test(), expect()

\n\n

BDD syntax

\n\n
describe('My work', () => {\n  it('works', () => {\n    ···\n  })\n})\n
\n\n

it is an alias for test.\nSee: test()

\n\n

Setup

\n\n
beforeEach(() => { ... })\nafterEach(() => { ... })\n
\n\n
beforeAll(() => { ... })\nafterAll(() => { ... })\n
\n\n

See: afterAll() and more

\n\n

Focusing tests

\n\n
describe.only(···)\nit.only(···) // alias: fit()\n
\n\n

See: test.only

\n\n

Skipping tests

\n\n
describe.skip(···)\nit.skip(···) // alias: xit()\n
\n\n

See: test.skip

\n\n

Optional flags

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FlagDescription
--coverageSee a summary of test coverage
--detectOpenHandlesSee a summary of ports that didn’t close
--runInBandRun all tests one after the other
\n\n

Expect

\n\n

Basic expectations

\n\n
expect(value)\n  .not\n  .toBe(value)\n  .toEqual(value)\n  .toBeTruthy()\n
\n\n

Note that toEqual is a deep equality check.\nSee: expect()

\n\n

Snapshots

\n\n
expect(value)\n  .toMatchSnapshot()\n  .toMatchInlineSnapshot()\n
\n\n

Note that toMatchInlineSnapshot() requires Prettier to be set up for the project.\nSee: Inline snapshots

\n\n

Errors

\n\n
expect(value)\n  .toThrow(error)\n  .toThrowErrorMatchingSnapshot()\n
\n\n

Booleans

\n\n
expect(value)\n  .toBeFalsy()\n  .toBeNull()\n  .toBeTruthy()\n  .toBeUndefined()\n  .toBeDefined()\n
\n\n

Numbers

\n\n
expect(value)\n  .toBeCloseTo(number, numDigits)\n  .toBeGreaterThan(number)\n  .toBeGreaterThanOrEqual(number)\n  .toBeLessThan(number)\n  .toBeLessThanOrEqual(number)\n
\n\n

Objects

\n\n
expect(value)\n  .toBeInstanceOf(Class)\n  .toMatchObject(object)\n  .toHaveProperty(keyPath, value)\n
\n\n

Objects

\n\n
expect(value)\n  .toContain(item)\n  .toContainEqual(item)\n  .toHaveLength(number)\n
\n\n

Strings

\n\n
expect(value)\n  .toMatch(regexpOrString)\n
\n\n

Others

\n\n
expect.extend(matchers)\nexpect.any(constructor)\nexpect.addSnapshotSerializer(serializer)\n\nexpect.assertions(1)\n
\n\n

More features

\n\n

Asynchronous tests

\n\n
test('works with promises', () => {\n  return new Promise((resolve, reject) => {\n    ···\n  })\n})\n
\n\n
test('works with async/await', async () => {\n  const hello = await foo()\n  ···\n})\n
\n\n

Return promises, or use async/await.\nSee: Async tutorial

\n\n

Snapshots

\n\n
it('works', () => {\n  const output = something()\n  expect(output).toMatchSnapshot()\n})\n
\n\n

First run creates a snapshot. Subsequent runs match the saved snapshot.\nSee: Snapshot testing

\n\n

React test renderer

\n\n
import renderer from 'react-test-renderer'\n
\n\n
it('works', () => {\n  const tree = renderer.create(\n    <Link page=\"http://www.facebook.com\">Facebook</Link>\n  ).toJSON()\n\n  expect(tree).toMatchSnapshot()\n})\n
\n\n

React’s test renderer can be used for Jest snapshots.\nSee: Snapshot test

\n\n

Timers

\n\n
jest.useFakeTimers()\n
\n\n
it('works', () => {\n  jest.runOnlyPendingTimers()\n  jest.runTimersToTime(1000)\n  jest.runAllTimers()\n})\n
\n\n

See: Timer Mocks

\n\n

Mock functions

\n\n

Mock functions

\n\n
const fn = jest.fn()\n
\n\n
const fn = jest.fn(n => n * n)\n
\n\n

See: Mock functions

\n\n

Assertions

\n\n
expect(fn)\n  .toHaveBeenCalled()\n  .toHaveBeenCalledTimes(number)\n  .toHaveBeenCalledWith(arg1, arg2, ...)\n  .toHaveBeenLastCalledWith(arg1, arg2, ...)\n
\n\n
expect(fn)\n  .toHaveBeenCalledWith(expect.anything())\n  .toHaveBeenCalledWith(expect.any(constructor))\n  .toHaveBeenCalledWith(expect.arrayContaining([ values ]))\n  .toHaveBeenCalledWith(expect.objectContaining({ props }))\n  .toHaveBeenCalledWith(expect.stringContaining(string))\n  .toHaveBeenCalledWith(expect.stringMatching(regexp))\n
\n\n

Instances

\n\n
const Fn = jest.fn()\n\na = new Fn()\nb = new Fn()\n
\n\n
Fn.mock.instances\n// → [a, b]\n
\n\n

See: .mock property

\n\n

Calls

\n\n
const fn = jest.fn()\nfn(123)\nfn(456)\n
\n\n
fn.mock.calls.length   // → 2\nfn.mock.calls[0][0]    // → 123\nfn.mock.calls[1][0]    // → 456\n
\n\n

See: .mock property

\n\n

Return values

\n\n
const fn = jest.fn(() => 'hello')\n
\n\n

or:

\n\n
jest.fn().mockReturnValue('hello')\njest.fn().mockReturnValueOnce('hello')\n
\n\n

Mock implementations

\n\n
const fn = jest.fn()\n  .mockImplementationOnce(() => 1)\n  .mockImplementationOnce(() => 2)\n
\n\n
fn()    // → 1\nfn()    // → 2\n
\n\n

References

\n\n", "intro_html": "

A quick overview to Jest, a test framework for Node.js. This guide targets Jest v20.

", "description_html": "", "tags": ["Featurable"], "updated": "2020-06-17" },{ "id": "jquery-cdn", "title": "jQuery CDN", "url": "/jquery-cdn", "category": "JavaScript libraries", "keywords": null, "content_html": "

Google jQuery

\n\n
<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n
", "intro_html": "", "description_html": "", "tags": ["Archived"], "updated": null },{ "id": "jquery", "title": "jQuery", "url": "/jquery", "category": "JavaScript libraries", "keywords": null, "content_html": "

Traversing

\n\n
$('.box')\n  .children()\n  .closest('div')\n  .filter(':selected')\n  .find('div')\n  .has('div')\n  .first()\n  .next('div')\n  .nextUntil('div')\n
\n\n

Advanced features

\n\n

Extending selectors

\n\n
$.expr[':'].inline = function (el) {\n  return $(el).css('display') === 'inline'\n}\n
\n\n

Enables $(':inline')

\n\n

Extend CSS properties

\n\n
$.cssHooks.someCSSProp = {\n  get: function (elem, computed, extra) {\n  },\n  set: function (elem, value) {\n  }\n}\n\n// Disable \"px\"\n$.cssNumber[\"someCSSProp\"] = true\n
\n\n

fn.animate() hooks

\n\n
$.fn.step.someWhatever = function(fx) {\n  // ...\n}\n
", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "js-appcache", "title": "applicationCache", "url": "/js-appcache", "category": "JavaScript", "keywords": null, "content_html": "

Reference

\n\n

applicationCache checking

\n\n
if (window.applicationCache) {\n  // \"Naturally\" reload when an update is available\n  var reload = false\n\n  window.applicationCache.addEventListener('updateready', () => {\n    if (window.applicationCache.status === window.applicationCache.UPDATEREADY) {\n      window.applicationCache.swapCache()\n      reload = true\n    }\n  }, false)\n\n  setInterval(() => {\n    try {\n      // There's nothing to update for first-time load, browser freaks out :/\n      window.applicationCache.update()\n    } catch (e) { }\n  }, 1000 * 60 * 60) // Every hour\n}\n
\n\n

This is a deprecated HTML feature. See: Using the application cache (developer.mozilla.org)

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "js-array", "title": "JavaScript Arrays", "url": "/js-array", "category": "JavaScript", "keywords": null, "content_html": "

Arrays

\n\n
list = [a,b,c,d,e]\n
\n\n
list[1]                 // → b\nlist.indexOf(b)         // → 1\n
\n\n

Subsets

\n\n

Immutable

\n\n
list.slice(0,1)         // → [a        ]\nlist.slice(1)           // → [  b,c,d,e]\nlist.slice(1,2)         // → [  b      ]\n
\n\n

Mutative

\n\n
re = list.splice(1)     // re = [b,c,d,e]  list == [a]\nre = list.splice(1,2)   // re = [b,c]      list == [a,d,e]\n
\n\n

Adding items

\n\n

Immutable

\n\n
list.concat([X,Y])      // → [_,_,_,_,_,X,Y]\n
\n\n

Mutative

\n\n
list.push(X)            // list == [_,_,_,_,_,X]\nlist.unshift(X)         // list == [X,_,_,_,_,_]\nlist.splice(2, 0, X)    // list == [_,_,X,_,_,_]\n
\n\n

Inserting

\n\n
// after -- [_,_,REF,NEW,_,_]\nlist.splice(list.indexOf(REF)+1, 0, NEW))\n
\n\n
// before -- [_,_,NEW,REF,_,_]\nlist.splice(list.indexOf(REF), 0, NEW))\n
\n\n

Replace items

\n\n
list.splice(2, 1, X)    // list == [a,b,X,d,e]\n
\n\n

Removing items

\n\n
list.pop()              // → e    list == [a,b,c,d]\nlist.shift()            // → a    list == [b,c,d,e]\nlist.splice(2, 1)       // → [c]  list == [a,b,d,e]\n
\n\n

Iterables

\n\n
.filter(n => ...) => array\n
\n\n
.find(n => ...)  // es6\n.findIndex(...)  // es6\n
\n\n
.every(n => ...) => Boolean // ie9+\n.some(n => ..) => Boolean   // ie9+\n
\n\n
.map(n => ...)   // ie9+\n.reduce((total, n) => total) // ie9+\n.reduceRight(...)\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "js-date", "title": "JavaScript Date", "url": "/js-date", "category": "JavaScript", "keywords": null, "content_html": "

Date

\n\n

Constructor

\n\n
// Now\nnew Date()\n
\n\n
// ms since epoch\nnew Date(1419785527580)\n
\n\n
// Date format\nnew Date(\"May 17, 1995 03:24:00\")\n
\n\n
// ISO date format\nnew Date(\"2013-03-01T01:10:00\")\n
\n\n
new Date(2014, 2, 1, 13, 0, 59, 0)\n
\n\n

Constructor

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
new Date(2014,2,1,13,0,59,0)
DateYearMonthDayHourMinSecMilli
\n\n

Months are zero-indexed (eg, January is 0).

\n\n

Conversion

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodResult
d.toString()\"Mon Dec 29 2014 00:58:28 GMT+0800 (PHT)\"
d.toTimeString()\"00:58:46 GMT+0800 (PHT)\"
d.toUTCString()\"Sun, 28 Dec 2014 16:58:59 GMT\"
d.toDateString()\"Thu Jan 10 2013\"
d.toISOString()\"2013-01-09T16:00:00.000Z\"
d.toLocaleString()\"12/29/2014, 12:57:31 AM\"
d.toLocaleTimeString()\"12:57:31 AM\"
d.getTime()1419785527580
\n\n

Accessing

\n\n

Getters

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodResult
.getDate()1..31
.getDay()0..6 (sun..sat)
.getFullYear()2014
.getMonth()0..11
.getHours() 
.getMinutes() 
.getSeconds() 
.getMilliseconds() 
.getTime()ms since epoch
.getTimezoneOffset() 
\n\n

UTC versions are also available (eg, .getUTCDate(), .getUTCDay(), etc).

\n\n

Setters

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodResult
.setDate (val) 
.setDay (val) 
.setFullYear (val) 
.setMonth (val) 
.setHours (val) 
.setMinutes (val) 
.setSeconds (val) 
.setMilliseconds (val) 
.setTime (val) 
.setTimezoneOffset (val) 
\n\n

See the getters list.

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "js-fetch", "title": "fetch()", "url": "/js-fetch", "category": "JavaScript", "keywords": null, "content_html": "

Fetch

\n\n
fetch('/data.json')\n  .then(response => response.json())\n  .then(data => {\n    console.log(data)\n  })\n  .catch(err => ...)\n
\n\n

Response

\n\n
fetch('/data.json')\n.then(res => {\n  res.text()       // response body (=> Promise)\n  res.json()       // parse via JSON (=> Promise)\n  res.status       //=> 200\n  res.statusText   //=> 'OK'\n  res.redirected   //=> false\n  res.ok           //=> true\n  res.url          //=> 'http://site.com/data.json'\n  res.type         //=> 'basic'\n                   //   ('cors' 'default' 'error'\n                   //    'opaque' 'opaqueredirect')\n\n  res.headers.get('Content-Type')\n})\n
\n\n

Request options

\n\n
fetch('/data.json', {\n  method: 'post',\n  body: new FormData(form), // post body\n  body: JSON.stringify(...),\n\n  headers: {\n    'Accept': 'application/json'\n  },\n\n  credentials: 'same-origin', // send cookies\n  credentials: 'include',     // send cookies, even in CORS\n\n})\n
\n\n

Catching errors

\n\n
fetch('/data.json')\n  .then(checkStatus)\n
\n\n
function checkStatus (res) {\n  if (res.status >= 200 && res.status < 300) {\n    return res\n  } else {\n    let err = new Error(res.statusText)\n    err.response = res\n    throw err\n  }\n}\n
\n\n

Non-2xx responses are still successful requests. Use another function to turn them to errors.

\n\n

Using with node.js

\n\n
const fetch = require('isomorphic-fetch')\n
\n\n

See: isomorphic-fetch (npmjs.com)

\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "js-lazy", "title": "JavaScript lazy shortcuts", "url": "/js-lazy", "category": "JavaScript", "keywords": null, "content_html": "

Shortcuts

\n\n

Examples

\n\n
n = +'4096'    // n === 4096\ns = '' + 200   // s === '200'\n
\n\n
now = +new Date()\nisPublished = !!post.publishedAt\n
\n\n

Shortcuts

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
WhatLazy mode“The right way”
String to number+strparseInt(str, 10) or parseFloat()
Math floornum | 0Math.floor(num)
Number to string'' + numnum.toString()
Date to UNIX timestamp+new Date()new Date().getTime()
Any to boolean!!valueBoolean(value)
Check array contentsif (~arr.indexOf(v))if (arr.includes(v))
\n\n

.includes is ES6-only, otherwise use .indexOf(val) !== -1 if you don’t polyfill.

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "js-model", "title": "js-model", "url": "/js-model", "category": "JavaScript libraries", "keywords": null, "content_html": "

Example

\n\n
Project = Model \"project\", ->\n  @extend\n    findByTitle: (title) -> ...\n\n  @include\n    markAsDone: -> ...\n\n  # ActiveRecord::Base.include_root_in_json = false\n
\n\n
project = Project.find(1)\nproject = Project.findByTitle(\"hello\")\n\nproject.markAsDone()\n
\n\n

Persistence

\n\n
Project \"hi\", ->\n  @persistence Model.REST, \"/projects\"\n  @persistence Model.localStorage\n
\n\n
Project.load ->\n  # loaded\n
\n\n

Attrs

\n\n
project = new Project(name: \"Hello\")\n\nproject.attr('name', \"Hey\")\nproject.attr('name')\n\nproject.save()\nproject.destroy()\n
\n\n

Collection

\n\n
Food.add(egg)\nFood.all()\nFood.select (food) -> ...\nFood.first()\n
\n\n
Food.find(id)\n
\n\n

Events

\n\n
# Classes\nProject.bind \"add\", (obj) ->\nProject.bind \"remove\", (obj) ->\n
\n\n
# Instances\nproject.bind \"update\", ->\nproject.bind \"destroy\", ->\n
\n\n
project.trigger \"turn_blue\"\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "js-speech", "title": "JavaScript speech synthesis", "url": "/js-speech", "category": "JavaScript", "keywords": null, "content_html": "

SpeechSynthesisUtterance

\n\n
function speak (message) {\n  var msg = new SpeechSynthesisUtterance(message)\n  var voices = window.speechSynthesis.getVoices()\n  msg.voice = voices[0]\n  window.speechSynthesis.speak(msg)\n}\n
\n\n
speak('Hello, world')\n
\n\n

See: SpeechSynthesisUtterance (developer.mozilla.org)

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "jscoverage", "title": "jscoverage", "url": "/jscoverage", "category": "JavaScript libraries", "keywords": null, "content_html": "

Install

\n\n

Install via npm

\n\n
npm install --save-dev jscoverage\n
\n\n

Ignore output

\n\n
echo coverage.html >> .gitignore\n
\n\n

package.json

\n\n

The coverage task injects your source files (lib) with jscoverage hooks, runs mocha -R html-cov, then restores later.

\n\n
/* directory */\n\"coverage\": \"mv lib lib~; (jscoverage lib~ lib; mocha -R html-cov > coverage.html); rm -rf lib; mv lib~ lib\"\n
\n\n
/* single file */\n\"coverage\": \"(cp index.js index.js~; jscoverage index.js; mv index-cov.js index.js; mocha -R html-cov > coverage.html); mv index.js~ index.js\"\n
\n\n

Run

\n\n
npm run coverage\n
\n\n
open coverage.html\n
\n\n

Caveats

\n\n

If you’re using jsdom, be sure to expose the window._$jscoverage variable into \nthe global scope.

", "intro_html": "

A small guide into installing jscoverage. Also see mocha-blanket.

", "description_html": "", "tags": null, "updated": null },{ "id": "jsdoc", "title": "Jsdoc", "url": "/jsdoc", "category": "JavaScript", "keywords": null, "content_html": "

Functions

\n\n
/**\n * This is a function.\n *\n * @param {string} n - A string param\n * @return {string} A good string\n *\n * @example\n *\n *     foo('hello')\n */\n\nfunction foo(n) {\n  return n\n}\n
\n\n

See: http://usejsdoc.org/index.html

\n\n

Types

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TypeDescription
@param {string=} nOptional
@param {string} [n]Optional
@param {(string|number)} nMultiple types
@param {*} nAny type
@param {...string} nRepeatable arguments
@param {string} [n=\"hi\"]Optional with default
@param {string[]} nArray of strings
@return {Promise<string[]>} nPromise fulfilled by array of strings
\n\n

See: http://usejsdoc.org/tags-type.html

\n\n

Variables

\n\n
/**\n * @type {number}\n */\nvar FOO = 1\n
\n\n
/**\n * @const {number}\n */\nconst FOO = 1\n
\n\n

Typedef

\n\n
/**\n * A song\n * @typedef {Object} Song\n * @property {string} title - The title\n * @property {string} artist - The artist\n * @property {number} year - The year\n */\n
\n\n
/**\n * Plays a song\n * @param {Song} song - The {@link Song} to be played\n */\n\nfunction play(song) {}\n
\n\n

See: http://usejsdoc.org/tags-typedef.html

\n\n

Typedef Shorthand

\n\n
/**\n * A song\n * @typedef {{title: string, artist: string, year: number}} Song\n */\n
\n\n
/**\n * Plays a song\n * @param {Song} song - The {@link Song} to be played\n */\n\nfunction play(song) {}\n
\n\n

See: http://usejsdoc.org/tags-typedef.html

\n\n

Importing types

\n\n
/**\n * @typedef {import('./Foo').default} Bar\n */\n\n/**\n * @param {Bar} x\n */\n\nfunction test(x) {}\n
\n\n

This syntax is TypeScript-specific.

\n\n

Other keywords

\n\n
/**\n * @throws {FooException}\n * @private\n * @deprecated\n * @see\n *\n * @function\n * @class\n */\n
\n\n

See the full list: https://jsdoc.app/index.html#block-tags

\n\n

Renaming

\n\n
/*\n * @alias Foo.bar\n * @name Foo.bar\n */\n
\n\n

Prefer alias over name. See: http://usejsdoc.org/tags-alias.html

", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-06-23" },{ "id": "jshint", "title": "Jshint", "url": "/jshint", "category": "JavaScript libraries", "keywords": null, "content_html": "

Relaxing

\n\n

Enable these options to not throw errors in these conditions.\nSee: Relaxing

\n\n
/* jshint asi: true */\nallow()\nmissing_semicolons()\n
\n\n
/* jshint boss: true */\nif (m = str.match(/.../))\n
\n\n
/* jshint debug: true */\ndebugger;\n
\n\n
/* jshint eqnull: true */\nif (x == null)\n
\n\n
/* jshint evil: true */\neval('...')\n
\n\n
/* jshint expr: true */\nproduction && minify = true;\ndiv.innerWidth;\nexpect(x).be.true;\n
\n\n
/* jshint laxcomma: true */\nvar one = 1\n  , two = 2;\n
\n\n
/* jshint loopfunc: true */\nfor (i=0; i<10; x++) {\n  (function(i) { ... })(i);\n}\n
\n\n
/* jshint sub: true */\nprocess.env['name_here']\n
\n\n
/* jshint strict: \"global\" */\n\"use strict\";\n
\n\n

Enforcing

\n\n

Enable these options to catch more errors.\nSee: Enforcing

\n\n
/* jshint curly: true */\nwhile (day)                     // err: use { }'s\n  shuffle();\n
\n\n
/* jshint eqeqeq: true */\nif (a == null)                  // err: use ===\n
\n\n
/* jshint es3: true */\n// ...for legacy IE compatibility\na.default = function() { ... }; // err: reserved word\narray = [ 1, 2, 3, ];           // err: extra comma\n
\n\n
/* jshint forin: true */\nfor (key in obj) { ... }        // err: check obj.hasOwnProperty(key)\n
\n\n
/* jshint freeze: true */\nArray.prototype.count = ...;    // err: don't modify native prototypes\n
\n\n
/* jshint indent: 4 */\nif (x) {                        // err: expected indent of 4, found 2\n  ...;\n}\n
\n\n
/* jshint quotmark: single */\n/* jshint quotmark: double */\nalert(\"hi\");                    // err: only single allowed\n
\n\n
/* jshint strict: true */\nfunction() { ... }              // err: need \"use strict\"\n
\n\n
/* jshint white: true, indent: 4 */\n/* jshint maxdepth: 2 */\n/* jshint maxparams: 3 */\n/* jshint maxstatements: 4 */\n/* jshint maxcomplexity: 5 */\n/* jshint maxlen: 80 */\n
\n\n

Ignore

\n\n
/* jshint ignore:start */\n/* jshint ignore:end */\n
\n\n

Globals and Environments

\n\n
/* jshint undef: true */\n/* global jQuery */\n/* global -BAD_LIB */\n
\n\n
/* jshint devel: true */   console, alert, ...\n/* jshint browser: true */ window, document, location, ...\n/* jshint node: true */    module, exports, console, process, ...\n/* jshint jquery: true */  jQuery, $\n
\n\n

See: Environments

\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-12" },{ "id": "knex", "title": "Knex", "url": "/knex", "category": "Databases", "keywords": null, "content_html": "

Getting started

\n\n

Connect

\n\n
require('knex')({\n  client: 'pg',\n  connection: 'postgres://user:pass@localhost:5432/dbname'\n})\n
\n\n

See: Connect

\n\n

Create table

\n\n
knex.schema.createTable('user', (table) => {\n  table.increments('id')\n  table.string('name')\n  table.integer('age')\n})\n.then(() => ···)\n
\n\n

See: Schema

\n\n

Select

\n\n
knex('users')\n  .where({ email: 'hi@example.com' })\n  .then(rows => ···)\n
\n\n

See: Select

\n\n

Insert

\n\n
knex('users')\n  .insert({ email: 'hi@example.com' })\n
\n\n

See: Insert

\n\n

Update

\n\n
knex('users')\n  .where({ id: 135 })\n  .update({ email: 'hi@example.com' })\n
\n\n

See: Update

\n\n

Migrations

\n\n
knex init\nknex migrate:make migration_name\nknex migrate:make migration_name -x ts # Generates a TypeScript migration file\nknex migrate:latest\nknex migrate:rollback\n
\n\n

See: Migrations

\n\n

Seeds

\n\n
knex seed:make seed_name\nknex seed:make seed_name -x ts # Generates a TypeScript seed file\nknex seed:run # Runs all seed files\nknex seed:run --specific=seed-filename.js # Runs a specific seed file\n
\n\n

See: Seeds

\n\n

Connect

\n\n

Libraries

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
pgPostgreSQL
mysqlMySQL or MariaDB
sqlite3Sqlite3
mssqlMSSQL
\n\n

Install any of these packages along with knex.

\n\n

See: Node.js installation

\n\n

Connect via host

\n\n
var knex = require('knex')({\n  client: 'mysql',\n  connection: {\n    host: '127.0.0.1',\n    user: 'your_database_user',\n    password: 'your_database_password',\n    database: 'myapp_test'\n  },\n  pool: { min: 0, max: 7 }\n})\n
\n\n

See: Initializing the library

\n\n

Connect via URL

\n\n
var pg = require('knex')({\n  client: 'pg',\n  connection: process.env.DATABASE_URL,\n  searchPath: 'knex,public',\n  pool: { min: 0, max: 7 }\n})\n
\n\n

Connect via Sqlite

\n\n
var knex = require('knex')({\n  client: 'sqlite3',\n  connection: { filename: './mydb.sqlite' }\n})\n
\n\n

Select

\n\n

Where

\n\n
knex\n  .from('books')\n  .select('title', 'author', 'year')\n
\n\n

Where

\n\n
  .where('title', 'Hello')\n  .where({ title: 'Hello' })\n  .whereIn('id', [1, 2, 3])\n  .whereNot(···)\n  .whereNotIn('id', [1, 2, 3])\n
\n\n

Where conditions

\n\n
  .whereNull('updated_at')\n  .whereNotNull(···)\n
\n\n
  .whereExists('updated_at')\n  .whereNotExists(···)\n
\n\n
  .whereBetween('votes', [1, 100])\n  .whereNotBetween(···)\n
\n\n
  .whereRaw('id = ?', [1])\n
\n\n

Where grouping

\n\n
  .where(function () {\n    this\n      .where('id', 1)\n      .orWhere('id', '>', 10)\n  })\n
\n\n

See: Where clauses

\n\n

Join

\n\n
knex('users')\n
\n\n

Basic join

\n\n
  .join('contacts', 'users.id', '=', 'contacts.id')\n  .join('contacts', {'users.id': 'contacts.id'})\n
\n\n

Strings

\n\n
  .join('accounts', 'accounts.type', '=', knex.raw('?', ['admin']))\n
\n\n

Directions

\n\n
  .leftJoin(···)\n  .leftOuterJoin(···)\n  .rightJoin(···)\n  .rightOuterJoin(···)\n  .outerJoin(···)\n  .fullOuterJoin(···)\n  .crossJoin(···)\n
\n\n

Raw

\n\n
  .joinRaw('natural full join table1')\n
\n\n

Grouping

\n\n
  .join('accounts', function () {\n    this\n      .on('accounts.id', '=', 'users.account_id')\n      .orOn('accounts.owner_id', '=', 'users.id')\n\n      .onIn('accounts.id', [1, 2, 3, 5, 8])\n      .onNotIn(···)\n\n      .onNull('accounts.email')\n      .onNotNull(···)\n\n      .onExists(function () {\n        this.select(···)\n      })\n      .onNotExists(···)\n  })\n
\n\n

See: Join methods

\n\n

Others

\n\n
knex('users')\n  .distinct()\n
\n\n

Group

\n\n
  .groupBy('count')\n  .groupByRaw('year WITH ROLLUP')\n
\n\n

Order

\n
  .orderBy('name', 'desc')\n  .orderByRaw('name DESC')\n
\n\n

Offset/limit

\n\n
  .offset(10)\n  .limit(20)\n
\n\n

Having

\n\n
  .having('count', '>', 100)\n  .havingIn('count', [1, 100])\n
\n\n

Union

\n\n
  .union(function() {\n    this.select(···)\n  })\n  .unionAll(···)\n
\n\n

See: Query builder

\n\n

Etc

\n\n
knex('users')\n  .pluck('id')\n  .then(ids => { ··· })\n
\n
knex('users')\n  .first()\n  .then(user => { ··· })\n
\n\n

Booleans

\n\n
  .count('active')\n  .count('active as is_active')\n
\n\n

Numbers

\n\n
  .min('age')\n  .max('age')\n  .sum('age')\n  .sumDistinct('age')\n  .avg('age')\n
\n\n

See: Query builder

\n\n

Schema

\n\n

Create table

\n\n
knex.schema.createTable('accounts', table => {\n
\n\n

Columns

\n\n
  table.increments('id')\n  table.string('account_name')\n  table.integer('age')\n  table.float('age')\n  table.decimal('balance', 8, 2)\n  table.boolean('is_admin')\n  table.date('birthday')\n  table.time('created_at')\n  table.timestamp('created_at').defaultTo(knex.fn.now())\n  table.json('profile')\n  table.jsonb('profile')\n  table.uuid('id').primary()\n
\n\n

Constraints

\n\n
  table.unique('email')\n  table.unique(['email', 'company_id'])\n  table.dropUnique(···)\n
\n\n

Indices

\n\n
  table.foreign('company_id')\n    .references('companies.id')\n  table.dropForeign(···)\n
\n\n

Variations

\n\n
  table.integer('user_id')\n    .unsigned()\n    .references('users.id')\n
\n\n
})\n.then(() => ···)\n
\n\n

See: Schema builder

\n\n

Alter table

\n\n
knex.schema.table('accounts', table => {\n
\n\n

Create

\n\n
  table.string('first_name')\n
\n\n

Alter

\n\n
  table.string('first_name').alter()\n  table.renameColumn('admin', 'is_admin')\n
\n\n

Drop

\n\n
  table.dropColumn('admin')\n  table.dropTimestamps('created_at')\n
\n\n
})\n
\n\n

See: Schema builder

\n\n

Other methods

\n\n
knex.schema\n  .renameTable('persons', 'people')\n  .dropTable('persons')\n
\n\n
  .hasTable('users').then(exists => ···)\n  .hasColumn('users', 'id').then(exists => ···)\n
\n\n

See: Schema builder

\n\n

Modifying

\n\n

Insert

\n\n
knex('users')\n
\n\n

Insert one

\n\n
  .insert({ name: 'John' })\n
\n\n

Insert many

\n\n
  .insert([\n    { name: 'Starsky' },\n    { name: 'Hutch' }\n  ])\n
\n\n

See: Insert

\n\n

Update

\n\n
knex('users')\n  .where({ id: 2 })\n  .update({ name: 'Homer' })\n
\n\n

See: Update

\n\n

Delete

\n\n
knex('users')\n  .where({ id: 2 })\n  .del()\n
\n\n

See: Delete

\n\n

Migrations

\n\n

Setting up

\n\n

Create knexfile.js

\n\n
./node_modules/.bin/knex init\n
\n\n

Create a migration

\n\n
knex migrate:make migration_name\nknex migrate:make migration_name --env production\n
\n\n

Run migrations

\n\n
knex migrate:latest\nknex migrate:latest --env production\n
\n\n

Rollback

\n\n
knex migrate:rollback\nknex migrate:rollback --env production\n
\n\n

See: Migrations

", "intro_html": "

Knex is an SQL query builder for Node.js.\nThis guide targets v0.13.0.

", "description_html": "", "tags": null, "updated": "2020-06-03" },{ "id": "koa", "title": "Koa", "url": "/koa", "category": "JavaScript libraries", "keywords": null, "content_html": "

Reference

\n\n
app.use(function * (next) {\n  var ctx = this\n\n  ctx.request\n  ctx.response\n\n  ctx.body = 'hello'\n\n  ctx.state.user = yield User.find(id).fetch()\n\n  ctx.cookies.set('foo', 'hello', { signed: true })\n  ctx.cookies.get('foo')\n\n  ctx.throw(403)\n
\n\n

Request

\n\n
  ctx.header        // ctx.headers\n  ctx.method        // and =\n  ctx.url           // and =\n  ctx.originalUrl\n  ctx.origin        // => 'http://example.com'\n  ctx.href          // => 'http://example.com/foo?q=hello'\n  ctx.path          // and =\n  ctx.query         // { q: 'hello' }\n  ctx.query         // and =\n  ctx.querystring\n  ctx.querystring   // and =\n  ctx.host\n  ctx.hostname\n  ctx.fresh\n  ctx.stale\n  ctx.socket\n  ctx.protocol\n  ctx.secure\n  ctx.ip\n  ctx.ips\n  ctx.subdomains\n  ctx.is()                  // .is('html') .is('text/html')\n  ctx.accepts()             // .accepts('html') .accepts('html', 'json')\n  ctx.acceptsEncodings()    // .acceptsEncodings('gzip')\n  ctx.acceptsCharsets()\n  ctx.acceptsLanguages()\n  ctx.get()\n\n  ctx.request.type          // => 'image/jpg'\n  ctx.request.charset       // => 'utf-8'\n  ctx.request.protocol      // => 'https'\n  ctx.request.secure        // => true\n  ctx.request.ip            // (supports X-Forwarded-For if app.proxy)\n  ctx.request.ips\n  ctx.request.subdomains\n\n  ctx.request.fresh\n  ctx.request.stale\n
\n\n

Response

\n\n
  ctx.body = 'hello'\n\n  ctx.throw(403)\n  ctx.throw('name required', 403)\n  ctx.throw(403, 'name required')\n  ctx.throw('oops')\n  ctx.assert(ctx.state.user, 401, 'You must log in')\n
\n\n

Middlewares

\n\n
exports.conditionalGet = require('koa-conditional-get');\nexports.responseTime = require('koa-response-time');\nexports.ratelimit = require('koa-ratelimit');\nexports.compress = require('koa-compress');\nexports.rewrite = require('koa-rewrite');\nexports.favicon = require('koa-favicon');\nexports.session = require('koa-session');\nexports.static = require('koa-static');\nexports.logger = require('koa-logger');\nexports.mount = require('koa-mount');\nexports.etag = require('koa-etag');\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "kotlin", "title": "Kotlin", "url": "/kotlin", "category": "Java & JVM", "keywords": null, "content_html": "

Variables

\n\n

Mutability

\n\n
var mutableString: String = \"Adam\"\nval immutableString: String = \"Adam\"\nval inferredString = \"Adam\"\n
\n\n

Strings

\n\n
val name = \"Adam\"\nval greeting = \"Hello, \" + name\nval greetingTemplate = \"Hello, $name\"\n
\n\n

Numbers

\n\n
val intNum = 10\nval doubleNum = 10.0\nval longNum = 10L\nval floatNum = 10.0F\n
\n\n

Booleans

\n\n
val trueBoolean = true\nval falseBoolean = false\nval andCondition = trueBoolean && falseBoolean\nval orCondition = trueBoolean || falseBoolean\n
\n\n

Static Fields

\n\n
class Person {\n    companion object {\n        val NAME_KEY = \"name_key\"\n    }\n}\n\nval key = Person.NAME_KEY\n
\n\n

Null Safety

\n\n

Nullable properties

\n\n
val cannotBeNull: String = null // Invalid\nval canBeNull: String? = null // Valid\n\nval cannotBeNull: Int = null // Invalid\nval canBeNull: Int? = null // Valid\n
\n\n

Checking for null

\n\n
val name: String? = \"Adam\"\n\nif (name != null && name.length > 0) {\n    print(\"String length is ${name.length}\")\n} else {\n    print(\"String is empty.\")\n}\n
\n\n

Safe Operator

\n\n
val nullableStringLength: Int? = nullableString?.length\nval nullableDepartmentHead: String? = person?.department?.head?.name\n
\n\n

Elvis Operator

\n\n
val nonNullStringLength: Int = nullableString?.length ?: 0\nval nonNullDepartmentHead: String = person?.department?.head?.name ?: \"\"\nval nonNullDepartmentHead: String = person?.department?.head?.name.orEmpty()\n
\n\n

Safe Casts

\n
// Will not throw ClassCastException\nval nullableCar: Car? = (input as? Car)\n
\n\n

Collections

\n\n

Creation

\n\n
val numArray = arrayOf(1, 2, 3)\nval numList = listOf(1, 2, 3)\nval mutableNumList = mutableListOf(1, 2, 3)\n
\n\n

Accessing

\n\n
val firstItem = numList[0]\nval firstItem = numList.first()\nval firstItem = numList.firstOrNull()\n
\n\n

Maps

\n\n
val faceCards = mutableMapOf(\"Jack\" to 11, \"Queen\" to 12, \"King\" to 13)\nval jackValue = faceCards[\"Jack\"] // 11\nfaceCards[\"Ace\"] = 1\n
\n\n

Mutability

\n\n
val immutableList = listOf(1, 2, 3)\nval mutableList = immutableList.toMutableList()\n\nval immutableMap = mapOf(\"Jack\" to 11, \"Queen\" to 12, \"King\" to 13)\nval mutableMap = immutableMap.toMutableMap()\n
\n\n

Iterating

\n\n
for (item in myList) {\n    print(item)\n}\n\nmyList.forEach {\n    print(it)\n}\n\nmyList.forEachIndexed { index, item -> \n    print(\"Item at $index is: $item\")\n}\n
\n\n

Filtering & Searching

\n\n
val evenNumbers = numList.filter { it % 2 == 0 }\nval containsEven = numList.any { it % 2 == 0 }\nval containsNoEvens = numList.none { it % 2 == 0 }\nval containsNoEvens = numList.all { it % 2 == 1 }\nval firstEvenNumber: Int = numList.first { it % 2 == 0 }\nval firstEvenOrNull: Int? = numList.firstOrNull { it % 2 == 0 }\n
\n\n

Note: it is the implicit name for a single parameter.

\n\n

Functions

\n\n

Parameters & Return Types

\n\n
fun printName() {\n    print(\"Adam\")\n}\n\nfun printName(person: Person) {\n    print(person.name)\n}\n\nfun getGreeting(person: Person): String {\n    return \"Hello, ${person.name}\"\n}\n\nfun getGreeting(person: Person): String = \"Hello, ${person.name}\"\nfun getGreeting(person: Person) = \"Hello, ${person.name}\"\n
\n\n

Higher Order Functions

\n\n
fun callbackIfTrue(condition: Boolean, callback: () -> Unit) {\n    if (condition) {\n        callback()\n    }\n}\n\ncallbackIfTrue(someBoolean) {\n    print(\"Condition was true\")\n}\n
\n\n

Extension Functions

\n\n
fun Int.timesTwo(): Int {\n    return this * 2\n}\n\nval four = 2.timesTwo()\n
\n\n

Default Parameters

\n\n
fun getGreeting(person: Person, intro: String = \"Hello,\") {\n    return \"$intro ${person.name}\"\n}\n\n// Returns \"Hello, Adam\"\nval hello = getGreeting(Person(\"Adam\"))\n\n// Returns \"Welcome, Adam\"\nval welcome = getGreeting(Person(\"Adam\"), \"Welcome,\")\n
\n\n

Named Parameters

\n\n
class Person(val name: String = \"\", age: Int = 0)\n\n// All valid\nval person = Person()\nval person = Person(\"Adam\", 100)\nval person = Person(name = \"Adam\", age = 100)\nval person = Person(age = 100)\nval person = Person(age = 100, name = \"Adam\")\n
\n\n

Static Functions

\n\n
class Fragment(val args: Bundle) {\n    companion object {\n        fun newInstance(args: Bundle): Fragment {\n            return Fragment(args)\n        }\n    }\n}\n\nval fragment = Fragment.newInstance(args)\n
\n\n\n\n

Classes

\n\n

Primary Constructor

\n\n
class Person(val name: String, val age: Int)\nval adam = Person(\"Adam\", 100)\n
\n\n

Secondary Constructors

\n\n
class Person(val name: String) {\n    private var age: Int? = null\n\n    constructor(name: String, age: Int) : this(name) {\n        this.age = age\n    }\n}\n\n// Above can be replaced with default params\nclass Person(val name: String, val age: Int? = null)\n
\n\n

Inheritance & Implementation

\n\n
open class Vehicle\nclass Car : Vehicle()\n\ninterface Runner {\n    fun run()\n}\n\nclass Machine : Runner {\n    override fun run() {\n        // ...\n    }\n}\n
\n\n

Control Flow

\n\n

If Statements

\n\n
if (someBoolean) {\n    doThing()\n} else {\n    doOtherThing()\n}\n
\n\n

For Loops

\n\n
for (i in 0..10) { } // 1 - 10\nfor (i in 0 until 10) // 1 - 9\n(0..10).forEach { }\nfor (i in 0 until 10 step 2) // 0, 2, 4, 6, 8\n
\n\n

When Statements

\n\n
when (direction) {\n    NORTH -> {\n        print(\"North\")\n    }\n    SOUTH -> print(\"South\")\n    EAST, WEST -> print(\"East or West\")\n    \"N/A\" -> print(\"Unavailable\")\n    else -> print(\"Invalid Direction\")\n}\n
\n\n

While Loops

\n\n
while (x > 0) {\n    x--\n}\n\ndo {\n    x--\n} while (x > 0)\n
\n\n

Destructuring Declarations

\n\n

Objects & Lists

\n\n
val person = Person(\"Adam\", 100)\nval (name, age) = person\n\nval pair = Pair(1, 2)\nval (first, second) = pair\n\nval coordinates = arrayOf(1, 2, 3)\nval (x, y, z) = coordinates\n
\n\n

ComponentN Functions

\n\n
class Person(val name: String, val age: Int) {\n\toperator fun component1(): String {\n\t\treturn name\n\t}\n\n\toperator fun component2(): Int {\n\t\treturn age\n\t}\n}\n
\n\n

References

\n\n", "intro_html": "

Kotlin is a statically typed programming language for modern multiplatform applications.

", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "kramdown", "title": "Kramdown", "url": "/kramdown", "category": "Markup", "keywords": null, "content_html": "

Configuration

\n\n\n\n

For the GFM parser:

\n\n\n\n

http://kramdown.gettalong.org/parser/gfm.html

\n\n

For jekyll (gh-pages)

\n\n
# _config.yml\nmarkdown: kramdown\nkramdown:\n  input: GFM\n
\n\n

Footnotes (Kramdown)

\n\n
This is some text.[^1]. Other text.[^footnote].\n\n[^1]: Some *crazy* footnote definition.\n
\n\n

Abbreviations (Kramdown)

\n\n
This is some text not written in HTML but in another language!\n\n*[another language]: It's called Markdown\n*[HTML]: HyperTextMarkupLanguage\n
\n\n

Classes and IDs (Kramdown)

\n\n
A simple paragraph with an ID attribute.\n{: #para-one}\n\n> A blockquote with a title\n{:title=\"The blockquote title\"}\n{: #myid}\n\n* {:.cls} This item has the class \"cls\"\n\n{:.ruby}\n    Some code here\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "layout-thrashing", "title": "Layout thrashing", "url": "/layout-thrashing", "category": "HTML", "keywords": null, "content_html": "

Layout thrashing

\n\n

Things that cause invalidation

\n\n

Element

\n\n\n\n

MouseEvent

\n\n\n\n

Window

\n\n\n\n

Frame, Document & Image

\n\n\n\n

jQuery

\n\n\n\n

Also see

\n\n", "intro_html": "

These are CSS properties that will cause “layout thrashing”. Avoid changing them to prevent bottlenecks in your UI performance.

", "description_html": "", "tags": null, "updated": "2017-10-19" },{ "id": "ledger-csv", "title": "Ledger CSV format", "url": "/ledger-csv", "category": "Ledger", "keywords": null, "content_html": "

Ledger CSV format

\n\n
$ ledger csv\n
\n\n
date         , ?  , desc     , account            , currency , amt     , pending/cleared , ?\n\"2013/09/02\" , \"\" , \"things\" , \"Assets:Cash\"      , \"P\"      , \"-2000\" , \"*\"             , \"\"\n\"2013/09/02\" , \"\" , \"things\" , \"Liabilities:Card\" , \"P\"      , \"-200\"  , \"*\"             , \"\"\n\"2013/09/02\" , \"\" , \"things\" , \"Expenses:Things\"  , \"P\"      , \"2200\"  , \"*\"             , \"\"\n\"2013/09/04\" , \"\" , \"stuff\"  , \"Assets:Cash\"      , \"P\"      , \"-20\"   , \"*\"             , \"\"\n\"2013/09/04\" , \"\" , \"stuff\"  , \"Expneses:Others\"  , \"P\"      , \"20\"    , \"*\"             , \"\"\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ledger-examples", "title": "Ledger examples", "url": "/ledger-examples", "category": "Ledger", "keywords": null, "content_html": "

Inspecting transactions:

\n\n
# show me expenses for october (--period)\n  ledger r Expenses -p oct\n\n# what's the most expensive? (--sorted)\n  ledger r Expenses -S amount --tail 10\n\n# how much was spent on grocery? (--weekly, --monthly)\n  ledger r Grocery\n  ledger r Grocery -W\n  ledger r Grocery -M\n\n# what did I spend my Mastercard on? (--period, --begin, --end)\n  ledger r mastercard\n  ledger r mastercard -p \"january\"\n  ledger r mastercard -b 01/25 -e 01/31\n
\n\n

Graphing:

\n\n
# Graph my bank account balance, monthly\n  ledger r Savings -M\n\n# Graph my expenses, monthly (-n = --collapse)\n  ledger r Expenses -M -n\n\n# ...what's the average per month?\n  ledger r Expenses -M -n --average\n
\n\n

Simple:

\n\n
# what did I do yesterday?\n# ..list transactions on this day\n  ledger r -p 01/26\n  ledger r -p yesterday\n
\n\n

Switches:

\n\n
# what's everything I got in USD? (--exchange)\n  ledger b Assets -X USD\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ledger-format", "title": "Ledger format", "url": "/ledger-format", "category": "Ledger", "keywords": null, "content_html": "
2015/01/01 Pay rent\n  Assets:Savings     -$300\n  Expenses:Rent\n
\n\n

First line

\n\n
2015/01/01 *       Pay rent       ; tagname:\n^          ^       ^\nDate       Flag    Description    ^ comment/tag\n
\n\n

Balance assertion

\n\n
2015/01/01 Pay rent\n  Assets:Savings     -$300 = $1200  ; assert there's $1200 left after\n  Expenses:Rent\n
\n

Flags:

\n\n
* cleared\n! pending\n
\n\n

Accounts

\n

Only relevant with --strict or --pedantic

\n\n
account Expenses:Food\n    note This account is all about the chicken!\n    alias food\n    payee ^(KFC|Popeyes)$\n    check commodity == \"$\"\n    assert commodity == \"$\"\n    eval print(\"Hello!\")\n    default\n
\n\n

Others

\n\n
D $1,000.00     ; set default commodity\n\nalias Cash = Assets:Cash\n\nY2015           ; set default year (you can use 01/25 as date after)\n
\n\n

Prefix all transactions with an account

\n\n
account Home\ninclude home.journal\nend\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ledger-periods", "title": "Ledger periods", "url": "/ledger-periods", "category": "Ledger", "keywords": null, "content_html": "
[INTERVAL] [BEGIN] [END]\n
\n\n

Interval:

\n\n
every day\nevery week\nevery month\nevery quarter\nevery year\nevery N days     # N is any integer\nevery N weeks\nevery N months\nevery N quarters\nevery N years\ndaily\nweekly\nbiweekly\nmonthly\nbimonthly\nquarterly\nyearly\n
\n\n

Begin:

\n\n
from <SPEC>\nsince <SPEC>\n
\n\n

The end time can be either of:

\n\n
to <SPEC>\nuntil <SPEC>\n
\n\n

Spec:

\n\n
2004\n2004/10\n2004/10/1\n10/1\noctober\noct\nthis week  # or day, month, quarter, year\nnext week\nlast week\n
\n\n

Examples:

\n\n
$ ledger r -p \"since last month\"\n
\n\n

See: http://ledger-cli.org/3.0/doc/ledger3.html#Period-Expressions

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ledger-query", "title": "Ledger queries", "url": "/ledger-query", "category": "Ledger", "keywords": null, "content_html": "

Query characters

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
QueryDescription
@payeePayee
%tagTag
=noteNote
#codeCode
TERM and TERMBoolean and
TERM or TERMBoolean or
not TERMBoolean not
\n\n

Examples

\n\n
ledger r @taco\nledger r comment =~ /landline/\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ledger", "title": "Ledger CLI", "url": "/ledger", "category": "Ledger", "keywords": null, "content_html": "

Basic usage

\n\n
$ ledger bal\n$ ledger reg\n
\n\n
$ ledger reg grocery  # show entries for 'grocery'\n$ ledger bal assets   # check if i'm broke\n
\n\n
  -b 01/01   # --begin\n  -e 01/31   # --end\n  -S date    # --sort\n  -S amount\n
\n\n

Examples

\n\n
# any/all matches\n  ledger bal Rent Transportation  # any\n  ledger bal Income and Job       # all\n  ledger bal Expenses and not (Drinks or Food)\n
\n\n
# what did I spend on most? (--sorted)\n  ledger reg Expenses -S amount\n
\n\n
# how much did I have at this date? (--end)\n  ledger bal -e 01/15 ^Assets ^Liabilities\n
\n\n
# how much did I spend and earn this month?\n  ledger bal ^Expenses ^Income --invert\n
\n\n
# how much was spent over the course of 3 days? (totalled)\n  ledger reg -b 01/25 -e 01/27 --subtotal\n  ledger reg -b 01/25 -e 01/27 --subtotal grocery\n
\n\n

Format

\n\n

Basic format

\n\n
2013/01/03 * Rent for January\n  Expenses:Rent   $600.00\n  Assets:Savings\n
\n\n

* = cleared, ! = pending

\n\n

Secondary dates

\n\n
2008/01/01=2008/01/14 Client invoice\n
\n\n

It can mean anything you want, eg, for the estimated date you’ll be paid.

\n\n

Balance assertions

\n\n
2008/01/01 * KFC\n  Expenses:Food    $20\n  Assets:Cash     $-20  = $500\n
\n\n

Cash $X = $500 ensures Cash is at $500 after the transaction.

\n\n

Balance assignment

\n\n
2008/01/01 * Cash balance\n  Assets:Cash              = $500\n  Equity:Adjustments\n\n2008/01/01 * KFC\n  Expenses:Food            $20\n  Assets:Cash              = $500\n
\n\n

ACCOUNT = $500 figures out what’s needed to make it $500.

\n\n

Payables

\n\n
2008/04/25 * Rent\n  (Assets:Checking)  -$200\n  Expenses:Rent\n
\n\n

Commodities

\n\n
; cost per item\n2010/05/31 * Market\n  Assets:Fridge                35 apples @ $0.42\n  Assets:Cash\n
\n\n
; total cost\n2010/05/31 * Market\n  Assets:Fridge                35 apples @@ $14.70\n  Assets:Cash\n
\n\n
; fixed lot prices\n2010/05/31 * Gas\n  Expenses:Gasoline             11 GAL {=$2.299}\n  Assets:Cash\n
\n\n

Commodity definitions

\n\n
commodity $\n  note American Dollars\n  format $1,000.00\n  nomarket\n  default\n
\n\n

Budgeting

\n\n
~ Monthly\n  Expenses:Rent  $500\n  Expenses:Food  $100\n  Expenses        $40 ; everything else\n  Assets\n\n~ Yearly\n
\n\n
ledger bal --budget Expenses\nledger bal --unbudgeted Expenses\n
\n\n

Comments

\n\n
; line comment\n# also line comment\n% also line comment\n| also line comment\n* also line comment\n
\n\n

Querying

\n\n

Periods

\n\n
[interval] [begin] [end]\n
\n\n
interval:\n  every day|week|month|quarter|year\n  every N days|weeks|...\n  daily|weekly|...\n
\n\n
begin:\n  from <spec>\nend:\n  to <spec>\n
\n\n
spec:\n  2004\n  2004/10/1\n
\n\n
$ ledger bal|reg --period \"until aug\"\n$ ledger bal|reg --period \"last oct\"\n$ ledger bal|reg --period \"every week\"\n
\n\n

Register

\n\n
$ ledger reg\n
\n\n
  -D, --daily\n  -W, --weekly\n  -M, --monthly\n      --quarterly\n  -Y, --yearly\n  -s, --subtotal\n  --start-of-week monday\n
\n\n
  -S, --sort date\n  -S, --sort amount\n
\n\n

Filters

\n\n
-b, --begin DATE\n-e, --end DATE\n\n-d payee =~ /pioneer/\n\n-C, --cleared    # (with *)\n-U, --uncleared  # (no *)\n    --pending    # (with !)\n\n-R, --real       # ignore virtual postings (eg: \"(Cash)  $-400\")\n-L, --actual     # no automated postings (eg: \"= /^Income/\")\n\n-r, --related   # show the other side\n                # \"reg -r savings\" shows where it comes from)\n
\n\n

Queries

\n\n
^regex$\n@payee\n%tag\n%tag=value\n=note\n#code\nterm and term\nterm or term\nnot term\n\\( term \\)\n
\n\n

Example:

\n\n
ledger r ^expenses and @Denny's\nledger r food and @Starbucks and not dining\n
\n\n

Display

\n\n
-n, --collapse       # [register] collapse entries\n                     # [balance] no grand total\n-s, --subtotal       # [balance] show sub-accounts\n                     # [other] show subtotals\n--flat\n
\n\n

Effective dates

\n\n
2008/01/01=2008/01/14 Client invoice  ;  estimated date you'll be paid\n  Assets:Accounts Receivable            $100.00\n  Income: Client name\n
\n\n

Say you’re in business. If you bill a customer, you can enter something like above.\nThen, when you receive the payment, you change it to:

\n\n
2008/01/01=2008/01/15 Client invoice ;  actual date money received\n  Assets:Accounts Receivable            $100.00\n  Income: Client name\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-05-23" },{ "id": "less", "title": "Less.js", "url": "/less", "category": "Others", "keywords": null, "content_html": "

Functions

\n\n
unit(30px / 5px)  #=> 6\nunit(5, px)       #=> 5px\n\ne(\"ms:stuff()\")   #=> ms:stuff() (unquote)\n\n%(\"count: %d\", 1+2) #=> \"count: 3\"\n\niscolor(@x)\nisstring(@x)\nisnumber(@x)\niskeyword(@x)\nisurl(url(...))\nispixel()\nisem()\nispercentage()\nisunit()\n\nhue(@color)\nsaturation(@color)\nlightness(@color)\nluma(@color)\nluminance(@color)\n\nfade(@color, amount)\nfadein(@color, amount)\nfadeout(@color, amount)\nspin(@color, degrees)\nmix(@a, @b, amount)\n
\n\n

Conditionals

\n\n
.image when (luma(@color) > 50%) { }\n.image when (not(...)) { }\n.image when (default()) {}\n.image when (e(@shape) = 'circle') { }\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "licenses", "title": "Licenses", "url": "/licenses", "category": "Others", "keywords": null, "content_html": "

Licenses

\n\n

MIT License

\n\n
The MIT License (MIT)\n\nCopyright (c) 2015 $NAME\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n
\n\n

ISC

\n\n
Copyright (c) 2015, $NAME\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n
\n\n

BSD 2C

\n\n
Copyright (c) 2015, $NAME\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n
\n\n

BSD 3C

\n\n
Copyright (c) 2015, $NAME\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of simpler-extend nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-08-30" },{ "id": "linux", "title": "Linux", "url": "/linux", "category": "Others", "keywords": null, "content_html": "

Mounting a RAM drive

\n\n
$ mount -t tmpfs -o size=5G,nr_inodes=5k,mode=700 tmpfs /tmp\n
\n\n

Visudo

\n\n
sudo visudo\n\nusername ALL=(ALL) NOPASSWD:/sbin/restart whatever\n
\n\n

Display the amount of available disk space

\n\n
df\ndf -h   # human-readable format\ndf -a   # all filesystems\n
\n\n

Display disk usage

\n\n
du\ndu -hsx * | sort -rh | head -10    # largest 10 folders\n
\n\n

Answer yes in a bash script

\n\n
yes | /your/command\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "lodash", "title": "Lodash", "url": "/lodash", "category": "JavaScript libraries", "keywords": null, "content_html": "

Collections

\n\n

Finding

\n\n
_.filter(list, (n) => n % 2)    // → Array\n_.find(list, (n) => n % 2)      // → item\n_.findLast(list, ...)           // → item\n
\n\n

Works for both arrays and objects.

\n\n

Accessing

\n\n
_.at([ abcd ], 0)               // → [ a ] - same as list[0]\n_.at([ abcd ], [ 0, 1 ])        // → [ ab ]\n
\n\n

Set/get

\n\n
_.set(object, 'users[0].name', value)\n_.get(object, 'users[0].name')\n_.get(object, ['users', 0, 'name'])\n
\n\n

Iteration

\n\n
_.forEach(list, (item, i) => ...)\n_.forEachRight(list, ...)\n\n_.map(list, ...)\n
\n\n
_.every(users, (u) => u.active)  // → true|false (aka _.all)\n_.any(users, ...)                // → true|false (aka _.some)\n
\n\n

Array

\n\n

Arrays

\n\n
_.chunk([ abcd ], 2)           // → [ [ab], [cd] ]\n_.compact(list)\n\n_.fill(Array(4), 'x')          // → [ 'x', 'x', 'x', 'x' ]\n_.flatten\n_.flattenDeep\n
\n\n

Filtering

\n\n
_.drop([ abcdef ], 2)          // → [   cdef ]\n_.dropRight([ abcdef ], 2)     // → [ abcd   ]\n_.take([ abcdef ], 2)          // → [ ab     ]\n_.takeRight([ abcdef ], 2)     // → [     de ]\n_.slice([ abcdef ], 2, 4)      // → [   cd   ]\n
\n\n
_.initial([ abcdef ])          // → [ abcde  ] - dropRight(list, 1)\n_.rest([ abcdef ])             // → [  bcdef ] - takeRight(list, 1)\n
\n\n
_.dropWhile(list, 'active')            // works like filter\n_.dropWhile(list, 'active', true)\n_.dropWhile(list, { active: true })\n_.dropWhile(list, (n) => ...)\n_.dropRightWhile(list, ...)\n
\n\n
_.without([ abcde ], b)        // → [ acde ]\n
\n\n
_.remove(list, (n) => n % 2)\n
\n\n

Accessing

\n\n
_.first([ abcdef ])            // → a\n_.last([ abcdef ])             // → f\n
\n\n

Sets

\n\n
_.uniq()\n_.difference([ abc ], [ bc ])       // → [ a    ]\n_.intersection([ abc ], [ bcd ])    // → [  bc  ]\n_.union([ abc ], [ bcd ])           // → [ abcd ] (unique)\n
\n\n
Array#concat()\n
\n\n

Indexes

\n\n
_.findIndex(list, fn)\n_.findLastIndex(list, fn)\n
\n\n
_.sortedIndex(list, val)\n_.sortedLastIndex(list, val)\n
\n\n
_.indexOf(list, val)\n
\n\n

Functions

\n\n

Currying

\n\n
greet = (greeting, name) => `${greeting}, ${name}!`\n
\n\n
fn = _.partial(fn, 'hi')\nfn('joe')    // → 'hi, joe!'\n\nfn = _.partial(fn, 'joe')\nfn('yo')     // → 'yo, joe!'\n
\n\n
_.curry(greet)('hi')         // → function(name)\n_.curryRight(greet)('joe')   // → function(greet)\n
\n\n

Decorating functions

\n\n

Throttling

\n\n
_.throttle(fn)\n_.debounce(fn)\n
\n\n

Limiting

\n\n
_.before(5, fn)         // only works 5 times\n_.after(5, fn)          // works only after 5 times\n_.once(fn)              // like _.before(fn, 1)\n
\n\n

Etc

\n\n
_.wrap(_.escape, (name) => `hi ${name}`)\n// same as doing `name = _.escape(name)`\n\n_.delay(fn, 2000)\n\n_.negate(fn)\n\n_.memoize(fn)\n_.memoize(fn, ...)\n
\n\n

Strings

\n\n

Capitalization

\n\n
_.capitalize('hello world')   // → 'Hello world'\n_.startCase('hello_world')    // → 'Hello World'\n_.snakeCase('hello world')    // → 'hello_world'\n_.kebabCase('hello world')    // → 'hello-world'\n_.camelCase('hello world')    // → 'helloWorld'\n
\n\n

Padding

\n\n
_.pad('abc', 3)           // → 'abc'\n_.pad('abc', 8)           // → '   abc  '\n_.pad('abc', 8, '_-')     // → '_-abc_-_'\n_.padStart('abc', 3)      // → 'abc'\n_.padStart('abc', 6)      // → '   abc'\n_.padStart('abc', 6, '_-')// → '_-_abc'\n_.padEnd('abc', 3)        // → 'abc'\n_.padEnd('abc', 6)        // → 'abc   '\n_.padEnd('abc', 6, '_-')  // → 'abc_-_'\n
\n\n

Trim

\n\n
_.trim('  str  ')         // → 'str' \n_.trimLeft('  str  ')     // → 'str  '\n_.trimRight('  str  ')    // → '  str'\n
\n\n

Etc

\n\n
_.repeat('-', 2)              // → '--'\n_.deburr('déjà vu')           // → 'deja vu'\n_.trunc('hello world', 5)     // → 'hello...'\n
\n\n
_.startsWith('abc', 'a')   // → true\n_.endsWith('abc', 'c')     // → true\n
\n\n

Objects

\n\n

Keys and values

\n\n
_.keys(obj)\n_.values(obj)\n
\n\n

Chaining

\n\n

Chain and value

\n\n
_([1, 2, 3])\n  .reduce((total, n) => total + n)\n  .map((n) => n * n)\n  .tap(console.log)\n  .thru((n) => n.reverse())\n  .value()\n
", "intro_html": "", "description_html": "

This is not a complete list.

", "tags": null, "updated": "2020-06-24" },{ "id": "lua", "title": "Lua", "url": "/lua", "category": "Others", "keywords": null, "content_html": "

Comments

\n\n
-- comment\n--[[ Multiline\n     comment ]]\n
\n\n

Invoking functions

\n\n
print()\nprint(\"Hi\")\n\n-- You can omit parentheses if the argument is one string or table literal\nprint \"Hello World\"     <-->     print(\"Hello World\")\ndofile 'a.lua'          <-->     dofile ('a.lua')\nprint [[a multi-line    <-->     print([[a multi-line\n message]]                        message]])\nf{x=10, y=20}           <-->     f({x=10, y=20})\ntype{}                  <-->     type({})\n
\n\n

Tables / arrays

\n\n
t = {}\nt = { a = 1, b = 2 }\nt.a = function() ... end\n\nt = { [\"hello\"] = 200 }\nt.hello\n\n-- Remember, arrays are also tables\narray = { \"a\", \"b\", \"c\", \"d\" }\nprint(array[2])       -- \"b\" (one-indexed)\nprint(#array)         -- 4 (length)\n
\n\n

Loops

\n\n
while condition do\nend\n\nfor i = 1,5 do\nend\n\nfor i = start,finish,delta do\nend\n\nfor k,v in pairs(tab) do\nend\n\nrepeat\nuntil condition\n\n-- Breaking out:\nwhile x do\n  if condition then break end\nend\n
\n\n

Conditionals

\n\n
if condition then\n  print(\"yes\")\nelseif condition then\n  print(\"maybe\")\nelse\n  print(\"no\")\nend\n
\n\n

Variables

\n\n
local x = 2\ntwo, four = 2, 4\n
\n\n

Functions

\n\n
function myFunction()\n  return 1\nend\n\nfunction myFunctionWithArgs(a, b)\n  -- ...\nend\n\nmyFunction()\n\nanonymousFunctions(function()\n  -- ...\nend)\n\n-- Not exported in the module\nlocal function myPrivateFunction()\nend\n\n-- Splats\nfunction doAction(action, ...)\n  print(\"Doing '\"..action..\"' to\", ...)\n  --> print(\"Doing 'write' to\", \"Shirley\", \"Abed\")\nend\n\ndoAction('write', \"Shirley\", \"Abed\")\n
\n\n

Lookups

\n\n
mytable = { x = 2, y = function() .. end }\n\n-- The same:\nmytable.x\nmytable['x']\n\n-- Syntactic sugar, these are equivalent:\nmytable.y(mytable)\nmytable:y()\n\nmytable.y(mytable, a, b)\nmytable:y(a, b)\n\nfunction X:y(z) .. end\nfunction X.y(self, z) .. end\n
\n\n

Metatables

\n\n
mt = {}\n\n-- A metatable is simply a table with functions in it.\nmt.__tostring = function() return \"lol\" end\nmt.__add      = function(b) ... end       -- a + b\nmt.__mul      = function(b) ... end       -- a * b\nmt.__index    = function(k) ... end       -- Lookups (a[k] or a.k)\nmt.__newindex = function(k, v) ... end    -- Setters (a[k] = v)\n\n-- Metatables allow you to override behavior of another table.\nmytable = {}\nsetmetatable(mytable, mt)\n\nprint(myobject)\n
\n\n

Classes

\n\n
Account = {}\n\nfunction Account:new(balance)\n  local t = setmetatable({}, { __index = Account })\n\n  -- Your constructor stuff\n  t.balance = (balance or 0)\n  return t\nend\n\nfunction Account:withdraw(amount)\n  print(\"Withdrawing \"..amount..\"...\")\n  self.balance = self.balance - amount\n  self:report()\nend\n\nfunction Account:report()\n  print(\"Your current balance is: \"..self.balance)\nend\n\na = Account:new(9000)\na:withdraw(200)    -- method call\n
\n\n

Constants

\n\n
nil\nfalse\ntrue\n
\n\n

Operators (and their metatable names)

\n\n
-- Relational (binary)\n-- __eq  __lt  __gt  __le  __ge\n   ==    <     >     <=    >=\n~=   -- Not equal, just like !=\n\n-- Arithmetic (binary)\n-- __add  __sub  __muv  __div  __mod  __pow\n   +      -      *      /      %      ^\n\n-- Arithmetic (unary)\n-- __unm (unary minus)\n   -\n\n-- Logic (and/or)\nnil and false  --> nil\nfalse and nil  --> false\n0 and 20       --> 20\n10 and 20      --> 20\n\n\n-- Length\n-- __len(array)\n#array\n\n\n-- Indexing\n-- __index(table, key)\nt[key]\nt.key\n\n-- __newindex(table, key, value)\nt[key]=value\n\n-- String concat\n-- __concat(left, right)\n\"hello, \"..name\n\n-- Call\n-- __call(func, ...)\n
\n\n

API: Global functions (ref)

\n\n
dofile(\"hello.lua\")\nloadfile(\"hello.lua\")\n\nassert(x)    -- x or (raise an error)\nassert(x, \"failed\")\n\ntype(var)   -- \"nil\" | \"number\" | \"string\" | \"boolean\" | \"table\" | \"function\" | \"thread\" | \"userdata\"\n\n-- Does /not/ invoke meta methods (__index and __newindex)\nrawset(t, index, value)    -- Like t[index] = value\nrawget(t, index)           -- Like t[index]\n\n_G  -- Global context\nsetfenv(1, {})  -- 1: current function, 2: caller, and so on -- {}: the new _G\n\npairs(t)     -- iterable list of {key, value}\nipairs(t)    -- iterable list of {index, value}\n\ntonumber(\"34\")\ntonumber(\"8f\", 16)\n
\n\n

API: Strings

\n\n
'string'..'concatenation'\n\ns = \"Hello\"\ns:upper()\ns:lower()\ns:len()    -- Just like #s\n\ns:find()\ns:gfind()\n\ns:match()\ns:gmatch()\n\ns:sub()\ns:gsub()\n\ns:rep()\ns:char()\ns:dump()\ns:reverse()\ns:byte()\ns:format()\n
\n\n

API: Tables

\n\n
table.foreach(t, function(row) ... end)\ntable.setn\ntable.insert(t, 21)          -- append (--> t[#t+1] = 21)\ntable.insert(t, 4, 99)\ntable.getn\ntable.concat\ntable.sort\ntable.remove(t, 4)\n
\n\n

API: Math (ref)

\n\n
math.abs     math.acos    math.asin       math.atan    math.atan2\nmath.ceil    math.cos     math.cosh       math.deg     math.exp\nmath.floor   math.fmod    math.frexp      math.ldexp   math.log\nmath.log10   math.max     math.min        math.modf    math.pow\nmath.rad     math.random  math.randomseed math.sin     math.sinh\nmath.sqrt    math.tan     math.tanh\n\nmath.sqrt(144)\nmath\n
\n\n

API: Misc

\n\n
io.output(io.open(\"file.txt\", \"w\"))\nio.write(x)\nio.close()\n\nfor line in io.lines(\"file.txt\")\n\nfile = assert(io.open(\"file.txt\", \"r\"))\nfile:read()\nfile:lines()\nfile:close()\n
\n\n

Reference

\n\n

http://www.lua.org/pil/13.html\n http://lua-users.org/wiki/ObjectOrientedProgramming

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "machinist", "title": "Machinist", "url": "/machinist", "category": "Ruby libraries", "keywords": null, "content_html": "

Installing

\n\n
# Gemfile\ngem 'machinist', '>= 2.0.0.beta2', group: 'test'\n\n# ~$ bundle\n# ~$ rails generate machinist:install\n
\n\n

Building objects

\n\n
User.make\n\n# `make` builds it, and `make!` builds+saves it\nUser.make!\nUser.make! name: \"David\"\nUser.make!(:admin)\n
\n\n

Defining blueprints

\n\n
User.blueprint do\n  name  { \"User #{sn}\" }\n  email { \"user-#{sn}@example.com\" }\nend\n\nUser.blueprint(:admin) do\n  name  { \"Admin User #{sn}\" }\n  admin { true }\nend\n
\n\n

Associations

\n\n
Post.blueprint do\n  author { User.make }\n\n  comments(3)    # Makes 3 comments (has_many / habtm)\n\n  author         # autodetect (Assumes there's User.blueprint)\n\nend\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "macos-mouse-acceleration", "title": "Mouse Acceleration", "url": "/macos-mouse-acceleration", "category": "macOS", "keywords": ["defaults write .GlobalPreferences com.apple.mouse.scaling -1"], "content_html": "

Acceleration

\n\n

Disabling

\n\n
defaults write .GlobalPreferences com.apple.mouse.scaling -1\n
\n\n

Note: Log out to take effect. If you change Tracking Speed under System Preferences, it will undo this fix. Only affects the mouse, not the trackpad.

\n\n

Re-enabling

\n\n

Under System PreferencesMouse, change Tracking Speed.

\n\n

Trackpad acceleration

\n\n
defaults write .GlobalPreferences com.apple.trackpad.scaling -1\n
\n\n

Works the same way, but only affects trackpads.

\n\n

References

\n\n", "intro_html": "

Disable mouse acceleration with this one weird trick.

", "description_html": "", "tags": null, "updated": "2018-03-20" },{ "id": "make-assets", "title": "Make for assets", "url": "/make-assets", "category": "Others", "keywords": null, "content_html": "

Basic compiling

\n\n
bin := ./node_modules/.bin\n\nall: build/foo.js\n\nbuild/%.js: src/%.coffee\n    @$(bin)/coffee < $^ > $@\n
\n\n

Stylus + Autoprefixer

\n\n
bin := ./node_modules/.bin\nstylus := $(bin)/stylus\nautoprefixer := $(bin)/autoprefixer\nstyl_files := $(shell find web/ -name \"*.styl\")\n\nall: public/app.css\n\npublic/app.css: css/app.styl\n\n%.css: %.styl $(styl_files)\n    @$(stylus) $< | $(autoprefixer) -b \"> 1%\" > $@\n
\n\n

Hint

\n\n
hint:\n   $(js_files)\n
\n\n

Watching

\n\n
watch:\n    @echo \"... watching for changes\"\n    @while true; do make -s; sleep 1; done\n
\n\n

Browserify

\n\n
js_files := $(shell find web/ -name \"*.js\")\n\npublic/app.js: web/app.js\npublic/vendor.js: web/vendor.js\n\npublic/%.js: web/%.js $(js_files)\n    $(browserify) -t [ cssify -x .css ] $< > $@\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "makefile", "title": "Makefile", "url": "/makefile", "category": "CLI", "keywords": null, "content_html": "

Var assignment

\n\n
uglify = $(uglify)        # lazy assignment\ncompressor := $(uglify)   # immediate assignment\nprefix ?= /usr/local      # safe assignment\nhello += world            # append\n
\n\n

= expressions are only evaluated when they’re being used.

\n\n

Magic variables

\n\n
out.o: src.c src.h\n  $@   # \"out.o\" (target)\n  $<   # \"src.c\" (first prerequisite)\n  $^   # \"src.c src.h\" (all prerequisites)\n\n%.o: %.c\n  $*   # the 'stem' with which an implicit rule matches (\"foo\" in \"foo.c\")\n\nalso:\n  $+   # prerequisites (all, with duplication)\n  $?   # prerequisites (new ones)\n  $|   # prerequisites (order-only?)\n\n  $(@D) # target directory\n
\n\n

Command prefixes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PrefixDescription
-Ignore errors
@Don’t print command
+Run even if Make is in ‘don’t execute’ mode
\n\n
build:\n    @echo \"compiling\"\n    -gcc $< $@\n\n-include .depend\n
\n\n

Find files

\n\n
js_files  := $(wildcard test/*.js)\nall_files := $(shell find images -name \"*\")\n
\n\n

Substitutions

\n\n
file     = $(SOURCE:.cpp=.o)   # foo.cpp => foo.o\noutputs  = $(files:src/%.coffee=lib/%.js)\n\noutputs  = $(patsubst %.c, %.o, $(wildcard *.c))\nassets   = $(patsubst images/%, assets/%, $(wildcard images/*))\n
\n\n

More functions

\n\n
$(strip $(string_var))\n\n$(filter %.less, $(files))\n$(filter-out %.less, $(files))\n
\n\n

Building files

\n\n
%.o: %.c\n  ffmpeg -i $< > $@   # Input and output\n  foo $^\n
\n\n

Includes

\n\n
-include foo.make\n
\n\n

Options

\n\n
make\n  -e, --environment-overrides\n  -B, --always-make\n  -s, --silent\n\n  -j, --jobs=N   # parallel processing\n
\n\n

Conditionals

\n\n
foo: $(objects)\nifeq ($(CC),gcc)\n        $(CC) -o foo $(objects) $(libs_for_gcc)\nelse\n        $(CC) -o foo $(objects) $(normal_libs)\nendif\n
\n\n

Recursive

\n\n
deploy:\n  $(MAKE) deploy2\n
\n\n

Further reading

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "man", "title": "Man", "url": "/man", "category": "CLI", "keywords": null, "content_html": "

Man paths

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
1General User Commands
2System Calls
3Library Routines
4Special Files and Sockets
5File formats and Conventions
6Games and Fun Stuff
7Miscellaneous Documentation
8System Administration
9Kernel and Programming Style
nTcl/Tk
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "markdown", "title": "Markdown", "url": "/markdown", "category": "Markup", "keywords": null, "content_html": "

Reference

\n\n

Headers

\n\n
# h1\n## h2\n### h3\n#### h4\n##### h5\n###### h6\n
\n\n
Header 1\n========\n
\n\n
Header 2\n--------\n
\n\n

Emphasis

\n\n
*italic*\n_italic_\n
\n\n
**bold**\n__bold__\n
\n\n
`code`\n
\n\n

Lists

\n\n
* Item 1\n* Item 2\n
\n\n
- Item 1\n- Item 2\n
\n\n
- [ ] Checkbox off\n- [x] Checkbox on\n
\n\n
1. Item 1\n2. Item 2\n
\n\n

Links

\n\n
[link](http://google.com)\n
\n\n
[link][google]\n[google]: http://google.com\n
\n\n
<http://google.com>\n
\n\n

Images

\n\n
![Image alt text](/path/to/img.jpg)\n![Image alt text](/path/to/img.jpg \"title\")\n![Image alt text][img]\n
\n\n
[img]: http://foo.com/img.jpg\n
\n\n

Code

\n\n
    4 space indent\n    makes a code block\n
\n\n
```\ncode fences\n```\n
\n\n
```js\ncodeFences.withLanguage()\n```\n
\n\n

Blockquotes

\n\n
> This is\n> a blockquote\n>\n> > Nested\n> > Blockquote\n
\n\n

Horizontal line

\n\n
----\n
\n\n
****\n
\n\n

Tables

\n\n
| Column 1 Heading | Column 2 Heading |\n| ---------------- | ---------------- |\n| Some content     | Other content    |\n
\n\n
Column 1 Heading | Column 2 Heading\n--- | ---\nSome content | Other content\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-07-01" },{ "id": "meow", "title": "Meow", "url": "/meow", "category": "JavaScript libraries", "keywords": null, "content_html": "

Typical settings

\n\n
const cli = require('meow')(`\n  Usage: appname [options]\n\n  Options:\n        --lang LANG    set the language\n\n  Other options:\n    -h, --help         show usage information\n    -v, --version      print version info and exit\n`, {\n  string: ['lang'],\n  boolean: ['help', 'version'],\n  alias: { h: 'help', v: 'version' }\n})\n
\n\n

string and boolean lets meow/minimist know which flags expect arguments (string) and which don’t (boolean).

\n\n

Using the result

\n\n
cli.flags   // { lang: 'en' }\ncli.input   // []\n
\n\n

Yes, flags are automatically camelCased!

\n\n

Lesser-used settings

\n\n
meow(`...`, {\n  // Default values if flags are not specified\n  default: { lang: 'en' },\n\n  // allow using -- to stop processing flags\n  '--': true,\n\n  // Populate `_` with first non-option\n  stopEarly: true,\n\n  // Invoked on unknown param\n  unknown: function () { ... }\n})\n
\n\n

Also see minimist.

", "intro_html": "

meow is the easiest way to write command line apps for Node.js.

", "description_html": "", "tags": null, "updated": "2017-10-30" },{ "id": "meta-tags", "title": "Meta-tags gem", "url": "/meta-tags", "category": "Ruby libraries", "keywords": null, "content_html": "

Titles

\n\n
set_meta_tags title: 'Member Login'\n# <title>Some Page Title</title>\n
\n\n
set_meta_tags site: 'Site Title', title: 'Member Login'\n# <title>Site Title | Page Title</title>\n
\n\n
set_meta_tags(\n  site: 'Site Title',\n  title: 'Member Login',\n  reverse: true,\n  separator: '&middot;'.html_safe\n)\n# <title>Page Title · Site Title</title>\n
\n\n

Works in a controller or a view.

\n\n

Setting defaults

\n\n
rails generate meta_tags:install\n
\n\n

This creates config/initializers/meta_tags.rb that you can edit.

\n\n

Others

\n\n
set_meta_tags site: 'Site name'\nset_meta_tags title: 'Title'\nset_meta_tags description: \"All text about keywords\"\n
\n\n
set_meta_tags keywords: %w[abc def ghi]\nset_meta_tags canonical: 'http://...'\nset_meta_tags icon: 'favicon.ico'\nset_meta_tags author: 'http://...'\nset_meta_tags alternate: { 'fr' => 'http://...' }\nset_meta_tags prev: 'http://...'\nset_meta_tags next: 'http://...'\nset_meta_tags image_src: 'http://...'\n
\n\n
set_meta_tags noindex: true\nset_meta_tags nofollow: true\nset_meta_tags follow: true\n
\n\n
set_meta_tags og: { image: ['...'] }\nset_meta_tags twitter: { description: '...' }\n
\n
set_meta_tags separator: '·'   # Site · Page title\nset_meta_tags prefix: ' '      # Around the separator\nset_meta_tags suffix: ' '\n
\n\n
set_meta_tags lowercase: true  # Lowercase page title\nset_meta_tags reverse: true    # Site name last\n
\n\n

In views

\n\n
# Displaying tags\n<%= display_meta_tags %>\n
\n\n
# Displaying tags individually\n<h1><%= title %></h1>\n
\n\n
# Setting tags\n<% title 'Member Login' %>\n<% description 'My page' %>\n<% keywords '..' %>\n
\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-08" },{ "id": "fitness/micronutrients", "title": "Essential micronutrients", "url": "/fitness/micronutrients", "category": "Fitness", "keywords": null, "content_html": "

Vitamins

\n\n

Vitamin D

\n\n\n\n

See: Examine.com

\n\n

Zinc

\n\n\n\n

See: Examine.com

\n\n

Magnesium

\n\n\n\n

See: Examine.com

\n\n

Selenium

\n\n\n\n

See: Examine.com

\n\n

Vitamin E

\n\n\n\n

See: nih.gov

\n\n

Vitamin C

\n\n\n\n

See: Examine.com

\n\n

Vitamin K

\n\n\n\n

See: Examine.com

\n\n

Thiamin (Vitamin B1)

\n\n\n\n

Riboflavin (Vitamin B2)

\n\n\n\n

Niacin (Vitamin B3)

\n\n\n\n

Vitamin B6

\n\n\n\n

Vitamin B12

\n\n\n\n

Potassium

\n\n\n\n

Omega 3

\n\n\n\n

Calcium

\n\n\n\n

See: nih.gov

\n\n

Iodine

\n\n\n\n

See: whfoods.com

\n\n

Vitamin A

\n\n\n\n

See: nih.gov

\n\n

Iron

\n\n\n\n

See: whfoods.com

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "middleman", "title": "Middleman 3", "url": "/middleman", "category": "JavaScript libraries", "keywords": null, "content_html": "

NB: This is for Middleman 3, not Middleman 4+.

\n\n

Compass config

\n\n
compass_config do |config|\n  config.output_style = :compact\nend\n
\n\n

Config

\n\n
# Automatic image dimensions on image_tag helper\nactivate :automatic_image_sizes\n
\n\n

Gems

\n\n
# Susy grids in Compass\n# First: gem install compass-susy-plugin\nrequire 'susy'\n\n# CodeRay syntax highlighting in Haml\n# First: gem install haml-coderay\nrequire 'haml-coderay'\n\n# CoffeeScript filters in Haml\n# First: gem install coffee-filter\nrequire 'coffee-filter'\n
\n\n

Page command

\n\n
# With no layout\npage \"/path/to/file.html\", :layout => false\n\n# With alternative layout\npage \"/path/to/file.html\", :layout => :otherlayout\n\n# A path which all have the same layout\nwith_layout :admin do\n  page \"/admin/*\"\nend\n\n# Proxy (fake) files\npage \"/this-page-has-no-template.html\", :proxy => \"/template-file.html\" do\n  @which_fake_page = \"Rendering a fake page with a variable\"\nend\n
\n\n

Helpers

\n\n
helpers do\n  def some_helper\n    \"Helping\"\n  end\nend\n
\n\n

Directories

\n\n
set :css_dir, \"alternative_css_directory\"\nset :js_dir, \"alternative_js_directory\"\nset :images_dir, \"alternative_image_directory\"\n
\n\n

Build-specific configuration

\n\n
configure :build do\n  activate :minify_css\n  activate :minify_javascript\n\n  # Enable cache buster\n  activate :cache_buster\n\n  # Use relative URLs\n  activate :relative_assets\n\n  # Compress PNGs after build\n  # First: gem install middleman-smusher\n  # require \"middleman-smusher\"\n  activate :smusher\n\n  # Or use a different image path\n  set :http_path, \"/Content/images/\"\nend\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "minimist", "title": "minimist", "url": "/minimist", "category": "JavaScript libraries", "keywords": null, "content_html": "

Usage

\n\n
var minimist = require('minimist')\n
\n\n
var args = minimist(process.argv.slice(2), {\n  string: 'lang',           // --lang xml\n  boolean: ['version'],     // --version\n  alias: { v: 'version' }\n})\n
\n\n
console.log(args)\n
\n\n

All options are optional, but it’s recommended you set string and boolean at least.

\n\n

All options

\n\n
var args = minimist(process.argv.slice(2), {\n  string: [ 'lang' ],\n  boolean: [ 'pager' ],\n  alias: { h: 'help', v: 'version' },\n  default: { lang: 'en' },\n  '--': true,\n  stopEarly: true, /* populate _ with first non-option */\n  unknown: function () { ... } /* invoked on unknown param */\n})\n
\n\n

All options are optional.

\n\n

Result

\n\n

With --lang xml --no-pager -h index.js package.json, you get:

\n\n
args == {\n  lang: 'xml',\n  version: false,\n  h: true,\n  help: true,\n  _: [ 'index.js', 'package.json' ]\n}\n
\n\n

Meow

\n\n

Help and version

\n\n

Use meow to automatically add support for --help, --version and more.

\n\n
meow(`\n    Usage:\n        $0 FILES [options]\n\n    Options:\n        -h, --help         print usage information\n        -v, --version      show version info and exit\n`, {\n  alias: { h: 'help', v: 'version' }\n  /* minimist options */\n})\n
\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "minitest", "title": "Minitest", "url": "/minitest", "category": "Ruby", "keywords": null, "content_html": "

Usage

\n\n
require 'minitest/autorun'\n\ndescribe \"X\" do\n  before do .. end\n  after do .. end\n  subject { .. }\n  let(:list) { Array.new }\n\n  it \"should work\" do\n    assert true\n  end\nend\n
\n\n

Specs (.must/.wont)

\n\n
expect(x)\n.must_be :==, 0\n.must_equal b\n.must_be_close_to 2.99999\n.must_be_same_as b\n\n.must_include needle\n.must_be_empty\n\n.must_be_kind_of\n.must_be_instance_of\n.must_be_nil\n.must_match /regex/\n.must_be :<=, 42\n.must_respond_to msg\n\n.must_be_silent  ( proc { \"no stdout or stderr\" }.must_be_silent)\n.must_output \"hi\"\n\nproc { ... }.must_output out_or_nil [, err]\nproc { ... }.must_raise exception\nproc { ... }.must_throw sym\n
\n\n

Test

\n\n
class TestHipster < Minitest::Test\n  def setup\n    @subject = [\"silly hats\", \"skinny jeans\"]\n  end\n\n  def teardown\n    @hipster.destroy!\n  end\n\n  def test_for_helvetica_font\n    assert_equal \"helvetica!\", @hipster.preferred_font\n  end\n\n  def test_not_mainstream\n    refute @hipster.mainstream?\n  end\nend\n
\n\n

Assertions

\n\n
assert\nassert_block { ... }\nassert_empty\nassert_equal 2, @size\nassert_in_delta @size, 1, 1\nassert_in_epsilon\nassert_includes @list, \"item\"\nassert_instance_of Array, @list\nassert_kind_of Enumerable, @list\nassert_match @str, /regex/\nassert_nil\nassert_operator @n, :==, 0\nassert_output\nassert_raises\nassert_respond_to\nassert_same\nassert_send\nassert_silent\nassert_throws\n
\n\n

Minitest::Mock

\n\n

A simple and clean mock system. There two essential methods at our disposal: expect and verify.

\n\n
require 'minitest/autorun'\n\ndescribe Twipster, \"Make every tweet a hipster tweet.\" do\n  before do\n    @twitter  = Minitest::Mock.new\n    @twipster = Twipster.new(@twitter)\n  end\n\n  it \"should append a #lolhipster hashtag and update Twitter with our status\" do\n    tweet = \"Skyrim? Too mainstream.\"\n    @twitter.expect :update, true, [\"#{tweet} #lolhipster\"]\n    @twipster.submit(tweet)\n    assert @twitter.verify # verifies tweet and hashtag was passed to `@twitter.update`\n  end\nend\n
\n\n

Reporters

\n\n
gem 'minitest-reporters'\n\nrequire 'minitest/reporters'\nMinitest::Reporters.use! Minitest::Reporters::SpecReporter.new\n\n[Default, Spec, Progress, RubyMate, RubyMine, JUnit]\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "mixpanel", "title": "Mixpanel", "url": "/mixpanel", "category": "Analytics", "keywords": null, "content_html": "

Identify

\n\n
mixpanel.identify('284')\nmixpanel.people.set({ $email: 'hi@gmail.com' })\n
\n\n
// Set common properties\nmixpanel.register({ age: 28, gender: 'male' })\n
\n\n

Track events

\n\n
mixpanel.track('Login success')\nmixpanel.track('Search', { query: 'cheese' })\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "mobx", "title": "Mobx", "url": "/mobx", "category": "JavaScript libraries", "keywords": null, "content_html": "

Properties

\n\n
import {observable, computed} from 'mobx'\n\nclass Page {\n  @observable title = ''\n  @observable published = false\n  @observable author = null\n\n  @computed get authorName () {\n    return this.author || 'Anonymous'\n  }\n}\n
\n\n

Actions

\n\n
class Page {\n  @action publish () {\n    this.published = true\n    // do ajax/async here if you like\n  }\n}\n
\n\n

Plain objects

\n\n
const person = observable({\n  name: 'Ella Fitzgerald'\n})\n
\n\n
const temp = observable(23)\ntemp.get()\ntemp.set(25)\ntemp.observe(...)\n
\n\n

Reactions

\n\n

Importing

\n\n
import {autorun, autorunAsync, when} from 'mobx'\n
\n\n

autorun()

\n\n
// Runs it, finds out what it accessed, then observe those\nautorun(() => {\n  console.log(page.title)\n})\n
\n\n

when()

\n\n
class Foo {\n  constructor () {\n    when(\n      () => !this.isVisible,\n      () => this.doSomething())\n  }\n}\n
\n\n

expr()

\n\n
// A temporary computed value. Its result is cached.\nrender () {\n  const isPublished = expr(() => page.published === true)\n  if (isPublished) { ... }\n}\n
\n\n

Modifiers

\n\n\n\n

React

\n\n

mobx-react

\n\n
import { observer } from 'mobx-react'\n\n@observer\nclass PageView extends React.Component {\n  render () {\n    return <div>{this.props.page.title}</div>\n  }\n}\n\n<PageView page={page} />\n
\n\n

Functional components

\n\n
import { observer } from 'mobx-react'\n\nconst PageView = observer(({page}) => {\n  <div>{page.title}</div>\n})\n\n<PageView page={page} />\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-05-14" },{ "id": "mocha-blanket", "title": "Mocha blanket", "url": "/mocha-blanket", "category": "JavaScript libraries", "keywords": null, "content_html": "

Quickstart guide

\n\n

Install blanket:

\n\n
npm i --save-dev blanket\n
\n\n

In your test helpers, use Blanket before requireing:

\n\n
if (process.env.COVERAGE) {\n  require('blanket')({\n    pattern: require('path').resolve('./index.js')\n  });\n}\nthing = require('../index');\n
\n\n

Add to package.json:

\n\n
\"scripts\": {\n  \"coverage\": \"env COVERAGE=1 mocha -R html-cov > coverage.html && open coverage.html\"\n}\n
\n\n

Be sure to ignore it:

\n\n
echo \"coverage.html\" >> .gitignore\n
\n\n

Then run:

\n\n
npm run coverage\n
\n\n

Travis + coveralls.io support

\n\n

Visit coveralls.io then activate your repo. Then install the appropriate packages:

\n\n
npm i --save-dev mocha-lcov-reporter coveralls\n
\n\n

Add this to .travis.yml:

\n\n
after_success:\n  - ./node_modules/.bin/mocha -R mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js\n
\n\n

Commit, push, wait for Travis to finish.

", "intro_html": "

Use blanket for easy coverage reporting for Mocha JavaScript tests.

", "description_html": "", "tags": null, "updated": null },{ "id": "mocha-html", "title": "Mocha HTML", "url": "/mocha-html", "category": "JavaScript libraries", "keywords": null, "content_html": "

This is a mocha template that loads js/css from cdn.

\n\n
<!doctype html>\n<html>\n<head>\n  <meta charset='utf-8'>\n  <title>Mocha</title>\n  <meta name='viewport' content='width=device-width, initial-scale=1.0'>\n  <link href='https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css' rel='stylesheet' />\n</head>\n<body>\n  <div id='mocha'></div>\n  <script src='https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js'></script>\n  <script src='https://cdn.rawgit.com/chaijs/chai/2.3.0/chai.js'></script>\n  <script>window.onerror=function(msg,url,line){document.getElementById('mocha').innerHTML+='<h1>'+msg+'</'+'h1>'+'<h2>'+url+':'+line+'</'+'h2>';return false}</script>\n  <script>mocha.setup('bdd')</script>\n  <!-- what to test: -->\n  <script src='../index.js'></script>\n  <!-- tests to run: -->\n  <script src='first_test.js'></script>\n  <script src='second_test.js'></script>\n  <script>mocha.run()</script>\n</body>\n</html>\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "mocha-tdd", "title": "Mocha.js TDD interface", "url": "/mocha-tdd", "category": "JavaScript libraries", "keywords": null, "content_html": "

TDD

\n\n
mocha.setup('tdd');\n\nsuite('something', function() {\n  setup(function() {\n  });\n\n  test('should work', function() {\n  });\n\n  teardown(function() {\n  });\n});\n
\n\n

Async

\n\n
test('should save', function(done) {\n  var user = new User();\n  user.save(function(err) {\n    if (err) throw err;\n    done();\n  });\n});\n
\n\n

Chai: Expect

\n\n
var expect = chai.expect;\n\nexpect(foo).to.be.a('string');\nexpect(foo).to.equal('bar');\nexpect(foo).to.have.length(3);\nexpect(tea).to.have.property('flavors').with.length(3);\n
\n\n

See also

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "mocha", "title": "Mocha.js", "url": "/mocha", "category": "JavaScript libraries", "keywords": null, "content_html": "

BDD

\n\n
mocha.setup('bdd');\n\ndescribe('something', function() {\n  beforeEach(function() {\n  });\n\n  it('should work', function() {\n  });\n});\n
\n\n

Async

\n\n
it('should save', function(done) {\n  var user = new User();\n  user.save(function(err) {\n    if (err) throw err;\n    done();\n  });\n});\n
\n\n

Chai: Shoulds

\n\n
chai.should();\n\nfoo.should.be.a('string');\nfoo.should.equal('bar');\nfoo.should.have.length(3);\ntea.should.have.property('flavors').with.length(3);\n
\n\n

See also

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "modella", "title": "Modella", "url": "/modella", "category": "JavaScript libraries", "keywords": null, "content_html": "

Defining models

\n\n
User = Modella('User')\n
\n\n
  .attr('name')\n  .attr('email', { required: true })\n  .use(require('modella-validators'))\n
\n\n
  .validator (u) ->\n    u.error('username', 'is required')  unless u.has('username')\n
\n\n

Instances

\n\n
user\n  .name()\n  .name('John')\n  .set(name: 'John')\n
\n\n
  .has('name')   # → true\n  .isNew()\n  .isValid()\n
\n\n
  .save (err) ->\n  .remove (err) ->\n  .removed\n  .model         # === User\n
\n\n

Events

\n\n

Emitting

\n\n
Model.emit('event', [data...])\n
\n\n
record.emit('event', [data...])\n
\n\n

List of events

\n\n
user\n  .on 'save', ->\n  .on 'create', ->\n  .on 'saving', (data, done) -> done()\n
\n\n
  .on 'remove', ->\n  .on 'removing', (data, done) -> done()\n
\n\n
  .on 'valid', ->\n  .on 'invalid', ->\n
\n\n
  .on 'change', ->\n  .on 'change email', ->\n
\n\n
  .on 'initializing', (instance, attrs) ->\n  .on 'initialize', ->\n
\n\n
  .on 'error', -> failed to save model\n
\n\n
  .on 'setting', (instance, attrs) ->  # on Model#set()\n  .on 'attr', -> # new attr via Model.attr()\n
\n\n

Misc

\n\n

Plugins

\n\n
MyPlugin = ->\n  return (Model) ->\n\n    Model.method = ...\n    Model.prototype.method = ...\n    Model.attr(...)\n\n    Model\n
\n\n

A plugin is a function that returns a model decorator (ie, a function that takes in a model and returns a model).

\n\n

Memory

\n\n
User\n  .all (err, users) ->\n  .find id, (err, user) ->\n
\n\n
  .remove ->\n  .save ->\n  .update ->\n
", "intro_html": "

Modella allows you to create simple models in JavaScript. This is a guide on basic usage of Modella in CoffeeScript.

", "description_html": "", "tags": null, "updated": null },{ "id": "modernizr", "title": "Modernizr", "url": "/modernizr", "category": "JavaScript libraries", "keywords": null, "content_html": "

Script

\n\n
<script src='//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js'></script>\n
\n\n

Detections

\n\n

JavaScript

\n\n\n\n

CSS

\n\n\n\n

HTML5

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "moment", "title": "Moment.js", "url": "/moment", "category": "JavaScript libraries", "keywords": null, "content_html": "

Parsing

\n\n
m = moment('2013-03-01', 'YYYY-MM-DD')\n
\n\n

This parses the given date using the given format. Returns a moment object.

\n\n

Formatting

\n\n
m.format()            // \"2013-03-01T00:00:00+01:00\"\nm.format('dddd')      // \"Friday\"\nm.format('MMM Do YY') // \"Mar 1st 13\"\nm.fromNow()           // \"7 years ago\"\nm.calendar()          // \"03/01/2013\"\n
\n\n

Add

\n\n
m.add(1, 'day')\nm.subtract(2, 'days')\n
\n\n
m.startOf('day')\nm.endOf('day')\nm.startOf('hour')\n
\n\n

Internationalization

\n\n
.format('L')      // 06/09/2014\n.format('l')      // 6/9/2014\n.format('LL')     // June 9 2014\n.format('ll')     // Jun 9 2014\n.format('LLL')    // June 9 2014 9:32 PM\n.format('lll')    // Jun 9 2014 9:32 PM\n.format('LLLL')   // Monday, June 9 2014 9:32 PM\n.format('llll')   // Mon, Jun 9 2014 9:32 PM\n
\n\n

See datetime for more.

\n\n

Formatting

\n\n

Examples

\n\n

Date

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
YYYY-MM-DD2014-01-01
dddd, MMMM Do YYYYFriday, May 16th 2014
\n\n

Time

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
hh:mm a12:30 pm
\n\n

Used by Moment.js and date-fns/format. Similar to Java SimpleDateFormat.

\n\n

Date

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SymbolExampleArea
d0..6Weekday
ddSu 
dddSun 
ddddSunday 
YY13Year
YYYY2013 
M1..12 (Jan is 1)Month
Mo1st..12th 
MM01..12 (Jan is 1) 
MMMJan 
MMMMJanuary 
Q1..4Quarter
Qo1st..4th 
D1..31Day
Do1st..31st 
DD01..31 
DDD1..365Day of year
DDDo1st..365th 
DDDD001..365 
w1..53Week of year
wo1st..53rd 
ww01..53 
\n\n

Time

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SymbolExampleArea
H0..2324h hour
HH00..23 
h1..1212h hour
hh01..12 
m0..59Minutes
mm00..59 
s0..59Seconds
ss00..59 
aamAM/PM
AAM 
Z+07:00Timezone offset
ZZ+0730 
S0..9Deciseconds
SS00..99Centiseconds
SSS000..999Milliseconds
X Unix timestamp
x Millisecond Unix timestamp
\n\n

Presets

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExampleOutput
LT8:30 PM
LTS8:30:25 PM
LLAugust 2 1985
llAug 2 1985
LLLAugust 2 1985 08:30 PM
lllAug 2 1985 08:30 PM
LLLLThursday, August 2 1985 08:30 PM
llllThu, Aug 2 1985 08:30 PM
\n\n

References

\n\n

Alternatives

\n\n\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2018-09-15" },{ "id": "mysql", "title": "MySQL", "url": "/mysql", "category": "Databases", "keywords": null, "content_html": "

Browsing

\n\n
SHOW DATABASES;\nSHOW TABLES;\nSHOW FIELDS FROM table / DESCRIBE table;\nSHOW CREATE TABLE table;\nSHOW PROCESSLIST;\nKILL process_number;\n
\n\n

Select

\n\n
SELECT * FROM table;\nSELECT * FROM table1, table2;\nSELECT field1, field2 FROM table1, table2;\nSELECT ... FROM ... WHERE condition\nSELECT ... FROM ... WHERE condition GROUPBY field;\nSELECT ... FROM ... WHERE condition GROUPBY field HAVING condition2;\nSELECT ... FROM ... WHERE condition ORDER BY field1, field2;\nSELECT ... FROM ... WHERE condition ORDER BY field1, field2 DESC;\nSELECT ... FROM ... WHERE condition LIMIT 10;\nSELECT DISTINCT field1 FROM ...\nSELECT DISTINCT field1, field2 FROM ...\n
\n\n

Select - Join

\n\n
SELECT ... FROM t1 JOIN t2 ON t1.id1 = t2.id2 WHERE condition;\nSELECT ... FROM t1 LEFT JOIN t2 ON t1.id1 = t2.id2 WHERE condition;\nSELECT ... FROM t1 JOIN (t2 JOIN t3 ON ...) ON ...\n
\n\n

Conditions

\n\n
field1 = value1\nfield1 <> value1\nfield1 LIKE 'value _ %'\nfield1 IS NULL\nfield1 IS NOT NULL\nfield1 IS IN (value1, value2)\nfield1 IS NOT IN (value1, value2)\ncondition1 AND condition2\ncondition1 OR condition2\n
\n\n

Create / Open / Delete Database

\n\n
CREATE DATABASE DatabaseName;\nCREATE DATABASE DatabaseName CHARACTER SET utf8;\nUSE DatabaseName;\nDROP DATABASE DatabaseName;\nALTER DATABASE DatabaseName CHARACTER SET utf8;\n
\n\n

Backup Database to SQL File

\n\n
mysqldump -u Username -p dbNameYouWant > databasename_backup.sql\n
\n\n

Restore from backup SQL File

\n\n
mysql - u Username -p dbNameYouWant < databasename_backup.sql;\n
\n\n

Repair Tables After Unclean Shutdown

\n\n
mysqlcheck --all-databases;\nmysqlcheck --all-databases --fast;\n
\n\n

Insert

\n\n
INSERT INTO table1 (field1, field2) VALUES (value1, value2);\n
\n\n

Delete

\n\n
DELETE FROM table1 / TRUNCATE table1\nDELETE FROM table1 WHERE condition\nDELETE FROM table1, table2 FROM table1, table2 WHERE table1.id1 =\n  table2.id2 AND condition\n
\n\n

Update

\n\n
UPDATE table1 SET field1=new_value1 WHERE condition;\nUPDATE table1, table2 SET field1=new_value1, field2=new_value2, ... WHERE\n  table1.id1 = table2.id2 AND condition;\n
\n\n

Create / Delete / Modify Table

\n\n

Create

\n\n
CREATE TABLE table (field1 type1, field2 type2);\nCREATE TABLE table (field1 type1, field2 type2, INDEX (field));\nCREATE TABLE table (field1 type1, field2 type2, PRIMARY KEY (field1));\nCREATE TABLE table (field1 type1, field2 type2, PRIMARY KEY (field1,field2));\n
\n\n
CREATE TABLE table1 (fk_field1 type1, field2 type2, ...,\n  FOREIGN KEY (fk_field1) REFERENCES table2 (t2_fieldA))\n    [ON UPDATE|ON DELETE] [CASCADE|SET NULL]\n
\n\n
CREATE TABLE table1 (fk_field1 type1, fk_field2 type2, ...,\n FOREIGN KEY (fk_field1, fk_field2) REFERENCES table2 (t2_fieldA, t2_fieldB))\n
\n\n
CREATE TABLE table IF NOT EXISTS;\n
\n\n
CREATE TEMPORARY TABLE table;\n
\n\n

Drop

\n\n
DROP TABLE table;\nDROP TABLE IF EXISTS table;\nDROP TABLE table1, table2, ...\n
\n\n

Alter

\n\n
ALTER TABLE table MODIFY field1 type1\nALTER TABLE table MODIFY field1 type1 NOT NULL ...\nALTER TABLE table CHANGE old_name_field1 new_name_field1 type1\nALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 NOT NULL ...\nALTER TABLE table ALTER field1 SET DEFAULT ...\nALTER TABLE table ALTER field1 DROP DEFAULT\nALTER TABLE table ADD new_name_field1 type1\nALTER TABLE table ADD new_name_field1 type1 FIRST\nALTER TABLE table ADD new_name_field1 type1 AFTER another_field\nALTER TABLE table DROP field1\nALTER TABLE table ADD INDEX (field);\n
\n\n

Change field order

\n\n
ALTER TABLE table MODIFY field1 type1 FIRST\nALTER TABLE table MODIFY field1 type1 AFTER another_field\nALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 FIRST\nALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 AFTER\n  another_field\n
\n\n

Keys

\n\n
CREATE TABLE table (..., PRIMARY KEY (field1, field2))\nCREATE TABLE table (..., FOREIGN KEY (field1, field2) REFERENCES table2\n(t2_field1, t2_field2))\n
\n\n

Users and Privileges

\n\n
CREATE USER 'user'@'localhost';\nGRANT ALL PRIVILEGES ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';\nGRANT SELECT, INSERT, DELETE ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';\nREVOKE ALL PRIVILEGES ON base.* FROM 'user'@'host'; -- one permission only\nREVOKE ALL PRIVILEGES, GRANT OPTION FROM 'user'@'host'; -- all permissions\nFLUSH PRIVILEGES;\n
\n\n
SET PASSWORD = PASSWORD('new_pass');\nSET PASSWORD FOR 'user'@'host' = PASSWORD('new_pass');\nSET PASSWORD = OLD_PASSWORD('new_pass');\n
\n\n
DROP USER 'user'@'host';\n
\n\n

Host ‘%’ indicates any host.

\n\n

Main Data Types

\n\n
TINYINT (1o: -217+128)\nSMALLINT (2o: +-65 000)\nMEDIUMINT (3o: +-16 000 000)\nINT (4o: +- 2 000 000 000)\nBIGINT (8o: +-9.10^18)\n
\n\n
Precise interval: -(2^(8*N-1)) -> (2^8*N)-1\n
\n\n

⚠ INT(2) = “2 digits displayed” – NOT “number with 2 digits max”

\n\n
FLOAT(M,D)\nDOUBLE(M,D)\nFLOAT(D=0->53)\n
\n\n

⚠ 8,3 -> 12345,678 – NOT 12345678,123!

\n\n
TIME (HH:MM)\nYEAR (AAAA)\nDATE (AAAA-MM-JJ)\nDATETIME (AAAA-MM-JJ HH:MM; années 1000->9999)\nTIMESTAMP (like DATETIME, but 1970->2038, compatible with Unix)\n
\n\n
VARCHAR (single-line; explicit size)\nTEXT (multi-lines; max size=65535)\nBLOB (binary; max size=65535)\n
\n\n

Variants for TEXT&BLOB: TINY (max=255), MEDIUM (max=~16000), and LONG (max=4Go). Ex: VARCHAR(32), TINYTEXT, LONGBLOB, MEDIUMTEXT

\n\n
ENUM ('value1', 'value2', ...) -- (default NULL, or '' if NOT NULL)\n
\n\n

Reset Root Password

\n\n
$ /etc/init.d/mysql stop\n
\n\n
$ mysqld_safe --skip-grant-tables\n
\n\n
$ mysql # on another terminal\nmysql> UPDATE mysql.user SET password=PASSWORD('new_pass') WHERE user='root';\n
\n\n
## Switch back to the mysqld_safe terminal and kill the process using Control + \\\n$ /etc/init.d/mysql start\n
\n\n

Your commands may vary depending on your OS.

", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-07-05" },{ "id": "ncftp", "title": "ncftp", "url": "/ncftp", "category": "CLI", "keywords": null, "content_html": "

Bookmarking

\n\n
$ ncftp\n$ open -u username ftp.host.com\n$ bookmark bookmarkname\n
\n\n

Mass download

\n\n
$ ncftpget -R bookmarkname /www/ .\n
\n\n

Mass upload

\n\n
$ ncftpput -R bookmarkname /www/ .\n
\n\n

Upload just the changed files

\n\n
$ git show --pretty=\"format:\" --name-only HEAD~1\n$ ncftpget -R -C log bookmarkname /www/ .\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "nock", "title": "Nock", "url": "/nock", "category": "JavaScript libraries", "keywords": null, "content_html": "

Nock

\n\n
scope = nock('http://foo.com')\nscope = nock('http://foo.com', { allowUnmocked: true })\n
\n\n
nock('http://foo.com')\n  .get('/user')\n  .reply(200, { id: 1234 })\n
\n\n

Filtering

\n\n
nock('http://foo.com')\n  .filteringPath(/[&\\?]token=[^&]*/g, '')\n  .get('/user')\n\n// catches \"/user?token=...\" as well\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "nocode", "title": "Nocode", "url": "/nocode", "category": "Others", "keywords": null, "content_html": "

Nothing

\n\n

































", "intro_html": "

Nocode is the best way to write secure and reliable applications. Write nothing; deploy nowhere.

", "description_html": "", "tags": null, "updated": "2018-03-17" },{ "id": "nodejs-assert", "title": "assert", "url": "/nodejs-assert", "category": "Node.js", "keywords": null, "content_html": "

Assertions

\n\n
assert(val)\nassert.equal(actual, expected)\nassert.notEqual(a, e)\n
\n\n
assert.deepEqual(a, e)\nassert.notDeepEqual(a, e)\n
\n\n
assert.throws(fn)\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "nodejs-fs", "title": "fs", "url": "/nodejs-fs", "category": "Node.js", "keywords": null, "content_html": "

Reading

\n\n
fs.readFile('file.txt', function(err, data) { .. });\nfs.readFile('file.txt', {encoding: 'utf-8'}, function(err, data) { .. });\n
\n\n

Writing

\n\n
fs.writeFile('output.txt', function(err) { .. });\nfs.appendFile('output.txt', function(err) { .. });\n
\n\n

Watch

\n\n
fs.watch('dir OR file.txt', { persistent: true }, function(event, file) {\n  event; /* rename | change */\n});\n
\n\n

Getting info

\n\n
fs.exists('file.txt', function(exists /*bool*/) { ... });\n\nfs.stat('file.txt', function(stats) {\n  stats.isFile();\n  stats.isDirectory();\n  stats.isSymbolicLink();\n});\n
\n\n

File operations

\n\n
fs.rename('old.txt', 'new.txt', function(){});\nfs.chown('file.txt', uid, gid, function(){});\nfs.symlink('src', 'dest', function(){});\nfs.unlink('path', function(){});\nfs.rmdir('path', function(){});\n\nfs.readdir('path', function(err, files) { .. }); /* `files` = array of names */\n
\n\n

Path

\n\n
fs.realpath('/etc/passwd', function(err, path) { /* \"/private/etc/passwd\" */ });\n
\n\n

Sync

\n\n
data = fs.readFileSync('input.txt');\nfs.writeFileSync('output.txt', data);\nfs.appendFileSync('output.txt', data);\nfs.existsSync('file.txt');\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "nodejs-path", "title": "Node.js path API", "url": "/nodejs-path", "category": "Node.js", "keywords": null, "content_html": "

Functions

\n\n
const fs = require('fs')\n\nfs.realpath('/etc/passwd', function (err, path) {\n  path // => \"/private/etc/passwd\"\n})\n
\n\n
const path = require('path')\ndir = path.join('etc', 'passwd')\ndir = path.resolve('/etc', 'passwd', '..', 'var')\n
\n\n
path.dirname('/etc/passwd') //      => \"/etc\"\npath.basename('/etc/passwd') //     => \"passwd\"\npath.basename('/etc/rc.d', '.d') // => \"rc\"\n
\n\n

References

\n\n", "intro_html": "

Quick reference to the Node.js path API.

", "description_html": "", "tags": null, "updated": null },{ "id": "nodejs-process", "title": "process", "url": "/nodejs-process", "category": "Node.js", "keywords": null, "content_html": "

Streams

\n\n
process.stdout.write('...');\nprocess.stderr.write('...');\n\nfunction stdin(fn) {\n  var data = '';\n\n  process.stdin.setEncoding('utf8');\n  process.stdin.on('readable', function() {\n    var chunk = process.stdin.read();\n    if (chunk !== null) data += chunk;\n  });\n\n  process.stdin.on('end', function() {\n    fn(null, data);\n  });\n}\n
\n\n

stuff

\n\n
process.argv; //=> ['node', 'file.js', 'one', 'two']\nprocess.env; //=> {TERM: 'screen-256color', SHELL: '/bin/bash', ...}\n\nprocess.exit();\nprocess.exit(1);\n
\n\n

Directories

\n\n
process.cwd(); //=> \"/tmp\"\nprocess.chdir('dir');\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "nodejs-stream", "title": "Node.js streams", "url": "/nodejs-stream", "category": "Node.js", "keywords": null, "content_html": "

Types

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
StreamDescription
ReadableData emitter
WritableData receiver
TransformEmitter and receiver
DuplexEmitter and receiver (independent)
\n\n

See: Stream (nodejs.org)

\n\n

Streams

\n\n
const Readable = require('stream').Readable\nconst Writable = require('stream').Writable\nconst Transform = require('stream').Transform\n
\n\n

Piping

\n\n
clock()              // Readable stream\n  .pipe(xformer())   // Transform stream\n  .pipe(renderer())  // Writable stream\n
\n\n

Methods

\n\n
stream.push(/*...*/)         // Emit a chunk\nstream.emit('error', error)  // Raise an error\nstream.push(null)            // Close a stream\n
\n\n

Events

\n\n
const st = source()\nst.on('data', (data) => { console.log('<-', data) })\nst.on('error', (err) => { console.log('!', err.message) })\nst.on('close', () => { console.log('** bye') })\nst.on('finish', () => { console.log('** bye') })\n
\n\n

Assuming source() is a readable stream.

\n\n

Flowing mode

\n\n
// Toggle flowing mode\nst.resume()\nst.pause()\n
\n\n
// Automatically turns on flowing mode\nst.on('data', /*...*/)\n
\n\n

Stream types

\n\n

Readable

\n\n
function clock () {\n  const stream = new Readable({\n    objectMode: true,\n    read() {}\n  })\n\n  setInterval(() => {\n    stream.push({ time: new Date() })\n  }, 1000)\n\n  return stream\n}\n\n// Implement read() if you\n// need on-demand reading.\n
\n\n

Readable streams are generators of data. Write data using stream.push().

\n\n

Transform

\n\n
function xformer () {\n  let count = 0\n\n  return new Transform({\n    objectMode: true,\n    transform: (data, _, done) => {\n      done(null, { ...data, index: count++ })\n    }\n  })\n}\n
\n\n

Pass the updated chunk to done(null, chunk).

\n\n

Writable

\n\n
function renderer () {\n  return new Writable({\n    objectMode: true,\n    write: (data, _, done) => {\n      console.log('<-', data)\n      done()\n    }\n  })\n}\n
\n\n

All together now

\n\n
clock()              // Readable stream\n  .pipe(xformer())   // Transform stream\n  .pipe(renderer())  // Writable stream\n
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-08-30" },{ "id": "nodejs", "title": "Node.js API", "url": "/nodejs", "category": "Node.js", "keywords": null, "content_html": "

Globals

\n\n
__filename\n__dirname\n
\n\n

exec

\n\n
var exec = require('child_process').exec,\n\nvar child = exec('cat *.js bad_file | wc -l',\n  function (error, stdout, stderr) {\n    console.log('stdout: ' + stdout);\n    console.log('stderr: ' + stderr);\n    if (error !== null) {\n      console.log('exec error: ' + error);\n    }\n});\n
\n\n

Snippets

\n\n
info = require('../package.json')\ninfo.version\n\nprocess.stdout.write(util.inspect(objekt, false, Infinity, true) + '\\n');\n
\n\n

Spawn - passthru the in/out

\n\n
var spawn = require('child_process').spawn;\nvar proc = spawn(bin, argv, { stdio: 'inherit' });\nproc.on('error', function(err) {\n  if (err.code == \"ENOENT\") { \"does not exist\" }\n  if (err.code == \"EACCES\") { \"not executable\" }\n});\nproc.on('exit', function(code) { ... });\n\n// also { stdio: ['pipe', 'pipe', process.stdout] }\n// also { stdio: [process.stdin, process.stderr, process.stdout] }\n\nproc.stdout.on('data', function (data) {\n});\nproc.stderr.on('data', function (data) {\n});\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "nopt", "title": "Nopt", "url": "/nopt", "category": "JavaScript libraries", "keywords": null, "content_html": "
var args = require('nopt')({\n  foo: [String, null],\n  size: ['big', 'medium', 'small'],\n  many: [String, Array],\n  debug: Boolean,\n  version: Boolean,\n  help: Boolean\n}, {\n  h: '--help',\n  v: '--version'\n}, process.argv);\n\nargs == {\n  debug: true,\n  version: true,\n  size: 'big',\n  argv: {\n    remain: ['...', '...'],\n    cooked: ...,\n    original: ...\n  }\n}\n
\n\n
if (args.help) {\n  console.log([\n      'Usage:',\n      '  hicat [options] [file]',\n      '',\n      'Options:',\n      '  -h, --help         print usage information',\n      '  -v, --version      show version info and exit',\n  ].join('\\n'));\n  process.exit(0);\n}\n\nif (args.version) {\n  console.log(require('../package.json').version);\n  process.exit(0);\n}\n
\n\n

https://www.npmjs.org/package/nopt

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "npm", "title": "npm", "url": "/npm", "category": "JavaScript", "keywords": null, "content_html": "

Package management

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
npm iAlias for npm install
npm installInstall everything in package.json
npm install --productionInstall everything in package.json, except devDependecies
npm install lodashInstall a package
npm install --save-dev lodashInstall as devDependency
npm install --save-exact lodashInstall with exact
\n\n

--save is the default as of npm@5. Previously, using npm install without --save doesn’t update package.json.

\n\n

Install names

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
npm i saxNPM package
npm i sax@latestSpecify tag latest
npm i sax@3.0.0Specify version 3.0.0
npm i sax@\">=1 <2.0\"Specify version range
npm i @org/saxScoped NPM package
npm i user/repoGitHub
npm i user/repo#masterGitHub
npm i github:user/repoGitHub
npm i gitlab:user/repoGitLab
npm i /path/to/repoAbsolute path
npm i ./archive.tgzTarball
npm i https://site.com/archive.tgzTarball via HTTP
\n\n

Listing

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
npm listLists the installed versions of all dependencies in this software
npm list -g --depth 0Lists the installed versions of all globally installed packages
npm viewLists the latest versions of all dependencies in this software
npm outdatedLists only the dependencies in this software which are outdated
\n\n

Updating

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
npm updateUpdate production packages
npm update --devUpdate dev packages
npm update -gUpdate global packages
npm update lodashUpdate a package
\n\n

Misc features

\n\n
# Add someone as an owner\nnpm owner add USERNAME PACKAGENAME\n
\n\n
# list packages\nnpm ls\n
\n\n
# Adds warning to those that install a package of old versions\nnpm deprecate PACKAGE@\"< 0.2.0\" \"critical bug fixed in v0.2.0\"\n
\n\n
# update all packages, or selected packages\nnpm update [-g] PACKAGE\n
\n\n
# Check for outdated packages\nnpm outdated [PACKAGE]\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2019-12-24" },{ "id": "org-mode", "title": "Org Mode", "url": "/org-mode", "category": "Apps", "keywords": null, "content_html": "

Syntax

\n\n

Headings

\n\n
* Welcome to Org mode\n\n  Lines starting with * are headings.\n  These lines without are notes.\n\n** Sub-heading\n\n   Two stars mark a 2nd-level subheading (h2).\n
\n\n

Lists

\n\n
* Lists\n\nTo buy:\n1. Milk\n2. Eggs\n   - Organic\n3. Cheese\n   + Parmesan\n   + Mozarella\n
\n\n

Inline styles

\n\n
*bold*\n/italic/\n_underline_\n=code=\n~verbatim~\n+strike-through+\n
\n\n

To do

\n\n
* TODO buy airplane\n
\n\n

Cycle by using S-LEFT / S-RIGHT. List all TODO’s via C-c C-v.

\n\n

Shortcuts

\n\n

Basic shortcuts

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
(Un) foldTAB / S-TAB
Move upM-UP / M-DOWN
New headlineM-RET
Cycle workflowS-LEFT / S-RIGHT
Cycle priorityS-UP / S-DOWN
\n\n

Timer

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Start timerC-c C-x 0
Stop timerC-c C-x _
Pause timerC-c C-x ,
Start countdownC-c C-x ;
\n\n

You can use this for Pomodoro!

\n\n

Agenda

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Agenda menuC-c a
Add documentC-c [
Remove documentC-c ]
Add dateC-c .
Add time & dateC-u C-c .
\n\n

Start by adding the current file to the agenda (C-c [), then use the agenda menu to navigate.

\n\n

Export

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Export menuC-c C-e
\n\n

Lets you export the document as Markdown, HTML, and others.

\n\n

References

\n\n", "intro_html": "

Org mode is for keeping hierarchal notes (and more) in Emacs.

", "description_html": "", "tags": ["WIP"], "updated": "2018-02-19" },{ "id": "osx", "title": "OS X", "url": "/osx", "category": "macOS", "keywords": null, "content_html": "

Locations of startup items

\n\n
~/Library/LaunchAgents\n/System/Library/LaunchAgents/\n/System/Library/LaunchDaemons/\n/Library/LaunchAgents/\n/Library/LaunchDaemons/\n\n__Running `launchctl list` show you what launch scripts are currently loaded.__\n
\n\n

Hide desktop icons

\n\n
defaults write com.apple.finder CreateDesktop -bool false\nkillall Finder\n
\n\n

Auto-hide other windows on dock switch

\n\n
defaults write com.apple.dock single-app -bool TRUE\nkillall Dock\n\ndefaults delete com.apple.dock single-app\nkillall Dock\n
\n\n

Flush DNS

\n\n
killall -HUP mDNSResponder   # 10.8+\ndscacheutil -flushcache      # 10.7 below\n
\n\n

Disable spotlight indexing

\n\n
mdutil -a -i off                    # disable indexing for all volumes\nmdutil -i off MOUNT_POINT           # disable for specific volume\ntouch FOLDER/.metadata_never_index  # disable for FOLDER\n
\n\n

Turn on/off proxy

\n\n
sudo networksetup -setsocksfirewallproxystate Wi-Fi off\nsudo networksetup -setsocksfirewallproxystate Ethernet off\nsudo networksetup -setsocksfirewallproxy Wi-Fi 127.0.0.1 9999\nsudo networksetup -setsocksfirewallproxy Ethernet 127.0.0.1 9999\nsudo networksetup -setsocksfirewallproxystate Wi-Fi on\nsudo networksetup -setsocksfirewallproxystate Ethernet on\n
\n\n

System utils

\n\n\n\n

Useful utils

\n\n\n\n

INFO: brew (link) is highly recommended utility

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "package-json", "title": "package.json", "url": "/package-json", "category": "Node.js", "keywords": null, "content_html": "

Basic

\n\n
{\n  \"name\": \"expo\",\n  \"description\": \"My package\",\n  \"version\": \"0.1.0\",\n  \"license\": \"MIT\",\n  \"keywords\": [\"http\", \"server\"],\n  \"author\": \"Rico Sta. Cruz <rstacruz@users.noreply.github.com>\",\n  \"engines\": {\n    \"node\": \">=0.8.0\"\n  },\n  \"main\": \"index\",\n  \"bin\": {\n    \"command\": \"./bin/command\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/rstacruz/___.git\"\n  },\n}\n
\n\n

Highlighted lines are required.

\n\n

Dependencies

\n\n
\"dependencies\": {\n  \"colors\":   \"*\",\n  \"flatiron\": \"0.1.x\",\n  \"flatiron\": \"~0.1.0\",\n  \"plates\":   \"https://github.com/user/project/tarball/branch\",\n  \"stuff\":    \"git://github.com/user/project.git#commit-ish\"\n},\n
\n\n
\"devDependencies\": { ··· },\n\"peerDependencies\": { ··· },\n\"optionalDependencies\": { ··· },\n
\n\n

See Semver cheatsheet for explanation of version ranges.

\n\n

Scripts

\n\n
\"scripts\": {\n  \"start\": \"node ./bin/xxx\",       /* npm start */\n  \"test\": \"vows --spec --isolate\", /* npm test */\n  \"postinstall\": \"...\",\n  \"prepublish\": \"grunt build\",     /* after 'npm install' and before 'npm \n                                      publish' */\n}\n
\n\n

Misc

\n\n
\"private\": true,\n\"preferGlobal\": true\n
\n\n

Config

\n\n
{\n  \"config\": {\n    \"foobar\": \"hello\"\n  },\n  \"scripts\": {\n    \"run\": \"echo $npm_package_config_foobar\"\n  }\n}\n
\n\n

Keys in config are exposed as env vars to scripts.

\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-06-23" },{ "id": "package", "title": "package.json", "url": "/package", "category": "Hidden", "keywords": null, "content_html": "", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "pacman", "title": "Pacman", "url": "/pacman", "category": "Linux", "keywords": null, "content_html": "

Commands

\n\n

Common commands

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pacman -Syu <pkg>Install (and update package list)
pacman -S <pkg>Install only
pacman -Rsc <pkg>Uninstall
pacman -Ss <keywords>Search
pacman -SyuUpgrade everything
\n\n

Query

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pacman -QeList explictly-installed packages
pacman -Ql <pkg>What files does this package have?
pacman -Qii <pkg>List information on package
pacman -Qo <file>Who owns this file?
pacman -Qs <query>Search installed packages for keywords
\n\n

Orphans

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pacman -QdtList unneeded packages
pacman -Rns $(pacman -Qdtq)Uninstall unneeded packages
\n\n

Avoid orphans by using pacman -Rsc to remove packages, which will remove unneeded dependencies.

\n\n

Other

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pactree <pkg>What does pkg depend on?
pactree -r <pkg>What depends on pkg?
\n\n

References

\n\n", "intro_html": "

Pacman is the package manager for Arch linux and its derivatives.

", "description_html": "", "tags": null, "updated": "2018-07-07" },{ "id": "parsimmon", "title": "Parsimmon", "url": "/parsimmon", "category": "JavaScript libraries", "keywords": null, "content_html": "
const P = require('parsimmon')\n\nP.regexp(/[a-z]+/)\n.parse('hello')\n//=> { status: true, value: ['hello'] }\n
\n\n

Atoms

\n\n
P.regexp(/[a-z]+/)\nP.string('hello')\nP.oneOf('abc')             // like P.regexp(/[abc]/)\n\nP.whitespace\nP.optWhitespace\nP.eof\n
\n\n

Combinators

\n\n
P.seq(a, b, c)             // sequence of these\nP.alt(a, b)                // any of these\nP.sepBy(a, P.string(','))  // sequence of `a`, separated by ','\nP.sepBy1(a, P.string(',')) // same, at least once\n\na.or(b)                    // like P.alt(a, b)\na.skip(b)                  // parses `b` but discards it\n\na.many()\na.times(3)\na.times(1, 4)              // 1 <= x <= 4\na.atMost(10)\na.atLeast(10)\n
\n\n

Formatting

\n\n
P.seq(P.number, P.oneOf('+-*/'), P.number)\n.map(([left, oper, right]) => ({ oper, left, right }))\n
\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "parsley", "title": "Parsley.js", "url": "/parsley", "category": "JavaScript libraries", "keywords": ["data-parsley-validate","$('#form').parsley()","errorClass","successClass","classHandler","errorsContainer","errorsWrapper","errorTemplate"], "content_html": "

Parsley

\n\n

Installing via NPM

\n\n
npm install --save parsleyjs\n
\n\n

parsleyjs is the Parsley form validator. (‘parsley’ is a different package)

\n\n

Enabling

\n\n

via HTML

\n\n
<form data-parsley-validate>\n<!-- ✗ not preferred -->\n
\n\n

via JavaScript

\n\n
$('#form').parsley(/* options */)\n
\n\n

It’s preferable to explicitly call $.fn.parsley().

\n\n

API

\n\n

Form

\n\n
$('#myform').parsley()\n  .isValid()  // → true | null\n  .validate()\n  .reset()\n  .destroy()\n
\n\n

Input

\n\n
$('#myform input').parsley()\n  .isValid()\n  .validate() // returns errors\n
\n\n

Validators

\n\n
<input ...>\n
\n\n

Required

\n\n
  required\n
\n\n

Types

\n\n
  type='email'\n
\n\n
  type='url'\n  data-parsley-type='url'\n
\n\n

Length

\n\n
  maxlength='6'\n  data-parsley-maxlength='6'\n  minlength='10'\n  data-parsley-minlength='10'\n
\n\n

Numeric

\n\n
  pattern='\\d+'\n  data-parsley-pattern='\\d+'\n
\n\n
  type='number'\n  data-parsley-type='number'\n  data-parsley-type='integer'\n  data-parsley-type='digits'\n  data-parsley-type='alphanum'\n
\n\n

Range

\n\n
  type='range'\n  data-parsley=range='[6, 10]'\n
\n\n
  max='10'\n  data-parsley-max='10'\n  min='6'\n  data-parsley-min='6'\n
\n\n

Checkboxes

\n\n
  data-parsley-mincheck='1'\n  data-parsley-maxcheck='3'\n  data-parsley-check='[1, 3]'\n
\n\n

Confirmation

\n\n
  data-parsley-equalto='#confirm'\n
\n\n

Options

\n\n

Form options

\n\n
// Supported & excluded inputs by default\n  inputs: 'input, textarea, select'\n  excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]'\n
\n\n
// Stop validating field on highest priority failing constraint\n  priorityEnabled: true\n
\n\n

See: Options

\n\n

Field options

\n\n
// identifier used to group together inputs\n// (e.g. radio buttons…)\n  multiple: null\n
\n\n
// identifier (or array of identifiers) used to\n// validate only a select group of inputs\n  group: null\n
\n\n

These options are only available for fields.

\n\n

UI Options

\n\n
// Enable/disable error messages\n  uiEnabled: true\n
\n\n
// Key events threshold before validation\n  validationThreshold: 3\n
\n\n
// Focused field on form validation error. ‘first’|’last’|’none’\n  focus: 'first'\n
\n\n
// $.Event() that will trigger validation. eg: keyup, change…\n  trigger: false\n
\n\n
// Class that would be added on every failing validation\n// Parsley field\n  errorClass: 'parsley-error'\n  successClass: 'parsley-success'\n
\n\n
// Return the $element that will receive these above\n// success or error classes. Could also be (and given\n// directly from DOM) a valid selector like '#div'\n  classHandler: function (ParsleyField) {}\n
\n\n
// Return the $element where errors will be appended.\n// Could also be (and given directly from DOM) a valid\n// selector like '#div'\n  errorsContainer: function (ParsleyField) {}\n
\n\n
// ul elem that would receive errors’ list\n  errorsWrapper: '<ul class=\"parsley-errors-list\"></ul>'\n
\n\n
// li elem that would receive error message\n  errorTemplate: '<li></li>'\n
\n\n

Examples

\n\n

Custom container

\n\n
$('[data-parsley]').parsley({\n  errorsContainer (field) {\n    return field.$element.closest('.block, .control')\n  }\n})\n
\n\n

Appends the error to the closest .block or .control.

\n\n

Custom markup

\n\n
$('[data-parsley]').parsley({\n  errorClass: '-error',\n  successClass: '-success',\n\n  errorsWrapper: '<ul class=\"parsley-error-list\"></ul>',\n  errorTemplate: '<li class=\"parsley-error\"></li>'\n})\n
\n\n

Uses custom markup.

\n\n

Custom fields

\n\n
$('[data-parsley]').parsley({\n  classHandler (field) {\n    const $parent = field.$element.closest('.input-group')\n    if ($parent.length) return $parent\n\n    return field.$element\n  }\n})\n
\n\n

Applies the errorClass and successClass to the closest .input-group, if available.

\n\n

Custom validator

\n\n

HTML

\n\n
<input type='text' data-parsley-multiple-of='3' />\n
\n\n

JavaScript

\n\n
window.Parsley\n  .addValidator('multipleOf', {\n    // string | number | integer | date | regexp | boolean\n    requirementType: 'integer',\n\n    // validateString | validateDate | validateMultiple\n    validateNumber (value, requirement) {\n      return 0 === value % requirement\n    },\n\n    messages: {\n      en: 'This value should be a multiple of %s'\n    }\n  })\n
\n\n

See: Custom validators

\n\n

Also see

\n\n", "intro_html": "

Parsley provides frontend form validation.

", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "pass", "title": "Pass", "url": "/pass", "category": "CLI", "keywords": null, "content_html": "

Reference

\n\n

Create

\n\n
$ pass init [-p] <gpg-id>\n$ pass git init\n$ pass git remote add origin <your.git:repository>\n$ pass git push -u --all\n
\n\n

Store

\n\n
$ pass insert [-m] twitter.com/rsc\n$ pass generate [-n] twitter.com/rsc length\n
\n\n

Retrieve

\n\n
$ pass ls twitter.com/\n$ pass show twitter.com/rsc\n$ pass -c twitter.com/rsc\n
\n\n

Search

\n\n
$ pass find twitter.com\n
\n\n

Management

\n\n
$ pass mv twitter.com twitter.com/rsc\n$ pass rm [-rf] twitter.com\n$ pass cp twitter.com/rsc twitter.com/ricosc\n
\n\n
$ pass edit twitter.com/rsc\n
\n\n

Synchronize

\n\n
$ pass git push\n$ pass git pull\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "passenger", "title": "Phusion Passenger", "url": "/passenger", "category": "Others", "keywords": null, "content_html": "

Enabling Phusion passenger

\n\n
server {\n   listen 80;\n   server_name www.yourhost.com;\n   root /somewhere/public;   # <--- be sure to point to 'public'!\n   passenger_enabled on;\n   autoindex on; # Show directory listings\n}\n
\n\n

This is an example nginx configuration.

", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "perl-pie", "title": "Perl-pie", "url": "/perl-pie", "category": "Development", "keywords": null, "content_html": "

Search and replace

\n\n
perl -p -i -e 's/hello/hola/g' *.txt\n
\n\n

Back-referencing

\n\n

Use \\1 et al.

\n\n
# '@include align-items(center);' => 'align-items: center;'\nperl -p -i -e \"s/\\@include (align-items)\\((.*)\\);/\\1: \\2;/g\"\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ph-food-delivery", "title": "Food delivery (Philippines)", "url": "/ph-food-delivery", "category": "Others", "keywords": null, "content_html": "

Numbers

\n\n

Western

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RestaurantOnline orderPhone
Army Navyarmynavy.com.ph331-3131
Burger Kingburgerkingdelivery.com.ph #2-22-22
KFCkfc.com.ph887-8888
Kenny Rogerskennys.com.ph555-9000
McDonald’smcdonalds.com.ph8-6236
Pancake Housepancakehouse.com.ph7-9000
Wendy’swendys.com.ph533-3333
\n\n

Pizza

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RestaurantOnline orderPhone
Angel’s Pizzaangelspizza.com.ph922-2222
Domino’sdominospizza.ph997-3030
Greenwichgreenwichdelivery.com5-5555
Papa John’spapajohns.com.ph887-7272
Pizza Hutpizzahut.com.ph911-1111
Shakey’sshakeyspizza.ph77-7777
Yellow Cabyellowcabpizza.com789-9999
\n\n

Asian

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RestaurantOnline orderPhone
Bonchonbonchon.com.ph (menu)633-1818
Chowkingchowkingdelivery.com9-8888
North Parknorthparkdelivery.com7-3737
Yoshinoyayoshinoya.ph288-2888
\n\n

Filipino

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RestaurantOnline orderPhone
Amber’samber.com.ph884-8888
Goldilock’sgoldilocksdelivery.com.ph888-1-999
Jollibeejollibeedelivery.com#8-7000
Mang Inasalmanginasal.com (menu)733-1111
Max’smaxschicken.com7-9000
\n\n

Dessert

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RestaurantOnline orderPhone
Krispy Kremenow.krispykreme.com.ph7-9000
Red Ribbonredribbononlinestore.com8-7777
\n\n

-

\n\n

Hint: you can get to this page via devhints.io/gutom 🍅🍟

", "intro_html": "

Food delivery numbers & sites for top restaurant chains in Metro Manila. For numbers outside Metro Manila, check their websites.

", "description_html": "", "tags": null, "updated": null },{ "id": "fitness/phat", "title": "Phat", "url": "/fitness/phat", "category": "Fitness", "keywords": null, "content_html": "

Day 1: Upper Body Power

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PurposeMovementSets x Reps
Pull: powerBent over / Pendlay rows3 x 3-5
Pull: assistanceWeighted Pull ups2 x 6-10
Pull: auxiliaryRack chins2 x 6-10
Press: powerFlat dumbbell presses3 x 3-5
Press: assistanceWeighted dips2 x 6-10
Press: assistanceSeated dumbbell shoulder presses3 x 6-10
Aux: curlingCambered bar curls3 x 6-10
Aux: extensionSkull crushers3 x 6-10
\n\n

Day 2: Lower Body Power

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PurposeMovementSets x Reps
Press: PowerSquats3 x 3-5
Press: AssistanceHack Squats2 x 6-10
Ext: AssistanceLeg extensions2 x 6-10
Pull: AssistanceStiff legged deadlifts3 x 5-8
Pull: Assistance (curl)Glute ham raises or lying leg curls2 x 6-10
Aux: calfStanding calf raise3 x 6-10
Aux: calfSeated calf raise2 x 6-10
\n\n

Day 4: Upper Body Hypertrophy

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PurposeMovementSets x Reps
Pull: speed workBent over / Pendlay rows6 x 3
PullRack chins3 x 8-12
PullSeated cable row3 x 8-12
PullDumbbell rows / shrugs against incline bench2 x 12-15
PullClose grip pulldowns2 x 15-20
ShoulderSeated dumbbell presses3 x 8-12
ShoulderUpright rows2 x 12-15
ShoulderSide lateral raises with dumbbells or cables3 x 12-20
\n\n

Speed work: with 65-70% of normal 3-5 rep max

\n\n

Day 5: Lower Body Hypertrophy

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PurposeMovementSets x Reps
Legs: speed workSquats6 x 3
PressHack squats3 x 8-12
PressLeg presses2 x 12-15
ExtensionLeg extensions3 x 15-20
PullRomanian deadlifts3 x 8-12
Pull/curlingLying leg curls2 x 12-15
Pull/curlingSeated leg curls2 x 15-20
CalfDonkey calf raises4 x 10-15
CalfSeated calf raises3 x 15-20
\n\n

Day 6: Chest/Arms Hypertrophy

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PurposeMovementSets x Reps
Press: speed workFlat dumbbell presses6 x 3
PressIncline dumbbell presses3 x 8-12
PressHammer strength chest press3 x 12-15
FlyIncline cable flyes2 x 15-20
CurlCambered bar preacher curls3 x 8-12
CurlDumbbell concentration curls2 x 12-15
CurlSpider curls against incline bench2 x 15-20
ExtensionSeated tricep extension with cambered bar3 x 8-12
ExtensionCable pressdowns with rope attachment2 x 12-15
ExtensionCable kickbacks2 x 15-20
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-08-30" },{ "id": "phoenix-conn", "title": "Phoenix: Plug.Conn", "url": "/phoenix-conn", "category": "Elixir", "keywords": null, "content_html": "

Request

\n\n

Request

\n\n
conn.host          # → \"example.com\"\nconn.method        # → \"GET\"\nconn.path_info     # → [\"posts\", \"1\"]\nconn.request_path  # → \"/posts/1\"\nconn.query_string  # → \"utm_source=twitter\"\nconn.port          # → 80\nconn.scheme        # → :http\nconn.peer          # → { {127, 0, 0, 1}, 12345 }\nconn.remote_ip     # → { 151, 236, 219, 228 }\nconn.req_headers   # → [{\"content-type\", \"text/plain\"}]\n
\n\n
conn |> get_req_header(\"content-type\")\n# → [\"text/plain\"]\n
\n\n

Updating conn

\n\n
conn\n|> put_req_header(\"accept\", \"application/json\")\n
\n\n

Usually only useful for tests.

\n\n

Response

\n\n

Response

\n\n
conn.resp_body     # → \"...\"\nconn.resp_charset  # → \"utf-8\"\nconn.resp_cookies  # → ...\nconn.resp_headers  # → ...\nconn.status        # → ...\n
\n\n

Sending responses

\n\n
# Plug.Conn\nconn\n|> html(\"<html><head>...\")\n|> json(%{ message: \"Hello\" })\n|> text(\"Hello\")\n
\n\n
|> redirect(to: \"/foo\")\n|> redirect(external: \"http://www.google.com/\")\n|> halt()\n
\n\n
|> put_resp_content_type(\"text/plain\")\n|> put_resp_cookie(\"abc\", \"def\")\n|> put_resp_header(\"X-Delivered-By\", \"myapp\")\n|> put_status(202)\n|> put_status(:not_found)\n
\n\n
|> put_private(:plug_foo, \"...\")  # reserved for libraries\n
\n\n
|> send_resp(201, \"\")\n
\n\n

Phoenix views

\n\n
# Phoenix.Controller\nconn\n|> render(\"index.html\")\n|> render(\"index.html\", hello: \"world\")\n|> render(MyApp.ErrorView, \"404.html\")\n
\n\n
|> put_layout(:foo)\n|> put_layout(false)\n|> put_view(ErrorView)\n
\n\n
|> put_secure_browser_headers()\n# prevent clickjacking, nosniff, and xss protection\n# x-frame-options, x-content-type-options, x-xss-protection\n
\n\n
|> put_new_view(ErrorView)  # if not set yet\n|> put_new_layout(:foo)\n
\n\n
layout(conn)\n
\n\n

Other features

\n\n

Other fields

\n\n
conn.assigns          # storage of crap\nconn.owner            # process\nconn.halted           # if pipeline was halted\nconn.secret_key_base  # ...\nconn.state            # :unset, :set, :file, :sent, :chunked\n
\n\n

Accepts

\n\n
plug :accepts, [\"html\", \"json\"]\nconn |> accepts([\"html\", \"json\"])\nget_format(conn)  # → \"html\"\nconn.accepts\n
\n\n

Assigns

\n\n
conn.assigns[:hello]\nconn |> assign(:user_id, 100)\n
\n\n
conn = async_assign(conn, :location, fn -> geoip_lookup() end)\nawait_assign(conn, :location)\n
\n\n

Session

\n\n
conn = fetch_session(conn)   # or plug :fetch_session\n\nconn = put_session(conn, :message, \"new stuff we just set in the session\")\nget_session(conn, :message)\nconn = clear_session(conn)\n
\n\n
conn\n|> put_flash(:info, \"Success\")\n|> put_flash(:error, \"Oh no\")\n
\n\n

Also available: flash cookie params

", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-01-19" },{ "id": "phoenix-ecto", "title": "Phoenix: Ecto", "url": "/phoenix-ecto", "category": "Elixir", "keywords": null, "content_html": "

Schemas

\n\n

Generating

\n\n
$ mix phx.gen.html \\\n    Accounts \\       # domain\n    Profile \\        # schema\n    profiles \\       # table name\n    email:string \\\n    age:integer\n
\n\n

Schema

\n\n
defmodule Myapp.Accounts.User do\n  use Ecto.Schema\n\n  schema \"users\" do\n    field :name\n    field :age, :integer\n    field :password, virtual: true\n\n    timestamps()\n  end\nend\n
\n\n

Field types

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Field
:id
:binary
:boolean
:string
:integer
:float
:decimal
{:array, inner_type}
:map
\n\n

Changesets

\n\n

Changesets

\n\n
def changeset(user, params \\\\ :empty) do\n  %User{}\n  |> Ecto.Changeset.change   # basic casting to changeset\n\n  user\n  |> cast(params, ~w(name email), ~w(age)) # params to Changeset\n\n  |> validate_format(:email, ~r/@/)\n\n  |> validate_inclusion(:age, 18..100)\n  |> validate_exclusion(:role, ~w(admin superadmin))\n  |> validate_subset(:pets, ~w(cat dog parrot whale))\n\n  |> validate_length(:body, min: 1)\n  |> validate_length(:body, min: 1, max: 160)\n  |> validate_length(:partners, is: 2)\n\n  |> validate_number(:pi, greater_than: 3)\n  |> validate_number(:pi, less_than: 4)\n  |> validate_number(:pi, equal_to: 42)\n\n  |> validate_change(:title, fn _, _ -> [])\n  |> validate_confirmation(:password, message: \"does not match\")\n\n  |> unique_constraint(:email)\n  |> foreign_key_constraint(:post_id)\n  |> assoc_constraint(:post)      # ensure post_id exists\n  |> no_assoc_constraint(:post)   # negative (useful for deletions)\nend\n
\n\n

Changeset fields

\n\n
changeset.valid?\nchangeset.errors     #=> [title: \"empty\"]\n\nchangeset.changes    #=> %{}\nchangeset.params[:title]\n\nchangeset.required   #=> [:title]\nchangeset.optional   #=> [:body]\n
\n\n

Updating

\n\n
changeset #(or model)\n|> change(title: \"New title\")\n|> change(%{ title: \"New title\" })\n|> put_change(:title, \"New title\")\n|> force_change(:title, \"New title\")\n|> update_change(:title, &(&1 <> \"...\"))\n\n|> delete_change(:title)\n|> merge(other_changeset)\n\n|> add_error(:title, \"empty\")\n
\n\n

Getting

\n\n
get_change(changeset, :title)    #=> \"hi\" (if changed)\nget_field(changeset, :title)     #=> \"hi\" (even if unchanged)\n\nfetch_change(changeset, :title)  #=> {:ok, \"hi\"} | :error\nfetch_field(changeset, :title)   #=> {:changes | :model, \"value\"} | :error\n
\n\n

Repo

\n\n

Get one

\n\n
Repo.get(User, id)\nRepo.get_by(User, email: \"john@hello.com\")  #=> %User{} | nil\n\n# also get! get_by!\n
\n\n

Create/update

\n\n
changeset |> Repo.update\nchangeset |> Repo.insert\nchangeset |> Repo.insert_or_update\n
\n\n
User\n|> Ecto.Changeset.change(%{name: \"hi\"})\n|> Repo.insert\n
\n\n

Many

\n\n

Queries

\n\n
from p in Post,\n  where: p.title == \"Hello\",\n  where: [state: \"Sweden\"],\n\n  limit: 1,\n  offset: 10,\n\n  order_by: c.name,\n  order_by: [c.name, c.title],\n  order_by: [asc: c.name, desc: c.title],\n\n  preload: [:comments],\n  preload: [comments: {c, likes: l}],\n\n  join: c in assoc(c, :comments),\n  join: p in Post, on: c.post_id == p.id,\n  group_by: p,\n\n  select: p,\n  select: {p.title, p.description},\n  select: [p.title, p.description],\n
\n\n

Get many

\n\n
Repo.all(User)\n
\n\n

Update many

\n\n
Repo.update_all(Post, set: [title: \"Title\"])\nRepo.update_all(Post, inc: [views: 1])\n
\n\n

Chaining _all with queries

\n\n
from(p in Post, where: p.id < 10)\n|> Repo.update_all(...)\n\nfrom(p in Post, where: p.id < 10)\n|> Repo.all()\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": "2017-08-30" },{ "id": "phoenix-ecto@1.2", "title": "Phoenix: Ecto models", "url": "/phoenix-ecto@1.2", "category": "Elixir", "keywords": null, "content_html": "

This is for Phoenix 1.2 and below. Phoenix 1.3 has a new API..

\n\n

Generating

\n\n
$ mix phoenix.gen.html Profile profiles email:string age:integer\n$ mix phoenix.gen.html User users email:string hashed_password:string\n
\n\n

Schema

\n\n
defmodule User do\n  use Ecto.Schema\n\n  schema \"users\" do\n    field :name\n    field :age, :integer\n    # :id :binary :integer :float :boolean :string :binary\n    # {:array, inner_type} :decimal :map\n\n    field :password, virtual: true\n  end\nend\n
\n\n

Changesets

\n\n
def changeset(user, params \\\\ :empty) do\n  %User{}\n  |> Ecto.Changeset.change   # basic casting to changeset\n\n  user\n  |> cast(params, ~w(name email), ~w(age)) # params to Changeset\n\n  |> validate_format(:email, ~r/@/)\n\n  |> validate_inclusion(:age, 18..100)\n  |> validate_exclusion(:role, ~w(admin superadmin))\n  |> validate_subset(:pets, ~w(cat dog parrot whale))\n\n  |> validate_length(:body, min: 1)\n  |> validate_length(:body, min: 1, max: 160)\n  |> validate_length(:partners, is: 2)\n\n  |> validate_number(:pi, greater_than: 3)\n  |> validate_number(:pi, less_than: 4)\n  |> validate_number(:pi, equal_to: 42)\n\n  |> validate_change(:title, fn _, _ -> [])\n  |> validate_confirmation(:password, message: \"does not match\")\n\n  |> unique_constraint(:email)\n  |> foreign_key_constraint(:post_id)\n  |> assoc_constraint(:post)      # ensure post_id exists\n  |> no_assoc_constraint(:post)   # negative (useful for deletions)\nend\n
\n\n
changeset.valid?\nchangeset.errors     #=> [title: \"empty\"]\n\nchangeset.changes    #=> %{}\nchangeset.params[:title]\n\nchangeset.required   #=> [:title]\nchangeset.optional   #=> [:body]\n
\n\n

Updating

\n\n
changeset #(or model)\n|> change(title: \"New title\")\n|> change(%{ title: \"New title\" })\n|> put_change(:title, \"New title\")\n|> force_change(:title, \"New title\")\n|> update_change(:title, &(&1 <> \"...\"))\n\n|> delete_change(:title)\n|> merge(other_changeset)\n\n|> add_error(:title, \"empty\")\n
\n\n

Getting

\n\n
get_change(changeset, :title)    #=> \"hi\" (if changed)\nget_field(changeset, :title)     #=> \"hi\" (even if unchanged)\n\nfetch_change(changeset, :title)  #=> {:ok, \"hi\"} | :error\nfetch_field(changeset, :title)   #=> {:changes | :model, \"value\"} | :error\n
\n\n

Ecto

\n\n

Get one

\n\n
Repo.get(User, id)\nRepo.get_by(User, email: \"john@hello.com\")  #=> %User{} | nil\n\n# also get! get_by!\n
\n\n

Create/update

\n\n
changeset |> Repo.update\nchangeset |> Repo.insert\nchangeset |> Repo.insert_or_update\n
\n\n
User\n|> Ecto.Changeset.change(%{name: \"hi\"})\n|> Repo.insert\n
\n\n

Many

\n\n

Queries

\n\n
from p in Post,\n  where: p.title == \"Hello\",\n  where: [state: \"Sweden\"],\n\n  limit: 1,\n  offset: 10,\n\n  order_by: c.name,\n  order_by: [c.name, c.title],\n  order_by: [asc: c.name, desc: c.title],\n\n  preload: [:comments],\n  preload: [comments: {c, likes: l}],\n\n  join: c in assoc(c, :comments),\n  join: p in Post, on: c.post_id == p.id,\n  group_by: p,\n\n  select: p,\n  select: {p.title, p.description},\n  select: [p.title, p.description],\n
\n\n

Get many

\n\n
Repo.all(User)\n
\n\n

Update many

\n\n
Repo.update_all(Post, set: [title: \"Title\"])\nRepo.update_all(Post, inc: [views: 1])\n
\n\n

Chaining _all with queries

\n\n
from(p in Post, where: p.id < 10)\n|> Repo.update_all(...)\n\nfrom(p in Post, where: p.id < 10)\n|> Repo.all()\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "phoenix-ecto@1.3", "title": "Phoenix: Ecto models", "url": "/phoenix-ecto@1.3", "category": "Hidden", "keywords": null, "content_html": "", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "phoenix-migrations", "title": "Phoenix: Ecto migrations", "url": "/phoenix-migrations", "category": "Elixir", "keywords": null, "content_html": "

Creating

\n\n
$ mix ecto.gen.migration update_posts_table\n  creating priv/repo/migrations/20160602085927_update_posts_table.exs\n  ···\n
\n\n
$ mix ecto.migrate\n$ mix ecto.rollback\n
\n\n

Creates a migration (no models).

\n\n

Creating models

\n\n
$ mix phoenix.gen.model Message messages user_id:integer content:text\n
\n\n

This is only for Phoenix 1.2 or older; models aren’t available in Phoenix 1.3+.

\n\n

Creating context

\n\n
$ mix phx.gen.context Images Album albums title:string subtitle:string privacy:string\n
\n\n

Migration functions

\n\n

Creating tables

\n\n
create table(:documents) do\n  add :title, :string\n  add :title, :string, size: 40\n  add :title, :string, default: \"Hello\"\n  add :title, :string, default: fragment(\"now()\")\n  add :title, :string, null: false\n  add :body, :text\n  add :age, :integer\n  add :price, :float\n  add :price, :float\n  add :price, :decimal, precision: 10, scale: 2\n  add :published_at, :utc_datetime\n  add :group_id, references(:groups)\n  add :object, :json\n\n  timestamps  # inserted_at and updated_at\nend\n\ncreate_if_not_exists table(:documents) do: ... end\n
\n\n

Other operations

\n\n
alter table(:posts) do\n  add :summary, :text\n  modify :title, :text\n  remove :views\nend\n
\n\n
rename table(:posts), :title, to: :summary\nrename table(:posts), to: table(:new_posts)\n
\n\n
drop table(:documents)\ndrop_if_exists table(:documents)\n
\n\n
table(:documents)\ntable(:weather, prefix: :north_america)\n
\n\n

Indices

\n\n
create index(:posts, [:slug], concurrently: true)\ncreate unique_index(:posts, [:slug])\ndrop index(:posts, [:name])\n
\n\n

Execute SQL

\n\n
execute \"UPDATE posts SET published_at = NULL\"\nexecute create: \"posts\", capped: true, size: 1024\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-02-23" },{ "id": "phoenix-routing", "title": "Phoenix: Routing", "url": "/phoenix-routing", "category": "Elixir", "keywords": null, "content_html": "

Showing routes

\n\n
mix phx.routes        # 1.3+\nmix phoenix.routes    # 1.2 and below\n
\n\n

See: Mix.Tasks.Phoenix.Routes (hexdocs.pm)

\n\n

Single routes

\n\n
get \"/\", PageController, :index\n
\n\n

Also: put post patch options delete head

\n\n

Resources

\n\n
resources \"/users\", UserController\nresources \"/users\", UserController, only: [:index, :show]\nresources \"/users\", UserController, except: [:delete]\n
\n\n
resources \"/users\", UserController,\n  as: :person    # helper name (person_path)\n  name: :person  # ...?\n  param: :id     # name of parameter for this resource\n
\n\n

Generates these routes:

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodPathHelper
GET/usersuser_path(:index)
GET/users/newuser_path(:new)
GET/users/:iduser_path(:show, user)
GET/users/:id/edituser_path(:edit, user)
POST/usersuser_path(:create, user)
PATCH/PUT/users/:iduser_path(:update, user)
DELETE/users/:iduser_path(:delete, user)
\n\n

See: resources/4 (hexdocs.pm)

\n\n

Path helpers

\n\n
user_path(conn, :index)                 # → /users\nuser_path(conn, :show, 17)              # → /users/17\nuser_path(conn, :show, %User{id: 17})   # → /users/17\nuser_path(conn, :show, 17, admin: true) # → /users/17?admin=true\n
\n\n
user_url(conn, :index) # → \"http://localhost:4000/users\"\n
\n\n
MyApp.Router.Helpers.user_path(MyApp.Endpoint, :index)\n
\n\n

See: Helpers (hexdocs.pm)

\n\n

Nested resources

\n\n
resources \"/users\", UserController do\n  resources \"/posts\", PostController\nend\n
\n\n
user_post_path(:index, 17)     # → /users/17/posts\nuser_post_path(:show, 17, 12)  # → /users/17/posts/12\n
\n\n

See: Scopes and resources (hexdocs.pm)

\n\n

Scoped routes

\n\n
scope \"/admin\" do\n  pipe_through :browser\n  resources \"/reviews\", MyApp.Admin.ReviewController\nend\n# reviews_path() -> /admin/reviews\n
\n\n
scope \"/admin\", as: :admin do: ... end\n# admin_reviews_path() -> /admin/reviews\n
\n\n

See: scope/2 (hexdocs.pm)

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "phoenix", "title": "Phoenix", "url": "/phoenix", "category": "Elixir", "keywords": null, "content_html": "

Quick start

\n\n
# Install Phoenix\nmix local.hex\nmix archive.install https://github.com/phoenixframework/archives/raw/master/phx_new.ez\n
\n\n
# Create a new project\nmix phx.new hello\n
\n\n
# Start the application\nmix phx.server\n
\n\n

Install Erlang, Elixir, Node.js, PostgreSQL first.\nSee: Installation (hexdocs.pm)

\n\n

Directory structure

\n\n
./\n├── _build\n├── assets/\n│   ├── css/\n│   ├── js/\n│   ├── static/\n│   └── node_modules/\n├── config/\n├── deps/\n├── lib/\n│   ├── hello/\n│   ├── hello.ex\n│   ├── hello_web/\n│   │   ├── channels/\n│   │   ├── controllers/\n│   │   ├── templates/\n│   │   ├── views/\n│   │   ├── router.ex\n│   │   └── gettext.ex\n│   └── hello_web.ex\n├── priv/\n└── test/\n
\n\n

See: Adding pages (hexdocs.pm)

\n\n

Migrations

\n\n
$ mix ecto.gen.migration update_posts_table\n  creating priv/repo/migrations/20160602085927_update_posts_table.exs\n  ···\n
\n\n
create table(:documents) do\n  add :title, :string\n  add :title, :string, default: \"Hello\"\n  add :body, :text\n  add :age, :integer\n  add :price, :float, precision: 10, scale: 2\n  timestamps\nend\n
\n\n

Ecto migrations cheatsheet

\n\n

Routing

\n\n
get \"/\", PageController, :index\n\nresources \"/users\", UserController do\n  resources \"/posts\", PostController\nend\n
\n\n
user_post_path(conn, :index, 17)     # → /users/17/posts\nuser_post_path(conn, :show, 17, 12)  # → /users/17/posts/12\n
\n\n

Phoenix routing cheatsheet

\n\n

Conn

\n\n
conn.host          # → \"example.com\"\nconn.method        # → \"GET\"\nconn.path_info     # → [\"posts\", \"1\"]\nconn.request_path  # → \"/posts/1\"\n
\n\n
conn\n|> put_status(202)\n|> html(\"<html><head>···\")\n|> json(%{ message: \"Hello\" })\n|> text(\"Hello\")\n|> redirect(to: \"/foo\")\n|> render(\"index.html\")\n|> render(\"index.html\", hello: \"world\")\n|> render(MyApp.ErrorView, \"404.html\")\n
\n\n

Phoenix conn cheatsheet

\n\n

Ecto

\n\n
$ mix phx.gen.html \\\n    Accounts \\       # domain\n    Profile \\        # schema\n    profiles \\       # table name\n    email:string \\\n    age:integer\n
\n\n

Ecto cheatsheet

\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-03-06" },{ "id": "phoenix@1.2", "title": "Phoenix 1.2", "url": "/phoenix@1.2", "category": "Elixir", "keywords": null, "content_html": "

See Phoenix for a more updated cheatsheet.

\n\n

Directory structure (Legacy 1.2)

\n\n
├── _build\n├── config/\n├── deps/\n├── lib/\n│   ├── hello/\n│   ├── hello.ex\n├── node_modules/\n├── priv/\n├── test/\n└── web/\n│   ├── channels/\n│   ├── controllers/\n│   ├── models/\n│   ├── static/\n│   ├── templates/\n│   ├── views/\n│   ├── gettext.ex\n│   ├── router.ex\n│   ├── web.ex\n├── mix.exs\n
\n\n

This is Phoenix 1.2’s structure. Phoenix 1.3 has no models.

", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-03-06" },{ "id": "wip/php", "title": "PHP", "url": "/wip/php", "category": "PHP", "keywords": null, "content_html": "

Hello world

\n\n

hello.php

\n\n
<?php\nfunction greetMe($name) {\n  return \"Hello, \" . $name . \"!\";\n}\n\n$message = greetMe($name);\necho $message;\n
\n\n

All PHP files start with <?php.

\n\n

See: PHP tags

\n\n

Objects

\n\n
<?php\n\n$fruitsArray = array(\n  \"apple\" => 20,\n  \"banana\" => 30\n);\necho $fruitsArray['banana'];\n
\n\n

Or cast as object

\n\n
<?php\n\n$fruitsObject = (object) $fruits;\necho $fruitsObject->banana;\n
\n\n

Inspecting objects

\n\n
<?php\nvar_dump($object)\n
\n\n

Prints the contents of a variable for inspection.

\n\n

See: var_dump

\n\n

Classes

\n\n
class Person {\n    public $name = '';\n}\n\n$person = new Person();\n$person->name = 'bob';\n\necho $person->name;\n
\n\n

Getters and setters

\n\n
class Person \n{\n    public $name = '';\n\n    public function getName()\n    {\n        return $this->name;\n    }\n\n    public function setName($name)\n    {\n        $this->name = $name;\n        return $this;\n    }\n}\n\n$person = new Person();\n$person->setName('bob');\n\necho $person->getName();\n
\n\n

isset vs empty

\n
\n$options = [\n  'key' => 'value',\n  'blank' => '',\n  'nothing' => null,\n];\n\nvar_dump(isset($options['key']), empty($options['key'])); // true, false\nvar_dump(isset($options['blank']), empty($options['blank'])); // true, true\nvar_dump(isset($options['nothing']), empty($options['nothing'])); // false, true\n\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "plantuml", "title": "PlantUML", "url": "/plantuml", "category": "Others", "keywords": null, "content_html": "

Format

\n\n
@startuml\nCar : drive()\nDog : bark()\n@enduml\n\n# plantuml file.uml && open file.png\n
\n\n

Classes

\n\n\n\n

Methods

\n\n
Car : drive()\n
\n\n

Methods (alt)

\n\n
class Car {\n  String make\n  year : Integer\n  void drive()\n\n  -private()\n  #protected()\n  ~package private()\n  +public()\n\n  {static} String id\n  {abstract} void methods()\n}\n
\n\n

Lines

\n\n
class Car {\n  These are separated by lines.\n  The next line is a dotted line\n  ..\n  Next is a double-stroke\n  ==\n  Next is a plain line\n  --\n  Next is a strong line\n  __\n  You can make headers with it\n  .. header ..\n}\n
\n\n

Associations

\n\n
Car <|-- SmallCar      # extension\nCar *-- Engine         # composition\nCars o-- Car           # aggregation\nCar <|.. SmallCar      # dotted line (use .. instead of --)\nCar <|--* Car\n\n-left->\n-right->\n
\n\n

Relations

\n\n
Driver - Car : drives >\nCar -- Owner : < owns\nCar *-- Wheel : has 4 >\n
\n\n

Notes

\n\n
class Car {\n}\nnote left: Something something\n\nnote top of Car : This is a car.\n
\n\n

Namespaces

\n\n
namespace Client {\n  class Driver {\n  }\n}\n\nCar -- Client.Driver : owns >\n
\n\n

Activities

\n\n
(*) --> \"First Activity\"\n-->[You can put also labels] \"Second Activity\"\n--> (*)\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "pm2", "title": "pm2", "url": "/pm2", "category": "CLI", "keywords": null, "content_html": "

Fork mode

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pm2 start app.js --name my-apiStart and name a process
\n\n

Cluster mode

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pm2 start app.js -i 0Will start maximum processes with LB depending on available CPUs
\n\n

Listing

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pm2 listDisplay all processes status
pm2 jlistPrint process list in raw JSON
pm2 prettylistPrint process list in beautified JSON
pm2 describe 0Display all information about a specific process
pm2 monitMonitor all processes
\n\n

Logs

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pm2 logs [--raw]Display all processes logs in streaming
pm2 flushEmpty all log files
pm2 reloadLogsReload all logs
\n\n

Actions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pm2 stop allStop all processes
pm2 restart allRestart all processes
pm2 reload allWill 0s downtime reload (for NETWORKED apps)
pm2 stop 0Stop specific process id
pm2 restart 0Restart specific process id
pm2 delete 0Will remove process from pm2 list
pm2 delete allWill remove all processes from pm2 list
pm2 saveSave processes list to respawn at reboot
\n\n

Misc

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
pm2 reset <process>Reset meta data (restarted time…)
pm2 updatePM2Update in memory pm2
pm2 pingEnsure pm2 daemon has been launched
pm2 sendSignal SIGUSR2 my-appSend system signal to script
pm2 start app.js --no-daemonRun pm2 daemon in the foreground if it doesn’t exist already
pm2 start app.js --no-vizionSkip vizion features (versioning control)
pm2 start app.js --no-autorestartDo not automatically restart app
", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-05-08" },{ "id": "polyfill.io", "title": "Polyfill.io", "url": "/polyfill.io", "category": "JavaScript libraries", "keywords": null, "content_html": "

Usage

\n\n

Default usage

\n\n
<script src=\"https://cdn.polyfill.io/v2/polyfill.min.js\"></script>\n
\n\n

This is the default script for Polyfill.io.

\n\n

References

\n\n\n\n

Optimized

\n\n

For modern browsers

\n\n
<script>if(!(window.Promise&&[].includes&&Object.assign&&window.Map)){document.write('<script src=\"https://cdn.polyfill.io/v2/polyfill.min.js\"></scr'+'ipt>')}</script>\n
\n\n

This only includes polyfill.io when necessary, skipping it for modern browsers for faster load times.

\n\n

Extra features

\n\n
<script>if(!(window.fetch&&window.Promise&&[].includes&&Object.assign&&window.Map)){document.write('<script src=\"https://cdn.polyfill.io/v2/polyfill.min.js?features=default,fetch\"></scr'+'ipt>')}</script>\n
\n\n

This is the same as the previous, but also adds a polyfill for window.fetch(). We add a window.fetch check and loads the additional fetch feature.

", "intro_html": "

Polyfill.io is a service that serves JavaScript polyfills.

", "description_html": "", "tags": null, "updated": "2018-08-20" },{ "id": "postgresql-json", "title": "PostgreSQL JSON", "url": "/postgresql-json", "category": "Databases", "keywords": null, "content_html": "

Operators

\n\n

Accessors

\n\n
SELECT * FROM users WHERE data->>'name' = 'John';\nSELECT data->>'name' AS name FROM users;\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
OperatorDescriptionExampleReturns
-> intGet array element 2data->2JSON
-> textGet object key namedata->'name'JSON
#> text[]Get keypath a,b (eg, data.a.b)data#>'{a,b}'JSON
->> intGet array element 2data->>2Text
->> textGet object key namedata->>'name'Text
#>> text[]Get keypath a,b (eg, data.a.b)data#>>'{a,b}'Text
\n\n

> returns JSON, >> returns text.

\n\n

Boolean operators

\n\n
SELECT * FROM users WHERE data->tags ? 'admin';\nSELECT data->tags ? 'admin' AS is_admin FROM users;\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
OperatorDescriptionExample
? strDoes data have key name?data ? 'name'
?| text[]Does data have a or b?data ?| array['a','b']
?& text[]Does data have a and b?data ?& array['a','b']
@> jsonbDoes left include right?data @> '{\"b\":2}'::jsonb
<@ jsonbDoes right include left?data <@ '{\"a\":1,\"b\":2}'::jsonb
\n\n

When ?/?|/?& works on objects, it checks keys; when it works on arrays, it checks for elements.

\n\n

Updating

\n\n

Arrays and objects

\n\n
UPDATE users SET tags = tags || array['admin'];\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
OperatorExampleDescription
|| jsondata || array['a','b']Concatenate
- strdata - 'a'Delete a key
- intdata - 1Delete an array item
#- text[]data #- '{us,name}'Delete a path
\n\n

Only available in PostgreSQL 9.5+.

\n\n

jsonb_set

\n\n
UPDATE users SET data = jsonb_set(data, '{name}', '\"John\"');\n
\n\n

Only available in PostgreSQL 9.5+.

\n\n

Functions

\n\n

fn(json) → json

\n\n
jsonb_set(data, '{path}', value)\njsonb_strip_nulls(data)\n
\n\n

fn(···) → json

\n\n
to_json(\"Hello\"::text)\narray_to_json('{1,2}'::int[])\n
\n\n

Iteration

\n\n
SELECT * from json_each('{\"a\":1, \"b\":2}')\nSELECT * from json_each_text('{\"a\":1, \"b\":2}')\n-- key | value\n
\n\n

This is an incomplete list, there’s way too many!

\n\n

See: JSON functions

\n\n

More examples

\n\n\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "postgresql", "title": "PostgreSQL", "url": "/postgresql", "category": "Databases", "keywords": null, "content_html": "

Replace anything within <placeholder> accordingly

\n\n

Console

\n\n
$ psql #logs in to default database & default user\n$ sudo -u <rolename:postgres> psql #logs in with a particular user\n
\n\n

Commands

\n\n\n\n

Creating database

\n\n
 $ createdb databasename\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "premailer", "title": "Premailer", "url": "/premailer", "category": "Others", "keywords": null, "content_html": "

Custom CSS properties

\n\n\n
table, th, td {\n  /* Available on table, th and td elements */\n  -premailer-width: 32px;\n}\n\ntable, tr, th, td {\n  /* Available on table, tr, th and td elements */\n  -premailer-height: 32px;\n}\n\ntable {\n  /* Available on table elements */\n  -premailer-cellpadding: 32px;\n  -premailer-cellspacing: 32px;\n}\n
", "intro_html": "

Premailer is a Ruby library that inlines CSS into HTML.

", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "projectionist", "title": "Projectionist", "url": "/projectionist", "category": "Vim", "keywords": null, "content_html": "
/* .projectionist.vim */\n{\n  \"app/assets/react/components/*.jsx\": {\n    \"type\": \"component\",\n    \"template\": [\n      \"import React from 'react'\",\n      \"export default {} = React.createClass({ ... })\"\n    ]\n  }\n
\n\n

Available options

\n\n
{\n  \"lib/*.rb\": {\n    \"type\": \"lib\", /* enables :Elib */\n    \"alternate\": \"test/{}_spec.rb\", /* for :A */\n    \"template\": [ ... ],\n\n    \"path\": \"include\", /* for `gf` i think */\n\n    \"console\": \"node\", /* for :Console */\n    \"dispatch\": \"node\", /* for :Dispatch (dispatch.vim) */\n    \"start\": \"rails server\", /* for :Start (dispatch.vim) */\n    \"make\": \"node\", /* for makeprg */\n  }\n}\n
\n\n

Commands

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
:AEdit alternate
:A {file}Edit file
:ASEdit in split
:AVEdit in vsplit
:ATEdit in tab
:ADReplace with template
:Cdcd to root
:Cd {path}cd to path in root
:Lcdcd to root using :lcd
:ProjectDo {cmd}run command in root
\n\n

Reference

\n\n

See vim-projectionist.

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "promise", "title": "Promises", "url": "/promise", "category": "JavaScript", "keywords": null, "content_html": "

Reference

\n\n

Introduction

\n\n

intro: A quick reference to the JavaScript Promise API.

\n\n\n\n

Creating promises

\n\n
new Promise((resolve, reject) => {\n  doStuff(() => {\n    if (success) {\n      resolve('good')\n    } else {\n      reject(new Error('oops'))\n    }\n  })\n})\n
\n\n

Use new Promise to create new promises.

\n\n

Consuming promises

\n\n
promise\n  .then((result) => {\n    /* success */\n  })\n  .catch((error) => {\n    /* failure */\n  })\n
\n\n

then() runs a function when a promise resolves. catch() runs when a promise fails.

\n\n

Multiple promises

\n\n
const promises = [promise1(), promise2() /* ... */]\n
\n\n
// Succeeds when all succeed\nPromise.all(promises).then((results) => {\n  /* ... */\n})\n
\n\n
// Succeeds when one finishes first\nPromise.race(promises).then((result) => {\n  /* ... */\n})\n
\n\n

Converting other promises

\n\n
return Promise.resolve('result')\nreturn Promise.resolve(promise)\nreturn Promise.resolve(thenable)\n\nreturn Promise.reject('reason')\n\nPromise.resolve(result).then(() => {\n  /* ... */\n})\n
\n\n

Promise.resolve(val) will return a promise that resolves to the value given to it.

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "pry", "title": "Pry", "url": "/pry", "category": "Ruby libraries", "keywords": null, "content_html": "

cd

\n\n
> cd Array\n
\n\n
> ls\n  Array.methods: [] try_convert\n  Array#methods: & * + abbrev assoc at ...\n
\n\n
> show-source\n
\n\n

Code

\n\n
> show-method Array#select\n
\n\n

Docs

\n\n
> ri Array\n> ri Array#each\n\n> cd Gem\n> show-doc try_activate\n
\n\n

Finding

\n\n
> find-method each\n  Array#each\n  Array#each_index\n  Enumerable#each_slice\n  ...\n
\n\n

Editing

\n\n
> edit Pry#repl\n
\n\n

Gems

\n\n
> gem-cd foo      # Switch to gem's dir\n> gem-install foo\n> gem-list\n
\n\n

Misc commands

\n\n
> hist          # History\n> wtf?          # Trace of recent exception\n
\n\n

Rails

\n\n

Rails console

\n\n

Also consider pry-rails.

\n\n
$ pry -r ./config/environment\n
\n\n

Rails

\n\n
> show-models\n> show-routes\n> show-middleware\n
\n\n

ls

\n\n
> ls         # All\n\n> ls -m      # Methods\n> ls -M      # Instance methods\n\n> ls -g      # Globals\n> ls -l      # Local vars\n> ls -c      # Constants\n\n> ls -i      # Instance vars\n\n> ls -G xx   # Grey by regex\n
\n\n

Shell integration

\n\n

shell-mode adds dir to the prompt.

\n\n
pry(main)> shell-mode\npry(main):/home/x $\n
\n\n

Commands with . are shell commands.

\n\n
pry(main)> .cat hello.txt\n
\n\n

hirb

\n

Add the hirb gem.

\n\n
> table User.all\n> view User.all\n> view User.all, fields: %w[id name email]\n
\n\n

pry-rescue

\n

Add the pry-rescue gem.

\n\n
Pry::rescue {\n  # raise exceptions here\n}\n
\n\n

Or run:

\n\n
bundle exec rescue rspec\n
\n\n

Additional commands:

\n\n
pry(main)> cd-cause\npry(main)> try-again\n
\n\n

pry-remote

\n

Add the pry-remote gem.

\n\n
# In your code:\nbinding.remote_pry\n\n# In the shell:\nbundle exec pry-remote\n
\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "psdrb", "title": "PSD.rb", "url": "/psdrb", "category": "Ruby libraries", "keywords": null, "content_html": "

Opening

\n\n
psd = PSD.new(file, parse_layer_images: true)\npsd.parse!\n
\n\n

Traversing

\n\n
# Gets the root node.\n# A #<Node> can be a Group or a Layer.\nnode = psd.tree\n
\n\n
node.root\nnode.descendants\nnode.ancestors\nnode.siblings\nnode.subtree\n
\n\n
node.descendant_groups\nnode.descendant_layers\n
\n\n

Layer info

\n\n
node.name   #=> \"Layer 2\"\n
\n\n
node.top    #=> 3\nnode.left   #=> 3\nnode.bottom\nnode.right\n
\n\n
# Note: these are interchanged (?)\nnode.width\nnode.height\n
\n\n
node.visible?\nnode.hidden?\n
\n\n
node.layer?\nnode.group?\n
\n\n
node.blending_mode  #=> \"normal\"\nnode.opacity        #=> 0..255\nnode.fill_opacity   #=> 0..255\n
\n\n

Layer text

\n\n
node.text                  #=> (Hash)\nnode.text[:value]          #=> \"Text here\"\nnode.text[:font][:name]    #=> \"Arial\"\nnode.text[:font][:sizes]   #=> [6.9]\nnode.text[:font][:colors]  #=> [[255,255,255,255]]\nnode.text[:font][:css]     #=> \"font-family: ...;\"\nnode.text[:left]           #=> 3\nnode.text[:top]\nnode.text[:right]\nnode.text[:bottom]\nnode.text[:transform]      #=> (Hash)\n
\n\n

Layer effects

\n\n
fx = node.info[:object_effects]\n
\n\n
fx.data['Scl ']   # ?\nfx.data['GrFl']   # Gradient fill\n
\n\n

Layer mask

\n\n
node.mask[\"mask_size\"] == 0    # No mask\nnode.mask[\"mask_size\"] == 20   # Has mask\nnode.mask[\"top\"]\nnode.mask[\"left\"]\nnode.mask[\"bottom\"]\nnode.mask[\"right\"]\n
\n\n

Reference

\n\n", "intro_html": "

PSD.rb parses Photoshop documents in Ruby.

", "description_html": "", "tags": null, "updated": null },{ "id": "pug", "title": "Pug", "url": "/pug", "category": "JavaScript libraries", "keywords": null, "content_html": "

Pug

\n\n

Basic document

\n\n
doctype html\nhtml(lang='en')\n  h1.class#id(name='hi')\n    | This is some text, hello there,\n    = name\n\n  - javascript()\n
\n\n

Elements

\n\n
div\n  | Just a div\n
\n\n
.search\n  | A div, with class 'search'\n
\n\n
h1 A heading with text\n
\n\n
h1= page.title\n
\n\n
div.class\ndiv.class1.class2\nh1.header\n
\n\n

Attributes

\n\n
input(type='text' name='q' autofocus)\n
\n\n
- var authenticated = true\nbody(class=authenticated ? 'authed' : 'anon')\n
\n\n

See: Attributes

\n\n

Comments

\n\n
// This comment will appear in the HTML\n
\n\n
//- This is a silent comment\n
\n\n
//-\n  Nesting inside a comment creates\n  a comment block\n
\n\n

See: Comments

\n\n

Iteration

\n\n
ul\n  each user in users\n    li= user\n
\n\n

Layouts

\n\n
//- page.pug\nextends layout.pug\n\nblock title\n  | hello\n\nblock content\n  | hello\n
\n\n
//- layout.pug\ntitle\n  block title\nbody\n  block content\n
\n\n

Includes (partials)

\n\n
include ./includes/head.pug\n
\n\n
include:markdown article.md\n
\n\n

See: Includes

\n\n

Multiline text

\n\n
p.\n  This is text that doesn't need to\n  be prefixed by pipes.\n
\n\n
script.\n  // It's great for raw\n  // JavaScript and stuff\n  alert('hello')\n
\n\n

Conditionals

\n\n
if authenticated\n  a(href='/logout') Sign out\nelse\n  a(href='/login') Sign in\n
\n\n

See: Conditionals

\n\n

Mixins

\n\n

Mixins

\n\n
mixin list\n  ul\n    ···\n
\n\n
+list\n
\n\n

Mixins allow you to create reusable code blocks.\nSee: Mixins

\n\n

Mixin attributes

\n\n
mixin pet(name)\n  span.pet= name\n
\n\n
+pet('cat')\n
\n\n

See: Mixin attributes

\n\n

Mixin blocks

\n\n
mixin article(title)\n  article\n    h2.title= title\n    block\n
\n\n
+article('hello there')\n  p Content goes here\n
\n\n

See: Mixin blocks

", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2017-10-30" },{ "id": "python", "title": "Python", "url": "/python", "category": "Python", "keywords": null, "content_html": "

Lists

\n\n
list = []\nlist[i:j]  # returns list subset\nlist[-1]   # returns last element\nlist[:-1]  # returns all but the last element\n\nlist[i] = val\nlist[i:j] = otherlist  # replace ith to jth-1 elements with otherlist\ndel list[i:j]\n\nlist.append(item)\nlist.extend(another_list)\nlist.insert(index, item)\nlist.pop()        # returns and removes last element from the list\nlist.pop(i)       # returns and removes i-th element from the list\nlist.remove(i)    # removes the first item from the list whose value is i\nlist1 + list2     # combine two list    \nset(list)         # remove duplicate elements from a list\n\nlist.reverse()    # reverses the elements of the list in-place\nlist.count(item)\nsum(list)\n\nzip(list1, list2)  # returns list of tuples with n-th element of both list1 and list2\nlist.sort()        # sorts in-place, returns None\nsorted(list)       # returns sorted copy of list\n\",\".join(list)     # returns a string with list elements seperated by comma\n
\n\n

Dict

\n\n
dict.keys()\ndict.values()\n\"key\" in dict    # let's say this returns False, then...\ndict[\"key\"]      # ...this raises KeyError\ndict.get(\"key\")  # ...this returns None\ndict.setdefault(\"key\", 1)\n
\n\n

Iteration

\n\n
for item in [\"a\", \"b\", \"c\"]:\nfor i in range(4):        # 0 to 3\nfor i in range(4, 8):     # 4 to 7\nfor i in range(1, 9, 2):  # 1, 3, 5, 7\nfor key, val in dict.items():\nfor index, item in enumerate(list):\n
\n\n

String

\n\n
str[0:4]\nlen(str)\n\nstring.replace(\"-\", \" \")\n\",\".join(list)\n\"hi {0}\".format('j')\nf\"hi {name}\" # same as \"hi {}\".format('name')\nstr.find(\",\")\nstr.index(\",\")   # same, but raises IndexError\nstr.count(\",\")\nstr.split(\",\")\n\nstr.lower()\nstr.upper()\nstr.title()\n\nstr.lstrip()\nstr.rstrip()\nstr.strip()\n\nstr.islower()\n\n/* escape characters */\n>>> 'doesn\\'t'  # use \\' to escape the single quote...\n    \"doesn't\"\n>>> \"doesn't\"  # ...or use double quotes instead\n    \"doesn't\"\n>>> '\"Yes,\" they said.'\n    '\"Yes,\" they said.'\n>>> \"\\\"Yes,\\\" they said.\"\n    '\"Yes,\" they said.'\n>>> '\"Isn\\'t,\" they said.'\n    '\"Isn\\'t,\" they said.'\n
\n\n

Casting

\n\n
int(str)\nfloat(str)\nstr(int)\nstr(float)\n'string'.encode()\n
\n\n

Comprehensions

\n\n
[fn(i) for i in list]            # .map\nmap(fn, list)                    # .map, returns iterator\n\nfilter(fn, list)                 # .filter, returns iterator\n[fn(i) for i in list if i > 0]   # .filter.map\n
\n\n

Regex

\n\n
import re\n\nre.match(r'^[aeiou]', str)\nre.sub(r'^[aeiou]', '?', str)\nre.sub(r'(xyz)', r'\\1', str)\n\nexpr = re.compile(r'^...$')\nexpr.match(...)\nexpr.sub(...)\n
\n\n

File manipulation

\n\n

Reading

\n\n
file = open(\"hello.txt\", \"r\") # open in read mode 'r'\nfile.close() \n
\n\n
print(file.read())  # read the entire file and set the cursor at the end of file\nprint file.readline() # Reading one line\nfile.seek(0, 0) # place the cursor at the beggining of the file\n
\n\n

Writing (overwrite)

\n\n
file = open(\"hello.txt\", \"w\") # open in write mode 'w'\nfile.write(\"Hello World\") \n\ntext_lines = [\"First line\", \"Second line\", \"Last line\"] \nfile.writelines(text_lines)\n\nfile.close()\n
\n\n

Writing (append)

\n\n
file = open(\"Hello.txt\", \"a\") # open in append mode\nfile.write(\"Hello World again\")  \nfile.close()\n
\n\n

Context manager

\n\n
with open(\"welcome.txt\", \"r\") as file:\n    # 'file' refers directly to \"welcome.txt\"\n   data = file.read()\n\n# It closes the file automatically at the end of scope, no need for `file.close()`.\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "qjs", "title": "Q.js", "url": "/qjs", "category": "JavaScript libraries", "keywords": null, "content_html": "

Creating promises (Q.promise)

\n\n
Q.promise (ok, fail) =>\n  asyncFunction ->\n    if error\n      fail new Error(\"Failure\")\n    else\n      ok(data)\n
\n\n

For arrays

\n\n
promises = [saveDisk(), saveCloud()]\n\n# When all succeeds, or *at least one* error\nQ.all(promises).done ->\n  alert \"Saved\"\n\n# Same, but get the values\nQ.all(promises).spread (a, b) ->\n  alert \"Result A:\" + a\n  alert \"Result B:\" + b\n\n# When all either succeeds or errors\nQ.allSettled(promises).done -> ...\n
\n\n

Creating promises from Node

\n\n
# Works like .call() or .apply()\n\nQ.nfcall(FS.readFile, 'foo.txt', 'utf-8')\n.then -> ...\n\nQ.nfapply(FS.readFile, ['foo.txt', 'utf-8'])\n.then -> ...\n\nQ.npost(FS, 'readFile', ['foo.txt, 'utf-8'])\n.then -> ...\n\nQ.npost(FS, 'readFile', 'foo.txt, 'utf-8')\n.then -> ...\n\nreadFile = Q.denodeify(FS.readFile)\nreadFile('foo.txt').then -> ...\n
\n\n

Promises to Node async

\n\n
createUser = (next) ->\n  promiseMaker()\n  .nodeify(next)\n
\n\n

Promise sugars

\n\n
# Shortcut for .then(ok, fail, progress)\npromise\n.then (data) ->\n.catch (err) ->\n.progress (percent) ->\n
\n\n

Try

\n\n

Q.try ->\n promise()

\n\n

.catch (e) ->\n console.error “Oh well”, e

\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "qunit", "title": "Qunit", "url": "/qunit", "category": "JavaScript libraries", "keywords": null, "content_html": "
QUnit.module('a')\nQUnit.test('ok', function (t) {\n  /* ... */\n})\n
\n\n

Hooks

\n\n

Each test

\n\n
// each test\nQUnit.testStart(function)\nQUnit.testEnd(function)\n
\n\n
// each module\nQUnit.moduleStart(function)\nQUnit.moduleEnd(function)\n
\n\n
// all\nQUnit.begin(function)\nQUnit.done(function)\n
\n\n

Assertions

\n\n
t.equal(actual, expected)\nt.deepEqual(actual, expected)\nt.strictEqual(actual, expected)\nt.propEqual(actual, expected)\nt.notEqual(actual, expected)\nt.expect(amount)\n
", "intro_html": "

A quick reference for the QUnit testing library in JavaScript.

", "description_html": "", "tags": null, "updated": null },{ "id": "rack-test", "title": "rack-test", "url": "/rack-test", "category": "Ruby libraries", "keywords": null, "content_html": "

Methods

\n\n
get 'url'\npost 'url', 'name' => 'john'\nput\npatch\ndelete\noptions\nhead\n
\n\n
authorize 'user', 'pass'\nenv 'rack.session', csrf: 'token'\nheader 'Content-Type', 'text/html'\n
\n\n

See rack/test.rb.

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ractive", "title": "Ractive.js", "url": "/ractive", "category": "JavaScript libraries", "keywords": null, "content_html": "

Initialization

\n\n
new Ractive({\n  el: $('..'),\n  el: '#box',\n  template: '...', // required\n\n  // callbacks\n  init: function() {},    // on instantiate\n  complete: function() {}, // on finish animations\n\n  // objs\n  data: { ... },\n  partials: { ... },    // global: Ractive.partials\n  transitions: { ... }, // global: Ractive.transitions\n  components: { ... },\n  adaptors: [ ... ],\n\n  // options\n  magic: false\n  modifyArrays: true\n  twoway: true\n  noIntro: true // true = disable transition on initial render\n  lazy: false   // false = use keyevents, true = use change/blur\n  append: false // false = overwrite element, true = append\n  debug: false\n  sanitize: false\n})\n
\n\n

Instance methods

\n\n

Updating values

\n\n
view.add('count', 1)       //=> promise\nview.subtract('count', 1)  //=> promise\nview.toggle('shown')       //=> promise\n\nview.set('a', true)\nview.set({ a: true })\nview.reset({ a: true })\nview.merge('list', [a,b,c])\n\nview.get('a')\nview.data.a\n
\n\n

Nodes and components

\n\n
view.find('.klass')\nview.findAll('.klass')\nview.nodes\nview.nodes['hello']   // .find('#hello')\n\nview.findComponent('photo')\nview.findAllComponents('photo')\n
\n\n

Events

\n\n
view.on('event', function() { ... })\nview.off('event', fn)\nview.fire('event')\n
\n\n

Others

\n\n
view.update()\nview.updateModel()\n\nview.insert('.node .path')\n\nview.observe({ 'name': function() { ... } })\n\nview.toHTML()  //=> String\nview.render()\n
\n\n

Extend

\n\n
View = Ractive.extend({\n  ...\n})\nnew View()\n
\n\n

Components

\n\n

See: https://github.com/RactiveJS/Ractive/issues/74

\n\n
Widget = Ractive.extend({ ... })\n\nractive = new Ractive({\n  el: 'main',\n  template: '<widget foo=\"bar\"/>',\n  components: {\n    widget: Widget\n  }\n});\n
\n\n

Partials

\n\n
// Global partials\nRactive.partials.x = \"<..>\"\n
\n\n

Events

\n\n
view.on('teardown')\n
\n\n

DOM Events

\n\n
<button on-click='activate'>Activate!</button>\n\nview.on({\n  activate: function () { ... }\n});\n\n<button on-click='sort:name'>Sort by name</button>\nview.on('sort', function (e, column) {\n  console.log('sorting by #{column}');\n});\n
\n\n

Observing

\n\n
 view.observe(\"name\", function (name) {\n   console.log(\"Changed name to\", name);\n }, { init: false });\n
\n\n

Markup

\n\n
Hello, {{name}}\nBody: {{{unescaped}}}\n\n<!-- each -->\n{{#mylist:i}}\n  <li>{{this.name}}</li>\n  <li>{{name}}</li>\n  <li>{{.}}</li> <!-- same as 'this' -->\n{{/mylist}}\n\n{{^user}}Not logged in{{/user}} <!-- if false -->\n{{#user}}Welcome, sire{{/user}} <!-- if true -->\n\n{{>partialName}}\n<component>\n\n{{#statusDogs[selected]}}\n
\n\n

Transformed attributes

\n\n

This transforms the list attribute via a helper function called sort().

\n\n
{{# sort(list, \"name\") :num }}\n  <li>{{num}} - {{name}}</li>\n{{/ end. any text goes here }}\n\ndata: {\n  sort: function(array, column) { return array.whatever(); }\n}\n
\n\n

Transitions

\n\n
<div intro=\"fade\">\n<div intro=\"bump\">\n<div intro=\"bump:{duration:400}\">\n\nRactive.transitions.bump = function(t, params) {\n   params = t.processParams( params, {\n     duration: 400,\n     color: t.isIntro ? 'rgb(0,255,0)' : 'rgb(255,0,0)'\n   });\n\n  if (t.isIntro) {\n    /* enter */\n  } else {\n    /* exit */\n  }\n\n  t.complete();\n};\n
\n\n

Decorators

\n\n
<span decorator=\"tooltip:hello there\">Hover me</span>\n\ndecorators: {\n  tooltip: function (node, content) {\n    // setup code here\n    return {\n      teardown: function () {\n        // cleanup code here\n      }\n    }\n  }\n}\n\n<span decorator=\"tooltip:'a','b',2,'c'\">Hover me</span>\n\ntooltip: function (node, a, b, two, c) { ... }\n
\n\n

Adaptors

\n\n
myAdaptor = {\n  filter: function (object, keypath, ractive) {\n    // return `true` if a particular object is of the type we want to adapt\n  },\n  wrap: function (ractive, object, keypath, prefixer) {\n    // set up event bindings here\n    object.on('change', function () { ractive.set(prefixer({...})); });\n    // then return a wrapper:\n    return {\n      teardown: function () { .. },\n      // json representation\n      get: function () { return { a:2, b:3, c:4, ... }; },\n      // called on ractive.set\n      set: function (key, val) { },\n      // called on ractive.set on root (return false = die)\n      reset: function (data) { return false; }\n    };\n  }\n};\n
\n\n

Computed properties

\n\n
new Ractive({\n  template: '{{area}}',\n  computed: {\n    area: function () { return this.get('width') * this.get('height'); }\n    area: '${width} * ${height}'\n    fullname: {\n      get: '${first} + \" \" + ${last}\"\n      set: function (name) { ... }\n    }\n  }\n});\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails-controllers", "title": "Controllers", "url": "/rails-controllers", "category": "Rails", "keywords": null, "content_html": "

Common stuff

\n\n
redirect_to root_url\nredirect_to root_url, notice: \"Good.\"\n
\n\n

Special hashes

\n\n
session[:user_id] = nil\n\nflash[:notice] = \"Hello\"    # Gets flushed on next request\nflash.keep                  # Persist flash values\nflash.now[:error] = \"Boo\"   # Available on the same request\n\ncookies[:hello] = \"Hi\"\n\nparams[:page]\n\n# params is a combination of:\nquery_parameters\npath_parameters\nrequest_parameters\n
\n\n

respond_to

\n\n
respond_to do |format|\n  format.html\n  format.xml  { render xml: @users }\n  format.json { render json: @users }\n  format.js    # Will be executed by the browser\nend\n
\n\n

default_url_options

\n\n
# The options parameter is the hash passed in to 'url_for'\ndef default_url_options(options)\n  {:locale => I18n.locale}\nend\n
\n\n

Filters

\n\n
# Filter with callbacks\nbefore_filter :authenticate\nbefore_filter :authenticate, except: [:login]\nbefore_filter :authenticate, only: [:login]\ndef authenticate\n  redirect_to login_url unless controller.logged_in?\nend\n\n# Filter with inline\nbefore_filter do |controller|\n  redirect_to login_url unless controller.logged_in?\nend\n\n# Filter with external classes\nbefore_filter LoginFilter\nclass LoginFilter\n  def self.filter(controller) ...; end\nend\n\n# Filter exceptions\nskip_before_filter :require_login, only: [:new, :create]\n\n# Before/after filters\naround_filter :wrap_in_transaction\ndef wrap_in_transaction(&blk)\n  ActiveRecord::Base.transaction { yield }\nend\n
\n\n

HTTP basic authentication

\n\n
before_filter :authenticate\n\n# Basic authentication:\ndef authenticate\n  authenticate_or_request_with_http_basic { |u, p|\n    u == \"root\" && p == \"alpine\"\n  }\nend\n\n# ...or digest (hashed) authentication:\n# uses the ha1 hash (username:realm:password)\ndef authenticate_by_digest\n  realm = \"Secret3000\"\n  users = {\n    \"rsc\" => Digest::MD5.hexdigest(\"rsc:#{realm}:passwordhere\")\n  }\n\n  authenticate_or_request_with_http_digest(realm) { |user|\n    users[user]\n  }\nend\n\n# For integration tests\ndef test_access\n  auth = ActionController::HttpAuthentication::Basic.encode_credentials(user, pass)\n  get \"/notes/1.xml\", nil, 'HTTP_AUTHORIZATION' => auth\nend\n\n# Token auth\nis_logged_in = authenticate_with_http_token do |token, options|\n  token == our_secret_token\nend\n\nrequest_http_token_authentication  unless is_logged_in\n
\n\n

Request/response

\n\n
request.host            #=> \"www.example.com\"\nrequest.domain          #=> \"www.example.com\"\nrequest.domain(n=2)     #=> \"example.com\"\nrequest.port            #=> 80\nrequest.protocol        #=> \"http://\"\nrequest.query_string    #=> \"q=duck+tales\"\nrequest.url             #=> \"http://www.example.com/search?q=duck+tales\"\nrequest.fullpath        #=> \"/search?q=duck+tales\"\n\nrequest.headers         # Returns a hash\n\nrequest.format          #=> \"text/html\"\nrequest.remote_ip       #=> \"203.167.220.220\"\nrequest.local?          #=> true (if localhost/127.0.0.1)\n\nrequest.xhr?\n\nrequest.method          #=> \"POST\"\nrequest.method_symbol   #=> :post\nrequest.get?\nrequest.post?\nrequest.put?\nrequest.delete?\nrequest.head?\n
\n\n

response

\n\n
response.body\nresponse.status         #=> 404\nresponse.location       # Redirect location\nresponse.content_type\nresponse.charset\nresponse.headers\n\nresponse.headers[\"Content-Type\"] = \"application/pdf\"\n
\n\n

Streaming

\n\n
send_data pdfdata, filename: \"foo.pdf\", type: \"application/pdf\"\nsend_file Rails.root.join('public','filename.txt') [filename: '..', type: '..']\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails-forms", "title": "Form helpers", "url": "/rails-forms", "category": "Rails", "keywords": null, "content_html": "

Form builder

\n\n
- form_for @post do |f|\n
\n\n

Field names will be prefixed with post (the class name), and values will be derived from this object (eg, f.text_field :name from @post.name).

\n\n

Options

\n\n
- form_for @post, |\n  url: { method: 'put', action: 'create' }, |\n  html: { class: 'nifty_form' } |\n  do |f|\n
\n\n

Fields

\n\n

Text

\n\n
f.text_field :title\nf.text_area :body, size: '60x12'\n
\n\n

Checkbox

\n\n
f.check_box :remember_me\nf.label :remember_me, \"Remember me\"\n
\n\n

Radio

\n\n
f.radio_button :gender, 'male'\nf.label :gender_male, \"Male\"\n\nf.radio_button :gender, 'female'\nf.label :gender_female, \"Female\"\n
\n\n

Label

\n\n
f.label :title\nf.label :title, \"Title\"\nf.label :title, \"Title\", class: \"title\"\nf.label(:post, :terms) { \"Accept terms\" }\n
\n\n

Submit button

\n\n
f.submit \"Create\"\n
\n\n

Hidden fields

\n\n
f.hidden_field :id\n
\n\n

Misc

\n\n

The model

\n\n
f.object\n
\n\n

Fields for

\n\n
= form_for @post do |f|\n  = fields_for :author, @post.author do |ff|\n    = ff.text_field :name\n
\n\n

Select dropdowns

\n\n
f.select :city_id, [['Lisbon',1], ['Madrid',2], ...], 4\n# (4 = selected)\n\noptions_for_select [['Lisbon',1], ['Madrid',2], ...], 4\n# Just makes <option> tags\n
\n\n

Collections

\n\n
f.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial\nf.collection_select :city_id, City.all, :id, :name\n# (field, collection, value_key, label_key)\n
\n\n

Time select

\n\n
f.time_zone_select :time_zone\nf.date_select :birthday\n
\n

I18n

\n\n
helpers:\n  submit:\n    # helpers.submit.<action>\n    create: \"Create a %{model}\"\n    update: \"Confirm changes to %{model}\"\n\n    # helpers.submit.<model>.<action>\n    article:\n      create: \"Publish article\"\n      update: \"Update article\"\n\n  # helpers.label.<model>.<field>\n  label:\n    post:\n      body: \"Your body text\"\n
\n\n

Outside f

\n\n
radio_button(\"post\", \"category\", \"rails\")\nradio_button(\"post\", \"category\", \"java\")\n\n# picks from @post.category\n# <input type=\"radio\" id=\"post_category_rails\" name=\"post[category]\"\n#  value=\"rails\" checked=\"checked\" />\n
\n\n

Reference

\n\n
select(method, choices = nil, options = {}, html_options = {}, &block)\n  choices == [ ['label', id], ... ]\n\nsubmit(value=nil, options={})\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails-helpers", "title": "Helpers", "url": "/rails-helpers", "category": "Rails", "keywords": null, "content_html": "

Date

\n\n
distance_of_time_in_words(Time.now, project.end_date) #=> 3 hours\ndistance_of_time_in_words_to_now(project.end_date)    #=> 3 hours\n\ntime_ago_in_words 3.minutes.ago #=> \"3 minutes\"\n
\n\n

Numbers

\n\n
number_to_currency 20.33\nnumber_to_currency 20.33, precision: 0\nnumber_with_precision 3.14159, precision: 2\nnumber_to_percentage 32       #=> \"32%\"\nnumber_with_delimiter 2048    #=> \"2,048\"\nnumber_to_human 12000000      #=> \"12 million\"\nnumber_to_human_size 12000000 #=> \"12 MB\"\nnumber_to_phone \"5551234\"     #=> \"555-1234\"\n
\n\n

Cache

\n\n
<% cache project do %>\n<% cache [project, current_user] do %>\n\n<% cache_if admin?, project do %>\n<% cache_unless admin?, project do %>\n
\n\n

Tags

\n\n
tag(\"br\")\ntag(\"img\", src: \"image.jpg\")\ncontent_tag(:p, \"Hello\")\n
\n\n

Time select

\n\n
# Creates a time select tag that, when POSTed, will be stored in the article\n# variable in the sunrise attribute.\ntime_select \"article\", \"start_time\"\n\n# All options are optional\ntime_select \"article\", \"start_time\", \\\n  include_seconds: true,\n  minute_step: 15,\n  prompt: true,\n  prompt: { hour: \"Choose hr\", minute: \"Choose min\", second: \"Choose sec\" },\n  ampm: true\n\n# For dates (all options are optional)\ndate_select \"article\", \"written_on\", \\\n  start_year: 1995,\n  use_month_numbers: true,\n  discard_day: true,\n  include_blank: true,\n  order: [:day, :month, :year],\n  default: 3.days.from_now,\n  default: { day: 20 },\n  prompt: { day: 'Select day', month: 'Select month', year: 'Select year' }\n
\n\n

Time tag

\n\n
time_tag Date.today \n#=> '<time datetime=\"2010-11-04\">November 04, 2010<%rtime>'\n\ntime_tag Time.now\n#=> '<time datetime=\"2010-11-04T17:55:45+01:00\">November 04, 2010 17:55</time>'\n\ntime_tag Date.yesterday, 'Yesterday'\n#=> '<time datetime=\"2010-11-03\">Yesterday<%rtime>'\n\ntime_tag Date.today, pubdate: true\n#=> '<time datetime=\"2010-11-04\" pubdate=\"pubdate\">November 04, 2010</time>'\n\ntime_tag Date.today, \\\n  format: :short_date # (en.time.formats.short_date)\n
\n\n

Files

\n\n
= form_for @post, multipart: true do |f|\n  = f.file_field :picture\n
\n\n

i18n

\n\n
t('folders')\nt('folders.save')\n\nl(Time.now)\n\nt('x_files', count: files.count)\n# files:\n#    one: 'one file'\n#    other: '%{count} files'\n
\n\n

References

\n\n
* http://api.rubyonrails.org/classes/ActionView/Helpers.html\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails-i18n", "title": "i18n", "url": "/rails-i18n", "category": "Rails", "keywords": null, "content_html": "
t('my.messages.hello')\n\n# same as 'my.messages.hello'\nt(:hello, scope: 'my.messages')\nt(:hello, scope: [:my, :messages])\n\nt('my.messages.hello', default: \"Hello\")\n
\n\n
en:\n  my:\n    messages:\n      hello: \"Hello\"\n
\n\n

Interpolation

\n\n
t('hello', name: \"John\")\n
\n\n
hello: \"Hello %{name}\"\n
\n\n

Lazy lookup

\n\n
# from the 'books/index' view\nt('.title')\n
\n\n
en:\n  books:\n    index:\n      title: \"Título\"\n
\n\n

Plural

\n\n
t(:inbox, count: 1)  #=> 'one message'\nt(:inbox, count: 2)  #=> '2 messages'\n
\n\n
inbox:\n  one: 'one message',\n  other: '%{count} messages'\n
\n\n

Localizing

\n\n

Time

\n\n
l(Time.now)\nl(Time.now, format: :short)\n
\n\n
en:\n  time:\n    formats:\n      default: \"%a, %d %b %Y %H:%M:%S %z\"\n      long: \"%B %d, %Y %H:%M\"\n      short: \"%d %b %H:%M\"\n
\n\n

Date

\n\n
l(Date.today)\n
\n\n
en:\n  date:\n    formats:\n      default: \"%Y-%m-%d\" # 2015-06-25\n      long: \"%B %d, %Y\"   # June 25, 2015\n      short: \"%b %d\"      # Jun 25\n
\n\n

ActiveRecord

\n\n

Model names

\n\n
User.model_name.human            #=> \"User\"\nChild.model_name.human(count: 2) #=> \"Children\"\n
\n\n
en:\n  activerecord:\n    models:\n      user: \"User\"\n      child:\n        one: \"Child\"\n        other: \"Children\"\n
\n\n

Attributes

\n\n
User.human_attribute_for :name   #=> \"Name\"\n
\n\n
en:\n  activerecord:\n    attributes:\n      user:\n        # activerecord.attributes.<model>.<field>\n        name: \"Name\"\n        email: \"Email\"\n
\n\n

Error messages

\n\n
error_messages_for(...)\n
\n\n
activerecord:\n  errors:\n    models:\n      venue:\n        attributes:\n          name:\n            blank: \"Please enter a name.\"\n
\n\n

Possible scopes (in order):

\n\n
activerecord.errors.models.[model_name].attributes.[attribute_name].[error]\nactiverecord.errors.models.[model_name].[error]\nactiverecord.errors.messages.[error]\nerrors.attributes.[attribute_name].[error]\nerrors.messages.[error]\n
\n\n

Where [error] can be:

\n\n
validates\n  confirmation - :confirmation\n  acceptance   - :accepted\n  presence     - :blank\n  length       - :too_short (%{count})\n  length       - :too_long (%{count})\n  length       - :wrong_length (%{count})\n  uniqueness   - :taken\n  format       - :invalid\n  numericality - :not_a_number\n
\n\n

Form labels

\n\n
form_for @post do\n  f.label :body\n
\n\n
helpers:\n  # helpers.label.<model>.<field>\n  label:\n    post:\n      body: \"Your body text\"\n
\n\n

Submit buttons

\n\n
form_for @post do\n  f.submit\n
\n\n
helpers:\n  submit:\n    # helpers.submit.<action>\n    create: \"Create a %{model}\"\n    update: \"Confirm changes to %{model}\"\n\n    # helpers.submit.<model>.<action>\n    article:\n      create: \"Publish article\"\n      update: \"Update article\"\n
\n\n

Numbers

\n\n
number_to_delimited(2000)             #=> \"2,000\"\nnumber_to_currency(12.3)              #=> \"$12.30\"\nnumber_to_percentage(0.3)             #=> \"30%\"\nnumber_to_rounded(3.14, precision: 0) #=> \"3\"\nnumber_to_human(12_000)               #=> \"12 Thousand\"\nnumber_to_human_size(12345)           #=> \"12.3 kb\"\n
\n\n

Delimited

\n\n
number_to_delimited(n)\n
\n\n
number:\n  format:\n    separator: '.'\n    delimiter: ','\n    precision: 3\n    significant: false\n    strip_insignificant_zeroes: false\n
\n\n

Currencies

\n\n
number_to_currency(n)\n
\n\n
number:\n  currency:\n    format:\n      format: \"%u%n\" # %u = unit, %n = number\n      unit: \"$\"\n      separator: '.'\n      delimiter: ','\n      precision: 3\n      # (see number.format)\n
\n\n

Percentage

\n\n
number_to_percentage(n)\n
\n\n
number:\n  percentage:\n    format:\n      format: \"%n%\"\n      # (see number.format)\n
\n\n

Programmatic access

\n\n
I18n.backend.store_translations :en, ok: \"Ok\"\nI18n.locale = :en\nI18n.default_locale = :en\n\nI18n.available_locales\n\nI18n.translate :ok   # aka, I18n.t\nI18n.localize date   # aka, I18n.l\n
\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails-migrations", "title": "Migrations", "url": "/rails-migrations", "category": "Rails", "keywords": null, "content_html": "

Automatically make migrations

\n\n
$ rails generate migration RemovePartNumberFromProducts part_number:string\n$ rails generate migration remove_part_number_from_products part_number # rails assumes string if not type given - and you can use snake_case\n\n$ rails generate migration AddNameToWidgets name:string\n$ rails g migration add_name_to_widgets name:string # you can use the short cut 'g' instead of generate - they both do the same thing\n
\n\n

Run migrations

\n\n
$ rake db:migrate\n
\n\n

Creating tables

\n\n
create_table :users do |t|\n  t.string :name\n  t.text   :description\n\n  t.primary_key :id\n  t.string      :title\n  t.text        :description\n  t.integer     :games_count\n  t.float       :lol\n  t.decimal     :price\n  t.decimal     :price, :precision => 2, :scale => 10\n  t.datetime    :expiration\n  t.timestamp   :time_in\n  t.time        :time_in\n  t.date        :expiry\n  t.binary      :image_data\n  t.boolean     :is_admin\nend\n\n# Options:\n  :null (boolean)\n  :limit (integer)\n  :default\n
\n\n

Operations

\n\n
add_column    :users, :first_name, :string\nremove_column :users, :first_name, :string\n\nchange_column :users, :first_name, :text\n\nchange_column_default :users, :admin, nil\nchange_column_null    :users, :email, false # adds NOT NULL constraint\n\ncreate_table\nchange_table\ndrop_table\n\nadd_column\nchange_column\nrename_column\nremove_column\n\nadd_index\nremove_index\n
\n\n

Use models

\n\n
class AddFlagToProduct < ActiveRecord::Migration\n  class Product < ActiveRecord::Base\n  end\n \n  def change\n    add_column :products, :flag, :boolean\n    Product.reset_column_information\n    reversible do |dir|\n      dir.up { Product.update_all flag: false }\n    end\n  end\nend\n
\n\n

Associations

\n\n
t.references :category   # kinda same as t.integer :category_id\n\n# Can have different types\nt.references :category, polymorphic: true\n
\n\n

Auto-Add/remove columns

\n\n
$ rails generate migration RemovePartNumberFromProducts part_number:string\n
\n\n

Indices

\n\n
# Simple\nadd_index :suppliers, :name\n\n# Unique\nadd_index :accounts, [:branch_id, :party_id], :unique => true\n\n# Named (:name => ...)\nadd_index :accounts, [:branch_id, :party_id], :unique => true, :name => \"by_branch_party\"\n\n# Length\nadd_index :accounts, :name, :name => ‘by_name’, :length => 10\nadd_index :accounts, [:name, :surname], :name => ‘by_name_surname’,\n  :length => {\n    :name => 10,\n    :surname => 15\n  }\n\n# Sort order (no MySQL support)\nadd_index :accounts, [:branch_id, :party_id, :surname],\n  :order => {:branch_id => :desc, :part_id => :asc}\n
\n\n

In console

\n

Use ActiveRecord::Migration.

\n\n
ActiveRecord::Migration.add_index :posts, :slug\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails-models", "title": "Rails models", "url": "/rails-models", "category": "Rails", "keywords": null, "content_html": "

Generating

\n\n

Generating

\n\n
$ rails g model User\n
\n\n

Using models

\n\n

Query methods

\n\n
items = Model\n  .where(first_name: 'Harvey')\n  .where('id = 3')\n  .where('id = ?', 3)\n
\n\n
  .order(:title)\n  .order(title: :desc)\n  .order(\"title DESC\")\n
\n\n
  .reorder(:title)  # discards other .order's\n  .rewhere(...)     # discards other .where's\n
\n\n
  .limit(2)\n  .offset(1)\n  .uniq\n
\n\n

See: QueryMethods

\n\n

Advanced query methods

\n\n
items = Model\n  .select(:id)\n  .select([:id, :name])\n
\n\n
  .group(:name)   # GROUP BY name\n  .group('name AS grouped_name, age')\n  .having('SUM(price) > 30')  # needs to be chained with .group\n
\n\n
  .includes(:user)\n  .includes(user: [:articles])\n
\n\n
  .references(:posts)\n  # aka: .where(\"posts.name = 'foo'\").references(:posts)\n
\n\n

Finder methods

\n\n
item = Model.find(id)\nitem = Model.find_by_email(email)\nitem = Model.where(email: email).first\n
\n\n
Model\n  .exists?(5)\n  .exists?(name: \"David\")\n
\n\n
  .first\n  .last\n  .find_nth(4, [offset])\n
\n\n

See: FinderMethods

\n\n

Persistence

\n\n
item.new_record?\nitem.persisted?\nitem.destroyed?\n\nitem.serialize_hash\n
\n\n
item.save\nitem.save!      # Same as above, but raises an Exception\n
\n\n
item.update  name: 'John'  # Saves immediately\nitem.update! name: 'John'\n
\n\n
item.update_column  :name, 'John'  # skips validations and callbacks\nitem.update_columns  name: 'John'\nitem.update_columns! name: 'John'\n
\n\n
item.touch                 # updates :updated_at\nitem.touch :published_at\n
\n\n
item.destroy\nitem.delete  # skips callbacks\n
\n\n
Model.create     # Same an #new then #save\nModel.create!    # Same as above, but raises an Exception\n
\n\n

See: Persistence

\n\n

Attribute Assignment

\n\n
item.attributes                      # #<Hash>\n
\n\n
item.attributes = { name: 'John' }   # Merges attributes in. Doesn't save.\nitem.assign_attributes name: 'John'  # Same as above\n
\n\n

See: AttributeAssignment

\n\n

Dirty

\n\n
item.changed?\nitem.changed             # ['name']\nitem.changed_attributes  # { 'name' => 'Bob' } - original values\nitem.changes             # { 'name' => ['Bob', 'Robert'] }\nitem.previous_changes    # available after #save\nitem.restore_attributes\n
\n\n
item.name = 'Robert'\nitem.name_was         # 'Bob'\nitem.name_change      # [ 'Bob', 'Robert' ]\nitem.name_changed?    # true\nitem.name_changed?(from: 'Bob', to: 'Robert')\n
\n\n

See: Dirty

\n\n

Validations

\n\n
item.valid?\nitem.invalid?\n
\n\n

See: Validations

\n\n

Calculations

\n\n
Person.count\nPerson.count(:age)    # counts non-nil's\n
\n\n
Person.average(:age)\nPerson.maximum(:age)\nPerson.minimum(:age)\nPerson.sum('2 * age')\n
\n\n
Person.calculate(:count, :all)\n
\n\n

Advanced:

\n\n
Person.distinct.count\nPerson.group(:city).count\n
\n\n

See: Calculations

\n\n

Dynamic attribute-based finders

\n\n

Given a field called name:

\n\n
# Returns one record\nPerson.find_by_name(name)\nPerson.find_last_by_name(name)\nPerson.find_or_create_by_name(name)\nPerson.find_or_initialize_by_name(name)\n
\n\n
# Returns a list of records\nPerson.find_all_by_name(name)\n
\n\n
# Add a bang to make it raise an exception\nPerson.find_by_name!(name)\n
\n\n
# You may use `scoped` instead of `find`\nPerson.scoped_by_user_name\n
\n\n

Associations

\n\n

Associations

\n\n\n\n

Has many

\n\n
belongs_to :parent, :foreign_key => 'parent_id' class_name: 'Folder'\nhas_many :folders, :foreign_key => 'parent_id', class_name: 'Folder'\n\nhas_many :comments,                -> { order('posted_on DESC') }\nhas_many :comments,    :include    => :author\nhas_many :people,      :class_name => \"Person\"\nhas_many :people,      :conditions => \"deleted = 0\"\nhas_many :tracks,                  -> { order(:position) }\nhas_many :comments,    :dependent  => :nullify\nhas_many :comments,    :dependent  => :destroy\nhas_many :tags,        :as         => :taggable\nhas_many :reports,     :readonly   => true\nhas_many :subscribers, :through    => :subscriptions, class_name: \"User\", :source => :user\nhas_many :subscribers, :finder_sql =>\n    'SELECT DISTINCT people.* ' +\n    'FROM people p, post_subscriptions ps ' +\n    'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +\n    'ORDER BY p.first_name'\n
\n\n

belongs to

\n\n
belongs_to :author,\n  :dependent      => :destroy    # or :delete\n\n  :class_name     => \"Person\"\n  :select         => \"*\"\n  :counter_cache  => true\n  :counter_cache  => :custom_counter\n  :include        => \"Book\"\n  :readonly       => true\n\n  :conditions     => 'published = true'\n\n  :touch          => true\n  :touch          => :authors_last_updated_at\n\n  :primary_key    => \"name\"\n  :foreign_key    => \"author_name\"\n
\n\n

Many-to-many

\n\n

If you have a join model:

\n\n
class Programmer < ActiveRecord::Base\n  has_many :assignments\n  has_many :projects, :through => :assignments\nend\n
\n\n
class Project < ActiveRecord::Base\n  has_many :assignments\n  has_many :programmers, :through => :assignments\nend\n
\n\n
class Assignment\n  belongs_to :project\n  belongs_to :programmer\nend\n
\n\n

Many-to-many (HABTM)

\n\n
has_and_belongs_to_many :projects\nhas_and_belongs_to_many :projects, :include => [ :milestones, :manager ]\nhas_and_belongs_to_many :nations, :class_name => \"Country\"\nhas_and_belongs_to_many :categories, :join_table => \"prods_cats\"\nhas_and_belongs_to_many :categories, :readonly => true\nhas_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>\n\"DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}\"\n
\n\n

Polymorphic associations

\n\n
class Post\n  has_many :attachments, as: :parent\nend\n
\n\n
class Image\n  belongs_to :parent, polymorphic: true\nend\n
\n\n

And in migrations:

\n\n
create_table :images do |t|\n  t.references :post, polymorphic: true\nend\n
\n\n

Validation

\n\n

Validation

\n\n
class Person < ActiveRecord::Base\n
\n\n
  # Presence\n  validates :name,     presence: true\n
\n\n
  # Acceptance\n  validates :terms,    acceptance: true\n
\n\n
  # Confirm\n  validates :email,    confirmation: true\n
\n\n
  # Unique\n  validates :slug,     uniqueness: true\n  validates :slug,     uniqueness: { case_sensitive: false }\n  validates :holiday,  uniqueness: { scope: :year, message: 'yearly only' }\n
\n\n
  # Format\n  validates :code,     format: /regex/\n  validates :code,     format: { with: /regex/ }\n
\n\n
  # Length\n  validates :name,     length: { minimum: 2 }\n  validates :bio,      length: { maximum: 500 }\n  validates :password, length: { in: => 6..20 }\n  validates :number,   length: { is: => 6 }\n
\n\n
  # Include/exclude\n  validates :gender,   inclusion: %w(male female)\n  validates :gender,   inclusion: { in: %w(male female) }\n  validates :lol,      exclusion: %w(xyz)\n
\n\n
  # Numeric\n  validates :points,   numericality: true\n  validates :played,   numericality: { only_integer: true }\n  # ... greater_than, greater_than_or_equal_to,\n  # ... less_than, less_than_or_equal_to\n  # ... odd, even, equal_to\n
\n\n
  # Validate the associated records to ensure they're valid as well\n  has_many :books\n  validates_associated :books\n
\n\n
  # Length (full options)\n  validates :content, length: {\n    minimum:   300,\n    maximum:   400,\n    tokenizer: lambda { |str| str.scan(/\\w+/) },\n    too_short: \"must have at least %{count} words\",\n    too_long:  \"must have at most %{count} words\" }\n
\n\n
  # Multiple\n  validates :login, :email, presence: true\n
\n\n
  # Conditional\n  validates :description, presence: true, if: :published?\n  validates :description, presence: true, if: lambda { |obj| .. }\n
\n\n
  validates :title, presence: true, on: :save   # :save | :create | :update\n
\n\n
end\n
\n\n

Custom validations

\n\n
class Person < ActiveRecord::Base\n  validate :foo_cant_be_nil\n\n  def foo_cant_be_nil\n    errors.add(:foo, 'cant be nil')  if foo.nil?\n  end\nend\n
\n\n

Errors

\n\n
record.errors.valid?      # → false\nrecord.errors             # → { :name => [\"can't be blank\"] }\nrecord.errors.messages    # → { :name => [\"can't be blank\"] }\n
\n\n
record.errors[:name].any?\n
\n\n

Other API

\n\n

Callbacks

\n\n\n\n

Mass updates

\n\n
# Updates person id 15\nPerson.update 15, name: \"John\", age: 24\nPerson.update [1,2], [{name: \"John\"}, {name: \"foo\"}]\n
\n\n

Joining

\n\n
# Basic joins\nStudent.joins(:schools).where(schools: { type: 'public' })\nStudent.joins(:schools).where('schools.type' => 'public' )\n
\n\n
# Multiple associations\nArticle.joins(:category, :comments)\n
\n\n
# Nested associations\nArticle.joins(comments: :guest)\n
\n\n
# SQL\nAuthor.joins(\n  'INNER JOIN posts ' +\n  'ON posts.author_id = authors.id ' +\n  'AND posts.published = \"t\"'\n)\n
\n\n

Where interpolation

\n\n
where('name = ?', 'John')\nwhere(['name = :name', { name: 'John' }])\n
\n\n

Serialize

\n\n
class User < ActiveRecord::Base\n  serialize :preferences\nend\n
\n\n
user = User.create(\n  preferences: {\n    'background' => 'black',\n    'display' => 'large'\n  }\n)\n
\n\n

You can also specify a class option as the second parameter that’ll raise an \nexception if a serialized object is retrieved as a descendant of a class not in \nthe hierarchy.

\n\n
# Only Hash allowed!\nclass User < ActiveRecord::Base\n  serialize :preferences, Hash\nend\n
\n\n
# Reading it raises SerializationTypeMismatch\nuser = User.create(preferences: %w(one two three))\nUser.find(user.id).preferences\n
\n\n

Other tricks

\n\n

Overriding accessors

\n\n
class Song < ActiveRecord::Base\n  # Uses an integer of seconds to hold the length of the song\n\n  def length=(minutes)\n    write_attribute(:length, minutes.to_i * 60)\n  end\n\n  def length\n    read_attribute(:length) / 60\n  end\nend\n
\n\n

See: http://api.rubyonrails.org/classes/ActiveRecord/Base.html

\n\n

Callbacks

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails-plugins", "title": "Rails plugins", "url": "/rails-plugins", "category": "Rails", "keywords": null, "content_html": "

Generate a plugin

\n\n

Generate a Rails Engine plugin:

\n\n
rails plugin new myplugin --skip-bundle --full\n
\n\n

Initializers

\n\n\n\n

Subclass Railtie and provide an initializer method.

\n\n
module NewPlugin\n  class Railtie < Rails::Railtie\n    initializer \"newplugin.initialize\" do |app|\n \n      # subscribe to all rails notifications: controllers, AR, etc.\n      ActiveSupport::Notifications.subscribe do |*args|\n        event = ActiveSupport::Notifications::Event.new(*args)\n        puts \"Got notification: #{event.inspect}\"\n      end\n \n    end\n  end\nend\n
\n\n

Custom routes

\n\n\n\n

To create custom routes.rb keywords:

\n\n
# # routes.rb:\n# myplugin_for x\n#\nclass ActionDispatch::Routing\n  class Mapper\n    def myplugin_for(*x)\n    end\n  end\nend\n
\n\n

Example with a block:

\n\n
# authenticated do\n#   resources :users\n# end\n#\ndef authenticated\n  constraint = lambda { |request| request... }\n\n  constraints(constraint) { yield }\nend\n
\n\n

Custom generators

\n\n\n\n

Basic

\n\n
# rails g initializer\n# lib/generators/initializer_generator.rb\nclass InitializerGenerator < Rails::Generators::Base\n  def create_initializer_file\n    create_file \"config/initializers/initializer.rb\", \"# Add initialization content here\"\n  end\nend\n
\n\n\n\n

Generating a generator

\n\n
$ rails generate generator initializer\n
\n\n

NamedBase

\n\n

Use NamedBase instead if you want to take an argument. It will be available as \nfile_name.

\n\n
class InitializerGenerator < Rails::Generators::Base\n  def lol\n    puts file_name\n  end\nend\n
\n\n

More

\n\n
class InitializerGenerator < Rails::Generators::NamedBase\n  # \n  source_root File.expand_path(\"../templates\", __FILE__)\n  desc \"Description goes here.\"\nend\n
\n\n

Generators lookup

\n\n

When invoking rails g XXX:

\n\n
[rails/]generators/XXX/XXX_generator.rb\n[rails/]generators/XXX_generator.rb\n
\n\n

When invoking rails g XXX:YYY:

\n\n
[rails/]generators/XXX/YYY_generator.rb\n
\n\n

ActiveModel ‘acts as’

\n\n
# yaffle/lib/yaffle/acts_as_yaffle.rb\nmodule Yaffle\n  module ActsAsYaffle\n    extend ActiveSupport::Concern\n \n    included do\n    end\n \n    module ClassMethods\n      def acts_as_yaffle(options = {})\n        # your code will go here\n      end\n    end\n  end\nend\n \nActiveRecord::Base.send :include, Yaffle::ActsAsYaffle\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails-routes", "title": "Routes", "url": "/rails-routes", "category": "Rails", "keywords": null, "content_html": "

Multiple resources (resources)

\n\n
resources :photos\n\n# PhotosController:\n# index  =>    GET /photos\n# new    =>    GET /photos/new\n# create =>   POST /photos/new\n# show   =>    GET /photos/:id\n# edit   =>    GET /photos/:id/edit\n# update =>    PUT /photos/:id\n# delete => DELETE /photos/:id\n#\n# Helpers:\n# new_photo_path\n# photo_path(id)\n# edit_photo_path(id)\n
\n\n

Custom actions

\n\n
resources :photos do\n  member { get 'preview' }       # /photo/1/preview\n  collection { get 'search' }    # /photos/search\n\n  get 'preview', on: :member     # (..same as the first)\nend\n
\n\n

Options

\n\n
resources :photos,\n  path_names: { new: 'brand_new' }    # /photos/1/brand_new\n  path: 'postings'                    # /postings\n  only: :index\n  only: [:index, :show]\n  except: :show\n  except: [:index, :show]\n\n  shallow: true                       # also generate shallow routes\n  shalow_path: 'secret'\n  shallow_prefix: 'secret'\n
\n\n

Single resource (resource)

\n\n
resource :coder\n\n# CodersController:\n# new    =>    GET /coder/new\n# create =>   POST /coder/new\n# show   =>    GET /coder\n# edit   =>    GET /coder/edit\n# update =>    PUT /coder\n# delete => DELETE /coder\n
\n\n

Matching (match)

\n\n
match 'photo/:id' => 'photos#show'  # /photo/what-is-it\nmatch 'photo/:id', id: /[0-9]+/     # /photo/0192\nmatch 'photo/:id' => 'photos#show', constraints: { id: /[0-9]+/ }\nmatch 'photo/:id', via: :get\nmatch 'photo/:id', via: [:get, :post]\n\nmatch 'photo/*path' => 'photos#unknown'    # /photo/what/ever\n\n# params[:format] == 'jpg'\nmatch 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' }\n
\n\n

Get/post

\n\n

get is the same as match via: :get.

\n\n
get 'photo/:id' => 'photos#show'\n# same as match 'photo/:id' => 'photos#show', via: :get\n\npost 'photo/:id' => 'photos#update'\n# same as match 'photo/:id' => 'photos#show', via: :post\n
\n\n

Redirection

\n\n
match '/stories' => redirect('/posts')\nmatch '/stories/:name' => redirect('/posts/%{name}')\n
\n\n

Named

\n\n
# logout_path\nmatch 'exit' => 'sessions#destroy', as: :logout\n
\n\n

Constraints

\n\n
match '/', constraints: { subdomain: 'admin' }\n\n# admin.site.com/admin/photos\nnamespace 'admin' do\n  constraints subdomain: 'admin' do\n    resources :photos\n  end\nend\n
\n\n

Custom constraints

\n\n
class BlacklistConstraint\n  def initialize\n    @ips = Blacklist.retrieve_ips\n  end\n \n  def matches?(request)\n    @ips.include?(request.remote_ip)\n  end\nend\n \nTwitterClone::Application.routes.draw do\n  match \"*path\" => \"blacklist#index\",\n    :constraints => BlacklistConstraint.new\nend\n
\n\n

Scopes

\n\n
scope 'admin', constraints: { subdomain: 'admin' } do\n  resources ...\nend\n
\n\n

Rack middleware

\n\n
# Yes, Sprockets is middleware\nmatch '/application.js' => Sprockets\n
\n\n

Route helpers

\n\n
projects_path   # /projects\nprojects_url    # http://site.com/projects\n
\n\n

Default help text

\n\n
# The priority is based upon order of creation:\n# first created -> highest priority.\n\n# Sample of regular route:\nmatch 'products/:id' => 'catalog#view'\n\n# Keep in mind you can assign values other than :controller and :action\n\n# Sample of named route:\nmatch 'products/:id/purchase' => 'catalog#purchase', :as => :purchase\n\n# This route can be invoked with purchase_url(:id => product.id)\n\n# Sample resource route (maps HTTP verbs to controller actions automatically):\nresources :products\n\n# Sample resource route with options:\nresources :products do\n  member do\n    get 'short'\n    post 'toggle'\n  end\n\n  collection do\n    get 'sold'\n  end\nend\n\n# Sample resource route with sub-resources:\nresources :products do\n  resources :comments, :sales\n  resource :seller\nend\n\n# Sample resource route with more complex sub-resources\nresources :products do\n  resources :comments\n  resources :sales do\n    get 'recent', :on => :collection\n  end\nend\n\n# Sample resource route within a namespace:\nnamespace :admin do\n  # Directs /admin/products/* to Admin::ProductsController\n  # (app/controllers/admin/products_controller.rb)\n  resources :products\nend\n\n# You can have the root of your site routed with \"root\"\n# just remember to delete public/index.html.\nroot :to => 'welcome#index'\n\n# See how all your routes lay out with \"rake routes\"\n\n# This is a legacy wild controller route that's not recommended for RESTful applications.\n# Note: This route will make all actions in every controller accessible via GET requests.\nmatch ':controller(/:action(/:id(.:format)))'\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails-tricks", "title": "Rails tricks", "url": "/rails-tricks", "category": "Rails", "keywords": null, "content_html": "

in config/environments/development.rb:

\n\n
# Source maps for Sass\nconfig.sass.debug_info = true\nconfig.sass.line_comments = false\n\n# Don't break apart\nconfig.assets.debug = false\n
\n\n

Partial locals

\n\n
<%= render 'article', full: true %>\n<%= render 'article' %>\n\n<% if local_assigns[:full] %>\n  ...\n<% end %>\n
\n\n

HTML in i18n

\n\n
en:\n  read_more_html: \"read <b>more</b>...\"\n
\n\n

Exception handling:

\n\n
# config/application.rb\nconfig.exceptions_app = self.routes\n\nget '/404', to: 'errors#not_found'\nget '/500', to: 'errors#server_error'\n\nclass ErrorsController\n  def not_found\n    render status: :not_found\n  end\n end\n
\n\n

Rails updating:

\n\n
rake rails:update\n
\n\n

Distinct pluck:

\n\n
Article.distinct.pluck('author')\n
\n\n

Relation#merge

\n\n
scope :with_drafts, -> {\n  uniq.joins(:articles).merge(Article.draft)\n}\n
\n\n

Order

\n\n
scope :recent, -> { order created_at: :desc }\n
\n\n

Group by month

\n\n
.group(\"to_char(created_at, 'YYYY-MM')\")\n.group(\"to_char(created_at, 'YYYY-MM')\").count\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rails", "title": "Rails", "url": "/rails", "category": "Rails", "keywords": null, "content_html": "

Helpers

\n\n
class ApplicationController\n  helper_method :logged_in?\n\n  def logged_in?\n    \"Something\"\n  end\nend\n
\n\n

CSS/JS packages

\n\n
stylesheet_link_tag :monkey\njavascript_link_tag :monkey\n
\n\n

Forms

\n\n
# http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html\n\n- form_for @person do |f|\n  = f.label :first_name\n  = f.label :first_name, \"First name\"\n  = f.text_field :first_name\n\n  = f.label :last_name>\n  = f.text_field :last_name>\n\n  - fields_for @person.permission do |fields|\n    = fields.checkbox :admin\n\n  -# name=\"person[admin]\"\n  - fields_for :person, @client do |fields|\n    = fields.checkbox :admin\n\n  = f.submit\n\n# Also: check_box, email_field, fields_for\n# file_field, hidden_field, label, number_field, password_field\n# radio_button, range_field, search_field, telephonen_field,\n# text_area, text_field, url_field\n
\n\n

Controllers

\n\n

http://apidock.com/rails/ActionController/Base

\n\n
class ProjectsController\n  layout 'project'   # Actually defaults to `projects` based\n                     # on the controller name\n\n  def save\n  end\n\n  def edit\n  end\nend\n
\n\n

Before filter

\n\n
class ApplicationController < ActionController::Base\n  before_filter :validate, only: [:save, :edit]\n  before_filter :ensure_auth, except: [:logout]\n\n  before_filter :require_login\n \n  private\n \n  def require_login\n    unless logged_in?\n      flash[:error] = \"You must be logged in to access this section\"\n      redirect_to new_login_url # halts request cycle\n    end\n  end\nend\n
\n\n

Default URL optinos

\n\n
class ApplicationController < ActionController::Base\n  # The options parameter is the hash passed in to 'url_for'\n  def default_url_options(options)\n    {:locale => I18n.locale}\n  end\nend\n
\n\n

Hashes

\n\n
session[:what]\nflash[:notice] = \"Your session expired\"\nparams[:id]\n
\n\n

XML and JSON

\n\n
class UsersController < ApplicationController\n  def index\n    @users = User.all\n    respond_to do |format|\n      format.html # index.html.erb\n      format.xml  { render :xml => @users}\n      format.json { render :json => @users}\n    end\n  end\nend\n
\n\n

Redirection

\n\n
redirect_to action: 'show', id: @entry.id\nredirect_to root_url          # a path\n
\n\n

Render

\n\n
render nothing: true\nrender template: 'products/show'\nrender status: 500\nrender status: :forbidden\nrender text: '...'\nrender layout: 'special_layout'\nrender layout: false\nrender action: 'something'    # same as `file: 'my/something'`\n                              # Renders the template only, does not execute\n                              # the action\n\nrender json: object\nrender xml: object\n\nrender location: photo_url(photo)\n
\n\n

Head-only responses

\n\n
head :bad_request\nhead :created, location: photo_path(@photo)\n
\n\n

Layouts

\n\n
# app/views/layouts/application.html.erb\n<%= content_for?(:content) ? yield :content : yield %>\n\n# app/views/layouts/news.html.erb\n<% content_for :content do %>\n   ...\n<% end %>\n<% render template: :'layouts/application' %>\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rake", "title": "Rake", "url": "/rake", "category": "Ruby", "keywords": null, "content_html": "

Basic syntax

\n\n
namespace :foo do\n  desc \"Description\"\n  task :bar do\n    ...\n  end\n\n  task :baz => :dependency do\n  end\n\n  task :baz => [:dep1, :dep2, :dep3] do\n  end\nend\n\n# rake foo:bar\n
\n\n

Rake task with arguments

\n\n
desc \"Do something\"\ntask :workit, [:id] => :environment do |_, args|\n  id = args[:id]\nend\n\n# rake workit[234]\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rbenv", "title": "rbenv", "url": "/rbenv", "category": "Ruby", "keywords": null, "content_html": "

Installation

\n\n

Install rbenv and ruby-build

\n\n
git clone https://github.com/sstephenson/rbenv.git ~/.rbenv\ngit clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build\n
\n\n

Add to ~/.bash_profile

\n\n
echo 'export PATH=\"$HOME/.rbenv/bin:$PATH\"' >> ~/.bash_profile\necho 'eval \"$(rbenv init -)\"' >> ~/.bash_profile\n
\n\n

Verify installation

\n\n
type rbenv   # → \"rbenv is a function\"\n
\n\n

These are generic instructions; there may be rbenv packages available for your OS.

\n\n

See: Installation

\n\n

Managing versions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
rbenv install -lList all available versions
rbenv install 2.2.1Install Ruby 2.2.1
rbenv uninstall 2.2.1Uninstall Ruby 2.2.1
rbenv versionsSee installed versions
rbenv versionSee current version
rbenv which <NAME>Display path to executable
rbenv rehashRe-write binstubs
\n\n

Using versions

\n\n

Locally

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
rbenv local 2.2.2Use Ruby 2.2.2 in project
rbenv local --unsetUndo above
\n\n

Application-specific version numbers are stored in .ruby-version.

\n\n

Globally

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
rbenv global 2.2.2Use Ruby 2.2.2 globally
rbenv global --unsetUndo above
\n\n

Global version numbers are stored in ~/.rbenv/version.

\n\n

Shell

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
rbenv shell 2.2.2Use Ruby 2.2.2 in shell
rbenv shell --unsetUndo above
\n\n

Shell-local version numbers are stored as environment variables.

\n\n

References

\n\n", "intro_html": "

rbenv lets you manage installations of multiple Ruby versions.

", "description_html": "

A one-page guide to rbenv Ruby version manager, with usage examples and more.

", "tags": null, "updated": "2018-02-20" },{ "id": "rdoc", "title": "Rdoc", "url": "/rdoc", "category": "Markup", "keywords": null, "content_html": "

Basic RDoc format

\n\n
# Foo.\n#\n# @example\n#\n#   y\n#   g\n#\n# @param [String] param_name The xx and xx.\n#\n# @see http://url.com\n#\n# @return [true] if so\n
\n\n

Inline

\n\n
*bold*\n_emphasized_\n+code+\n
\n\n
http://www.link.com\nSee Models::User@Examples\n{Google}[http://google.com]\n
\n\n

Skip

\n\n
def input # :nodoc:\n
\n\n
module MyModule # :nodoc: all\n
\n\n

Definition lists

\n\n
# == Definition lists\n#\n# list::  hi.\n# +foo+:: parameterized\n
\n\n
# == Definition lists\n# [foo]   also\n# [bar]   like this\n
\n\n

Return types

\n\n
# @return [String]\n# @return [String, nil] the name\n
\n\n

Callseq

\n\n
# :call-seq:\n#   ARGF.readlines(sep=$/)     -> array\n#   ARGF.readlines(limit)      -> array\n#   ARGF.readlines(sep, limit) -> array\n#\n#   ARGF.to_a(sep=$/)     -> array\n#   ARGF.to_a(limit)      -> array\n#   ARGF.to_a(sep, limit) -> array\n
\n\n

Category

\n\n
# :category: Utilities\n
\n\n

Sections

\n\n
# :section: Expiry methods\n# methods relating to expiring\n\ndef expire!\ndef expired?\n...\n
\n\n

Using tomdoc

\n\n
# :markup: TomDoc\n
\n\n

Place this at the beginning of the file.

\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "react-router", "title": "React-router", "url": "/react-router", "category": "React", "keywords": null, "content_html": "

Basic

\n\n
import { default as Router, Route } from 'react-router'\n\nconst routes = (\n  <Route>\n    <Route path='*' handler={RootView} />\n  </Route>\n)\n\nRouter.run(routes, Router.HashLocation, (Root) => {\n  React.render(<Root />, document.getElementById('all'))\n})\n
\n\n

Nesting

\n\n
const routes = (\n  <Route handler={Chrome}>\n    <Route path='about' handler={About} />\n    <Route path='inbox' handler={Inbox} />\n    <Route path='messages/:id' handler={Message} />\n  </Route>\n)\n\nimport { RouteHandler } from 'react-router'\n\nconst Chrome = React.createClass({\n  render () {\n    return (\n      <div>\n        <h1>App</h1>\n        <RouteHandler />\n      </div>\n    )\n  }\n})\n
\n\n

URL params

\n\n
var Message = React.createClass({\n  componentDidMount: function () {\n    // from the path `/inbox/messages/:id`\n    var id = this.props.params.id\n    ...\n
\n\n

Link

\n\n
import { Link } from 'react-router'\n\n<!-- make a named route `user` -->\n<Link to='user' params={{userId: 10}} />\n\n<Link to='login'\n  activeClassName='-active'\n  onClick='...'>\n\n
\n\n

Other config

\n\n
<Route path='/'>\n  <DefaultRoute handler={Home} />\n  <NotFoundRoute handler={NotFound} />\n  \n  <Redirect from='login' to='sessions/new' />\n  <Redirect from='login' to='sessions/new' params={{from: 'home'}} />\n  <Redirect from='profile/:id' to='about-user' />\n\n  <Route name='about-user' ... />\n
\n\n

Router.create

\n\n
var router = Router.create({\n  routes: <Route>...</Route>,\n  location: Router.HistoryLocation\n})\n\nrouter.run((Root) => { ... })\n
\n\n

Navigation

\n\n
import { Navigation } from 'react-router'\n\nReact.createClass({\n  mixins: [ Navigation ], ...\n})\n\nthis\n  .transitionTo('user', {id: 10})\n  .transitionTo('/path')\n  .transitionTo('http://...')\n  .replaceWith('about')\n  .makePath('about') // return URL\n  .makeHref('about') // return URL\n  .goBack()\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "react", "title": "React.js", "url": "/react", "category": "React", "keywords": ["React.Component","render()","componentDidMount()","props/state","dangerouslySetInnerHTML"], "content_html": "

Components

\n\n

Components

\n\n
import React from 'react'\nimport ReactDOM from 'react-dom'\n
\n\n
class Hello extends React.Component {\n  render () {\n    return <div className='message-box'>\n      Hello {this.props.name}\n    </div>\n  }\n}\n
\n\n
const el = document.body\nReactDOM.render(<Hello name='John' />, el)\n
\n\n

Use the React.js jsfiddle to start hacking. (or the unofficial jsbin)

\n\n

Import multiple exports

\n\n
import React, {Component} from 'react'\nimport ReactDOM from 'react-dom'\n
\n\n
class Hello extends Component {\n  ...\n}\n
\n\n

Properties

\n\n
<Video fullscreen={true} autoplay={false} />\n
\n\n
render () {\n  this.props.fullscreen\n  const { fullscreen, autoplay } = this.props\n  ···\n}\n
\n\n

Use this.props to access properties passed to the component.

\n\n

See: Properties

\n\n

States

\n\n
constructor(props) {\n  super(props)\n  this.state = { username: undefined }\n}\n
\n\n
this.setState({ username: 'rstacruz' })\n
\n\n
render () {\n  this.state.username\n  const { username } = this.state\n  ···\n}\n
\n\n

Use states (this.state) to manage dynamic data.

\n\n

With Babel you can use proposal-class-fields and get rid of constructor

\n\n
class Hello extends Component {\n  state = { username: undefined };\n  ...\n}\n
\n\n

See: States

\n\n

Nesting

\n\n
class Info extends Component {\n  render () {\n    const { avatar, username } = this.props\n\n    return <div>\n      <UserAvatar src={avatar} />\n      <UserProfile username={username} />\n    </div>\n  }\n}\n
\n

As of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM.

\n\n
import React, {\n  Component,\n  Fragment\n} from 'react'\n\nclass Info extends Component {\n  render () {\n    const { avatar, username } = this.props\n\n    return (\n      <Fragment>\n        <UserAvatar src={avatar} />\n        <UserProfile username={username} />\n      </Fragment>\n    )\n  }\n}\n
\n\n

Nest components to separate concerns.

\n\n

See: Composing Components

\n\n

Children

\n\n
<AlertBox>\n  <h1>You have pending notifications</h1>\n</AlertBox>\n
\n\n
class AlertBox extends Component {\n  render () {\n    return <div className='alert-box'>\n      {this.props.children}\n    </div>\n  }\n}\n
\n\n

Children are passed as the children property.

\n\n

Defaults

\n\n

Setting default props

\n\n
Hello.defaultProps = {\n  color: 'blue'\n}\n
\n\n

See: defaultProps

\n\n

Setting default state

\n\n
class Hello extends Component {\n  constructor (props) {\n    super(props)\n    this.state = { visible: true }\n  }\n}\n
\n\n

Set the default state in the constructor().

\n\n

And without constructor using Babel with proposal-class-fields.

\n\n
class Hello extends Component {\n  state = { visible: true }\n}\n
\n\n

See: Setting the default state

\n\n

Other components

\n\n

Functional components

\n\n
function MyComponent ({ name }) {\n  return <div className='message-box'>\n    Hello {name}\n  </div>\n}\n
\n\n

Functional components have no state. Also, their props are passed as the first parameter to a function.

\n\n

See: Function and Class Components

\n\n

Pure components

\n\n
import React, {PureComponent} from 'react'\n\nclass MessageBox extends PureComponent {\n  ···\n}\n
\n\n

Performance-optimized version of React.Component. Doesn’t rerender if props/state hasn’t changed.

\n\n

See: Pure components

\n\n

Component API

\n\n
this.forceUpdate()\n
\n\n
this.setState({ ... })\nthis.setState(state => { ... })\n
\n\n
this.state\nthis.props\n
\n\n

These methods and properties are available for Component instances.

\n\n

See: Component API

\n\n

Lifecycle

\n\n

Mounting

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodDescription
constructor (props)Before rendering #
componentWillMount()Don’t use this #
render()Render #
componentDidMount()After rendering (DOM available) #
componentWillUnmount()Before DOM removal #
componentDidCatch()Catch errors (16+) #
\n\n

Set initial the state on constructor().\nAdd DOM event handlers, timers (etc) on componentDidMount(), then remove them on componentWillUnmount().

\n\n

Updating

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodDescription
componentDidUpdate (prevProps, prevState, snapshot)Use setState() here, but remember to compare props
shouldComponentUpdate (newProps, newState)Skips render() if returns false
render()Render
componentDidUpdate (prevProps, prevState)Operate on the DOM here
\n\n

Called when parents change properties and .setState(). These are not called for initial renders.

\n\n

See: Component specs

\n\n

Hooks (New)

\n\n

State Hook

\n\n
import React, { useState } from 'react';\n\nfunction Example() {\n  // Declare a new state variable, which we'll call \"count\"\n  const [count, setCount] = useState(0);\n\n  return (\n    <div>\n      <p>You clicked {count} times</p>\n      <button onClick={() => setCount(count + 1)}>\n        Click me\n      </button>\n    </div>\n  );\n}\n
\n\n

Hooks are a new addition in React 16.8.

\n\n

See: Hooks at a Glance

\n\n

Declaring multiple state variables

\n\n
function ExampleWithManyStates() {\n  // Declare multiple state variables!\n  const [age, setAge] = useState(42);\n  const [fruit, setFruit] = useState('banana');\n  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);\n  // ...\n}\n
\n\n

Effect hook

\n\n
import React, { useState, useEffect } from 'react';\n\nfunction Example() {\n  const [count, setCount] = useState(0);\n\n  // Similar to componentDidMount and componentDidUpdate:\n  useEffect(() => {\n    // Update the document title using the browser API\n    document.title = `You clicked ${count} times`;\n  }, [count]);\n\n  return (\n    <div>\n      <p>You clicked {count} times</p>\n      <button onClick={() => setCount(count + 1)}>\n        Click me\n      </button>\n    </div>\n  );\n}\n
\n\n

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

\n\n

By default, React runs the effects after every render — including the first render.

\n\n

Building your own hooks

\n\n

Define FriendStatus

\n
import React, { useState, useEffect } from 'react';\n\nfunction FriendStatus(props) {\n  const [isOnline, setIsOnline] = useState(null);\n\n  useEffect(() => {\n    function handleStatusChange(status) {\n      setIsOnline(status.isOnline);\n    }\n\n    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);\n    return () => {\n      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);\n    };\n  }, [props.friend.id]);\n\n  if (isOnline === null) {\n    return 'Loading...';\n  }\n  return isOnline ? 'Online' : 'Offline';\n}\n
\n\n

Effects may also optionally specify how to “clean up” after them by returning a function.

\n\n

Use FriendStatus

\n\n
function FriendStatus(props) {\n  const isOnline = useFriendStatus(props.friend.id);\n\n  if (isOnline === null) {\n    return 'Loading...';\n  }\n  return isOnline ? 'Online' : 'Offline';\n}\n
\n\n

See: Building Your Own Hooks

\n\n

Hooks API Reference

\n\n

Also see: Hooks FAQ

\n\n

Basic Hooks

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
HookDescription
useState(initialState) 
useEffect(() => { … }) 
useContext(MyContext)value returned from React.createContext
\n\n

Full details: Basic Hooks

\n\n

Additional Hooks

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
HookDescription
useReducer(reducer, initialArg, init) 
useCallback(() => { … }) 
useMemo(() => { … }) 
useRef(initialValue) 
useImperativeHandle(ref, () => { … }) 
useLayoutEffectidentical to useEffect, but it fires synchronously after all DOM mutations
useDebugValue(value)display a label for custom hooks in React DevTools
\n\n

Full details: Additional Hooks

\n\n

DOM nodes

\n\n

References

\n\n
class MyComponent extends Component {\n  render () {\n    return <div>\n      <input ref={el => this.input = el} />\n    </div>\n  }\n\n  componentDidMount () {\n    this.input.focus()\n  }\n}\n
\n\n

Allows access to DOM nodes.

\n\n

See: Refs and the DOM

\n\n

DOM Events

\n\n
class MyComponent extends Component {\n  render () {\n    <input type=\"text\"\n        value={this.state.value}\n        onChange={event => this.onChange(event)} />\n  }\n\n  onChange (event) {\n    this.setState({ value: event.target.value })\n  }\n}\n
\n\n

Pass functions to attributes like onChange.

\n\n

See: Events

\n\n

Other features

\n\n

Transferring props

\n\n
<VideoPlayer src=\"video.mp4\" />\n
\n\n
class VideoPlayer extends Component {\n  render () {\n    return <VideoEmbed {...this.props} />\n  }\n}\n
\n\n

Propagates src=\"...\" down to the sub-component.

\n\n

See Transferring props

\n\n

Top-level API

\n\n
React.createClass({ ... })\nReact.isValidElement(c)\n
\n\n
ReactDOM.render(<Component />, domnode, [callback])\nReactDOM.unmountComponentAtNode(domnode)\n
\n\n
ReactDOMServer.renderToString(<Component />)\nReactDOMServer.renderToStaticMarkup(<Component />)\n
\n\n

There are more, but these are most common.

\n\n

See: React top-level API

\n\n

JSX patterns

\n\n

Style shorthand

\n\n
const style = { height: 10 }\nreturn <div style={style}></div>\n
\n\n
return <div style={{ margin: 0, padding: 0 }}></div>\n
\n\n

See: Inline styles

\n\n

Inner HTML

\n\n
function markdownify() { return \"<p>...</p>\"; }\n<div dangerouslySetInnerHTML={{__html: markdownify()}} />\n
\n\n

See: Dangerously set innerHTML

\n\n

Lists

\n\n
class TodoList extends Component {\n  render () {\n    const { items } = this.props\n\n    return <ul>\n      {items.map(item =>\n        <TodoItem item={item} key={item.key} />)}\n    </ul>\n  }\n}\n
\n\n

Always supply a key property.

\n\n

Conditionals

\n\n
<Fragment>\n  {showMyComponent\n    ? <MyComponent />\n    : <OtherComponent />}\n</Fragment>\n
\n\n

Short-circuit evaluation

\n\n
<Fragment>\n  {showPopup && <Popup />}\n  ...\n</Fragment>\n
\n\n

New features

\n\n

Returning multiple elements

\n\n

You can return multiple elements as arrays or fragments.

\n\n

Arrays

\n\n
render () {\n  // Don't forget the keys!\n  return [\n    <li key=\"A\">First item</li>,\n    <li key=\"B\">Second item</li>\n  ]\n}\n
\n\n

Fragments

\n
render () {\n  // Fragments don't require keys!\n  return (\n    <Fragment>\n      <li>First item</li>\n      <li>Second item</li>\n    </Fragment>\n  )\n}\n
\n\n

See: Fragments and strings

\n\n

Returning strings

\n\n
render() {\n  return 'Look ma, no spans!';\n}\n
\n\n

You can return just a string.

\n\n

See: Fragments and strings

\n\n

Errors

\n\n
class MyComponent extends Component {\n  ···\n  componentDidCatch (error, info) {\n    this.setState({ error })\n  }\n}\n
\n\n

Catch errors via componentDidCatch. (React 16+)

\n\n

See: Error handling in React 16

\n\n

Portals

\n\n
render () {\n  return React.createPortal(\n    this.props.children,\n    document.getElementById('menu')\n  )\n}\n
\n\n

This renders this.props.children into any location in the DOM.

\n\n

See: Portals

\n\n

Hydration

\n\n
const el = document.getElementById('app')\nReactDOM.hydrate(<App />, el)\n
\n\n

Use ReactDOM.hydrate instead of using ReactDOM.render if you’re rendering over the output of ReactDOMServer.

\n\n

See: Hydrate

\n\n

Property validation

\n\n

PropTypes

\n\n
import PropTypes from 'prop-types'\n
\n\n

See: Typechecking with PropTypes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
anyAnything
\n\n

Basic

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
string 
number 
funcFunction
boolTrue or false
\n\n

Enum

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
oneOf(any)Enum types
oneOfType(type array)Union
\n\n

Array

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
array 
arrayOf(…) 
\n\n

Object

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
object 
objectOf(…)Object with values of a certain type
instanceOf(…)Instance of a class
shape(…) 
\n\n

Elements

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
elementReact element
nodeDOM node
\n\n

Required

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
(···).isRequiredRequired
\n\n

Basic types

\n\n
MyComponent.propTypes = {\n  email:      PropTypes.string,\n  seats:      PropTypes.number,\n  callback:   PropTypes.func,\n  isClosed:   PropTypes.bool,\n  any:        PropTypes.any\n}\n
\n\n

Required types

\n\n
MyCo.propTypes = {\n  name:  PropTypes.string.isRequired\n}\n
\n\n

Elements

\n\n
MyCo.propTypes = {\n  // React element\n  element: PropTypes.element,\n\n  // num, string, element, or an array of those\n  node: PropTypes.node\n}\n
\n\n

Enumerables (oneOf)

\n\n
MyCo.propTypes = {\n  direction: PropTypes.oneOf([\n    'left', 'right'\n  ])\n}\n
\n\n

Arrays and objects

\n\n
MyCo.propTypes = {\n  list: PropTypes.array,\n  ages: PropTypes.arrayOf(PropTypes.number),\n  user: PropTypes.object,\n  user: PropTypes.objectOf(PropTypes.number),\n  message: PropTypes.instanceOf(Message)\n}\n
\n\n
MyCo.propTypes = {\n  user: PropTypes.shape({\n    name: PropTypes.string,\n    age:  PropTypes.number\n  })\n}\n
\n\n

Use .array[Of], .object[Of], .instanceOf, .shape.

\n\n

Custom validation

\n\n
MyCo.propTypes = {\n  customProp: (props, key, componentName) => {\n    if (!/matchme/.test(props[key])) {\n      return new Error('Validation failed!')\n    }\n  }\n}\n
\n\n

Also see

\n\n", "intro_html": "

React is a JavaScript library for building user interfaces. This guide targets React v15 to v16.

", "description_html": "", "tags": ["Featured"], "updated": "2020-07-05" },{ "id": "react@0.14", "title": "React.js (v0.14)", "url": "/react@0.14", "category": "React", "keywords": null, "content_html": "

Components

\n\n
var Component = React.createClass({\n  render: function () {\n    return <div>Hello {this.props.name}</div>;\n  }\n});\n
\n\n
ReactDOM.render(<Component name=\"John\" />, document.body);\n
\n\n

Use the React.js jsfiddle to start hacking. (or the unofficial jsbin)

\n\n

Nesting

\n\n
var UserAvatar  = React.createClass({...});\nvar UserProfile = React.createClass({...});\n
\n\n
var Info = React.createClass({\n  render() {\n    return <div>\n      <UserAvatar src={this.props.avatar} />\n      <UserProfile username={this.props.username} />\n    </div>;\n  }\n});\n
\n\n

Nest components to separate concerns. See multiple components.

\n\n

States & Properties

\n\n

States and props

\n\n
<MyComponent fullscreen={true} />\n
\n\n
// props\n  this.props.fullscreen //=> true\n\n// state\n  this.setState({ username: 'rstacruz' });\n  this.replaceState({ ... });\n  this.state.username //=> 'rstacruz'\n
\n\n
render: function () {\n  return <div className={this.props.fullscreen ? 'full' : ''}>\n    Welcome, {this.state.username}\n  </div>;\n}\n
\n\n

Use props (this.props) to access parameters passed from the parent.\nUse states (this.state) to manage dynamic data.

\n\n

Setting defaults

\n\n
React.createClass({\n  getInitialState: function () {\n    return { comments: [] };\n  },\n\n  getDefaultProps: function () {\n    return { name: \"Hello\" };\n  }\n);\n
\n\n

Pre-populates this.state.comments and this.props.name.

\n\n

Components

\n\n

Component API

\n\n
ReactDOM.findDOMNode(c)  // 0.14+\nReact.findDOMNode(c)  // 0.13\nc.getDOMNode()        // 0.12 below\n
\n\n
c.forceUpdate()\nc.isMounted()\n\nc.state\nc.props\n\nc.setState({ ... })\nc.replaceState({ ... })\n\nc.setProps({ ... })       // for deprecation\nc.replaceProps({ ... })   // for deprecation\n\nc.refs\n
\n\n

These are methods available for Component instances. See Component API.

\n\n

Component specs

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodWhat
render() 
getInitialState() 
getDefaultProps() 
mixins: [ ... ]Mixins … more
propTypes: { ... }Validation … more
statics: { ... }Static methods
displayName: \"...\"Automatically filled by JSX
\n\n

Methods and properties you can override. See component specs.

\n\n

Lifecycle

\n\n

Mounting

\n\n\n \n \n \n \n \n \n \n \n \n \n
componentWillMount()Before rendering (no DOM yet)
componentDidMount()After rendering
\n\n

Before initial rendering occurs. Add your DOM stuff on didMount (events, timers, etc). See reference.

\n\n

Updating

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
componentWillReceiveProps(newProps={})Use setState() here
shouldComponentUpdate(newProps={}, newState={})Skips render() if returns false
componentWillUpdate(newProps={}, newState={})Can’t use setState() here
componentDidUpdate(prevProps={}, prevState={})Operate on the DOM here
\n\n

Called when parents change properties and .setState(). These are not called for initial renders. See reference.

\n\n

Unmounting

\n\n\n \n \n \n \n \n \n
componentWillUnmount()Invoked before DOM removal
\n\n

Clear your DOM stuff here (probably done on didMount). See reference.

\n\n

Examples

\n\n

Example: loading data

\n\n
React.createClass({\n  componentDidMount: function () {\n    $.get(this.props.url, function (data) {\n      this.setState(data);\n    }.bind(this));\n  },\n\n  render: function () {\n    return <CommentList data={this.state.data} />\n  }\n});\n
\n\n

See initial AJAX data.

\n\n

DOM nodes

\n\n

References

\n\n
<input ref=\"myInput\">\n
\n\n
this.refs.myInput\nReactDOM.findDOMNode(this.refs.myInput).focus()\nReactDOM.findDOMNode(this.refs.myInput).value\n
\n\n

DOM Events

\n

Add attributes like onChange. See events.

\n\n
<input type=\"text\"\n    value={this.state.value}\n    onChange={this.handleChange} />\n
\n\n
handleChange: function(event) {\n  this.setState({ value: event.target.value });\n}\n
\n\n

Allows access to DOM nodes. See References.

\n\n

Two-way binding

\n\n
Email: <input type=\"text\" valueLink={this.linkState('email')} />\n
\n\n
React.createClass({\n  mixins: [React.addons.LinkedStateMixin]\n});\n
\n\n
this.state.email\n
\n\n

Use LinkedStateMixin for easier two-way binding.

\n\n

Property validation

\n\n

Basic types

\n\n
React.createClass({\n  propTypes: {\n    email:      React.PropTypes.string,\n    seats:      React.PropTypes.number,\n    settings:   React.PropTypes.object,\n    callback:   React.PropTypes.func,\n    isClosed:   React.PropTypes.bool,\n    any:        React.PropTypes.any,\n  }\n});\n
\n

Primitive types: .string, .number, .func, and .bool. See propTypes.

\n\n

Required types

\n\n
propTypes: {\n  requiredFunc:  React.PropTypes.func.isRequired,\n  requiredAny:   React.PropTypes.any.isRequired,\n
\n\n

Add .isRequired.

\n\n

React elements

\n\n
propTypes: {\n  element:  React.PropTypes.element,  // react element\n  node:     React.PropTypes.node,     // num, string, element\n                                      // ...or array of those\n
\n\n

Use .element, .node.

\n\n

Enumerables

\n\n
propTypes: {\n  enum:     React.PropTypes.oneOf(['M','F']),  // enum\n  union:    React.PropTypes.oneOfType([        // any\n              React.PropTypes.string,\n              React.PropTypes.number ]),\n
\n\n

Use .oneOf, .oneOfType.

\n\n

Arrays and objects

\n\n
propTypes: {\n  array:    React.PropTypes.array,\n  arrayOf:  React.PropTypes.arrayOf(React.PropTypes.number),\n  object:   React.PropTypes.object,\n  objectOf: React.PropTypes.objectOf(React.PropTypes.number),\n\n  message:  React.PropTypes.instanceOf(Message),\n\n  object2:  React.PropTypes.shape({\n    color:  React.PropTypes.string,\n    size:   React.PropTypes.number\n  }),\n
\n\n

Use .array[Of], .object[Of], .instanceOf, .shape.

\n\n

Custom validation

\n\n
propTypes: {\n  customProp: function(props, propName, componentName) {\n    if (!/matchme/.test(props[propName])) {\n      return new Error('Validation failed!');\n    }\n  }\n}\n
\n\n

Supply your own function.

\n\n

Other features

\n\n

Class set

\n\n
var cx = require('classnames');\n\nrender: function() {\n  var classes = cx({\n    'message': true,\n    'message-important': this.props.isImportant,\n    'message-read': this.props.isRead\n  });\n\n  return <div className={classes}>Great Scott!</div>;\n}\n
\n\n

Manipulate DOM classes with classnames, previously known as React.addons.classSet. See Class set.

\n\n

Propagating properties

\n\n
<VideoPlayer src=\"video.mp4\" />\n
\n\n
var VideoPlayer = React.createClass({\n  render: function() {\n    /* propagates src=\"...\" down to this sub component */\n    return <VideoEmbed {...this.props} controls='false' />;\n  }\n});\n
\n\n

See Transferring props.

\n\n

Mixins

\n\n
var SetIntervalMixin = {\n  componentWillMount: function() { .. }\n}\n
\n\n
var TickTock = React.createClass({\n  mixins: [SetIntervalMixin]\n}\n
\n\n

See addons for some built-in mixins.

\n\n

Top level API

\n\n
React.createClass({ ... })\n\nReact.isValidElement(c)\n\nReactDOM.findDOMNode(c) // 0.14+\nReactDOM.render(<Component />, domnode, [callback]) // 0.14+\nReactDOM.unmountComponentAtNode(domnode) // 0.14+\n\nReactDOMServer.renderToString(<Component />) // 0.14+\nReactDOMServer.renderToStaticMarkup(<Component />) // 0.14+\n
\n\n

JSX patterns

\n\n

Style shorthand

\n\n
var style = { backgroundImage: 'url(x.jpg)', height: 10 };\nreturn <div style={style}></div>;\n
\n\n

See inline styles.

\n\n

InnerHTML

\n\n
function markdownify() { return \"<p>...</p>\"; }\n<div dangerouslySetInnerHTML={{__html: markdownify()}} />\n
\n\n

See dangerously set innerHTML.

\n\n

Lists

\n\n
var TodoList = React.createClass({\n  render: function() {\n    function item(itemText) {\n      return <li>{itemText}</li>;\n    };\n    return <ul>{this.props.items.map(item)}</ul>;\n  }\n});\n
\n\n

See also

\n\n", "intro_html": "

Deprecated: this guide targets an old version of React (v0.14). See the updated React cheatsheet for new versions.

", "description_html": "", "tags": null, "updated": null },{ "id": "redux", "title": "Redux", "url": "/redux", "category": "React", "keywords": null, "content_html": "

Creating a store

\n\n
import { createStore } from 'redux'\n
\n\n
// Reducer\nfunction counter (state = { value: 0 }, action) {\n  switch (action.type) {\n  case 'INCREMENT':\n    return { value: state.value + 1 }\n  case 'DECREMENT':\n    return { value: state.value - 1 }\n  default:\n    return state\n  }\n}\n
\n\n
let store = createStore(counter)\n
\n\n
// Optional - you can pass `initialState` as a second arg\nlet store = createStore(counter, { value: 0 })\n
\n\n

A store is made from a reducer function, which takes the current state, and\nreturns a new state depending on the action it was given.

\n\n

Using a store

\n\n
let store = createStore(counter)\n
\n\n
// Dispatches an action; this changes the state\nstore.dispatch({ type: 'INCREMENT' })\nstore.dispatch({ type: 'DECREMENT' })\n
\n\n
// Gets the current state\nstore.getState()\n
\n\n
// Listens for changes\nstore.subscribe(() => { ... })\n
\n\n

Dispatch actions to change the store’s state.

\n\n

React Redux

\n\n

Provider

\n\n
import { Provider } from 'react-redux'\n
\n\n
React.render(\n  <Provider store={store}>\n    <App />\n  </Provider>, mountNode)\n
\n\n

The <Provider> component makes the store available in your React components. You need this so you can use connect().

\n\n

Mapping state

\n\n
import { connect } from 'react-redux'\n
\n\n
// A functional React component\nfunction App ({ message, onMessageClick }) {\n  return (\n    <div onClick={() => onMessageClick('hello')}>\n      {message}\n    </div>\n  )\n}\n
\n\n
// Maps `state` to `props`:\n// These will be added as props to the component.\nfunction mapState (state) {\n  return { message: state.message }\n}\n\n// Maps `dispatch` to `props`:\nfunction mapDispatch (dispatch) {\n  return {\n    onMessageClick (message) {\n      dispatch({ type: 'click', message })\n    }\n  }\n}\n\n// Connect them:\nexport default connect(mapState, mapDispatch)(App)\n
\n\n

Shorthand

\n\n
export default connect(\n  (state) => ({\n    message: state.message\n  }),\n  (dispatch) => ({\n    onMessageClick: (message) => {\n      dispatch({ type: 'click', message })\n    }\n  })\n)(App)\n
\n\n

Same as above, but shorter.

\n\n

Combining reducers

\n\n
const reducer = combineReducers({\n  counter, user, store\n})\n
\n\n

Combines multiple reducers into one reducer function. See: combineReducers (redux.js.org)

\n\n

Middleware

\n\n

Signature

\n\n
// noop middleware\nconst logger = store => dispatch => action { dispatch(action) }\n
\n\n
const logger = store => {\n  // This function runs on createStore().\n  // It returns a decorator for dispatch().\n\n  return dispatch => {\n    // Runs on createStore(), too.\n    // It returns a new dispatch() function\n\n    return action => {\n      // Runs on every dispatch()\n    }\n  }\n}\n
\n\n

Middlewares are simply decorators for dispatch() to allow you to take\ndifferent kinds of actions, and to perform different tasks when receiving\nactions.

\n\n

Applying middleware

\n\n
const enhancer = applyMiddleware(logger, thunk, ...)\n
\n\n
const store = createStore(reducer, {}, enhancer)\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-01-17" },{ "id": "regexp", "title": "regexp", "url": "/regexp", "category": "Others", "keywords": null, "content_html": "

RegExp

\n\n

Character classes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PatternDescription
.Any character, except newline
\\wWord
\\dDigit
\\sWhitespace
\\WNot word
\\DNot digit
\\SNot whitespace
[abc]Any of a, b, or c
[a-e]Characters between a and e
[1-9]Digit between 1 and 9
[[:print:]]Any printable character including spaces
[^abc]Any character except a, b or c
\n\n

Anchors

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PatternDescription
\\GStart of match
^Start of string
$End of string
\\AStart of string
\\ZEnd of string
\\zAbsolute end of string
\\bA word boundry
\\BNon-word boundry
^abcStart with abc
abc$End with abc
\n\n

Escaped characters

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PatternDescription
\\. \\* \\\\Escape special character used by regex
\\tTab
\\nNewline
\\rCarriage return
\n\n

Groups

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PatternDescription
(abc)Capture group
(a|b)Match a or b
(?:abc)Match abc, but don’t capture
\n\n

Quantifiers

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PatternDescription
a*Match 0 or more
a+Match 1 or more
a?Match 0 or 1
a{5}Match exactly 5
a{,3}Match up to 3
a{3,}Match 3 or more
a{1,3}Match between 1 and 3
\n\n

Lookahead & Lookbehind

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PatternDescription
a(?=b)Match a in baby but not in bay
a(?!b)Match a in Stan but not in Stab
(?<=a)bMatch b in crabs but not in cribs
(?<!a)bMatch b in fib but not in fab
", "intro_html": "", "description_html": "

Basic cheatsheets for regular expression

", "tags": null, "updated": "2020-03-10" },{ "id": "rename", "title": "rename", "url": "/rename", "category": "CLI", "keywords": null, "content_html": "

Installation

\n\n
brew install rename\n
\n\n

See: http://plasmasturm.org/code/rename/

\n\n

Regex substitution

\n\n
rename 's/hello/world/' *.txt\n
\n\n

Rename hello.txt to world.txt and so on in *.txt.

\n\n

Replace extension

\n\n
rename -s .png .jpg.png *.png\n
\n\n

Replace .png with .jpg.png in *.png.

\n\n

Options

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
OptionDescription
-nSimulation
-lSymlink instead of rename
-iInteractive
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "resolutions", "title": "Screen resolutions", "url": "/resolutions", "category": "Others", "keywords": null, "content_html": "

Resolutions

\n\n

Mobile

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ResolutionDPPXActual resolutionDPPIActual PPISizeDevices
320 x 480@1x320 x 480163 ppi163 ppi3.5”iPhone 2G/3G/3GS
320 x 480@2x640 x 960163 ppi326 ppi3.5”iPhone 4/4S
320 x 568@2x640 x 1136163 ppi326 ppi4”iPhone 5/5C/5S
375 x 667@2x750 x 1334163 ppi326 ppi4.7”iPhone 6/6S
320 x 568@2x640 x 1136163 ppi326 ppi4”iPhone SE
375 x 667@2x750 x 1334163 ppi326 ppi4.7”iPhone 7/8/SE2
414 x 736@3x1242 x 2208133 ppi401 ppi5.5”iPhone 6+/6S+/7+/8+
414 x 896@2x828 x 1792162 ppi326 ppi6.1”iPhone Xr/11
375 x 812@3x1125 x 2436152 ppi458 ppi5.8”iPhone X/Xs/11 Pro
414 x 896@3x1242 x 2688162 ppi458 ppi6.5”iPhone Xs Max/11 Pro Max
360 x 640@2x720 x 1280153 ppi306 ppi4.8”Galaxy S3
360 x 640@3x1080 x 1920147 ppi441 ppi5”Galaxy S4
360 x 640@3x1080 x 1920144 ppi432 ppi5.1”Galaxy S5
360 x 640@4x1440 x 2560144 ppi577 ppi5.1”Galaxy S6/Edge
\n\n

Tablet

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ResolutionDPPXActual resolutionDPPIActual PPISizeDevices
1024 x 768@2x2048 x 1536163 ppi326 ppi7.9”iPad Mini Retina
1024 x 768@2x2048 x 1536132 ppi264 ppi9.7”iPad Air
", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-07-03" },{ "id": "rest-api", "title": "RESTful API", "url": "/rest-api", "category": "API", "keywords": null, "content_html": "

Status codes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescription
200 OKSuccessful get, patch (return a JSON object)
201 CreatedSuccessful post (return a JSON object)
202 AcceptedSuccessful post, delete, path - async
204 No contentSuccessful delete
206 Partial contentSuccessful get - async
\n\n

Error status

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescription
401 UnauthorizedNot authenticated
403 ForbiddenAuthenticated, but no permissions
422 Unprocessable entityValidation
\n\n

Errors

\n\n
HTTP/1.1 401 Unauthorized\nContent-Type: application/json\n{\n  'id': 'auth_failed',\n  'message': \"You're not logged in.\"\n}\n
\n\n

Here’s an example of a possible error reply.

\n\n

Versioning

\n\n
GET /api/foo\nAccept: application/json; version=1\n
\n\n

You can pass a version=x to the Accept request header. Info here

\n\n

Authentication

\n\n
curl -is https://$TOKEN@api.example.com/\n
\n\n

Methods

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RequestDescription
GET /articles/1read, returns 200
PUT /articles/1edit (or path), returns 200
DELETE /articles/1delete, returns 200
POST /articlescreate, returns 201
GET /articleslist, returns 200
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2019-07-07" },{ "id": "riot", "title": "Riot.js", "url": "/riot", "category": "JavaScript libraries", "keywords": null, "content_html": "

Tags

\n\n
/* tag-name.tag */\n<tag-name>\n  <div>\n    hello {name}\n  </div>\n\n  this.name = opts.name\n</tag-name>\n
\n\n
<!-- in html -->\n<tag-name>\n<script>riot.mount('*')</script>\n<script>riot.mount('tag-name')</script>\n<script>riot.mount('tag-name', { title: 'my app', ... })</script>\n
\n\n

Expressions

\n\n
{value}\n{value || 'its a js expression'}\n\n<input checked={null}>   /* null values ignore the tag */\n<p class={ selected: true }>\n
\n\n

Loops

\n\n
<li each={movies}>{title}</li>\n
\n\n

Conditional

\n
<div if={error}>\n<div show={error}> /* show using display: '' */\n<div hide={error}> /* hide using display: none */\n
\n\n

Events

\n\n
<button onclick={go}>\n\nthis.go = function (e) { ... }\n
\n\n

API

\n\n
this.update()\nthis.update({ data: 'hi' }\n\nthis.unmount()\nthis.unmount(true) // keep parent tag\n\nriot.update() // update all\n
\n\n

Nesting

\n\n
<my-tag>\n  <child></child>\n  var child = this.tags.child\n</my-tag>\n
\n\n

Names

\n\n
<my-tag>\n  <child name='xyz'></child>\n  var child = this.tags.xyz\n</my-tag>\n
\n\n

Nested HTML

\n\n
<yield/>\n
\n\n

Yield to/from

\n\n
<post>\n  <yield to='title'>Hello</yield>\n  <yield to='body'>Hey there world</yield>\n</post>\n
\n\n
<post>\n  <yield from='title'/>\n  <yield from='body'/>\n</post>\n
\n\n

Router

\n\n
riot.route('customers/*/edit', (id) => {\n})\nriot.route('customers/234/edit')\nriot.route.start()\nriot.route.start(true) // exec the current url\n
\n\n

Lifecycle

\n\n
this.on('before-mount', function() {\n// before the tag is mounted\n})\n\nthis.on('mount', function() {\n// right after the tag is mounted on the page\n})\n\nthis.on('update', function() {\n// allows recalculation of context data before the update\n})\n\nthis.on('updated', function() {\n// right after the tag template is updated\n})\n\nthis.on('before-unmount', function() {\n// before the tag is removed\n})\n\nthis.on('unmount', function() {\n// when the tag is removed from the page\n})\n\n// curious about all events ?\nthis.on('all', function(eventName) {\nconsole.info(eventName)\n})\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rollup", "title": "Rollup.js", "url": "/rollup", "category": "JavaScript libraries", "keywords": ["rollup.watch","bundle","rollup.config.js"], "content_html": "

Basic config

\n\n

rollup.config.js

\n\n
export default {\n  input: 'src/main.js',\n  output: {\n    file: 'bundle.js',\n    format: 'cjs'\n  }\n}\n
\n

Terminal

\n\n
npm install -D rollup\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
rollup -c -o bundle.jsbundle using config
rollup main.js --o bundle.js --f cjsbundle
rollup --watchbundle continuously
\n\n

You may need to use ./node_modules/.bin/rollup as a command if you did not install rollup globally.

\n\n

Multiple outputs

\n\n

rollup.config.js

\n\n
export default [\n  {\n    input: 'src/main.js',\n    output: {\n      file: __dirname + '/public/main.js',\n      format: 'cjs',\n      name: 'main'\n    }\n  },\n  {\n    input: 'src/vendor.js',\n    output: {\n      file: __dirname + 'public/vendor.js',\n      format: 'cjs',\n      name: 'vendor'\n    }\n  }\n]\n
\n\n

This creates main.js and vendor.js.

\n\n

Using plugins

\n\n

Plugins

\n\n

Terminal

\n\n
npm install -D @rollup/plugin-json\n
\n\n

rollup.config.js

\n\n
import json from '@rollup/plugin-json'\n\nexport default {\n  input: 'src/main.js',\n  output: {\n    file: 'bundle.js',\n    format: 'cjs'\n  },\n  plugins: [ json() ]\n}\n\n
\n\n

npm packages

\n\n

Terminal

\n
npm install -D @rollup/plugin-node-resolve\n
\n\n

rollup.config.js

\n
import resolve from '@rollup/plugin-node-resolve'\n\nexport default {\n  input: 'src/main.js',\n  output: {\n    file: 'bundle.js',\n    format: 'cjs'\n  },\n  plugins: [ resolve() ]\n}\n
\n\n

When you run a npm run build, no warning is emitted and contains the imported modules.

\n\n

Peer dependencies

\n\n

Terminal

\n\n
npm install -D @rollup/plugin-node-resolve\n
\n\n

rollup.config.js

\n\n
import resolve from '@rollup/plugin-node-resolve'\n\nexport default {\n  input: 'src/main.js',\n  output: {\n    file: 'bundle.js',\n    format: 'cjs'\n  },\n  plugins: [resolve({\n    // pass custom options to the resolve plugin\n    customResolveOptions: {\n      moduleDirectory: 'node_modules'\n    }\n  })],\n  // indicate which modules should be treated as external\n  external: ['lodash']\n}\n
\n\n

Babel

\n\n

Terminal

\n\n
npm install -D rollup-plugin-babel\n
\n\n

rollup.config.js

\n\n
import resolve from '@rollup/plugin-node-resolve'\nimport babel from 'rollup-plugin-babel'\n\nexport default {\n  input: 'src/main.js',\n  output: {\n    file: 'bundle.js',\n    format: 'cjs'\n  },\n  plugins: [\n    resolve(),\n    babel({\n      exclude: 'node_modules/**' // only transpile our source code\n    })\n  ]\n}\n
\n\n

src/.babelrc

\n\n
{\n  \"presets\": [\n    [\"latest\", {\n      \"es2015\": {\n        \"modules\": false\n      }\n    }]\n  ],\n  \"plugins\": [\"external-helpers\"]\n}\n
", "intro_html": "

Rollup Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application.

", "description_html": "", "tags": null, "updated": "2020-01-29" },{ "id": "ronn", "title": "Ronn", "url": "/ronn", "category": "Ruby libraries", "keywords": null, "content_html": "

Getting started

\n\n

Installation

\n\n

Installation

\n\n
gem install ronn\n
\n\n

Usage

\n\n
ronn foo.1.md        # creates foo.1.html\nronn -r foo.1.md     # creates foo.1 (--roff)\nronn -r -h foo.1.md  # builds --roff and --html\nronn -m foo.1.md     # view as manpage\n
\n\n

Ronn is a Ruby gem.

\n\n

Basic template

\n\n
name(1) -- short, single-sentence description\n=============================================\n\n## SYNOPSIS\n\n`name` [<optional>...] <flags>\n\n## DESCRIPTION\n\nA normal paragraph. This can span multiple lines and is terminated with two\nor more line endings just like Markdown.\n\n## OPTIONS\n\n * `-h`, `--help` :\n   Displays the help screen.\n\n * `--version` : \n   Displays version information.\n\n## EXAMPLES\n\nIndent examples with 4 spaces.\n\n    $ ls\n    $ ls -la\n\n## COPYRIGHT\n\n**PROJECTNAME** is copyright (c) 2015, Rico Sta. Cruz. Released under the MIT\nlicense.\n\n## SEE ALSO\n\nronn-format(7), ronn(1)\n
\n\n

Formatting tags

\n\n

Inline

\n\n

Bold

\n\n
`code`\n**strong**\n
\n\n

Underline

\n\n
<variable>\n_emphasis_\n*emphasis*\n
\n\n

Linking

\n\n

Manual references

\n\n
sh(1)\nmarkdown(7)\n
\n\n

Sections

\n\n
[STANDARDS][]\n[SEE ALSO][]\n[DIFFERENT TEXT][#SEE-ALSO]\n
\n\n

URL links

\n\n
[URL link](http://github.com/rstacruz)\n<http://github.com>\n
\n\n

Frequently-used sections

\n\n

Sections

\n\n\n\n

Other CLI options

\n\n

Options

\n\n
--pipe                       # write to stdout\n--server, -S                 # serve in http://localhost:1207\n
\n\n
--html, -5                   # default\n--fragment, -f               # html without header/title/footer\n
\n\n
--style=toc,80c              # toc (table of contents)\n                             # 80c (use 80c instead of 100c)\n                             # print (include print stylesheet)\n                             # dark\n
\n\n
--manual=\"MY MANUAL\"         # shown on top-center\n--organization=\"RONN 0.7.0\"  # shown on bottom-left\n--date=\"YYYY-MM-DD\"          # shown on bottom-center\n
\n\n

Sections

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SectionDescription
1General commands
2System calls
3C standard lib
4Special files (/dev) and drivers
5File formats
6Games
7Misc
8System administration commands and procedures
\n\n

See Man page sections (december.com).

\n\n

Using with npm

\n\n

npm scripts

\n\n

Place manual files in man/xxx.1.md, then in package.json:

\n\n
\"scripts\": {\n  \"prepublish\": \"npm run build-man\",\n  \"build-man\": \"if which ronn; then ronn man/*.md --html --roff --style=toc,80c --organization=\\\"@rstacruz\\\"; fi\"\n},\n\"directories\": {\n  \"man\": \"man\"\n}\n
\n\n

marked-man

\n\n
npm install -g marked-man\nmarked-man foo.1.md > foo.1\n
\n\n

Differences

\n\n\n\n

See marked-man.

", "intro_html": "

Ronn generates Man pages. See ronn(1), ronn-format(7). Also see it on GitHub: rtomayko/ronn.

", "description_html": "", "tags": null, "updated": "2017-10-15" },{ "id": "rspec-rails", "title": "Rspec-rails", "url": "/rspec-rails", "category": "Ruby", "keywords": null, "content_html": "

Spec tasks

\n\n
rake spec:controllers\nrake spec:helpers\nrake spec:lib\nrake spec:mailers\nrake spec:models\nrake spec:requests\nrake spec:routing\nrake spec:views\n
\n\n

Models

\n\n
# spec/models/*.rb\ndescribe MyModel do\nend\n
\n\n

Controllers

\n\n
# spec/controllers/*.rb\ndescribe MyController do\n  describe \"POST update\" do\n    render_views #optional\n\n    it \"works\" do\n      post :update, { user: { name: \"john\" } }\n\n      controller\n      controller.send ...\n\n      response\n      expect(response).to be_success\n      expect(response).to have_http_status(200)\n      expect(response).to render_template(\"index\")\n      expect(response).to redirect_to '/..'\n\n      expect(assigns :article).to eq article\n\n      response.status\n    end\n  end\nend\n
\n\n

Request

\n\n
# spec/requests/*.rb\ndescribe \"home page\" do\n  it \"displays the user's username after successful login\" do\n    get \"/login\"\n    post \"/login\", username: \"jdoe\", password: \"secret\"\n\n    expect(response.status).to eql 200\n    expect(response).to redirect_to(...)\n    expect(response).to render_template(:show)\n    expect(response.body).to include 'hello'\n    follow_redirect!\n  end\nend\n
\n\n

Routing

\n\n
# spec/routing/*.rb\ndescribe \"routing to profiles\" do\n  it \"routes /profile/:username to profile#show for username\" do\n    expect(get: \"/profiles/jsmith\").to route_to(\n      controller: \"profiles\",\n      action: \"show\",\n      username: \"jsmith\"\n    )\n  end\n\n  it \"does not expose a list of profiles\" do\n    expect(get: \"/profiles\").not_to be_routable\n  end\nend\n
\n\n

Helpers

\n\n
# spec/helpers/*.rb\ndescribe EventsHelper do\n  describe \"#link_to_event\" do\n    it \"displays the title, and formatted date\" do\n      event = Event.new(\"Ruby Kaigi\", Date.new(2010, 8, 27))\n\n      # helper is an instance of ActionView::Base configured with the\n      # EventsHelper and all of Rails' built-in helpers\n      expect(helper.link_to_event).to match /Ruby Kaigi, 27 Aug, 2010/\n    end\n  end\nend\n
\n\n

Features

\n\n
# spec/features/*.rb\nfeature 'Signing in' do\n  given(:something) { \"hi\" }\n\n  background do\n    User.make email: 'hi@gmail.com'\n  end\n\n  scenario 'Signing in with credentials' do\n  end\nend\n
\n\n

Matchers

\n\n
be_a_new(Widget)  # new_record?\nrender_template(\"new\")\nrender_template(partial: 'form', locals: {...})\nredirect_to(widgets_path)\nroute_to(..)\nbe_routable\nhave_http_status(500)\nhave_http_status(:created)\n
\n\n

Time helpers

\n\n
travel_to Time.new(2014, 11, 14, 01, 04, 44)\n...\ntravel_back\n\ntravel_to Time.new(2014, 11, 14, 01, 04, 44) do\n  ...\nend\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rspec", "title": "RSpec", "url": "/rspec", "category": "Ruby", "keywords": null, "content_html": "

Invoking tests

\n\n
rake -T spec      # List spec tasks\n\nrake spec         # Run all\n\nrake spec/models/mymodel_spec.rb\nrake spec/models/mymodel_spec.rb:27\n
\n\n

Writing tests

\n\n
describe \"A User (in general)\" do\n  include UserSpecHelper\n\n  subject { Person.new }\n\n  let(:admin) { Person.new(role: :admin) }\n\n  context \"setter methods\" do\n    it \"should do this\" do\n      pending \"some other thing\"\n\n      expect(subject.name).to eq 'x'\n    end\n  end\nend\n
\n\n

Before/after

\n\n
before :each do\n  # before all tests\nend\n\nbefore do\n  # before this suite\nend\n\nafter do\n  # after this suite\nend\n
\n\n

Subjects

\n\n
subject { CheckingAccount.new }\nit { is_expected.to be_empty }\n\n# also names: subject(:account) { ... }\n
\n\n

Expectations

\n\n
target.should eq 1\ntarget.should_not eq 1\n\nexpect(target).to eq 1\nexpect(target).not_to eq 1\n
\n\n

Numeric

\n\n
expect(5).to be < 6\nexpect(5).to == 5\nexpect(5).to equal value\nexpect(5).to be_between(1, 10)\nexpect(5).to be_within(0.05).of value\n
\n\n

Comparison

\n\n
expect(x).to be value\nexpect(x).to satisfy { |arg| ... }\nexpect(x).to match /regexp/\n
\n\n

Predicate

\n\n
expect(x).to be_zero    # FixNum#zero?\nexpect(x).to be_empty   # Array#empty?\nexpect(x).to have_key   # Hash#has_key?\n
\n\n

Objects

\n\n
expect(obj).to be_an_instance_of MyClass\nexpect(obj).to be_a_kind_of MyClass\nexpect(obj).to respond_to :save!\n
\n\n

Control flow

\n\n
expect { user.save! }.to raise_error\nexpect { user.save! }.to raise_error(ExceptionName, /msg/)\nexpect { user.save! }.to throw :symbol\n
\n\n

Enumerables/arrays

\n\n
expect(list).to include(<object>)\n\nexpect(list).to have(1).things\nexpect(list).to have_at_least(2).things\nexpect(list).to have_at_most(3).things\n\nexpect(list).to have(2).errors_on(:field)\n
\n\n

Change

\n\n
expect { thing.approve! }.to \\\n  change(thing, :status)\n  .from(Status::AWAITING_APPROVAL)\n  .to(Status::APPROVED)\n\nexpect { thing.destroy }.to \\\n  change(Thing, :count)\n  .by(-1)\n
\n\n

Doubles

\n\n
book = double('book')\nbook = instance_double('Book', pages: 250)\n
\n\n

Method stubs

\n\n
allow(die).to receive(:roll)\nallow(die).to receive(:roll) { 3 }\nallow_any_instance_of(Die).to receive(:roll)\n\nexpect(die).to receive(:roll)\n  .with(1)\n  .with(1, true)\n  .with(boolean)\n  .with(anything)\n  .with(any_args)\n  .with(1, any_args)\n  .with(no_args)\n  .with(hash_including(a: 1))\n  .with(hash_excluding(a: 1))\n  .with(array_including(:a, :b))\n  .with(array_excluding(:a, :b))\n  .with(instance_of(Fixnum))\n  .with(kind_of(Numeric))\n  .with(<matcher>)\n\n  .once\n  .twice\n  .exactly(n).times\n  .at_least(:once)\n  .at_least(:twice)\n  .at_least(n).times\n  .at_most(:once)\n  .at_most(:twice)\n  .at_most(n).times\n
\n\n

https://relishapp.com/rspec/rspec-mocks/docs

\n\n

Spec helpers

\n\n
module UserSpecHelper\n  def valid_user_attributes\n    { :email => \"joe@bloggs.com\",\n      :username => \"joebloggs\",\n      :password => \"abcdefg\"}\n  end\nend\n
\n\n
describe User do\n  include UserSpecHelper\n\n  ...\nend\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rst", "title": "ReStructuredText", "url": "/rst", "category": "Markup", "keywords": null, "content_html": "

Comments

\n\n
.. @theme 2010\n.. include:: ../themes/2010/common.rst\n.. contents::\n.. |substitute| replace:: replacement name\n
\n\n

Headings

\n\n
Heading\n=======\n\n.. class:: brief\n\nHello there. |substitute| **This is bold**\n\n\n - Bullet list with a link_ (or `link with words`_)\n - Yes\n\n.. _link: http://link.org\n
\n\n

PDF page break

\n\n
.. raw:: pdf\n\n   PageBreak oneColumn\n
\n\n\n\n
Internal link target_.\n\n.. _target:\n\nThis is where _target will end up in.\n
\n\n

Tables (?)

\n\n
.. class:: hash-table\n\n.. list-table::\n\n   * - :key:`Cuisine:`\n     - :val:`French/fusion`\n   * - :key:`Number of ingredients:`\n     - :val:`8`\n   * - :key:`Preparation time:`\n     - :val:`30 hours`\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rsync", "title": "Rsync", "url": "/rsync", "category": "CLI", "keywords": null, "content_html": "

Basic example

\n\n
# syncing folder src into dest:\nrsync -avz ./src /dest\n# syncing the content of src into dest:\nrsync -avz ./src/ /dest\n
\n\n

OSX

\n\n
--exclude '.Trashes'\n--exclude '.Spotlight-V100'\n--exclude '.fseventsd'\n
\n\n

Transfer options

\n\n
-z, --compress\n-n, --dry-run\n    --partial   # allows resuming of aborted syncs\n    --bwlimit=RATE    # limit socket I/O bandwidth\n
\n\n

Display options

\n\n
-q, --quiet\n-v, --verbose\n    --stats\n-h, --human-readable\n    --progress\n-P                     # same as --partial --progress\n
\n\n

Skipping options

\n\n
-u, --update     # skip files newer on dest\n-c, --checksum   # skip based on checksum, not mod-time & size\n
\n\n

Backup options

\n\n
-b, --backup           # backup with suffix\n    --suffix=SUFFIX    # default ~ without --backup-dir\n    --backup-dir=DIR\n
\n\n

Include options

\n\n
--exclude=PATTERN\n--include=PATTERN\n
\n\n
--exclude-from=FILE\n--include-from=FILE\n--files-from=FILE    # read list of filenames from FILE\n
\n\n
-C, --cvs-exclude    # exclude from local/global .cvsignore\n
\n\n

Archive options

\n\n
-a, --archive    # archive (-rlptgoD)\n
\n\n
-r, --recursive\n-l, --links      # copy symlinks as links\n-p, --perms      # preserve permissions\n-t, --times      # preserve times\n-g, --group      # preserve group\n-o, --owner      # preserve owner\n-D               # --devices --specials\n
\n\n
--delete         # Delete extra files\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "rtorrent", "title": "rTorrent", "url": "/rtorrent", "category": "CLI", "keywords": null, "content_html": "

Shortcuts

\n\n

Global

\n\n\n \n \n \n \n \n \n
^qQuit
\n\n

Main view

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
bkspAdd torrent
->View download
1 - 7Change view
^SStart download
^DStop download (or remove stopped)
^KClose a torrent
+ / -Change priority
\n\n

Throttling

\n\n

Upload

\n\n\n \n \n \n \n \n \n \n \n \n \n
a / s / dIncrease upload throttle by 1/5/50 KB
z / x / cDecrease upload throttle by 1/5/50 KB
\n\n

Download

\n\n\n \n \n \n \n \n \n \n \n \n \n
A / S / DIncrease download throttle by 1/5/50 KB
Z / X / CDecrease download throttle by 1/5/50 KB
\n\n

Download view

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
1 / 2Adjust max uploads
3 / 4Adjust min peers
5 / 6Adjust max peers
\n\n

File list view

\n\n\n \n \n \n \n \n \n
spaceChange priority
\n\n

Also see

\n\n", "intro_html": "

rTorrent is a command-line torrent application. Here are some shortcut keys.

", "description_html": "", "tags": null, "updated": null },{ "id": "ruby", "title": "Ruby", "url": "/ruby", "category": "Ruby", "keywords": null, "content_html": "

Reference

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescription
$!latest error message
$@location of error
$_string last read by gets
$.line number last read by interpreter
$&string last matched by regexp
$~the last regexp match, as an array of subexpressions
$nthe nth subexpression in the last match (same as $~[n])
$=case-insensitivity flag
$/input record separator
$\\output record separator
$0the name of the ruby script file
$* (or ARGV)the command line arguments
$$interpreter’s process ID
$?exit status of last executed child process
$-i $-l $-p $-vCommand line switches
$-v (or $VERBOSE)verbose mode
", "intro_html": "

Quick reference to some features of the Ruby programming language.

", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "ruby21", "title": "Ruby 2.1", "url": "/ruby21", "category": "Ruby", "keywords": null, "content_html": "

Named arguments with defaults

\n\n
# length is required\ndef pad(num, length:, char: \"0\")\n  num.to_s.rjust(length, char)\nend\n
\n\n
pad(42, length: 6) #=> \"000042\"\npad(42) #=> #<ArgumentError: missing keyword: length>\n
\n\n

Module.prepend

\n\n
prepend(\n  Module.new do\n    define_method ...\n  end\n)\n
\n\n

References

\n\n", "intro_html": "

Quick reference to the new features in Ruby 2.1.

", "description_html": "", "tags": ["Archived"], "updated": null },{ "id": "rubygems", "title": "Rubygems", "url": "/rubygems", "category": "Ruby", "keywords": null, "content_html": "

Building and publishing

\n\n
gem build *.gemspec         # Build a gem\ngem install *.gem           # Install locally\ngem push *.gem              # Upload to rubygems.org\ngem yank foogem -v 0.0.1    # Take it back\n
\n\n

Querying

\n\n
gem owner foogem -a rico@ricostacruz.com\n\ngem list                    # List local gems\ngem which rake              # Point to where lib/rake.rb is\ngem search -r rails         # [remote] Search for gems\n
\n\n

Opening a gem

\n\n
# https://github.com/fnando/gem-open\ngem open foogem\nGEM_EDITOR=\"vim\" gem open foogem\n
\n\n

Changing to a directory

\n\n
cd $(basename `gem which rake`)  # Go to a gem's path\n
", "intro_html": "

A quick reference to common rubygems CLI commands.

", "description_html": "", "tags": null, "updated": null },{ "id": "sass", "title": "Sass", "url": "/sass", "category": "CSS", "keywords": ["Variables","mixins","darken()","adjust-color()","@for @each @while @if @else","$list: (a b c)","$map: (a: b, c: d)"], "content_html": "

Basics

\n\n

Introduction

\n\n

This is a quick reference to Sass stylesheets.

\n\n\n\n

Variables

\n\n
$red: #833;\n
\n\n
body {\n  color: $red;\n}\n
\n\n

Nesting

\n\n
.markdown-body {\n  a {\n    color: blue;\n    &:hover {\n      color: red;\n    }\n  }\n}\n
\n\n

to properties

\n
text: {\n  align: center;          // like text-align: center\n  transform: uppercase;   // like text-transform: uppercase\n}\n
\n\n

Comments

\n\n
/* Block comments */\n// Line comments\n
\n\n

Mixins

\n\n
@mixin heading-font {\n  font-family: sans-serif;\n  font-weight: bold;\n}\n
\n\n
h1 {\n  @include heading-font;\n}\n
\n\n

with parameters

\n\n
@mixin font-size($n) {\n  font-size: $n * 1.2em;\n}\n
\n\n
body {\n  @include font-size(2);\n}\n
\n\n

with default values

\n\n
@mixin pad($n: 10px) {\n  padding: $n;\n}\n
\n\n
body {\n  @include pad(15px);\n}\n
\n\n

with a default variable

\n\n
// Set a default value\n$default-padding: 10px;\n
\n\n
@mixin pad($n: $default-padding) {\n  padding: $n;\n}\n
\n\n
body {\n  @include pad(15px);\n}\n
\n\n

Extend

\n\n
.button {\n  ···\n}\n
\n\n
.push-button {\n  @extend .button;\n}\n
\n\n

Composing

\n\n
@import './other_sass_file';\n
\n\n

The .scss or .sass extension is optional.

\n\n

Color functions

\n\n

rgba

\n\n
rgb(100, 120, 140)\nrgba(100, 120, 140, .5)\nrgba($color, .5)\n
\n\n

Mixing

\n\n
mix($a, $b, 10%)   // 10% a, 90% b\n
\n\n

Modifying HSLA

\n\n
darken($color, 5%)\nlighten($color, 5%)\n
\n\n
saturate($color, 5%)\ndesaturate($color, 5%)\ngrayscale($color)\n
\n\n
adjust-hue($color, 15deg)\ncomplement($color)    // like adjust-hue(_, 180deg)\ninvert($color)\n
\n\n
fade-in($color, .5)   // aka opacify()\nfade-out($color, .5)  // aka transparentize() - halves the opacity\nrgba($color, .5)      // sets alpha to .5\n
\n\n

Getting individual values

\n\n

HSLA

\n\n
hue($color)         // → 0deg..360deg\nsaturation($color)  // → 0%..100%\nlightness($color)   // → 0%..100%\nalpha($color)       // → 0..1 (aka opacity())\n
\n\n

RGB

\n\n
red($color)         // → 0..255\ngreen($color)\nblue($color)\n
\n\n

See: hue(), red()

\n\n

Adjustments

\n\n
// Changes by fixed amounts\nadjust-color($color, $blue: 5)\nadjust-color($color, $lightness: -30%)   // like darken(_, 30%)\nadjust-color($color, $alpha: -0.4)       // like fade-out(_, .4)\nadjust-color($color, $hue: 30deg)        // like adjust-hue(_, 15deg)\n
\n\n
// Changes via percentage\nscale-color($color, $lightness: 50%)\n
\n\n
// Changes one property completely\nchange-color($color, $hue: 180deg)\nchange-color($color, $blue: 250)\n
\n\n

Supported: $red $green $blue $hue $saturation $lightness $alpha

\n\n

Other functions

\n\n

Strings

\n\n
unquote('hello')\nquote(hello)\n
\n\n
to-upper-case(hello)\nto-lower-case(hello)\n
\n\n
str-length(hello world)\nstr-slice(hello, 2, 5)      // \"ello\" - it's 1-based, not 0-based\nstr-insert(\"abcd\", \"X\", 1)  // \"Xabcd\"\n
\n\n

Units

\n\n
unit(3em)        // 'em'\nunitless(100px)  // false\n
\n\n

Numbers

\n\n
floor(3.5)\nceil(3.5)\nround(3.5)\nabs(3.5)\n
\n\n
min(1, 2, 3)\nmax(1, 2, 3)\n
\n\n
percentage(.5)   // 50%\nrandom(3)        // 0..3\n
\n\n

Misc

\n\n
variable-exists(red)    // checks for $red\nmixin-exists(red-text)  // checks for @mixin red-text\nfunction-exists(redify)\n
\n\n
global-variable-exists(red)\n
\n\n
selector-append('.menu', 'li', 'a')   // .menu li a\nselector-nest('.menu', '&:hover li')  // .menu:hover li\nselector-extend(...)\nselector-parse(...)\nselector-replace(...)\nselector-unify(...)\n
\n\n

Feature checks

\n\n

Feature check

\n\n
feature-exists(global-variable-shadowing)\n
\n\n

Features

\n\n\n\n

Loops

\n\n

For loops

\n\n
@for $i from 1 through 4 {\n  .item-#{$i} { left: 20px * $i; }\n}\n
\n\n

Each loops (simple)

\n\n
$menu-items: home about services contact;\n\n@each $item in $menu-items {\n  .photo-#{$item} {\n    background: url('images/#{$item}.jpg');\n  }\n}\n
\n\n

Each loops (nested)

\n
$backgrounds: (home, 'home.jpg'), (about, 'about.jpg');\n\n@each $id, $image in $backgrounds {\n  .photo-#{$id} {\n    background: url($image);\n  }\n}\n
\n\n

While loops

\n\n
$i: 6;\n@while $i > 0 {\n  .item-#{$i} { width: 2em * $i; }\n  $i: $i - 2;\n}\n
\n\n

Other features

\n\n

Conditionals

\n\n
@if $position == 'left' {\n   position: absolute;\n   left: 0;\n}\n@else if $position == 'right' {\n   position: absolute;\n   right: 0;\n}\n@else {\n   position: static;\n}\n
\n\n

Interpolation

\n\n
.#{$klass} { ... }      // Class\ncall($function-name)    // Functions\n\n@media #{$tablet}\nfont: #{$size}/#{$line-height}\nurl(\"#{$background}.jpg\")\n
\n\n

Lists

\n\n
$list: (a b c);\n\nnth($list, 1)  // starts with 1\nlength($list)\n\n@each $item in $list { ... }\n
\n\n

Maps

\n\n
$map: (key1: value1, key2: value2, key3: value3);\n\nmap-get($map, key1)\n
\n\n

See also

\n\n", "intro_html": "", "description_html": "", "tags": ["Featured"], "updated": "2020-07-03" },{ "id": "saucelabs", "title": "Saucelabs", "url": "/saucelabs", "category": "Others", "keywords": null, "content_html": "

Getting started

\n\n

Sign up for opensauce:

\n\n\n\n

Install zuul:

\n\n
npm i -g zuul\n
\n\n

Configure zuul:

\n\n
# ~/.zuulrc\nsauce_username: me\nsauce_key: abc12348-e3e2-...\n
\n\n

Add .zuul.yml to your project:

\n\n
# .zuul.yml\nui: mocha-bdd\nbrowsers:\n  - name: chrome\n    version: latest\n  - name: ie\n    version: 6..latest\n  - name: firefox\n    version: latest\n
\n\n

Try to run tests:

\n\n
zuul test/test.js\nzuul --local test/test.js\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "scp", "title": "scp", "url": "/scp", "category": "CLI", "keywords": null, "content_html": "

Usage

\n\n
scp <options> source_path destination_path\n
\n\n

Conditions

\n\n
-r      # transfer directory \n-v      # see the transfer details\n-C      # copy files with compression\n-l 800  # limit bandwith with 800\n-p      # preserving the original attributes of the copied files\n-q      # hidden the output\n
\n\n

Commands

\n\n
$ scp file user@host:/path/to/file                        # copying a file to the remote system using scp command\n$ scp user@host:/path/to/file /local/path/to/file         # copying a file from the remote system using scp command\n
\n\n
$ scp file1 file2 user@host:/path/to/directory            # copying multiple files using scp command\n$ scp -r /path/to/directory user@host:/path/to/directory  # Copying an entire directory with scp command\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-12-25" },{ "id": "sed", "title": "sed", "url": "/sed", "category": "CLI", "keywords": null, "content_html": "

In place replacements

\n\n

In-place replacement (GNU)

\n\n
sed -i -e 's/foo/bar/' example.md\n
\n\n

In GNU sed: use -i without arg.

\n\n

In-place replacement (BSD)

\n\n
sed -i '' -e 's/foo/bar/' example.md\n
\n\n

In OSX, -i '' is required.

\n\n

File regions

\n\n

Print until a certain line is met

\n\n
sed '/begin api/q'\n
\n\n

Print until a certain line is met, but not that line

\n\n
sed '/^# begin/,$d'\n
\n\n

Print everything after a given line

\n\n
sed -n '/end api/,$p'\n
\n\n

Print after a given line is found.

\n\n

Print everything except matching

\n\n
sed -n '/regex/d;'\n
\n\n

Print everything except lines matching regex. Useful for printing files with comments.

", "intro_html": "

Here’s some hints on using sed.

", "description_html": "", "tags": null, "updated": null },{ "id": "semver", "title": "Semver", "url": "/semver", "category": "Others", "keywords": null, "content_html": "

Semver

\n\n

Given a version number MAJOR.MINOR.PATCH:

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MAJORincompatible API changes
MINORadd functionality (backwards-compatible)
PATCHbug fixes (backwards-compatible)
\n\n

Simple ranges

\n\n
  1.2.3\n =1.2.3\n >1.2.3\n <1.2.3\n>=1.2.3\n
\n\n

Note that suffixed versions (1.2.3-rc1) are not matched.

\n\n

Ranges

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RangeDescriptionNotes
~1.2.3is >=1.2.3 <1.3.0 
^1.2.3is >=1.2.3 <2.0.0 
^0.2.3is >=0.2.3 <0.3.0(0.x.x is special)
^0.0.1is =0.0.1(0.0.x is special)
^1.2is >=1.2.0 <2.0.0(like ^1.2.0)
~1.2is >=1.2.0 <1.3.0(like ~1.2.0)
^1is >=1.0.0 <2.0.0 
~1same 
1.xsame 
1.*same 
1same 
*any version 
xsame 
\n\n

Hyphenated ranges

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
RangeDescription
1.2.3 - 2.3.4is >=1.2.3 <=2.3.4
\n\n

Partial right

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RangeDescription
1.2.3 - 2.3is >=1.2.3 <2.4.0
1.2.3 - 2is >=1.2.3 <3.0.0
\n\n

Partial left

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
RangeDescription
1.2 - 2.3.0is 1.2.0 - 2.3.0
\n\n

When the right is partial (eg, 2.3), missing pieces are assumed to be x (eg, 2.3.x).

\n\n

When the left is partial (eg, 1.2), missing pieces are assumed to be 0 (eg, 1.2.0).

\n\n

Combining ranges

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
RangeDescription
>=0.14 <16And (space-separated)
0.14.x || 15.x.xOr (pipe-separated)
\n\n

Pre-releases

\n\n
1.2.3-prerelease+build\n
\n\n

Explanation

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
^means “compatible with”
~means “reasonably close to”
0.x.xis for “initial development”
1.x.xmeans public API is defined
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2019-12-31" },{ "id": "sequel", "title": "Sequel", "url": "/sequel", "category": "Ruby libraries", "keywords": null, "content_html": "

Open a database

\n\n
require 'rubygems'\nrequire 'sequel'\n\nDB = Sequel.sqlite('my_blog.db')\nDB = Sequel.connect('postgres://user:password@localhost/my_db')\nDB = Sequel.postgres('my_db', :user => 'user', :password => 'password', :host => 'localhost')\nDB = Sequel.ado('mydb')\n
\n\n

Open an SQLite memory database

\n\n

Without a filename argument, the sqlite adapter will setup a new sqlite database in memory.

\n\n
DB = Sequel.sqlite\n
\n\n

Logging SQL statements

\n\n
require 'logger'\nDB = Sequel.sqlite '', :loggers => [Logger.new($stdout)]\n# or\nDB.loggers << Logger.new(...)\n
\n\n

Using raw SQL

\n\n
DB.run \"CREATE TABLE users (name VARCHAR(255) NOT NULL, age INT(3) NOT NULL)\"\ndataset = DB[\"SELECT age FROM users WHERE name = ?\", name]\ndataset.map(:age)\nDB.fetch(\"SELECT name FROM users\") do |row|\n  p row[:name]\nend\n
\n\n

Create a dataset

\n\n
dataset = DB[:items]\ndataset = DB.from(:items)\n
\n\n

Most dataset methods are chainable

\n\n
dataset = DB[:managers].where(:salary => 5000..10000).order(:name, :department)\n
\n\n

Insert rows

\n\n
dataset.insert(:name => 'Sharon', :grade => 50)\n
\n\n

Retrieve rows

\n\n
dataset.each{|r| p r}\ndataset.all # => [{...}, {...}, ...]\ndataset.first # => {...}\n
\n\n

Update/Delete rows

\n\n
dataset.filter(~:active).delete\ndataset.filter('price < ?', 100).update(:active => true)\n
\n\n

Datasets are Enumerable

\n\n
dataset.map{|r| r[:name]}\ndataset.map(:name) # same as above\n\ndataset.inject(0){|sum, r| sum + r[:value]}\ndataset.sum(:value) # same as above\n
\n\n

Filtering (see also doc/dataset_filtering.rdoc)

\n\n

Equality

\n\n
dataset.filter(:name => 'abc')\ndataset.filter('name = ?', 'abc')\n
\n\n

Inequality

\n\n
dataset.filter{value > 100}\ndataset.exclude{value <= 100}\n
\n\n

Inclusion

\n\n
dataset.filter(:value => 50..100)\ndataset.where{(value >= 50) & (value <= 100)}\n\ndataset.where('value IN ?', [50,75,100])\ndataset.where(:value=>[50,75,100])\n\ndataset.where(:id=>other_dataset.select(:other_id))\n
\n\n

Subselects as scalar values

\n\n
dataset.where('price > (SELECT avg(price) + 100 FROM table)')\ndataset.filter{price > dataset.select(avg(price) + 100)}\n
\n\n

LIKE/Regexp

\n\n
DB[:items].filter(:name.like('AL%'))\nDB[:items].filter(:name => /^AL/)\n
\n\n

AND/OR/NOT

\n\n
DB[:items].filter{(x > 5) & (y > 10)}.sql \n# SELECT * FROM items WHERE ((x > 5) AND (y > 10))\n\nDB[:items].filter({:x => 1, :y => 2}.sql_or & ~{:z => 3}).sql \n# SELECT * FROM items WHERE (((x = 1) OR (y = 2)) AND (z != 3))\n
\n\n

Mathematical operators

\n\n
DB[:items].filter((:x + :y) > :z).sql \n# SELECT * FROM items WHERE ((x + y) > z)\n\nDB[:items].filter{price - 100 < avg(price)}.sql \n# SELECT * FROM items WHERE ((price - 100) < avg(price))\n
\n\n

Ordering

\n\n
dataset.order(:kind)\ndataset.reverse_order(:kind)\ndataset.order(:kind.desc, :name)\n
\n\n

Limit/Offset

\n\n
dataset.limit(30) # LIMIT 30\ndataset.limit(30, 10) # LIMIT 30 OFFSET 10\n
\n\n

Joins

\n\n
DB[:items].left_outer_join(:categories, :id => :category_id).sql \n# SELECT * FROM items LEFT OUTER JOIN categories ON categories.id = items.category_id\n\nDB[:items].join(:categories, :id => :category_id).join(:groups, :id => :items__group_id) \n# SELECT * FROM items INNER JOIN categories ON categories.id = items.category_id INNER JOIN groups ON groups.id = items.group_id\n
\n\n

Aggregate functions methods

\n\n
dataset.count #=> record count\ndataset.max(:price)\ndataset.min(:price)\ndataset.avg(:price)\ndataset.sum(:stock)\n\ndataset.group_and_count(:category)\ndataset.group(:category).select(:category, :AVG.sql_function(:price))\n
\n\n

SQL Functions / Literals

\n\n
dataset.update(:updated_at => :NOW.sql_function)\ndataset.update(:updated_at => 'NOW()'.lit)\n\ndataset.update(:updated_at => \"DateValue('1/1/2001')\".lit)\ndataset.update(:updated_at => :DateValue.sql_function('1/1/2001'))\n
\n\n

Schema Manipulation

\n\n
DB.create_table :items do\n  primary_key :id\n  String :name, :unique => true, :null => false\n  TrueClass :active, :default => true\n  foreign_key :category_id, :categories\n  DateTime :created_at\n  \n  index :created_at\nend\n\nDB.drop_table :items\n\nDB.create_table :test do\n  String :zipcode\n  enum :system, :elements => ['mac', 'linux', 'windows']\nend\n
\n\n

Aliasing

\n\n
DB[:items].select(:name.as(:item_name))\nDB[:items].select(:name___item_name)\nDB[:items___items_table].select(:items_table__name___item_name)\n# SELECT items_table.name AS item_name FROM items AS items_table\n
\n\n

Transactions

\n\n
DB.transaction do\n  dataset.insert(:first_name => 'Inigo', :last_name => 'Montoya')\n  dataset.insert(:first_name => 'Farm', :last_name => 'Boy')\nend # Either both are inserted or neither are inserted\n
\n\n

Database#transaction is re-entrant:

\n\n
DB.transaction do # BEGIN issued only here\n  DB.transaction\n    dataset << {:first_name => 'Inigo', :last_name => 'Montoya'}\n  end\nend # COMMIT issued only here\n
\n\n

Transactions are aborted if an error is raised:

\n\n
DB.transaction do\n  raise \"some error occurred\"\nend # ROLLBACK issued and the error is re-raised\n
\n\n

Transactions can also be aborted by raising Sequel::Rollback:

\n\n
DB.transaction do\n  raise(Sequel::Rollback) if something_bad_happened\nend # ROLLBACK issued and no error raised\n
\n\n

Savepoints can be used if the database supports it:

\n\n
DB.transaction do\n  dataset << {:first_name => 'Farm', :last_name => 'Boy'} # Inserted\n  DB.transaction(:savepoint=>true) # This savepoint is rolled back\n    dataset << {:first_name => 'Inigo', :last_name => 'Montoya'} # Not inserted\n    raise(Sequel::Rollback) if something_bad_happened\n  end\n  dataset << {:first_name => 'Prince', :last_name => 'Humperdink'} # Inserted\nend\n
\n\n

Miscellaneous:

\n\n
dataset.sql # \"SELECT * FROM items\"\ndataset.delete_sql # \"DELETE FROM items\"\ndataset.where(:name => 'sequel').exists # \"EXISTS ( SELECT * FROM items WHERE name = 'sequel' )\"\ndataset.columns #=> array of columns in the result set, does a SELECT\nDB.schema(:items) => [[:id, {:type=>:integer, ...}], [:name, {:type=>:string, ...}], ...]\n
\n\n
\n\n

Documents

\n\n
http://sequel.rubyforge.org/rdoc/files/doc/association_basics_rdoc.html\nhttp://sequel.rubyforge.org/rdoc/classes/Sequel/Schema/Generator.html\nhttp://sequel.rubyforge.org/rdoc/files/doc/validations_rdoc.html\nhttp://sequel.rubyforge.org/rdoc/classes/Sequel/Model.html\n
\n\n

Alter table

\n\n
database.alter_table :deals do\n  add_column :name, String\n  drop_column :column_name\n  rename_column :from, :to\n\n  add_constraint :valid_name, :name.like('A%')\n  drop_constraint :constraint\n\n  add_full_text_index :body\n  add_spacial_index [columns]\n\n  add_index :price\n  drop_index :index\n\n  add_foreign_key :artist_id, :table\n  add_primary_key :id\n  add_unique_constraint [columns]\n  set_column_allow_null :foo, false\n  set_column_default :title, ''\n\n  set_column_type :price, 'char(10)'\nend\n
\n\n

Model associations

\n\n
class Deal < Sequel::Model\n\n  # Us (left) <=> Them (right)\n  many_to_many  :images,\n    left_id:    :deal_id,\n    right_id:   :image_id,\n    join_table: :image_links\n\n  one_to_many   :files,\n    key:        :deal_id,\n    class:      :DataFile,\n\n  many_to_one   :parent, class: self\n  one_to_many   :children, key: :parent_id, class: self\n\n  one_to_many :gold_albums, class: :Album do |ds|\n    ds.filter { copies_sold > 50000 }\n  end\n
\n\n

Provided by many_to_many

\n\n
Deal[1].images\nDeal[1].add_image\nDeal[1].remove_image\nDeal[1].remove_all_images\n
\n\n

Validations

\n\n
  def validate\n    super\n    errors.add(:name, 'cannot be empty') if !name || name.empty?\n\n    validates_presence [:title, :site]\n    validates_unique :name\n    validates_format /\\Ahttps?:\\/\\//, :website, :message=>'is not a valid URL'\n    validates_includes %w(a b c), :type\n    validates_integer :rating\n    validates_numeric :number\n    validates_type String, [:title, :description]\n\n    validates_integer :rating  if new?\n\n    # options: :message =>, :allow_nil =>, :allow_blank =>,\n    #          :allow_missing =>,\n\n    validates_exact_length 17, :isbn\n    validates_min_length 3, :name\n    validates_max_length 100, :name\n    validates_length_range 3..100, :name\n    \n    # Setter override\n    def filename=(name)\n      @values[:filename] = name\n    end\n  end\nend\n\ndeal.errors\n
\n\n

Model stuff

\n\n
deal = Deal[1]\ndeal.changed_columns\ndeal.destroy  # Calls hooks\ndeal.delete   # No hooks\ndeal.exists?\ndeal.new?\ndeal.hash  # Only uniques\ndeal.keys  #=> [:id, :name]\ndeal.modified!\ndeal.modified?\n\ndeal.lock!\n
\n\n

Callbacks

\n\n
before_create\nafter_create\n\nbefore_validation\nafter_validation\nbefore_save\nbefore_update\nUPDATE QUERY\nafter_update\nafter_save\n\nbefore_destroy\nDELETE QUERY\nafter_destroy\n
\n\n

Schema

\n\n
class Deal < Sequel::Model\n  set_schema do\n    primary_key :id\n    primary_key [:id, :title]\n    String :name, primary_key: true\n    \n    String  :title\n    Numeric :price\n    DateTime :expires\n\n    unique :whatever\n    check(:price) { num > 0 }\n\n    foreign_key :artist_id\n    String :artist_name, key: :id\n\n    index :title\n    index [:artist_id, :name]\n    full_text_index :title\n\n    # String, Integer, Fixnum, Bignum, Float, Numeric, BigDecimal,\n    # Date, DateTime, Time, File, TrueClass, FalseClass\n  end\nend\n
\n\n

Unrestrict primary key

\n\n
Category.create id: 'travel'   # error\nCategory.unrestrict_primary_key\nCategory.create id: 'travel'   # ok\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "sequelize", "title": "Sequelize", "url": "/sequelize", "category": "Ruby libraries", "keywords": null, "content_html": "

API

\n\n
sequelize.sync().done -> ...\n
\n\n

Models

\n\n
Project = sequelize.define('Project', {\n  title: Sequelize.STRING,\n  description: Sequelize.TEXT,\n  myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW },\n  title: { type: Sequelize.STRING, allowNull: false },\n  id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },\n}, {\n  classMethods: { ... },\n  instanceMethods: { ... }\n});\n\nProject.hasMany(Task)\n
\n\n

Finders

\n\n
Project.find(123).success (project) ->\n\nProject.find({ where: {title: 'Hello'} })\nProject.find({ where: {id: [1,3,4]} })\nProject.find({ where: [\"id > ?\", 25] })\n\nProject.find(\n  where: {title: 'a'}\n  attributes: ['id', ['name', 'title']]\n)\n\n.findOrCreate(...)\n\n.findAll\n.findAll({ where: ... })\n.findAll({ order: 'title DESC' })\n.findAll({ limit: 10 })\n.findAll({ offset: 10, limit: 2 })\n\n.count()\n
\n\n

Build

\n\n
item = Project.build({ ... })\n\nitem.title = '...'\n\nitem.save().success (item) ->\n\nitem.updateAttributes({ title: '...' })\n\nitem.destroy().success ->\n\nitem.values\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "sh-pipes", "title": "Shell: named pipes", "url": "/sh-pipes", "category": "CLI", "keywords": null, "content_html": "

Named pipes

\n\n
diff <(ls ./old) <(ls ./new)\n
\n\n

This creates a virtual file with the contents of the output of ls ./old.

\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "sh", "title": "Shell scripting", "url": "/sh", "category": "CLI", "keywords": null, "content_html": "", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "shelljs", "title": "Shell.js", "url": "/shelljs", "category": "JavaScript libraries", "keywords": null, "content_html": "

Example

\n\n
var shell = require('shelljs')\n
\n\n
if (!shell.which('git')) {\n  shell.echo('Sorry, this script requires git')\n  shell.exit(1)\n}\n
\n\n
// Copy files to release dir\nshell.rm('-rf', 'out/Release')\nshell.cp('-R', 'stuff/', 'out/Release')\n
\n\n
// Replace macros in each .js file\nshell.cd('lib')\nshell.ls('*.js').forEach(function (file) {\n  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file)\n  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file)\n  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\\n/, shell.cat('macro.js'), file)\n})\nshell.cd('..')\n
\n\n
// Run external tool synchronously\nif (shell.exec('git commit -am \"Auto-commit\"').code !== 0) {\n  shell.echo('Error: Git commit failed')\n  shell.exit(1)\n}\n
\n\n

Taken from the Readme.

\n\n

Require

\n\n
const sh = require('shelljs')\n
\n\n

Paths

\n\n
sh.cd('dir')\n
\n\n
sh.mkdir('dir')\nsh.mkdir('-p', 'dir')\n
\n\n

File manipulation

\n\n
sh.cp('src', 'dest')\nsh.cp('-rf', 'src', 'dest')\n
\n\n
sh.rm('file')\nsh.rm('-rf', 'file')\n
\n\n
sh.mv('src', 'dest')\nsh.mv(['src1','src2'], 'dest')\n
\n\n
sh.chmod('644', 'file')\nsh.chmod(755, 'file')\nsh.chmod('u+x', 'file')\n
\n\n

Tests

\n\n
sh.test('-b', 'path')  // block device\nsh.test('-d', 'path')  // dir\nsh.test('-e', 'path')  // exists\nsh.test('-f', 'path')  // file\nsh.test('-L', 'path')  // symlink\n
\n\n

Cat and output

\n\n
src = sh.cat('file*.txt')\n
\n\n
'hello'.to('output.txt')\n'hello'.toEnd('append.txt')\n
\n\n
sh.cat('input.txt').to('output.txt')\n
\n\n

Utils

\n\n
sh.which('x')\nsh.pwd()\n
\n\n
sh.echo('hi')\n
\n\n
sh.exec('node --version').code\nsh.exec('node --version').output\nsh.exec('node --version', { silent: true }).output\n
\n\n
sh.exec('node --version', (code, output) => {\n  sh.echo(`exit code ${code}`)\n})\n
\n\n
sh.tempdir()\n
\n\n
sh.error()  // null if no error\n
\n\n

Also see

\n\n", "intro_html": "

ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API.

", "description_html": "", "tags": null, "updated": "2017-10-27" },{ "id": "siege", "title": "Siege", "url": "/siege", "category": "Others", "keywords": null, "content_html": "

Basic usage

\n\n
siege -b -c=10 -t=5m \"http://...\"\n
\n\n

Options

\n\n

Repetitions

\n\n
-c, --concurrent=N\n-t, --time=MINSm\n-r, --reps=N\n
\n\n

Modes

\n\n
-i, --internet       Hit URLs randomly\n-b, --benchmark      No delay between requests\n
\n\n

Configuration

\n\n
-f, --file=FILE      load urls.txt\n-R, --rc=FILE        load siegerc\n
\n\n

Headers

\n\n
-H, --header=\"Cookie: foo=bar\"\n-A, --user-agent=\"Mozilla\"\n-T, --content-type=\"text/html\"\n
\n\n

References

\n\n

Also see: siegerc

", "intro_html": "

Siege is an HTTP and HTTPS load testing tool.

", "description_html": "", "tags": null, "updated": null },{ "id": "simple_form", "title": "SimpleForm", "url": "/simple_form", "category": "Others", "keywords": null, "content_html": "

Inputs

\n\n
<%= f.input :email, required: false, autofocus: true %>\n<%= f.input :password, required: false %>\n<%= f.input :remember_me, as: :boolean %>\n<%= f.button :submit, \"Sign in\" %>\n
\n\n

Adding a wrapper

\n\n
simple_form_for @x, wrapper: :small\n
", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "sinon-chai", "title": "Sinon-chai", "url": "/sinon-chai", "category": "JavaScript libraries", "keywords": null, "content_html": "\n\n

Initialization

\n\n
var sinon = require('sinon');\nrequire('chai').use(require('sinon-chai'));\n
\n\n

Assert

\n\n
expect(spy).called\nexpect(spy).calledOnce\nexpect(spy).calledTwice\nexpect(spy).calledThrice\nexpect(spy).calledBefore\nexpect(spy).calledAfter\nexpect(spy).calledWithNew\nexpect(spy).alwaysCalledWithNew\nexpect(spy).calledOn\nexpect(spy).alwaysCalledOn\nexpect(spy).calledWith\nexpect(spy).alwaysCalledWith\nexpect(spy).calledWithExactly\nexpect(spy).alwaysCalledWithExactly\nexpect(spy).calledWithMatch\nexpect(spy).alwaysCalledWithMatch\nexpect(spy).returned\nexpect(spy).alwaysReturned\nexpect(spy).threw\nexpect(spy).alwaysThrew\n
\n\n

Should

\n\n
spy.should.have.been.called\nspy.should.have.been.calledOnce\nspy.should.have.been.calledTwice\nspy.should.have.been.calledThrice\nspy1.should.have.been.calledBefore(spy2)\nspy1.should.have.been.calledAfter(spy2)\nspy.should.have.been.calledWithNew\nspy.should.always.have.been.calledWithNew\nspy.should.have.been.calledOn(context)\nspy.should.always.have.been.calledOn(context)\nspy.should.have.been.calledWith(...args)\nspy.should.always.have.been.calledWith(...args)\nspy.should.always.have.been.calledWithExactly(...args)\nspy.should.always.have.been.calledWithExactly(...args)\nspy.should.have.been.calledWithMatch(...args)\nspy.should.always.have.been.calledWithMatch(...args)\nspy.should.have.returned(returnVal)\nspy.should.have.always.returned(returnVal)\nspy.should.have.thrown(errorObjOrErrorTypeStringOrNothing)\nspy.should.have.always.thrown(errorObjOrErrorTypeStringOrNothing)\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "sinon", "title": "Sinon", "url": "/sinon", "category": "JavaScript libraries", "keywords": null, "content_html": "

Creating spies

\n\n
fn = sinon.spy()\nfn()\n
\n\n
fn.calledOnce == true\nfn.callCount == 1\n
\n\n

Spying/stubbing

\n\n
sinon.spy($, 'ajax')\n
\n\n
$.ajax();\n$.ajax.calledOnce == true\n
\n\n
sinon.stub($, 'ajax', function () { ... }) // function optional\n
\n\n
$.ajax.calledWithMatch({ url: '/x' })\n$.ajax.restore()\n
\n\n

Spy/stub properties

\n\n
spy\n  .args        //=> [ [..], [..] ] one per call\n  .thisValues\n  .returnValues\n
\n\n
  .called      //=> true\n  .notCalled\n  .callCount\n  .calledOnce\n  .calledTwice\n  .calledThrice\n
\n\n
  .getCalls()   //=> Array\n  .getCall(0)\n  .firstCall\n
\n\n

Anonymous stub

\n\n
stub = sinon.stub().returns(42)\nstub() == 42\n
\n\n
stub\n  .withArgs(42).returns(1)\n  .withArgs(43).throws(\"TypeError\")\n
\n\n
stub\n  .returns(1)\n  .throws(\"TypeError\")\n  .returnsArg(0) // Return 1st argument\n  .callsArg(0)\n
\n\n

Fake date

\n\n
sinon.useFakeTimers(+new Date(2011,9,1));\n
\n\n

Fake server

\n\n
server = sinon.fakeServer.create()\n
\n\n
$.get('/file.json', ...)\nserver.requests[0].respond(\n  200,\n  { 'Content-Type': 'application/json' },\n  JSON.stringify({ hello: 'world' })\n)\n
\n\n
server.restore()\n
\n\n

Fake XHR

\n\n
xhr = sinon.useFakeXMLHttpRequest()\nxhr.restore()\n
\n\n

Sandbox

\n\n
beforeEach(function() {\n  global.sinon = require('sinon').sandbox.create()\n})\n
\n\n
afterEach(function() {\n  global.sinon.restore()\n})\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-10-27" },{ "id": "sketch", "title": "Sketch", "url": "/sketch", "category": "Apps", "keywords": null, "content_html": "

Shortcuts

\n\n

Insert

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
VVector
PPencil
TText
LLine
RRectangle
OOval
URounded
\n\n

Show

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
^GShow grid
^LShow layout
^PShow pixels
^HShow selection handles
^RShow rulers
\n\n

Sidebars

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘⌥1Toggle left (layers)
⌘⌥2Toggle right (inspector)
⌘⌥3Toggle both
⌘.Presentation mode
\n\n

Zoom

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘0100%
⌘1Fit to screen
⌘2Fit selection to screen
⌘3Center selection
\n\n

Arrange

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘⌥↑ / Forward or backward
^⌘⌥↑ / Front or back
\n\n

Distribute

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
^⌘HHorizontal
^⌘VVertical
\n\n

Layers

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘RRename layer
⌘FFind layer
⌘GGroup
⌘⇧GUngroup
\n\n

Font

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
⌘⌥ + / -Bigger/smaller
⌘⇧[Left align
⌘⇧\\Center align
⌘⇧]Right align
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-08-30" },{ "id": "slim", "title": "Slim", "url": "/slim", "category": "Ruby libraries", "keywords": null, "content_html": "

Example

\n\n
doctype html\nhtml\n  head\n    title Slim Examples\n    meta[charset='utf-8']\n    meta(name=\"keywords\" content=\"template language\")\n    meta name=\"author\" content=author\n    meta property='og:image' content=asset_url('foo.png')\n    meta property='og:image' content=(path_to_user user)\n    meta(\n      property='description'\n      content='this is the song that never ends')\n
\n\n

Attributes

\n\n
meta[charset='utf-8']\nmeta(name=\"keywords\" content=\"template language\")\nmeta name=\"author\" content=author\n
\n\n

You can use parentheses, brackets, or none at all.

\n\n

Ruby attributes

\n\n
a class=[:menu,:highlight]\n
\n\n

You can use Ruby expressions in attributes.

\n\n

Hash attributes

\n\n
.card *{'data-url' => place_path(place)}\n
\n\n

You can destructure Ruby hashes as attributes.

\n\n

Inline Ruby

\n\n
ruby:\n  def foobar\n    \"hello\"\n  end\n\ndiv= foobar\n
\n\n

Inline Markdown

\n\n
markdown:\n  ### On Markdown\n\n  I am *Markdown* _text_!\n  {: .classname}\n
\n\n

Slim can handle your Markdown content for longer content blocks or code.\nDepending on your parser, like Kramdown, other features might work, like assigning attributes or classes.

\n\n

Embedded JavaScript

\n\n
javascript:\n  alert('Slim supports embedded javascript!')\n
\n\n

Comments

\n\n
/ Comment\n/! HTML comment\n
\n\n

Ruby

\n\n
== yield\n= t('.hello')\n- 3.times do |i|\n  div\n
\n\n

Verbatim text

\n\n
div\n  | This is text\n    it is nice\n
\n\n

Advanced whitespaces

\n\n
div\n  ' This appends a whitespace\ndiv\n  |  This hackily prepends a whitespace\ndiv\n  => 'This appends a whitespace'\ndiv\n  =< 'This prepends a whitespace'\n
\n\n

Inline HTML

\n\n
<div class='foo'>\n  - if articles.empty?\n    | Nothing here\n</div>\n
\n\n

Inline tags

\n\n
ul\n  li: a(href='/') Home\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "social-images", "title": "Social media images", "url": "/social-images", "category": "Others", "keywords": null, "content_html": "

Facebook

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
WhatDimensions
Cover photo851 x 315
Display picture168 x 168 ?
Highlighted image1200 x 717 (appears 843 x 504)
Share link (og:image)940 x 492 (1.91:1, appears as 470 x 246)
Share link (square)1:1, appears as 114 x 114?
\n\n

Twitter

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
WhatDimensions
Page header1500 x 500
Display picture400 x 400 (shown as 200x200)
In-stream photo preview440 x 220 (2:1)
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "spacemacs", "title": "Spacemacs", "url": "/spacemacs", "category": "Apps", "keywords": null, "content_html": "

Shortcuts

\n\n

Layers

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
SPC fFile
SPC pProject
SPC tToggle
SPC bBuffer
SPC mMajor mode
,Same as SPC m
SPC gGit
SPC lLayout
SPC aApps
SPC hHelp
\n\n

More

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
M-xSPC SPC
TerminalSPC '
SearchSPC /
\n\n

SPC h - Help

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Spacemacs helpSPC
Layersl
Documentationr
FAQf
VimtutorT
\n\n

SPC f - File

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Saves
Save allS
Copyc
DeleteD
Show filenamey
\n\n

SPC b - Buffer

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Next buffer (:bnext)n
Previous buffer (:bprev)p
Delete buffer (:bd)d
\n\n

SPC f e - Config

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Edit configd
Edit config and templateD
Reload configR
\n\n

SPC w - Window

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Help.
Selecth / j / k / l
MoveH / J / K / L
Splits
Split & followS
Split vertv
Split vert & followV
\n\n

SPC p - Project

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Switch projectl
Switch projectp
Open files & recenth
Open filesf
Show treet
Open terminal'
Open terminal in root$ t
\n\n

SPC l w - Workspaces

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Help?
Switch previous layoutTAB
Switch to nth workspace09
RenameR
\n\n

SPC t - Toggle

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionShortcut
Line numbersn
\n\n

Major modes

\n\n

Markdown

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
, -Insert horizontal rule
, h 1Insert H1
\n\n

Other layers

\n\n

version-control

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
SPC g sStatus
SPC g mOpen dispatch menu
SPC g m sStage
SPC g m P pPush
SPC g m cCommit
SPC g tOpen time machine
SPC g l lOpen in GitHub
SPC g l LShow GitHub URL
\n\n

Version control is provided by Magit.

\n\n

Emacs standard

\n\n

File

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DescriptionEmacsSpacemacs
SaveC-x C-sSPC f s
OpenC-x C-fSPC f f
CloseC-x C-k 
Split horizontalC-x 2SPC w h
Split verticalC-x 3SPC w v
ConfirmC-c C-c 
AbortC-c C-k 
\n\n

References

\n\n", "intro_html": "

Spacemacs is a distribution for Emacs.

", "description_html": "", "tags": ["WIP"], "updated": "2020-05-22" },{ "id": "spine", "title": "Spine", "url": "/spine", "category": "JavaScript libraries", "keywords": null, "content_html": "

Models

\n\n
class User extends Spine.Model\n  @configure \"User\", \"name\", \"address\"\n\n  fullName: ->\n    [@first, @last].join ' '\n
\n\n

JavaScript

\n\n
// Subclassing\nUser = Spine.Model.sub()\n
\n\n

Class methods

\n\n
.configure 'modelname', attributes...\n\n# Inheritance\n.include(Module)\n.extend(Module)\n\n.create(name: \"John\")\n\n.count()\n\n# Events\n.on 'refresh change', (user) -> ...\n.trigger 'event'\n\n.change (user) -> ...  # same as on('change')\n.fetch (user) -> ...   # same as on('fetch')\n\n# JSON\n.toJSON()         # all records\n.fromJSON(json)   # from json string\n.fromForm(el)\n\n# Data\n.records     # Hash of instances\n.attributes  # array of attributes (from .configure)\n\n# Convenience\n.toString()  #=> \"User\"\n\n# Find by ID\n.exists(1)\n.find(1)     # throws error\n\n# Find by something\n.select (u) u.name == 'bob'\n.findByAttribute 'name', 'bob'\n.findAllByAttribute 'name', 'bob'\n\n.all()\n.slice(6, 13)  # cloned copies of instances\n\n# Iterating\n.each (user) ->\n\n# Ends\n.first()\n.last()\n\n# Deleting\n.deleteAll()\n.destroyAll()\n.destroyAll({ ..options.. })\n.destroy(2)\n
\n\n

Instance methods

\n\n
user = new User();\n\nuser\n.isNew()\n.exists()\n\n# Validation\n.isValid()\n.validate()    # validate = (-> \"Name required\" unless @name)\n\n.attributes()  # hash of attr values\n.eql(other)    # equality check\n\n# Update\n.load(attrs)\n.reload()\n.fromForm(form)\n.updateAttribute(\"name\", \"john\")\n.updateAttributes(name: \"John\")\n\n# Event\n.on 'event', -> ...\n.trigger 'event'\n\n# Retrieve\n.toJSON()\n\n# Persistence\n.save()\n\n.destroy()\n.dup()         # clone as unsaved\n
\n\n

Mixins

\n\n
class User extends Spine.Model\n  @include MyModule\n  @extend MyModule\n
\n\n

Events

\n\n
.on 'create'\n.on 'update'\n.on 'destroy'\n\n.on 'save'    # create / update\n.on 'change'  # create / update / destroy\n\n.on 'refresh'\n.on 'error'    # validation error\n
\n\n

Ajax

\n\n
class User extends Spine.Model\n  @extend Spine.Model.Ajax\n\n  @url: '/users'\n  @url: -> '/users'\n  scope: '2013'\n
\n\n

Using

\n\n
User.fetch()\nuser = new User()\n\nuser.url()            #=> \"/users\"\nuser.url('bands')     #=> \"/users/bands\"\n\nuser.scope = 'admin'\nuser.url()            #=> \"/admin/users\"\n
\n\n

Host

\n\n
Spine.Model.host = 'http://endpoint'\n
\n\n

Ajax mapping

\n\n
read    → GET    /collection\ncreate  → POST   /collection (201 created)\nupdate  → PUT    /collection/id\ndestroy → DELETE /collection/id\n
\n\n

Associations

\n\n
class Photo extends Spine.Model\n  @belongsTo 'album', 'Album'          # window['Album']\n  @belongsTo 'album', 'models/album'   # via require.js\n\nclass Album\n  @hasMany 'photos', 'models/photo'\n\nalbum.photos().all()\nalbum.photos().create(name: \"Vacation\")\nalbum.photos().find(id)\n\nphoto = Photo.create(album: album)\nphoto.album()\nphoto.album_id\n
\n\n

See

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "spreadsheet", "title": "Spreadsheet functions", "url": "/spreadsheet", "category": "Others", "keywords": null, "content_html": "

If

\n\n
=IF(test, then, else)\n=IF(EQ(A1, \"paid\"), \"true\", \"false\")\n
\n\n

Comparators

\n\n
=EQ(a,b)\n=NE(a,b)\n=GT(a,b)\n=GTE(a,b)\n=LT(a,b)\n=LTE(a,b)\n
\n\n

Math

\n\n
=POW(2, 32)   # 2^32\n=SIN() ACOS() etc\n=CEILING(n,sig,mode)\n=FLOOR(n,sig,mode)\n=INT(n)\n
\n\n
=SUM(range)\n
\n\n
=SUMIF(range, criteria, sum_range)\n=SUMIF(A1:A5, \">300\", B1:B5)          # if A# is >300, use B#\n
\n\n

Core

\n\n
=TO_DATE(number)\n
\n\n

Vlook

\n\n
=VLOOKUP(value, range, column_index)\n
", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "sql-join", "title": "SQL joins", "url": "/sql-join", "category": "Databases", "keywords": null, "content_html": "

Example

\n\n
SELECT * FROM order_items \\\n  LEFT OUTER JOIN orders \\\n  ON order_items.order_id = orders.id\n
\n\n

Joins are typically added to SELECT statements to add more columns and records.

\n\n

Diagram

\n\n
SELECT * FROM `A` INNER JOIN `B`\n
\n\n
┌────────┐\n│ A  ┌───┼────┐\n│    │ ∩ │    │\n└────┼───┘  B │\n     └────────┘\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
JoinWhat
Inner join
Left outer joinA +
Right outer join + B
Full outer joinA + + B
", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "stencil", "title": "Stencil", "url": "/stencil", "category": "JavaScript libraries", "keywords": ["@Component","@Prop()","@State()","render()","componentWillLoad()","componentWillUpdate()","Templating","Lifecycle"], "content_html": "

Quick-start guide

\n\n

Getting started

\n\n

JavaScript

\n\n
import { Component, Prop, State } from '@stencil/core'\n\n@Component({\n  tag: 'my-component',\n  styleUrl: 'my-component.scss'\n})\nexport class MyComponent {\n  @Prop() name: string\n  @State() isVisible: boolean = true\n\n  render () {\n    return <p>I am {this.name}!</p>\n    )\n  }\n}\n
\n\n

HTML

\n\n
<my-component name='Groot' />\n
\n\n

That’s the same example in the Readme, that’s as simple as you can get! Just use <my-component> like you would use any other HTML tag.

\n\n

DOM events

\n\n
export class MyComponent {\n  render () {\n    return (\n      <input\n        onChange={(event: UIEvent) => this.inputChanged(event)}\n      />\n    )\n  }\n\n  inputChanged (event) {\n    console.log('input changed:', event.target.value)\n  }\n}\n
\n\n

Stencil uses DOM events.

\n\n

See: Handling user input

\n\n

Multiple children

\n\n
render () {\n  return [\n    <h1>Hello there</h1>,\n    <p>This component returns multiple nodes</p>\n  ]\n}\n
\n\n

render() can return an array of elements.

\n\n

See: Complex template content

\n\n

State

\n\n

Managing state

\n\n
export class MyComponent {\n  @State() isVisible: boolean\n\n  show () {\n    this.isVisible = true\n  }\n}\n
\n\n

Just do assignments. You can’t do mutations though, see next section.

\n\n

See: Managing component state

\n\n

Updating arrays and objects

\n\n

✗ Bad

\n
this.names.push('Larry')  // ⚠️\nthis.options.show = true  // ⚠️\n
\n\n

✓ OK

\n\n
this.names = [ ...this.names, 'Larry' ]\nthis.options = { ...this.options, show: true }\n
\n\n

Mutable operations such as push() won’t work. You’ll need to assign a new copy.

\n\n

See: Updating arrays

\n\n

Slots

\n\n

Using slot

\n\n
<my-component>\n  <span>Hello, friends</span>\n</my-component>\n
\n\n

Component

\n\n
render() {\n  return <h1><slot /></h1>\n}\n
\n\n

You can pass JSX/HTML as child elements. Use the slot tag to use them inside your component.

\n\n

See: Slots

\n\n

Multiple slots

\n\n
<my-component>\n  <p slot='my-header'>Hello</p>\n  <p slot='my-footer'>Thanks</p>\n</my-component>\n
\n\n

Component

\n\n
render () {\n  return <div>\n    <header><slot name='my-header' /></header>\n    <footer><slot name='my-footer' /></footer>\n  </div>\n}\n
\n\n

See: Slots

\n\n

Lifecycle

\n\n

Lifecycle hooks

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
EventDescription
componentWillLoad()Before rendering
componentDidLoad()After rendering
componentWillUpdate()Before updating
componentDidUpdate()After updating
componentDidUnload()After unmounting
\n\n

See: Component lifecycle

\n\n

Example

\n\n
export class MyComponent {\n  componentWillUpdate () {\n    console.log('updating')\n  }\n}\n
\n\n

References

\n\n", "intro_html": "

Stencil is a compiler for web components made by the Ionic team. This guide targets Stencil v0.0.5.

", "description_html": "", "tags": null, "updated": "2019-05-08" },{ "id": "strftime", "title": "strftime format", "url": "/strftime", "category": "Others", "keywords": null, "content_html": "

{% include common/strftime_format.md title=”strftime” %}

", "intro_html": "

The strftime format is the standard date formatting for UNIX. It’s used in C, Ruby, and more.

", "description_html": "", "tags": ["Featurable"], "updated": "2017-11-27" },{ "id": "stylus", "title": "Stylus", "url": "/stylus", "category": "CSS", "keywords": null, "content_html": "

Getting started

\n\n

CSS syntax

\n\n
.box {\n  color: blue;\n\n  .button {\n    color: red;\n  }\n}\n
\n\n

Stylus is a CSS pre-processor.

\n\n

See: stylus-lang.com

\n\n

Indent syntax

\n\n
.box\n  color: blue\n\n  .button\n    color: red\n
\n\n

Also works! The colon is optional, as well. This is typically the syntax used with Stylus documents.

\n\n

Mixins

\n\n
caps-type()\n  text-transform: uppercase\n  letter-spacing: 0.05em\n
\n\n
h5\n  caps-type()\n
\n\n

See Mixins below.

\n\n

Variables

\n\n
royal-blue = #36a\n
\n\n
div\n  color: royal-blue\n
\n\n

Mixins

\n\n

Without arguments

\n\n
red-border()\n  border: solid 2px red\n
\n\n
div\n  red-border()\n
\n\n

See: Mixins

\n\n

With arguments

\n\n
border-radius(n)\n  -webkit-border-radius: n\n  border-radius: n\n
\n\n
div\n  border-radius: 2px\n  border-radius(2px)\n
\n\n

Mixins can be applied in two different ways.

\n\n

Argument defaults

\n\n
border-radius(n = 2px)\n  -webkit-border-radius: n\n
\n\n

Block mixins

\n\n
mobile()\n  @media (max-width: 480px)\n    {block}\n
\n\n
+mobile()\n  width: 10px\n
\n\n

See: Block mixins

\n\n

Rest params

\n\n
shadow(offset-x, args...)\n  box-shadow: offset-x args\n  margin-top: offset-x\n
\n\n
#login\n  shadow: 1px 2px 5px #eee\n
\n\n

See: Rest params

\n\n

Functions

\n\n

Functions

\n\n
add(a, b)\n  a + b\n
\n\n
body\n  padding: add(10px, 5)\n
\n\n

See: Functions

\n\n

Argument defaults

\n\n
add(a, b = 2)\n  a + b\n
\n\n

See: Argument defaults

\n\n

Named parameters

\n\n
shadow(x, y)\n  x y (y * 1.5) #000\n
\n\n
.button\n  box-shadow: shadow(x: 2, y: 4)\n
\n\n

See: Named parameters

\n\n

Multiple return values

\n\n
sizes()\n  8px 16px\n
\n\n
sizes()[0]  // → 8px\nsizes()[1]  // → 16px\n
\n\n

See: Multiple return values

\n\n

Values

\n\n

Conditional assignment

\n\n
royal-blue = #36a\nroyal-blue ?= #89f\n
\n\n
div\n  color: royal-blue  // #36a\n
\n\n

?= will only set a variable if it’s previously unset.

\n\n

See: Conditional assignment

\n\n

Property lookup

\n\n
.logo\n  width: w = 150\n  margin-left: -(w / 2)\n
\n\n

See: Property lookup

\n\n

Interpolation

\n\n
-{prefix}-border-radius: 2px\n
\n\n

See: Interpolation

\n\n

Color operators

\n\n
#888 + 50%    // → #c3c3c3 (lighten)\n#888 - 50%    // → #444 (darken)\n#f00 + 50deg  // → #ffd500 (hue)\n
\n\n

Casting

\n\n
n = 5px\n
\n\n
foo: (n)em\nfoo: (n * 5)%\n
\n\n

Lookup

\n\n
light-blue = #3bd\nname = 'blue'\nlookup('light-' + name)\n
\n\n

See: lookup

\n\n

Advanced features

\n\n

Conditional

\n\n
if color == blue\n  display: block\nelse if true and true\n  display: inline\nelse if 'hey' is not 'bye'\n  display: flex\nelse\n  display: none\n
\n\n

Aliases:

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
==is
!=is not
!=isnt
\n\n

See: Conditionals

\n\n

For loops

\n\n
font-size-1 = 10px\nfont-size-2 = 20px\nfont-size-3 = 30px\n\nfor i in 1..3\n  .text-{i}\n    font-size: lookup('font-size-' + i)\n
\n\n

Definition check

\n\n
if ohnoes is defined\n  color: blue\n
\n\n

See: is defined

\n\n

False values

\n\n
0\nnull\nfalse\n''\n
\n\n

Type check

\n\n
if val is a 'string'\nif val is a 'ident'\nif #fff is a 'rgba'    // → true\n
\n\n

See: Instance check

\n\n

Built-in functions

\n\n

Color functions

\n\n
alpha(#fff)   //→ 1\nalpha(rgba(0, 0, 0, 0.2))   //→ 0.2\n
\n\n
dark(black)  //→ true\nlight(black) //→ false\n
\n\n
hue(#0a0)         //→ 50deg\nsaturation(#f00)  //→ 100%\nlightness(#f00)   //→ 50%\nluminosity(#f00)  //→ 0.2126\n
\n\n
hue(#0a0, 0deg)\nsaturation(#f00, 50%)\nlightness(#f00)\n
\n\n
lighten(color, 10%)\ndarken(color, 10%)\nsaturate(color, 10%)\ndesaturate(color, 10%)\ninvert(color)\n
\n\n
tint(color, 50%)  // mix with white\nshade(color, 50%) // mix with black\n
\n\n
unquote(string)\n
\n\n

See: Built-in functions

\n\n

Image size

\n\n
width:  image-size('tux.png')[0]\nheight: image-size('tux.png')[1]\n
\n\n

Returns the width and height of a given image.

\n\n

See: image-size

\n\n

Caching

\n\n
size($width)\n  +cache('w' + $width)\n    width: $width\n.a { size: 10px }\n.b { size: 10px }\n
\n\n
// yields: .a, b { width: 10px }\n
\n\n

Applies its contents to the given selector on the first call, but would @extend the first call’s selector at the second call with the same params.

\n\n

See: cache

\n\n

Add Property

\n\n
gradient(color)\n  add-property('background-image', linear-gradient(top, color, darken(color, 20%)))\n  color\n
\n\n
body\n  background: gradient(red)\n
\n\n

See: add-property

\n\n

sprintf

\n\n
'-webkit-gradient(%s, %s, %s)' % (linear (0 0) (0 100%))\n// → -webkit-gradient(linear, 0 0, 0 100%)\n
\n\n
s(\"rgba(0, 0, 0, %s)\", 0.3)\n
\n\n

See: s

\n\n

Embed URL

\n\n
background: embedurl('logo.png')\n// → background: url(\"data:image/png;base64,…\")\n
\n\n

See: embedurl

", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2017-10-30" },{ "id": "sublime-text", "title": "Sublime Text", "url": "/sublime-text", "category": "Apps", "keywords": null, "content_html": "

Select & Expand

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
⌘ Dselect current word (repeat to include next instance of word)
⌘ Lselect current line (repeat to include next line)
⌘ ⇧ Lsplit selection into multiple lines
⌘ ⇧ Aselect text inside tag (repeat to expand)
Ctrl ⇧ Mselect to curly or angle brackets (repeat to expand)
\n\n

Replace ⌘ with Ctrl on Windows and Linux.

\n\n

Code Folding

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
⌘ Alt [fold closest block
⌘ Alt ]unfold closest block
⌘ K ⌘ 1fold all first level code blocks
⌘ K ⌘ 2fold all second level code blocks
⌘ K ⌘ 3 (etc)fold all third level code blocks (etc)
⌘ K ⌘ Tfold all HTML attributes
⌘ K ⌘ 0unfold everything
\n\n

Editing

\n\n\n \n \n \n \n \n \n \n \n \n \n
⌘ ⇧ Dduplicate current line/selection
⌘ ⇧ Kdelete current line/selection
\n\n

Goto

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
⌘ Pgoto anything
⌘ Ggoto line number
⌘ Rgoto symbol
⌘ P, :goto line number (enter number after :)
⌘ P, #goto and list fuzzy-matches of string (enter characters after #)
⌘ P, @goto and list symbol (begin typing symbol name after @)
\n\n

Command line

\n\n
$ subl .\n$ subl README.md\n
\n\n

Use subl to open files in Sublime from the terminal.

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "superagent", "title": "Superagent", "url": "/superagent", "category": "JavaScript libraries", "keywords": null, "content_html": "

Response object

\n
  res: {\n    // The HTTP Status Code (see: httpstatuses.com for definitions on HTTP status codes)\n    status: 202,\n    // True when res.status is 2xx\n    ok: true,\n    // True when res.status is 4xx or 5xx\n    error: false,\n    // True when res.status is 4xx\n    clientError: false,\n    // True when res.status is 5xx\n    serverError: false,\n\n    // True when res.status == 202\n    accepted: true,\n    // True when res.status == 204 || res.status == 1223 \n    noContent: false,\n    // True when res.status == 400\n    badRequest: false,\n    // True when res.status == 401\n    unauthorized: false,\n    // True when res.status == 406\n    notAcceptable: false,\n    // True when res.status == 404\n    notFound: false,\n    // True when res.status == 403\n    forbidden: false,\n\n    // Unparsed response text\n    text: '{\"user\":{\"username\":\"JohnDoe\",\"role\":\"admin\"}}'\n\n    // Parsed response text (only if response is 'application/json' or 'application/x-www-form-urlencoded'\n    body: {\n      // Example of parsed object from res.text\n      user: {\n        username: 'JohnDoe',\n        role: 'admin'\n      }\n    }\n\n    // The content-type (parsed from headers)\n    type: 'application/json'\n    // The charset (parsed from headers)\n    charset: 'UTF-8'\n    // Header object with each header field as a property\n    headers: {\n      'content-type': 'application/json; charset=UTF-8',\n      ...\n    }\n}\n
", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": "2018-04-21" },{ "id": "tabular", "title": "Tabular", "url": "/tabular", "category": "Vim", "keywords": null, "content_html": "

Common usage

\n\n

Tables

\n\n
:Tab /|\n
\n\n
| Fruit  | Color  |\n| -----  | -----  |\n| Apple  | Red    |\n| Banana | Yellow |\n| Kiwi   | Green  |\n
\n\n

Variables

\n\n
:Tab /=\n
\n\n
title = \"Hello\"\nsrc   = \"image.jpg\"\nwidth = 640\n
\n\n

Colons

\n\n
:Tab /:\\zs/l0l1\n
\n\n
title:       \"Hello world\"\ndescription: \"This is a description\"\nsrc:         \"image.jpg\"\nheight:      320\nwidth:       640\n
\n\n

Tab command

\n\n

Basic example

\n\n
:Tab /:\n
\n\n
title : My picture\nsrc   : img.jpg\n
\n\n

Right align

\n\n
:Tab /:/r0\n
\n\n
title:My picture\n  src:   img.jpg\n
\n\n

The \\zs atom

\n\n
:Tab /:\\zs\n
\n\n
title:  My picture\nsrc:    img.jpg\n
\n\n

The \\zs atom will exclude the : from the search match.

\n\n

Specifier

\n\n
:Tab /:/r1c1l0\n
\n\n
title : My picture\n  src : img.jpg\n
\n\n

Explanation

\n\n\n\n

Regexp

\n\n
:Tab /^[^,]*\\zs,/r0\n
\n\n
abc,hello\n  c,hi there\n  a,yo\n
\n\n

Specifiers

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SpecifierDescription
r1c1l0multiple specifiers, one per column
(the separator counts as a column)
lNLeft-align (with N spaces padding)
rNRight-align (with N spaces padding)
cNCenter-align (with N spaces padding)
\n\n

Also see

\n\n", "intro_html": "

Tabular is a Vim script for text alignment.

", "description_html": "", "tags": null, "updated": "2017-10-11" },{ "id": "tape", "title": "Tape", "url": "/tape", "category": "JavaScript libraries", "keywords": null, "content_html": "
test('things', (t) => {\n  t.plan(1)\n\n  t.equal('actual', 'expected')\n  t.equal('actual', 'expected', 'should be equal') // messages are optional\n\n  t.end(err)\n  t.fail('msg')\n  t.pass('msg')\n  t.timeoutAfter(2000)\n  t.skip('msg')\n\n  t.ok(value, 'is truthy')\n  t.notOk(value, 'is falsy')\n  t.error(err, 'is falsy (print err.message)')\n\n  t.equal(actual, expected, 'is equal')\n  t.notEqual\n\n  t.deepEqual(actual, expected, 'is equal (use node's deepEqual)')\n  t.notDeepEqual\n\n  t.looseEqual(actual, expected, 'is equal (use node's deepEqual with ==)')\n  t.notLooseEqual\n\n  t.throws(fn, /FooError/)\n  t.throws(fn, FooError /* class */)\n  t.doesNotThrow\n\n  t.comment('message')\n})\n
\n\n
test.only((t) => { ... })\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "textile", "title": "Textile", "url": "/textile", "category": "Markup", "keywords": null, "content_html": "

Reference

\n\n

Inlines

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescription
_em_ 
*strong* 
__bold-italic__ 
@code@ 
??citation?? 
-strikethrough- 
+insertion+ 
%span%HTML tag
%{color:red}formatting%CSS styles
\n\n

Blocks

\n\n
h1. Header 1\n
\n\n
h2. Header 2\n
\n\n
bq. Blockquote\n
\n\n
p(classname). Class.\n
\n\n
p(#id). ID.\n
\n\n

Lists

\n\n
## ordered list\n
\n\n
* unordered list\n
\n\n

Links

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescription
\"Hypertext\":index.htmlLink
\"Text link\":link
[link]http://link.com
Link via reference
\n\n

Images

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescription
!image.jpg!Image
!image.jpg(title text)! 
!image.jpg!:link.html 
!>right.jpg! 
\n\n

Escaped HTML

\n\n
<pre>\nI am <b>very serious.</b> -- this\nwill get escaped.\n</pre>\n
\n\n

Line breaks

\n\n
Line breaks.\nJust break the lines.\n
\n\n

Entities

\n\n
one(TM), two(R), three(C).\n
\n\n

Horizontal line

\n\n
--\n
\n\n

Footnotes

\n\n
Footnotes[1].\n
\n\n
fn1. Something.\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-20" },{ "id": "tig", "title": "Tig", "url": "/tig", "category": "Git", "keywords": null, "content_html": "

Installing

\n\n
# MacOS + Homebrew\n$ brew install tig --HEAD\n
\n\n
# Ubuntu\n$ sudo apt install tig\n
\n\n

Invocation

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CommandDescription
tig 
tig statusStatus
tig blame FILEBlame
tig masterShow a branch
tig test..masterShow difference between two branches
tig FILEShow history of file
tig v0.0.3:READMEShow contents of file in a specific revision
\n\n

You can substitute git logtig.

\n\n

Shortcut keys

\n\n

Switching views

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
mMain view
sStatus
tTree (files)
yStash view
gGrep
hHelp
\n\n

All views

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
j kUp/down
J KNext/previous
<Back
RRefresh
qClose
QClose all
^NNext on parent view
^PPrevious on parent view
\n\n

m - Main view

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DToggle date display modes
AToggle author display modes
XToggle commit sha
CCherry pick a commit
\n\n

s - Stage view

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
uStage/unstage file or chunk
!Revert file or chunk
CCommit
MMerge
1Stage line
[ ]Increase/decrease the diff context
\n\n

h - Branch view

\n\n\n \n \n \n \n \n \n
iChange sort header
\n\n

h - Blame view

\n\n\n \n \n \n \n \n \n
,Parent commit
", "intro_html": "", "description_html": "", "tags": null, "updated": "2018-11-16" },{ "id": "tmux", "title": "tmux", "url": "/tmux", "category": "CLI", "keywords": null, "content_html": "

Commands

\n\n
$ tmux\n  -u        # UTF8 mode\n  -S ~/.tmux.socket\n
\n\n

Sessions

\n\n
$ tmux new\n$ tmux new -s session_name\n\n$ tmux attach # Default session\n$ tmux attach -t session_name\n\n$ tmux switch -t session_name\n\n$ tmux ls     # List sessions\n\n$ tmux detach\n
\n\n

Windows

\n\n
$ tmux new-window\n
\n\n

Help

\n\n
C-b ?\n
\n\n

Scrolling

\n\n
C-b [       # Enter scroll mode then press up and down\n
\n\n

Copy/paste

\n\n
C-b [       # 1. Enter scroll mode first.\nSpace       # 2. Start selecting and move around.\nEnter       # 3. Press enter to copy.\nC-b ]       # Paste\n
\n\n

Panes

\n\n
C-b %       # vert\nC-b \"       # horiz\nC-b hkjl    # navigation\nC-b HJKL    # resize\nC-b o       # next window\nC-b q       # show pane numbers\nC-b x       # close pane\n\nC-b { or }  # move windows around\n
\n\n

Windows

\n\n
C-b c       # New window\nC-b 1       # Go to window 1\nC-b n       # Go to next window\nC-b p       # Go to previous window\nC-b w       # List all window\n
\n\n

Detach/attach

\n\n
C-b d       # Detach\nC-b ( )     # Switch through sessions\n$ tmux attach\n
\n\n

Niceties

\n\n
C-b t    # Time\n
\n\n

Status formats

\n\n
setw -g window-status-format `#[fg=8,bg=default]#I`\n
\n\n

See message-command-style in the man page.

\n\n

Attribute/colors

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
#[fg=1]standard color
#[fg=yellow]yellow
#[bold]bold
#[fg=colour240]256 color
#[fg=default]default
#[fg=1,bg=2]combinations
#[default]reset
\n\n

Colors

\n\n\n\n

Attributes

\n\n\n\n

Variables

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
#(date)shell command
#Iwindow index
#Ssession name
#Wwindow name
#Fwindow flags
#HHostname
#hHostname, short
#Dpane id
#Ppane index
#Tpane title
\n\n

Options

\n\n
set -g status-justify [left|centre|right]\nset -g status-left '...'\n\nsetw -g window-status-style\nsetw -g window-status-activity-style\nsetw -g window-status-bell-style\nsetw -g window-status-content-style\nsetw -g window-status-current-style\nsetw -g window-status-last-style\n\nsetw -g window-status-format\nsetw -g window-status-current-format\n\nsetw -g window-status-separator\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "tomdoc", "title": "Tomdoc", "url": "/tomdoc", "category": "Markup", "keywords": null, "content_html": "

Tomdoc

\n\n
# Public: Duplicate some text an arbitrary number of times.\n#\n# text  - The String to be duplicated.\n# count - The Integer number of times to duplicate the text.\n#\n# Examples\n#\n#   multiplex('Tom', 4)\n#   # => 'TomTomTomTom'\n#\n# Returns the duplicated String.\ndef multiplex(text, count)\n  text * count\nend\n
\n\n

See tomdoc.org.

\n\n

Tags

\n\n\n\n

Options

\n\n
# options - The Hash options used to refine the selection (default: {}):\n#           :color  - The String color to restrict by (optional).\n#           :weight - The Float weight to restrict by. The weight should\n#                     be specified in grams (optional).\n
\n\n

Yields

\n\n
# Yields the Integer index of the iteration.\n
\n\n
# Returns the duplicated String.\n
\n\n
# Returns nothing.\n
\n\n
# Raises Errno::ENOENT if the file can't be found.\n
\n\n
# Returns something else and this is a wrapped\n#   multi-line comment.\n
\n\n

Signatures

\n\n
# Signature\n#\n#   find_by_<field>[_and_<field>...](args)\n#\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "top", "title": "top", "url": "/top", "category": "CLI", "keywords": null, "content_html": "

Shortcuts

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
hshows help
qquits the program
mswitches memory view
kkills process
Shift+psorts by CPU usage
Shift+msorts by memory usage
Shift+rreverses sorting
Shift+lsearches for string
oadds a filter
=clears filters
", "intro_html": "

See the processes in your Unix machine.

", "description_html": "", "tags": null, "updated": "2020-01-01" },{ "id": "travis", "title": "Travis.yml", "url": "/travis", "category": "Devops", "keywords": null, "content_html": "

Reference

\n\n

Node.js

\n\n
language: node_js\nnode_js:\n  - '4'\n
\n\n

Defaults install to npm install, and defaults test to npm test.

\n\n

Ruby

\n\n
language: ruby\nrvm:\n  - 2.0.0\n  - 1.9.3\n  - 1.8.7\n
\n\n

Defaults install to bundle install, defaults test to rake.

\n\n

Build lifecycle

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Lifecycle
before_install
install
before_script
script
after_success or after_failure
after_script
before_deploy (optional)
deploy (optional)
after_deploy (optional)
\n\n

Branches

\n\n
branches:\n  except: ['..']\n  only: ['master']\n
\n\n

Environment vars

\n\n
env:\n  - 'rack=master'\n  - 'rack=1.3.4'\n
\n\n

Custom test command

\n\n
script: make test\nbefore_script: make pretest\nafter_script:  make clean\n\nbefore_script:\n  - make pretest1\n  - make pretest2\n
\n\n

Branches

\n\n
branches:\n  except:\n    - legacy\n\n  only:\n    - gh-pages\n    - /^deploy/\n
\n\n

Apt packages

\n\n
before_install:\n  - sudo apt-get update -q\n  - sudo apt-get install gcc-4.8 -y\n
\n\n

https://docs.travis-ci.com/user/installing-dependencies/

\n\n

Etc

\n\n
gemfile:\n  - gemfiles/Gemfile.rails-2.3.x\n  - gemfiles/Gemfile.rails-3.0.x\n
\n\n

References

\n\n", "intro_html": "

Quick reference for Travis CI yaml configuration. See official documentation.

", "description_html": "", "tags": null, "updated": null },{ "id": "typescript", "title": "TypeScript", "url": "/typescript", "category": "JavaScript libraries", "keywords": null, "content_html": "

TypeScript is just like ES2015 with type-checking. All ES2015 (classes, etc) should work.

\n\n

Basic types

\n\n
any\nvoid\n\nboolean\nnumber\nstring\n\nnull\nundefined\n\nstring[]          /* or Array<string> */\n[string, number]  /* tuple */\n\nstring | null | undefined   /* union */\n\nnever  /* unreachable */\n
\n\n
enum Color {Red, Green, Blue = 4}\nlet c: Color = Color.Green\n
\n\n

Declarations

\n\n
let isDone: boolean\nlet isDone: boolean = false\n
\n\n
function add (a: number, b: number): number {\n  return a + b\n}\n\n// Return type is optional\nfunction add (a: number, b: number) { ... }\n
\n\n

Type assertions

\n\n

Variables

\n
let len: number = (input as string).length\nlet len: number = (<string> input).length  /* not allowed in JSX */\n
\n\n

Functions

\n
function object(this: {a: number, b: number}, a: number, b: number) {\n  this.a = a;\n  this.b = b;\n  return this;\n}\n\n// this is used only for type declaration\nlet a = object(1,2);\n// a has type {a: number, b: number}\n
\n\n

Interfaces

\n\n

Inline

\n\n
function printLabel (options: { label: string }) {\n  console.log(options.label)\n}\n\n// Note the semicolon\nfunction getUser (): { name: string; age?: number } {\n}\n
\n\n

Explicit

\n\n
interface LabelOptions {\n  label: string\n}\n\nfunction printLabel(options: LabelOptions) { ... }\n
\n\n

Optional properties

\n\n
interface User {\n  name: string,\n  age?: number\n}\n
\n\n

Read only

\n\n
interface User {\n  readonly name: string\n}\n
\n\n

Dynamic keys

\n\n
{\n  [key: string]: Object[]\n}\n
\n\n

Type aliases

\n\n
type Name = string | string[]\n
\n\n

Function types

\n\n
interface User { ... }\n\nfunction getUser(callback: (user: User) => any) { callback({...}) }\n\ngetUser(function (user: User) { ... })\n
\n\n

Classes

\n\n
class Point {\n  x: number\n  y: number\n  static instances = 0\n  constructor(x: number, y: number) {\n    this.x = x\n    this.y = y\n  }\n}\n
\n\n

Inheritance

\n\n
class Point {...}\n\nclass Point3D extends Point {...}\n\ninterface Colored {...}\n\nclass Pixel extends Point implements Colored {...}\n
\n\n

Short fields initialisation

\n\n
class Point {\n  static instances = 0;\n  constructor(\n    public x: number,\n    public y: number,\n  ){}\n}\n
\n\n

Fields which do not require initialisation

\n
class Point {\n  public someUselessValue!: number;\n  ...\n}\n
\n\n

Generics

\n\n
class Greeter<T> {\n  greeting: T\n  constructor(message: T) {\n    this.greeting = message\n  }\n}\n\nlet greeter = new Greeter<string>('Hello, world')\n
\n\n

Modules

\n\n
export interface User { ... }\n
\n\n

Type extraction

\n\n
interface Building {\n  room: {\n    door: string,\n    walls: string[],\n  };\n}\n\ntype Walls = Building['room']['walls']; // string[]\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ubuntu", "title": "Ubuntu", "url": "/ubuntu", "category": "Others", "keywords": null, "content_html": "

Aptitude stuff

\n\n
aptitude search mysql       # Look for something\ndpkg -S `which tsclient`    # What package does it belong to?\ndpkg -L aria2c              # What does this package provide?\ndpkg -i *.deb               # Install a deb file\ndpkg -s nodejs              # Show info\n\ndpkg --get-selections       # list installed packages\n
\n\n

Apt archives path

\n\n
/var/cache/apt/archives\n
\n\n

List services

\n\n
service --status-all\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "umdjs", "title": "Universal JS module loader", "url": "/umdjs", "category": "JavaScript libraries", "keywords": null, "content_html": "

With dependency

\n\n
;(function (root, factory) {\n\n  if (typeof define === 'function' && define.amd) {\n    define(['jquery'], factory);\n  } else if (typeof exports === 'object') {\n    module.exports = factory(require('jquery'));\n  } else {\n    root.YourModule = factory(root.jQuery);\n  }\n\n}(this, function (jquery) {\n  return {};\n}));\n
\n\n

No dependencies

\n\n
;(function (root, factory) {\n\n  if (typeof define === 'function' && define.amd) {\n    define(factory);\n  } else if (typeof exports === 'object') {\n    module.exports = factory();\n  } else {\n    root.YourModule = factory();\n  }\n\n}(this, function () {\n  return {};\n}));\n
\n\n

Supports circular references

\n\n
(function (root, factory) {\n\n  if (typeof define === 'function' && define.amd) {\n    define(['exports', 'jquery'], factory);\n  } else if (typeof exports === 'object') {\n    factory(exports, require('jquery'));\n  } else {\n    factory((root.YourModule = {}), root.jQuery);\n  }\n\n}(this, function (exports, jQuery) {\n  exports.action = function () {};\n}));\n
\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "underscore-string", "title": "Underscore-string", "url": "/underscore-string", "category": "JavaScript libraries", "keywords": null, "content_html": "

Usage

\n\n
// Use it like so:\n_.str.trim(\"hey\");\n_s.trim(\"hey\");\n\n// Unless you do:\n_.mixin(_.string.exports());\n\n// So you can:\n_.trim(\"hey\");\n_(\"hey\").trim();\n
\n\n

Trimming

\n\n
_.truncate(\"Hello world\", 4) // => \"Hell...\"\n_.prune(\"Hello world\", 5)    // => \"Hello...\"\n\n_.trim(\" foo \")              // => \"foo\"\n_.trim(\"-foo-\", '-')         // => \"foo\"\n_.ltrim\n_.rtrim\n
\n\n

Numbers

\n\n
_.numberFormat(1000, 2)  // => \"1,000.00\"\n
\n\n

Caps

\n\n
_.capitalize(\"foo bar\")       // => \"Foo Bar\"\n_.humanize(\"hey-there foo\")   // => \"Hey there foo\"\n_.titleize('My name is hi')   // => \"My Name Is Hi\"\n\n_.dasherize('MozTransform')   // => \"-moz-transform\"\n_.underscored('MozTransform') // => \"moz_transform\"\n_.classify('-moz-transform')  // => \"MozTransform\"\n_.camelize('moz_transform')   // => \"MozTransform\"\n\n_.slugify(\"hey there\")        // => \"hey-there\"\n\n_.swapCase(\"hELLO\")           // => \"Hello\"\n
\n\n

Checks

\n\n
_.startsWith('image.gif', 'image') // => true\n_.endsWith('image.gif', '.gif')    // => true\n_.isBlank(\" \")                     // => true (also for \"\\n\", \"\")\n
\n\n

HTML

\n\n
_.escapeHTML(\"<div>\")\n_.unescapeHTML(\"&lt;div&gt;\")\n_.stripTags(\"<div>hi</div>\")\n
\n\n

Quote

\n\n
_.quote(\"hi\", '\"') // => '\"hi\"'\n_.unquote('\"hi\"')  // => \"hi\"\n
\n\n

Splits

\n\n
_.lines(\"hi\\nthere\")     // => [\"hi\",\"there\"]\n_.words(\"hi  there you\") // => [\"hi\",\"there\",\"you\"]\n
\n\n

Sprintf

\n\n
_.sprintf(\"%.1f\", 1.17)\n
\n\n

Pad

\n\n
_.pad(\"1\", 8)               // => \"       1\"\n_.pad(\"1\", 8, \"0\")          // => \"00000001\"\n_.pad(\"1\", 8, \" \", \"right\") // => \"1       \"\n_.pad(\"1\", 8, \" \", \"both\")  // => \"    1   \"\n\n_.lpad(..)  // same as _.pad(.., 'left')\n_.rpad(..)  // same as _.pad(.., 'right')\n_.lrpad(..) // same as _.pad(.., 'both')\n
\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "unicode", "title": "Unicode symbols", "url": "/unicode", "category": "Others", "keywords": null, "content_html": "
✈   \\u2708 airplane\n❄   \\u2744 snowflake\n⚑   \\u2691 flag\n☯   \\u262f yinyang\n♞   \\u265e horse\n☀   \\u2600 rays\n⚠   \\u26a0 warning\n\n★   star\n☆   star2\n\n⚐   \\u2690 flag\n⚑   \\u2691 flag\n
\n\n

Bullets

\n\n
•   \\u2022\n·   \\u00b7\n┄   \\u2504\n—   \\u2014 (mdash)\n–   \\u2013 (ndash)\n◦   \\u25e6 circle\n
\n\n

Checks

\n\n
✓   \\u2713 check\n✕   \\u2715\n✗   \\u2717 x mark\n✘   \\u2718 x mark bold\n❏   \\u274f checkbox\n×   times\n
\n\n

Spinners

\n\n
  ◜◠◝◞◡◟\n  ❘❙❚\n
\n\n

Triangles and arrows

\n\n
▲\n▼\n▶\n\n⬅   \\u2b05\n⬆   \\u2b06\n⬇   \\u2b07\n\n◢\n◣\n◤\n◥\n\n«   &laquo;\n»   &raquo;\n‹   &lsaquo;\n›   &rsaquo;\n•   &middot;\n\n⌘ – &#x2318; – &#8984; – Command Key\n⌥ – &#x2325; – &#8997; – Option Key\n⇧ – &#x21E7; – &#8679; – Shift Key\n⎋ – &#x238B; – &#9099; – ESC Key\n⇪ – &#x21ea; – &#8682; – Capslock\n⏎ – &#x23ce; – &#9166; – Return\n⌫ – &#x232b; – &#9003; – Delete / Backspace\n\n▸   \\u25b8 right arrow\n▹\n\n◇   \\u25c7\n◆\n\n◐\n◑\n◒\n◓\n\n\n♠   \\u2660\n♣   \\u2663\n♥   \\u2665\n♦   \\u2666\n\n\n✂  scissors\nℹ information &#008505;\n♡ heart &#009825;\n⚙ cog or gear &#009881;\n✉ envelope &#009993;\n✎ pencil &#009998;\n
\n\n

JavaScript

\n\n
\"x\".charCodeAt(0)\n\"x\".charCodeAt(0).toString(16)\n\nhttp://www.danshort.com/HTMLentities/index.php?w=dingb\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vagrant", "title": "Vagrant", "url": "/vagrant", "category": "Devops", "keywords": null, "content_html": "

Get started

\n\n

Add some base boxes:

\n\n
vagrant box add precise64 http://files.vagrantup.com/precise64.box\n
\n\n

Work it:

\n\n
mkdir test_box\ncd test_box\nvagrant init precise64\n
\n\n

Run it:

\n\n
vagrant up\nvagrant ssh\n
\n\n

To stop, use one of the following:

\n\n
vagrant ssh        # then: sudo shutdown -h now\nvagrant suspend\nvagrant destroy    # !!\n
\n\n

Also see

\n\n", "intro_html": "

Vagrant lets you build isolated virtual environments for your apps.

", "description_html": "", "tags": null, "updated": null },{ "id": "vagrantfile", "title": "Vagrantfile", "url": "/vagrantfile", "category": "Devops", "keywords": null, "content_html": "

Vagrantfile

\n\n
Vagrant.configure(\"2\") do |config|\n  # All Vagrant configuration is done here. The most common configuration\n  # options are documented and commented below. For a complete reference,\n  # please see the online documentation at vagrantup.com.\n\n  # Every Vagrant virtual environment requires a box to build off of.\n  config.vm.box = \"precise64\"\n\n  # The url from where the 'config.vm.box' box will be fetched if it\n  # doesn't already exist on the user's system.\n  # config.vm.box_url = \"http://domain.com/path/to/above.box\"\n\n  # Create a forwarded port mapping which allows access to a specific port\n  # within the machine from a port on the host machine. In the example below,\n  # accessing \"localhost:8080\" will access port 80 on the guest machine.\n  # config.vm.network :forwarded_port, guest: 80, host: 8080\n\n  # Create a private network, which allows host-only access to the machine\n  # using a specific IP.\n  # config.vm.network :private_network, ip: \"192.168.33.10\"\n\n  # Create a public network, which generally matched to bridged network.\n  # Bridged networks make the machine appear as another physical device on\n  # your network.\n  # config.vm.network :public_network\n\n  # If true, then any SSH connections made will enable agent forwarding.\n  # Default value: false\n  # config.ssh.forward_agent = true\n\n  # Share an additional folder to the guest VM. The first argument is\n  # the path on the host to the actual folder. The second argument is\n  # the path on the guest to mount the folder. And the optional third\n  # argument is a set of non-required options.\n  # config.vm.synced_folder \"../data\", \"/vagrant_data\"\n\n  # Provider-specific configuration so you can fine-tune various\n  # backing providers for Vagrant. These expose provider-specific options.\n  # Example for VirtualBox:\n  #\n  # config.vm.provider :virtualbox do |vb|\n  #   # Don't boot with headless mode\n  #   vb.gui = true\n  #\n  #   # Use VBoxManage to customize the VM. For example to change memory:\n  #   vb.customize [\"modifyvm\", :id, \"--memory\", \"1024\"]\n  # end\n  #\n  # View the documentation for the provider you're using for more\n  # information on available options.\n\n  # Enable provisioning with Puppet stand alone.  Puppet manifests\n  # are contained in a directory path relative to this Vagrantfile.\n  # You will need to create the manifests directory and a manifest in\n  # the file precise64.pp in the manifests_path directory.\n  #\n  # An example Puppet manifest to provision the message of the day:\n  #\n  # # group { \"puppet\":\n  # #   ensure => \"present\",\n  # # }\n  # #\n  # # File { owner => 0, group => 0, mode => 0644 }\n  # #\n  # # file { '/etc/motd':\n  # #   content => \"Welcome to your Vagrant-built virtual machine!\n  # #               Managed by Puppet.\\n\"\n  # # }\n  #\n  # config.vm.provision :puppet do |puppet|\n  #   puppet.manifests_path = \"manifests\"\n  #   puppet.manifest_file  = \"init.pp\"\n  # end\n\n  # Enable provisioning with chef solo, specifying a cookbooks path, roles\n  # path, and data_bags path (all relative to this Vagrantfile), and adding\n  # some recipes and/or roles.\n  #\n  # config.vm.provision :chef_solo do |chef|\n  #   chef.cookbooks_path = \"../my-recipes/cookbooks\"\n  #   chef.roles_path = \"../my-recipes/roles\"\n  #   chef.data_bags_path = \"../my-recipes/data_bags\"\n  #   chef.add_recipe \"mysql\"\n  #   chef.add_role \"web\"\n  #\n  #   # You may also specify custom JSON attributes:\n  #   chef.json = { :mysql_password => \"foo\" }\n  # end\n\n  # Enable provisioning with chef server, specifying the chef server URL,\n  # and the path to the validation key (relative to this Vagrantfile).\n  #\n  # The Opscode Platform uses HTTPS. Substitute your organization for\n  # ORGNAME in the URL and validation key.\n  #\n  # If you have your own Chef Server, use the appropriate URL, which may be\n  # HTTP instead of HTTPS depending on your configuration. Also change the\n  # validation key to validation.pem.\n  #\n  # config.vm.provision :chef_client do |chef|\n  #   chef.chef_server_url = \"https://api.opscode.com/organizations/ORGNAME\"\n  #   chef.validation_key_path = \"ORGNAME-validator.pem\"\n  # end\n  #\n  # If you're using the Opscode platform, your validator client is\n  # ORGNAME-validator, replacing ORGNAME with your organization name.\n  #\n  # If you have your own Chef Server, the default validation client name is\n  # chef-validator, unless you changed the configuration.\n  #\n  #   chef.validation_client_name = \"ORGNAME-validator\"\nend\n
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vainglory", "title": "Vainglory", "url": "/vainglory", "category": "Others", "keywords": null, "content_html": "

T3 items by use

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
UseCPWPUtil
Anti-armor/shieldMythBonesaw, Tension 
Stacking damageMythBreak 
LifestealEveSerpent, Shiv 
Raw powerShatterglassSorrowblade 
Burst damageAftershockTension 
Attack speedACTornado, Break 
Critical Monocle 
Auto-attack damageAC, AftershockeverythingStormcrown
CooldownClockwork, AftershockSpellswordStormcrown, Contraption, Nullwave, Halcyon Boots
SlowFrostburn Shiversteel
Reflex block  Aegis (self/shield)
Crucible (team/HP)
Ability repeatEcho  
\n\n

Tier 3 items

\n\n

Crystal power

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ItemCostCPUse
AS: Aftershock2400+35 cpBasic dmg, atk speed
+basic dmg after ability, +25% cooldown, +2.5 recharge
EoH: Eve of Harvest2600+55 cpLifesteal
+10% lifesteal, +250 energy, +5 recharge
AC: Alternating Current2800+60 cpBasic dmg
+basic dmg based on CP, +65% atk speed
BM: Broken Myth2150+70 cpStack dmg
+10% shield pierce, stacking dmg
FB: Frostburn2600+100 cpSlow
slow for 1.5s at (10% + 1% per 10CP)
SG: Shatterglass3000+150 cpRaw power
-
CW: Clockwork2500+30% cpCooldown
+40% cooldown, +250 energy, +7.5 recharge
Echo2500? Ability repeat
+250 energy, +4 recharge
\n\n

Weapon power

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ItemCostWPOther
TT: Tornado Trigger2600 Atk speed
+75% atk speed, +20% crit change, +20% crit dmg
BS: Bonesaw2700+15 wpArmor shred
stacking armor shred
TB: Tension Bow2300+45 wpBonus dmg
bonus dmg every 6s, +8% armor pierce
TM: Tyrant’s Monocle2750+50 wpCrit
+40% crit chance, +20% crit dmg
BP: Breaking Point2600+55 wpStacking dmg
stacking weapon dmg, +35% atk speed
SM: Serpent Mask2800+85 wpLifesteal
stacking lifesteal, +10% lifesteal
SB: Sorrowblade3100+150 wpRaw power
-
PS: Poisoned Shiv2250+30 wpMortal wounds
mortal wounds for 2s, +10% lifesteal, +30% atk speed
SS: Spellsword?+90 wpCooldown
?
\n\n

Utilities

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ItemCostHPUse
Halcyon Chargers2300+200 hp👟 Boots
+15% cooldown, +250 energy, +4 recharge
Stormcrown2200+200 hp🔴 Bonus dmg
+30% cooldown, +4 recharge, bonus true damage
Journey Boots1900+250 hp👟 Boots
damaging heroes resets sprint cooldown
Nullwave Gauntlet (2.0)2250+300 hp😶 Item silence
+25% cooldown
Contraption2100+350 hp👀 Vision
traps/flares, +40% cooldown, +3 recharge
Shiversteel1450+500 hp🐌 Slow
active: slow targets
War Treads2500+600 hp👟 Boots
gives sprint to nearby teammates
\n\n

Defense

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ItemCostHPArmorShieldUse
Aegis2250 +30 ar+125 shReflex block (self)
Fountain of Renewal2300+200 hp+30 ar+75 shHeal allies
Atlas Pauldron1900 +85 ar+35 sh🐌 Slow target attack speed
Metal Jacket2100 +170 ar+35 sh 
Crucible1850+600 hp  Reflex block (team)
Slumbering Husk (2.0)1600+400 hp  Fortification against burst damage
\n\n

Boots

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ItemMovement speedHPSprintUse
War Treads+0.4+600 hp2s (60s cooldown)
incl. nearby teammates
HP, assist
Halcyon Chargers+0.5 3s (50s cooldown)Energy
Journey Boots+0.6+250 hp2s (60s cooldown)
damaging resets cooldown
Gap close
\n\n

Skill tier names

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Just Beginning1
Getting There2
Rock Solid3
Worthy Foe4
Got Swagger5
Credible Threat6
The Hotness7
Simply Amazing8
Pinnacle of Awesome9
Vainglorious10
\n\n

See: Skill tier names

\n\n

References

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vim-diff", "title": "Vimdiff", "url": "/vim-diff", "category": "Vim", "keywords": null, "content_html": "

Getting started

\n\n

Navigating

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
]cNext difference
[cPrevious difference
\n\n

Editing

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
doDiff Obtain!
Pull the changes to the current file.
dpDiff Put!
Push the changes to the other file.
:diffupdateRe-scan the files for differences.
ZQQuit without checking changes
\n\n

Folds

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
zo / zOOpen
zc / zCClose
za / zAToggle
zvOpen folds for this line
zMClose all
zROpen all
zmFold more (foldlevel += 1)
zrFold less (foldlevel -= 1)
zxUpdate folds
\n\n

Also see

\n\n", "intro_html": "

Vim is a very efficient text editor. This reference was made for Vim 8.0.

", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "vim-digraphs", "title": "Vim digraphs", "url": "/vim-digraphs", "category": "Vim", "keywords": null, "content_html": "

Typing digraphs in insert mode

\n\n
<Ctrl-K>OK\n
\n\n

Listing digraphs

\n\n
:dig\n:digraphs\n
\n\n

Reference

\n\n

Symbols

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
©®±
SMTMCoRgPI/-/=+-
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
§µ£¢¥¤
SEMy$$CtYeCu
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
*2*1cHDbDw
\n\n\n \n \n \n \n \n \n \n \n \n \n
OKXX
\n\n

Dots and bullets

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
·
.P.M0mSbOb.::.:R::
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
0.020oOSsB
\n\n

Math

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ø
o/?-?=>==<=3!<!>!=
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
×÷
RT root/\\ times-: divide
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
(C subset)C superset(U intersection)U union
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
¼½¾³²
1412343s2s3S2S
\n\n

Triangles

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
UTuTDtdT
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PRTrPLTl
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
»«
»«<//><1>1
\n\n

Arrows

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
<-->-!-vUD<>
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
<==>==
\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vim-easyalign", "title": "Vim Easyalign", "url": "/vim-easyalign", "category": "Vim", "keywords": null, "content_html": "

Command mode

\n\n

Align by delimiters

\n\n
:EasyAlign :       \" preset characters (\\=:.,&#|)\n:EasyAlign |\n:EasyAlign \\       \" \\ means space\n
\n\n

Align by regexp

\n\n
:EasyAlign /[:;]+/\n
\n\n

Specify which

\n\n
:EasyAlign |       \" align by 1st `|`\n:EasyAlign 3 |     \" align by 3rd `|`\n:EasyAlign * |     \" align by all `|`s\n
\n\n

Add options

\n\n
:EasyAlign * | l4r1\n\n  l4     \" lN - left_margin\n  r1     \" rN - right_margin\n         \"    spaces to the left/right of `|`\n  ar     \" a[lrc] - align\n         \"    align left/right/center\n  dr     \" d[lrc] - delimiter_align\n         \"    alignment of the delimiter itself\n
\n\n

Spaces are optional

\n\n
:EasyAlign * /[;:]+/ l3\n:EasyAlign*/[;:]+/l3\n
\n\n

Examples

\n\n

:EasyAlign = dr (delimiter_align right)

\n\n
apple    = 1\nbanana  += apple\ncake   ||= banana\n
\n\n

:EasyAlign : (for json or yaml)

\n\n
url:      jdbc:mysql://localhost/test\ndatabase: test\n
\n\n

:EasyAlign *| (markdown tables)

\n\n
| `<Enter>` | right align                   |\n| `1`       | on 1st occurrence             |\n| `2`       | on 2nd occurrence (and so on) |\n
\n\n

Interactive mode

\n\n\n \n \n \n \n \n \n \n \n \n \n
{Visual} activate for selection
ga {motion}activate for motion/text object
\n\n

Then press options (if available), then a delimiter.

\n\n

Interactive mode options

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Set alignment
<ctrl-l> 4 ⏎Set left_margin (to the left of the delimiter)
<ctrl-r> 4 ⏎Set right_margin
no margin
\n\n

Example

\n\n\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vim-help", "title": "Vim helpfiles", "url": "/vim-help", "category": "Vim", "keywords": null, "content_html": "

Writing help files

\n\n

Creating a document

\n\n
:e doc/potion.txt\n:set ft=help\n:set ft=text\n
\n\n

Use ft=help to preview it, and ft=text to edit it.

\n\n

Example

\n\n
*ack.txt*   Plugin that integrates ack with Vim\n\n==============================================================================\nUSAGE INSTRUCTIONS                                                 *ack-usage*\n\n:Ack[!] {pattern}                                                       *:Ack*\n\n    Search recursively for {pattern}. See |:AckAdd|.\n    Also see http://beyondgrep.com for more information.\n\nvim:tw=78:ts=8:ft=help:norl:\n
\n\n

This is a cheatsheet for writing Vim help files. See: :help help-writing

\n\n

Syntax

\n\n

Reference

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDescriptionExample
Inline items  
*tags*Tags 
|link-to-tags|Links to tags|:command|
'vimoption'Vim option'textwidth'
{code-text}Code text{Visual}gf
<code-text>Code text<PageDown>
`code-text`Code text`set fo=want`
CTRL-XCode text 
Block items  
INTRODUCTION *tag*Section header 
Column heading~Highlighting 
www.url.comWeb URL 
=====Separator 
-----Separator 
\n\n

Tags

\n\n\n\n

Code blocks

\n\n
Example: >\n xyz\n<\n
\n\n

Surround with > and < characters

\n\n

File header

\n\n
*potion.txt*  functionality for the potion programming language\n
\n\n

It’s customary to start a file with a tag of the filename, plus a description.

\n\n

Heading

\n\n
==============================================================================\nCONTENTS                                                     *potion-contents*\n
\n\n

Starts with ALL CAPS, ends with *a-tag*

\n\n

Notes

\n

Using *Todo and *Error will highlight your notes.

\n\n
\t*Todo something to do\n\t*Error something wrong\n
\n\n

Final modeline

\n\n
vim:tw=78:ts=8:ft=help:norl:\n
\n\n

Conventions

\n\n

Table of contents

\n\n
|rails-introduction|            Introduction and Feature Summary\n|rails-commands|                General Commands\n|rails-navigation|              Navigation\n
\n\n
    1.Intro...................................|ergonomic|\n    2.Note to use..............................|CAPSLOCK|\n    3.Insert Mode Remappings............|ergonomicInsert|\n
\n\n

Author lines

\n\n
Author:  Jack Hackness <captain@time.com>         *xyz-author*\nLicense: Same terms as Vim itself (see |license|)\n
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-09" },{ "id": "vim-rails", "title": "Vim-rails", "url": "/vim-rails", "category": "Vim", "keywords": null, "content_html": "

Alternate files

\n\n\n \n \n \n \n \n \n \n \n \n \n
:Aalternate file (test)
:Rrelated file (controller/view)
\n\n

What it does

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
.:A:R
Modeltest/models/db/schema.rb
Controller methodtest/controllers/app/views/
View templatetest/views/app/controllers
\n\n

Abbreviations

\n\n

Type :Rabbrev for a full list.

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AbbrevExpansion
AC::ActionController
AR::ActiveRecord
AV::ActionView
...
logd(logger.debug
logi(logger.info
...
\n\n

Model

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AbbrevExpansion
bt(belongs_to
hm(has_many
ho(has_one
habtm(has_and_belongs_to_many
\n\n

Controllers

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AbbrevExpansion
pa[params
re(redirect_to
rp(render partial:
rst(respond_to
\n\n

Views

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AbbrevExpansion
dotiwdistance_of_time_in_words
taiwtime_ago_in_words
\n\n

Extracting partials

\n\n
# from view => app/views/home/_foo_partial.haml\n  :Rextract home/foo_partial\n\n# from model => app/models/concerns/foo_concern.rb\n  :Rextract FooConcern\n
\n\n

Loading files

\n\n

App

\n\n
:Econtroller <file>     # app/controllers/*_controller.rb\n:Ehelper                # app/helpers/*_helper.rb\n:Emodel <file>          # app/models/*.rb\n:Ejob <file>            # app/jobs/*_job.rb\n:Emailer <file>         # app/mailers/*.rb\n
\n\n

DB

\n\n
:Emigration <file>     # db/migrations/*.rb\n:Eschema               # db/schema.rb\n
\n\n

Lib

\n\n
:Elib <file>      # lib/*.rb\n:Elib             # Gemfile\n:Etask <file>     # lib/tasks/*.rake\n
\n\n

Assets

\n\n
:Estylesheet\n:Ejavascript\n
\n\n

Views

\n\n
:Eview\n:Elayout\n
\n\n

Test

\n\n
:Espec\n:Eunittest\n  # test/{unit,models,helpers}/*_test.rb\n  # spec/{unit,models,helpers}/*_spec.rb\n\n:Efunctionaltest\n  # test/{functional,controllers,mailers}/*_test.rb\n  # spec/{functional,controllers,mailers}/*_spec.rb\n\n:Eintegrationtest\n  # test/integration/*_test.rb\n  # spec/{features,requests,integration}/*_spec.rb\n  # features/*.feature\n\n:Efixtures\n:Efunctionaltest\n
\n\n

Config

\n\n
:Einitializer <file>          # config/initializers/*.rb\n:Elocale                      # config/locales/*.yml\n:Eenvironment                 # application.rb\n:Eenvironment development     # config/environments/*.rb\n
\n\n

Reference

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vim-unite", "title": "Vim-Unite", "url": "/vim-unite", "category": "Vim", "keywords": null, "content_html": "

Usage

\n\n
:Unite file\n:Unite file_rec/async:!\n:Unite tag\n:Unite buffer\n
\n\n

Sources

\n\n\n\n

Options

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
OptionDescription
-start-insert 
-no-quit 
-winheight=10 
-quick-matchselect by pressing asdf keys
-winwidth=40use with vertical
-no-splitopen in current buffer
-auto-previewgreat for outline
-verticalopen as sidebar
-buffer-name=xxx -resumeresume the next time it’s called (faster)
-input=reset input (use with -resume)
-uniqueremove duplicates (eg, if using file_rec with file_mru)
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vim", "title": "Vim", "url": "/vim", "category": "Vim", "keywords": null, "content_html": "

Getting started

\n\n

Exiting

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
:qaClose all files
:qa!Close all files, abandon changes
:wSave
:wq / :xSave and close file
:qClose file
:q!Close file, abandon changes
ZZSave and quit
ZQQuit without checking changes
\n\n

Navigating

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
h j k lArrow keys
<C-U> / <C-D>Half-page up/down
<C-B> / <C-F>Page up/down
\n\n

Words

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
b / wPrevious/next word
ge / ePrevious/next end of word
\n\n

Line

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
0 (zero)Start of line
^Start of line (after whitespace)
$End of line
\n\n

Character

\n\n\n \n \n \n \n \n \n \n \n \n \n
fcGo forward to character c
FcGo backward to character c
\n\n

Document

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
ggFirst line
GLast line
:nGo to line n
nGGo to line n
\n\n

Window

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
zzCenter this line
ztTop this line
zbBottom this line
HMove to top of screen
MMove to middle of screen
LMove to bottom of screen
\n\n

Search

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
nNext matching search pattern
NPrevious match
*Next whole word under cursor
#Previous whole word under cursor
\n\n

Tab pages

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
:tabedit [file]Edit file in a new tab
:tabfind [file]Open file if exists in new tab
:tabcloseClose current tab
:tabsList all tabs
:tabfirstGo to first tab
:tablastGo to last tab
:tabn Go to next tab
:tabp Go to previous tab
\n\n

Editing

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
aAppend
AAppend from end of line
iInsert
oNext line
OPrevious line
sDelete char and insert
SDelete line and insert
CDelete until end of line and insert
rReplace one character
REnter Replace mode
uUndo changes
<C-R>Redo changes
\n\n

Exiting insert mode

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
Esc / <C-[>Exit insert mode
<C-C>Exit insert mode, and abort current command
\n\n

Clipboard

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
xDelete character
ddDelete line (Cut)
yyYank line (Copy)
pPaste
PPaste before
\"*p / \"+pPaste from system clipboard
\"*y / \"+yPaste to system clipboard
\n\n

Visual mode

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
vEnter visual mode
VEnter visual line mode
<C-V>Enter visual block mode
\n\n

In visual mode

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
d / xDelete selection
sReplace selection
yYank selection (Copy)
\n\n

See Operators for other things you can do.

\n\n

Operators

\n\n

Usage

\n\n

Operators let you operate in a range of text (defined by motion). These are performed in normal mode.

\n\n\n \n \n \n \n \n \n \n \n \n \n
dw
OperatorMotion
\n\n

Operators list

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
dDelete
yYank (copy)
cChange (delete then insert)
>Indent right
<Indent left
=Autoindent
g~Swap case
gUUppercase
guLowercase
!Filter through external program
\n\n

See :help operator

\n\n

Examples

\n\n

Combine operators with motions to use them.

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
dd(repeat the letter) Delete current line
dwDelete to next word
dbDelete to beginning of word
2ddDelete 2 lines
dipDelete a text object (inside paragraph)
(in visual mode) dDelete selection
\n\n

See: :help motion.txt

\n\n

Text objects

\n\n

Usage

\n\n

Text objects let you operate (with an operator) in or around text blocks (objects).

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
vip
Operator[i]nside or [a]roundText object
\n\n

Text objects

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
pParagraph
wWord
sSentence
[ ( { <A [], (), or {} block
' \" `A quoted string
bA block [(
BA block in [{
tA XML tag block
\n\n

Examples

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
vipSelect paragraph
vipipipipSelect more
yipYank inner paragraph
yapYank paragraph (including newline)
dipDelete inner paragraph
cipChange inner paragraph
\n\n

See Operators for other things you can do.

\n\n

Diff

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
gvimdiff file1 file2 [file3]See differences between files, in HMI
\n\n

Misc

\n\n

Folds

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
zo / zOOpen
zc / zCClose
za / zAToggle
zvOpen folds for this line
zMClose all
zROpen all
zmFold more (foldlevel += 1)
zrFold less (foldlevel -= 1)
zxUpdate folds
\n\n

Uppercase ones are recursive (eg, zO is open recursively).

\n\n

Navigation

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
%Nearest/matching {[()]}
[( [{ [<Previous ( or { or <
])Next
[mPrevious method start
[MPrevious method end
\n\n

Jumping

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
<C-O>Go back to previous location
<C-I>Go forward
gfGo to file in cursor
\n\n

Counters

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
<C-A>Increment number
<C-X>Decrement
\n\n

Windows

\n\n\n \n \n \n \n \n \n
z{height}<Cr>Resize pane to {height} lines tall
\n\n

Tags

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
:tag ClassnameJump to first definition of Classname
<C-]>Jump to definition
g]See all definitions
<C-T>Go back to last tag
<C-O> <C-I>Back/forward
:tselect ClassnameFind definitions of Classname
:tjump ClassnameFind definitions of Classname (auto-select 1st)
\n\n

Case

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
~Toggle case (Case => cASE)
gUUppercase
guLowercase
gUUUppercase current line (also gUgU)
guuLowercase current line (also gugu)
\n\n

Do these in visual or normal mode.

\n\n

Marks

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
`^Last position of cursor in insert mode
`.Last change in current buffer
`\"Last exited current buffer
`0In last file edited
''Back to line in current buffer where jumped from
``Back to position in current buffer where jumped from
`[To beginning of previously changed or yanked text
`]To end of previously changed or yanked text
`<To beginning of last visual selection
`>To end of last visual selection
maMark this cursor position as a
`aJump to the cursor position a
'aJump to the beginning of the line with position a
d'aDelete from current line to line of mark a
d`aDelete from current position to position of mark a
c'aChange text from current line to line of a
y`aYank text from current position to position of a
:marksList all current marks
:delm aDelete mark a
:delm a-dDelete marks a, b, c, d
:delm abcDelete marks a, b, c
\n\n

Misc

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
.Repeat last command
]pPaste under the current indentation level
:set ff=unixConvert Windows line endings to Unix line endings
\n\n

Command line

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
<C-R><C-W>Insert current word into the command line
<C-R>\"Paste from “ register
<C-X><C-F>Auto-completion of path in insert mode
\n\n

Text alignment

\n\n
:center [width]\n:right [width]\n:left\n
\n\n

See :help formatting

\n\n

Calculator

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
<C-R>=128/2Shows the result of the division : ‘64’
\n\n

Do this in insert mode.

\n\n

Exiting with an error

\n\n
:cq\n:cquit\n
\n\n

Works like :qa, but throws an error. Great for aborting Git commands.

\n\n

Spell checking

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
:set spell spelllang=en_usTurn on US English spell checking
]sMove to next misspelled word after the cursor
[sMove to previous misspelled word before the cursor
z=Suggest spellings for the word under/after the cursor
zgAdd word to spell list
zwMark word as bad/mispelling
zu / C-X (Insert Mode)Suggest words for bad word under cursor from spellfile
\n\n

See :help spell

\n\n

Also see

\n\n", "intro_html": "

Vim is a very efficient text editor. This reference was made for Vim 8.0.
\nFor shortcut notation, see :help key-notation.

", "description_html": "", "tags": ["Featured"], "updated": "2020-07-05" },{ "id": "vimscript-functions", "title": "Vimscript functions", "url": "/vimscript-functions", "category": "Vim", "keywords": null, "content_html": "

Dictionaries

\n\n
let colors = {\n  \\ \"apple\": \"red\",\n  \\ \"banana\": \"yellow\"\n}\n\necho colors[\"a\"]\necho get(colors, \"apple\")   \" suppress error\n\nremove(colors, \"apple\")\n\n\" :help E715\nif has_key(dict, 'foo')\nif empty(dict)\nkeys(dict)\nlen(dict)\n\nmax(dict)\nmin(dict)\n\ncount(dict, 'x')\nstring(dict)\n\nmap(dict, '<>> \" . v:val')\nextend(s:fruits, { ... })\n
\n\n
for key in keys(mydict)\n  echo key . ': ' . mydict(key)\nendfor\n
\n\n

Lists

\n\n
let mylist = [1, two, 3, \"four\"]\n\nlet first = mylist[0]\nlet last  = mylist[-1]\n\n\" Suppresses errors\nlet second = get(mylist, 1)\nlet second = get(mylist, 1, \"NONE\")\n
\n\n

Functions

\n\n

Buffer

\n\n
line('.')             \" current line number\ncol('.')\ncol('$')\n\ngetline('.')          \" current line as a string\ngetline(1)            \" get line 1\ngetline(1, 5)         \" get lines 1-5\nsearch('^$')          \" next blank line, returns line number\nsearch('^$','n')      \" but don't move cursor\n\ngetcurpos()           \" [bufnum, lnum, col, off, curswant]\ngetpos('.')           \" [bufnum, lnum, col, off]\n\nnextnonblank(1)       \" next non-blank line after line1\nprevnonblank()\n
\n\n

Marks

\n\n
getpos(\"'a\")          \" position of a mark\nsetpos(\"'a\",...)\n\ngetpos(\"'<\")          \" position of selection start\n
\n\n

Cursor

\n\n
cursor(line,col)      \" moves cursor\ncursor(line,col,off,curswant)\n\ngetcurpos()           \" returns [bufnum,line,col,off,curswant]\n
\n\n

Expand

\n\n
expand('<cword>')      \" word under cursor\nexpand('%')            \" current file\n\n\" <cword>  current word on cursor\n\" :p    full path\n\" :h    head\n\" :p:h  dirname   (/Users/rsc/project)\n\" :t    tail      (file.txt)\n\" :r    root      (file)\n\" :e    extension (.txt)\n\" see :h cmdline-special\n
\n\n

Files

\n\n
fnameescape('string')\nfnamemodify('main.c', ':p:h')\nfnamemodify(fname, ':e')   \" current file extension - see expand()\nfilereadable(fname)\ngetfsize('file.txt')\ngetcwd()\n\nglobpath(&rtp, \"plugin/commentary.vim\")\n
\n\n

Math

\n\n
fmod(9, 2)  \" modulus\nabs(-0.5)\nsqrt(9)\n\ntrunc(1.84)\nfloor(1.84)\nceil(1.84)\nfloat2nr(3.14)\n
\n\n

Casting

\n\n
str2float('0.2')\nstr2nr('240')\nstr2nr('ff', '16')\n\nstring(0.3)\n
\n\n

Type checking

\n\n
type(var) == type(0)\ntype(var) == type(\"\")\ntype(var) == type(function(\"tr\"))\ntype(var) == type([])\ntype(var) == type({})\ntype(var) == type(0.0)\n
\n\n

Date/time

\n\n
strftime('%c')\nstrftime('%c',getftime('file.c'))\n
\n\n

Strings

\n\n
if a =~ '\\s*'\nsubstitute(str, '.', 'x', 'g')\nstrpart(\"abcdef\", 3, 2)    \" == \"de\" (substring)\nstrpart(\"abcdef\", 3)       \" == \"def\"\nstridx(\"abcdef\", \"e\")      \" == 4\nstrridx()                  \" reverse\n\nmatchstr('testing','test')  \" == 'test' (or '')\nmatch('testing','test')     \" == 0\nmatchend('testing','test')  \" == 4\nmatch('testing','\\ctest')   \" ignore case\n\nsplit(str, '\\zs')           \" split into characters\n\nstrlen(str)\nstrchars()                  \" accounts for composing chars\nstrwidth()                  \" accounts for ambig characters\nstrdisplaywidth()           \" accounts for tab stops\n\ntoupper(str)\ntolower(str)\ntr('foo', '_-', '  ')\n
\n\n

Syntax

\n\n
synstack(line('.'),col('.'))   \" returns many\nsynID(line('.'),col('.'),1)    \" only one\n\nsynIDattr(id,\"bg\")\nsynIDattr(id,\"name\")\nsynIDtrans()\n\n\" syntax stack\nmap(synstack(line('.'), col('.')), 'synIDattr(v:val, \"name\")')\n
\n\n

Shell

\n\n
system('ls '.shellescape(expand('%:h')))\n
\n\n

Registers

\n\n
getreg('*')\ngetregtype('*')     \" v(char), V(line) <ctrl-v>(block)\n
\n\n

Comparisons

\n\n
if name ==# 'John'     \" case-sensitive\nif name ==? 'John'     \" case-insensitive\nif name == 'John'      \" depends on :set ignorecase\n\" also: is#, is?, >=#, >=?, and so on\n\nif \"hello\" =~ '.*'\nif \"hello\" !~ '.*'\n
\n\n

Executing

\n\n

Running commands

\n\n
normal 'ddahello'\nexe 'normal ^C'  \" with expansions\nwincmd J\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vimscript-snippets", "title": "Vimscript snippets", "url": "/vimscript-snippets", "category": "Vim", "keywords": null, "content_html": "

Bind function to key and command

\n\n
command! YoFunctionHere call s:YoFunctionHere()\nnnoremap <silent> x :call <SID>FunctionHere()<CR>\nfunction! s:FunctionHere()\nendfunction\n
\n\n

Call a function in insert mode

\n\n
inoremap X <C-R>=script#myfunction()<CR>\ninoremap <F2> <C-R>=MyVimFunc()?'':''<CR>\n
\n\n

Checking plugins

\n\n
if globpath(&rtp, \"plugin/commentary.vim\") != \"\"\n
\n\n

Autoload

\n\n
\" autoload/hello.vim\nif exists(\"g:hello_loaded\") | finish | endif\nlet g:hello_loaded=1\n\nfunction hello#method()\nendfunction\n\n\" calling hello#method() will load only if autoload()\n
\n\n

Misc

\n\n

Version check

\n\n
if version < 704\n  echom \"requires vim >= 7.4\"\nendif\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vimscript", "title": "Vim scripting", "url": "/vimscript", "category": "Vim", "keywords": null, "content_html": "

Start hacking

\n\n
let name = \"John\"\necho \"Hello, \" . name\n
\n\n

You can either put this in a script (script.vim) and run it (:source script.vim), or you can type the commands individually in normal mode as :let and :echo.

\n\n

Learn by example

\n\n
function! SuperTab()\n  let l:part = strpart(getline('.'),col('.')-2,1)\n  if (l:part =~ '^\\W\\?$')\n      return \"\\<Tab>\"\n  else\n      return \"\\<C-n>\"\n  endif\nendfunction\n\nimap <Tab> <C-R>=SuperTab()<CR>\n
\n\n

Here’s another example with functions, variables and mapping.

\n\n

Variables

\n\n

Defining

\n\n
let var = \"hello\"\n
\n\n

Variable prefixes

\n\n
let g:ack_options = '-s -H'    \" g: global\nlet s:ack_program = 'ack'      \" s: local (to script)\nlet l:foo = 'bar'              \" l: local (to function)\n
\n\n

The s: prefix is also available in function names. See :help local-variables

\n\n

Other prefixes

\n\n
let w:foo = 'bar'    \" w: window\nlet b:state = 'on'   \" b: buffer\nlet t:state = 'off'  \" t: tab\necho v:var           \" v: vim special\n
\n\n
let @/ = ''          \" @  register (this clears last search pattern)\necho $PATH           \" $  env\n
\n\n

Vim options

\n\n
echo 'tabstop is ' . &tabstop\nif &insertmode\necho &g:option\necho &l:option\n
\n\n

Prefix Vim options with &

\n\n

Operators

\n\n
a + b             \" numbers only!\n'hello ' . name   \" concat\n
\n\n
let var -= 2\nlet var += 5\nlet var .= 'string'   \" concat\n
\n\n

Strings

\n\n

Strings

\n\n
let str = \"String\"\nlet str = \"String with \\n newline\"\n\nlet literal = 'literal, no \\ escaping'\nlet literal = 'that''s enough'  \" double '' => '\n\necho \"result = \" . re   \" concatenation\n
\n\n

Also see :help literal-string and :help expr-quote.\nSee: Strings

\n\n

String functions

\n\n
strlen(str)    \" length\nlen(str)       \" same\nstrchars(str)  \" character length\n\nsplit(\"one two three\")       \"=> ['one', 'two', 'three']\nsplit(\"one.two.three\", '.')  \"=> ['one', 'two', 'three']\n\njoin(['a', 'b'], ',')  \"=> 'a,b'\n\ntolower('Hello')\ntoupper('Hello')\n
\n\n

Also see :help functions\nSee: String functions

\n\n

Functions

\n\n

Functions

\n\n
\" prefix with s: for local script-only functions\nfunction! s:Initialize(cmd, args)\n  \" a: prefix for arguments\n  echo \"Command: \" . a:cmd\n\n  return true\nendfunction\n
\n\n

See: Functions

\n\n

Namespacing

\n\n
function! myplugin#hello()\n
\n\n

Calling functions

\n\n
call s:Initialize()\ncall s:Initialize(\"hello\")\n
\n\n

Consuming return values

\n\n
echo \"Result: \" . s:Initialize()\n
\n\n

Abortable

\n\n
function! myfunction() abort\nendfunction\n
\n\n

Aborts when an error occurs.

\n\n

Var arguments

\n\n
function! infect(...)\n  echo a:0    \"=> 2\n  echo a:1    \"=> jake\n  echo a:2    \"=> bella\n\n  for s in a:000  \" a list\n    echon ' ' . s\n  endfor\nendfunction\n\ninfect('jake', 'bella')\n
\n\n

See :help function-argument. See: Var arguments

\n\n

Loops

\n\n
for s in list\n  echo s\n  continue  \" jump to start of loop\n  break     \" breaks out of a loop\nendfor\n
\n\n
while x < 5\nendwhile\n
\n\n

Custom commands

\n\n

Custom commands

\n\n
command! Save :set fo=want tw=80 nowrap\n
\n\n

Custom commands start with uppercase letters. The ! redefines a command if it already exists.

\n\n

Commands calling functions

\n\n
command! Save call <SID>foo()\n
\n\n
function! s:foo()\n  ...\nendfunction\n
\n\n

Commands with arguments

\n\n
command! -nargs=? Save call script#foo(<args>)\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
WhatWhat
-nargs=00 arguments, default
-nargs=11 argument, includes spaces
-nargs=?0 or 1 argument
-nargs=*0+ arguments, space separated
-nargs=+1+ arguments, space reparated
\n\n

Flow

\n\n

Conditionals

\n\n
let char = getchar()\nif char == \"\\<LeftMouse>\"\n  \" ...\nelseif char == \"\\<RightMouse>\"\n  \" ...\nelse\n  \" ...\nendif\n
\n\n

Truthiness

\n\n
if 1 | echo \"true\"  | endif\nif 0 | echo \"false\" | endif\n
\n\n
if 1       \"=> 1 (true)\nif 0       \"=> 0 (false)\nif \"1\"     \"=> 1 (true)\nif \"456\"   \"=> 1 (true)\nif \"xfz\"   \"=> 0 (false)\n
\n\n

No booleans. 0 is false, 1 is true.\nSee: Truthiness

\n\n

Operators

\n\n
if 3 > 2\nif a && b\nif (a && b) || (c && d)\nif !c\n
\n\n

See :help expression-syntax.\nSee: Operators

\n\n

Strings

\n\n
if name ==# 'John'     \" case-sensitive\nif name ==? 'John'     \" case-insensitive\nif name == 'John'      \" depends on :set ignorecase\n\n\" also: is#, is?, >=#, >=?, and so on\n
\n\n

Identity operators

\n\n
a is b\na isnot b\n
\n\n

Checks if it’s the same instance object.

\n\n

Regexp matches

\n\n
\"hello\" =~ 'xx*'\n\"hello\" !~ 'xx*'\n\"hello\" =~ '\\v<\\d+>'\n
\n\n

\\v enables “extended” regex mode which allows word boundary (<>), +, and more.

\n\n

Single line

\n\n
if empty(a:path) | return [] | endif\na ? b : c\n
\n\n

Use | to join lines together.

\n\n

Boolean logic

\n\n
if g:use_dispatch && s:has_dispatch\n  ···\nendif\n
\n\n

Lists

\n\n

Lists

\n\n
let mylist = [1, two, 3, \"four\"]\n\nlet first = mylist[0]\nlet last  = mylist[-1]\n\n\" Suppresses errors\nlet second = get(mylist, 1)\nlet second = get(mylist, 1, \"NONE\")\n
\n\n

Functions

\n\n
len(mylist)\nempty(mylist)\n\nsort(list)\nlet sortedlist = sort(copy(list))\n\nsplit('hello there world', ' ')\n
\n\n

Concatenation

\n\n
let longlist = mylist + [5, 6]\nlet mylist += [7, 8]\n
\n\n

Sublists

\n\n
let shortlist = mylist[2:-1]\nlet shortlist = mylist[2:]     \" same\n\nlet shortlist = mylist[2:2]    \" one item\n
\n\n

Push

\n\n
let alist = [1, 2, 3]\nlet alist = add(alist, 4)\n
\n\n

Map

\n\n
call map(files, \"bufname(v:val)\")  \" use v:val for value\ncall filter(files, 'v:val != \"\"')\n
\n\n

Dictionaries

\n\n

Dictionaries

\n\n
let colors = {\n  \\ \"apple\": \"red\",\n  \\ \"banana\": \"yellow\"\n}\n\necho colors[\"a\"]\necho get(colors, \"apple\")   \" suppress error\n
\n\n

See :help dict

\n\n

Using dictionaries

\n\n
remove(colors, \"apple\")\n
\n\n
\" :help E715\nif has_key(dict, 'foo')\nif empty(dict)\nkeys(dict)\nlen(dict)\n
\n\n
max(dict)\nmin(dict)\n
\n\n
count(dict, 'x')\nstring(dict)\n
\n\n
map(dict, '<>> \" . v:val')\n
\n\n

Iteration

\n\n
for key in keys(mydict)\n  echo key . ': ' . mydict(key)\nendfor\n
\n\n

Prefixes

\n\n
keys(s:)\n
\n\n

Prefixes (s:, g:, l:, etc) are actually dictionaries.

\n\n

Extending

\n\n
\" Extending with more\nlet extend(s:fruits, { ... })\n
\n\n

Casting

\n\n
str2float(\"2.3\")\nstr2nr(\"3\")\nfloat2nr(\"3.14\")\n
\n\n

Numbers

\n\n

Numbers

\n\n
let int = 1000\nlet int = 0xff\nlet int = 0755   \" octal\n
\n\n

See :help Number.\nSee: Numbers

\n\n

Floats

\n\n
let fl = 100.1\nlet fl = 5.4e4\n
\n\n

See :help Float

\n\n

Arithmetic

\n\n
3 / 2     \"=> 1, integer division\n3 / 2.0   \"=> 1.5\n3 * 2.0   \"=> 6.0\n
\n\n

Math functions

\n\n
sqrt(100)\nfloor(3.5)\nceil(3.3)\nabs(-3.4)\n\nsin() cos() tan()\nsinh() cosh() tanh()\nasin() acos() atan()\n
\n\n

Vim-isms

\n\n

Execute a command

\n\n
execute \"vsplit\"\nexecute \"e \" . fnameescape(filename)\n
\n\n

Runs an ex command you typically run with :. Also see :help execute.\nSee: Execute a command

\n\n

Running keystrokes

\n\n
normal G\nnormal! G   \" skips key mappings\n\nexecute \"normal! gg/foo\\<cr>dd\"\n
\n\n

Use :normal to execute keystrokes as if you’re typing them in normal mode. Combine with :execute for special keystrokes.\nSee: Running keystrokes

\n\n

Getting filenames

\n\n
echo expand(\"%\")      \" path/file.txt\necho expand(\"%:t\")    \" file.txt\necho expand(\"%:p:h\")  \" /home/you/path/file.txt\necho expand(\"%:r\")    \" path/file\necho expand(\"%:e\")    \" txt\n
\n\n

See :help expand

\n\n

Silencing

\n\n
silent g/Aap/p\n
\n\n

Suppresses output. See :help silent

\n\n

Echo

\n\n
echoerr 'oh it failed'\nechomsg 'hello there'\necho 'hello'\n\nechohl WarningMsg | echomsg \"=> \" . a:msg | echohl None\n
\n\n

Settings

\n\n
set number\nset nonumber\nset number!     \" toggle\nset numberwidth=5\nset guioptions+=e\n
\n\n

Prompts

\n\n
let result = confirm(\"Sure?\")\nexecute \"confirm q\"\n
\n\n

Built-ins

\n\n
has(\"feature\")  \" :h feature-list\nexecutable(\"python\")\nglobpath(&rtp, \"syntax/c.vim\")\n\nexists(\"$ENV\")\nexists(\":command\")\nexists(\"variable\")\nexists(\"+option\")\nexists(\"g:...\")\n
\n\n

Mapping

\n\n

Mapping commands

\n\n
nmap\nvmap\nimap\nxmap\nnnoremap\nvnoremap\ninoremap\nxnoremap\n...\n
\n\n

Explanation

\n\n
[nvixso](nore)map\n
\n\n
 │       └ don't recurse\n │\n └ normal, visual, insert,\n   eX mode, select, operator-pending\n
\n\n

Arguments

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
<buffer>only in current buffer
<silent>no echo
<nowait> 
\n\n

Syntax

\n\n

Highlights

\n\n
hi Comment\n  term=bold,underline\n  gui=bold\n  ctermfg=4\n  guifg=#80a0ff\n
\n\n

Filetype detection

\n\n
augroup filetypedetect\n  au! BufNewFile,BufRead *.json setf javascript\naugroup END\n\nau Filetype markdown setlocal spell\n
\n\n

Conceal

\n\n
set conceallevel=2\nsyn match newLine \"<br>\" conceal cchar=}\nhi newLine guifg=green\n
\n\n

Region conceal

\n\n
syn region inBold concealends matchgroup=bTag start=\"<b>\" end=\"</b>\"\nhi inBold gui=bold\nhi bTag guifg=blue\n
\n\n

Syntax

\n\n
syn match :name \":regex\" :flags\n\nsyn region Comment  start=\"/\\*\"  end=\"\\*/\"\nsyn region String   start=+\"+    end=+\"+\t skip=+\\\\\"+\n\nsyn cluster :name contains=:n1,:n2,:n3...\n\nflags:\n  keepend\n  oneline\n  nextgroup=\n  contains=\n  contained\n\nhi def link markdownH1 htmlH1\n
\n\n

Include guards

\n\n
if exists('g:loaded_myplugin')\n  finish\nendif\n\n\" ...\n\nlet g:loaded_myplugin = 1\n
", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2020-07-05" },{ "id": "virtual-dom", "title": "Virtual-dom", "url": "/virtual-dom", "category": "JavaScript libraries", "keywords": null, "content_html": "

See https://www.npmjs.com/package/virtual-dom

\n\n
var h = require('virtual-dom/h')\nvar diff = require('virtual-dom/diff')\nvar patch = require('virtual-dom/patch')\nvar createElement = require('virtual-dom/create-element')\n
\n\n

Rendering

\n\n
tree = h('div', { style: { color: 'blue' } }, [ 'hello' ])\nel = createElement(tree)\ndocument.body.appendChild(root)\n
\n\n

Updating

\n\n
tree2 = h('div', { style: { color: 'blue' } }, [ 'hello world' ])\ndelta = diff(tree, tree2)\nel = patch(el, delta) // patch() modifies el\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vows", "title": "Vows", "url": "/vows", "category": "JavaScript libraries", "keywords": null, "content_html": "\n\n

CoffeeScript usage

\n\n
vows = require \"vows\"\nassert = require \"assert\"\n\nvows\n  .describe('My tests')\n  .addBatch\n    'context':\n      topic: ->\n        100\n      'should work': (number) ->\n        assert.equal number, 100\n\n  .export(module)\n
\n\n

Running

\n\n
vows test/*-test.* --spec\n
\n\n

Assertions

\n\n
assert.equal a, b\nassert.notEqual a, b\nassert.strictEqual a, b\n\nassert.isNaN(number)\nassert.instanceOf(object, klass)\nassert.isUndefined(object)\nassert.isFunction(func)\nassert.isNull(object)\nassert.isNotZero(object)\nassert.isObject(object)\nassert.isString(object)\n
\n\n

Async

\n\n
.addBatch\n  topic: ->\n    doStuff()\n    @callback 2\n  'check things': (n) ->\n    assert.equal 2, n\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "vscode", "title": "Visual Studio Code", "url": "/vscode", "category": "Apps", "keywords": ["⌘P: Show files","⌘B: Toggle sidebar","⌘J: Toggle panel","F5: Debug"], "content_html": "

Shortcuts

\n\n

Command palette

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
⇧⌘PShow all commands
⌘PShow files
\n\n

Sidebars

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
⌘BToggle sidebar
⇧⌘EExplorer
⇧⌘FSearch
⇧⌘DDebug
⇧⌘XExtensions
⇧^GGit (SCM)
\n\n

Search

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
⌘FFind
⌥⌘FReplace
⇧⌘FFind in files
⇧⌘HReplace in files
\n\n

Panel

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
⌘JToggle panel
⇧⌘MProblems
⇧⌘UOutput
⇧⌘YDebug console
^`Terminal
\n\n

View

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
⌘k zZen mode
⌘k uClose unmodified
⌘k wClose all
\n\n

Debug

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
KeyDescription
F5Start
⇧F5Stop
⇧⌘F5Restart
^F5Start without debugging
F9Toggle breakpoint
F10Step over
F11Step into
⇧F11Step out
⇧⌘DDebug sidebar
⇧⌘YDebug panel
\n\n

References

\n\n", "intro_html": "

Visual Studio Code, or VSCode, is an open-source code editor. This guide targets VSCode v1.19.

", "description_html": "", "tags": null, "updated": "2018-02-01" },{ "id": "vue", "title": "Vue.js", "url": "/vue", "category": "JavaScript", "keywords": null, "content_html": "

{%raw%}

\n\n

Expressions

\n\n

Expressions

\n\n
<div id=\"app\">\n  <p>I have a {{ product }}</p>\n  <p>{{ product + 's' }}</p>\n  <p>{{ isWorking ? 'YES' : 'NO' }}</p>\n  <p>{{ product.getSalePrice() }}</p>\n</div>\n
\n\n

See: Delimiters

\n\n

Binding

\n\n
<a v-bind:href=\"url\">...</a>\n
\n\n

Shorthand syntax

\n
<a :href=\"url\">...</a>\n
\n\n

True or false will add or remove attribute

\n
<button :disabled=\"isButtonDisabled\">...\n
\n\n

If isActive is truthy, the class ‘active’ will appear

\n
<div :class=\"{ active: isActive }\">...\n
\n\n

Style color set to value of activeColor

\n
<div :style=\"{ color: activeColor }\">\n
\n\n

See: v-bind

\n\n

Directives

\n\n

Element inserted/removed based on truthiness

\n
<p v-if=\"inStock\">{{ product }}</p>\n
\n
<p v-else-if=\"onSale\">...</p>\n<p v-else>...</p>\n
\n\n

Toggles the display: none CSS property

\n
<p v-show=\"showProductDetails\">...</p>\n
\n\n

Two-way data binding

\n
<input v-model=\"firstName\" >\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodDescription
v-model.lazy=\"...\"Syncs input after change event
v-model.number=\"...\"Always returns a number
v-model.trim=\"...\"Strips whitespace
\n\n

See: Directives

\n\n

Actions/Events

\n\n

Calls addToCart method on component

\n
<button v-on:click=\"addToCart\">...\n
\n\n

Shorthand syntax

\n
<button @click=\"addToCart\">...\n
\n\n

Arguments can be passed

\n
<button @click=\"addToCart(product)\">...\n
\n\n

To prevent default behavior (e.g. page reload)

\n
<form @submit.prevent=\"addProduct\">...\n
\n\n

Only trigger once

\n
<img @mouseover.once=\"showImage\">...\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodDescription
.stopStop all event propagation
.self Only trigger if event.target is element itself
\n\n

Keyboard entry example

\n
<input @keyup.enter=\"submit\">\n
\n\n

Call onCopy when control-c is pressed

\n
<input @keyup.ctrl.c=\"onCopy\">\n
\n\n

See: Events

\n\n

List rendering

\n\n

The :key is always recommended

\n
<li v-for=\"item in items\"\n    :key=\"item.id\">\n  {{ item }}\n</li>\n
\n\n

To access the position in the array

\n
<li v-for=\"(item, index) in items\">...\n
\n\n

To iterate through objects

\n
<li v-for=\"(value, key) in object\">...\n
\n\n

Using v-for with a component

\n
<cart-product v-for=\"item in products\"\n              :product=\"item\"\n              :key=\"item.id\">\n
\n\n

See: List Rendering

\n\n

Component

\n\n

Component anatomy

\n\n
Vue.component('my-component', {\n  components: {\n    // Components that can be used in the template\n    ProductComponent,\n    ReviewComponent\n  },\n  props: {\n    // The parameters the component accepts\n    message: String,\n    product: Object,\n    email: {\n      type: String,\n      required: true,\n      default: \"none\"\n      validator: function (value) {\n        // Should return true if value is valid\n      }\n    }\n  },\n  data: function() {\n    // `data` must be a function\n    return {\n      firstName: 'Vue',\n      lastName: 'Mastery'\n    }\n  },\n  computed: {\n    // Return cached values until dependencies change\n    fullName: function () {\n      return this.firstName + ' ' + this.lastName\n    }\n  },\n  watch: {\n    // Called when firstName changes value\n    firstName: function (value, oldValue) { ... }\n  },\n  methods: { ... },\n  template: '<span>{{ message }}</span>',\n  // Can also use backticks in `template` for multi-line\n})\n
\n\n

See: Components Basics

\n\n

Lifecycle hooks

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodDescription
beforeCreateAfter the instance has been initialized #
createdAfter the instance is created #
beforeMountBefore the first render #
mountedAfter the instance has been mounted #
beforeUpdateWhen data changes, before the DOM is patched #
updatedAfter a data change #
beforeDestroyBefore the instance is destroyed #
destroyedAfter a Vue instance has been destroyed #
\n\n

See: Lifecycle Hooks

\n\n

Custom events

\n\n

Set listener on component, within its parent

\n
<button-counter v-on:incrementBy=\"incWithVal\">\n
\n\n

Inside parent component

\n
methods: {\n  incWithVal: function (toAdd) { ... }\n}\n
\n\n

Inside button-counter template

\n
this.$emit(\n    'incrementBy', // Custom event name\n    5 // Data sent up to parent\n  )\n
\n\n

Use props to pass data into child components,\ncustom events to pass data to parent elements.

\n\n

See: Custom Events

\n\n

Single file components

\n\n

Single file

\n
<template>\n  <p>{{ greeting }} World!</p>\n</template>\n\n<script>\nmodule.exports = {\n  data: function () {\n    return {\n      greeting: 'Hello'\n    }\n  }\n}\n</script>\n\n<style scoped>\np {\n  font-size: 2em;\n  text-align: center;\n}\n</style>\n
\n\n

See: Single File Components

\n\n

Separation

\n
<template>\n  <div>This will be pre-compiled</div>\n</template>\n<script src=\"./my-component.js\"></script>\n<style src=\"./my-component.css\"></style>\n
\n\n

See: What About Separation of Concerns?

\n\n

Slots

\n\n

Using a single slot

\n\n

Component template

\n
<div>\n  <h2>I'm a title</h2>\n  <slot>\n    Only displayed if no slot content\n  </slot>\n</div>\n
\n\n

Use of component with data for slot

\n
<my-component>\n  <p>This will go in the slot</p>\n</my-component>\n
\n\n

See: Slots

\n\n

Multiple slots

\n\n

Component template

\n
<div class=\"container\">\n  <header>\n    <slot name=\"header\"></slot>\n  </header>\n  <main>\n    <slot>Default content</slot>\n  </main>\n  <footer>\n    <slot name=\"footer\"></slot>\n  </footer>\n</div>\n
\n\n

Use of component with data for slots

\n
<app-layout>\n  <h1 slot=\"header\">Page title</h1>\n  <p>the main content.</p>\n  <p slot=\"footer\">Contact info</p>\n</app-layout>\n
\n\n

See: Slots

\n\n

Also see

\n\n\n\n

{%endraw%}

", "intro_html": "

Vue.js is an open-source Model–view–viewmodel JavaScript framework for building user interfaces and single-page applications.

", "description_html": "", "tags": null, "updated": "2019-12-26" },{ "id": "vue@1.0.28", "title": "Vue.js v1.0.28", "url": "/vue@1.0.28", "category": "JavaScript", "keywords": null, "content_html": "

{% raw %}

\n\n

Lists

\n\n
<li v-for=\"todo in todos\">\n  {{ todo.text }}\n  {{ $index }}\n</li>\n
\n\n

Events

\n\n
<button v-on:click='submit'>Go</button>\n
\n\n

Components

\n\n
new Vue({\n  components: { app: App }\n})\n
\n\n

API

\n\n
Vue.extend({ ... })        // creating components\nVue.nextTick(() => {...})\n\nVue.set(object, key, val)  // reactive\nVue.delete(object, key)\n\nVue.directive('my-dir', { bind, update, unbind })\n// <div v-my-dir='...'></div>\n\nVue.elementDirective('my-dir', { bind, update, unbind })\n// <my-dir>...</my-dir>\n\nVue.component('my-component', Vue.extend({ .. }))\n\nVue.partial('my-partial', '<div>hi {{msg}}</div>')\n// <partial name='my-partial'></partial>\n
\n\n
new Vue({\n  data: { ... }\n  props: ['size'],\n  props: { size: Number },\n  computed: { fullname() { return this.name + ' ' + this.lastName } },\n  methods: { go() { ... } },\n  watch: { a (val, oldVal) { ... } },\n  el: '#foo',\n  template: '...',\n  replace: true, // replace element (default true)\n\n  // lifecycle\n  created () {},\n  beforeCompile () {},\n  compiled () {},\n  ready () {}, // $el is inserted for the first time\n  attached () {},\n  detached () {},\n  beforeDestroy () {},\n  destroyed () {},\n\n  // options\n  directives: {},\n  elementDirectives: {},\n  filters: {},\n  components: {},\n  transitions: {},\n  partials: {}\n})\n
\n\n

Vue templates

\n

Via vueify

\n\n
// app.vue\n<template>\n  <h1 class=\"red\">{{msg}}</h1>\n</template>\n \n<script>\n  module.exports = {\n    data () {\n      return {\n        msg: 'Hello world!'\n      }\n    }\n  }\n</script> \n
\n\n

Also

\n\n
<template lang='jade'>\nh1(class='red') {{msg}}\n</template>\n
\n\n

{% endraw %}

", "intro_html": "

Deprecated: this guide targets an old version of Vuej.js (v1.0.28). See the updated Vue.js cheatsheet for new versions.

", "description_html": "", "tags": null, "updated": null },{ "id": "watchexec", "title": "Watchexec", "url": "/watchexec", "category": "CLI", "keywords": ["watchexec --excts js,jsx -- npm test","watchexec --help"], "content_html": "

Installation

\n\n

OSX

\n\n
brew install watchexec\n
\n\n

Rust

\n\n
cargo install watchexec\n
\n\n

For Linux and Windows, get it from GitHub releases.

\n\n

Getting started

\n\n
watchexec --exts js,jsx -- npm test\n
\n\n

Runs npm test when js,jsx files change.

\n\n
watchman -w lib -w test -- npm test\n
\n\n

Runs npm test when lib/ and test/ files change.

\n\n

Other options

\n\n

Flags

\n\n\n \n \n \n \n \n \n \n \n \n \n
-c --clearClear screen
-r --restartRestart process if its still running
\n\n

Options

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
-s --signal SIGKILLKill signal to use
-d --debounce MSDebounce by MS milliseconds
-e --exts EXTSExtensions
-i --ignore PATTERNIgnore these files
-w --watch PATHWatch these directories
\n\n

Also see

\n\n", "intro_html": "

mattgreen/watchexec runs commands whenever certain files change.

", "description_html": "", "tags": null, "updated": "2017-10-18" },{ "id": "watchman", "title": "Watchman", "url": "/watchman", "category": "Others", "keywords": ["watchman watch ~/src","watchman watch-list","watchman -- trigger ~/rsc remake '*.js' -- make "], "content_html": "

Getting started

\n\n
watchman watch ./src\n
\n\n

Adds ./src to the watch list.

\n\n
watchman -- trigger ./src retest '*.js' -- npm test\n
\n\n

Adds a trigger called retest to run npm test every time *.js changes in ./src.

\n\n

Watching

\n\n
watchman watch ~/src\nwatchman watch-list\nwatchman watch-del ~/src\n
\n\n

Also see

\n\n", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-10-18" },{ "id": "web-workers", "title": "Web workers", "url": "/web-workers", "category": "JavaScript", "keywords": null, "content_html": "

Web workers

\n\n

Client

\n\n
var worker = new Worker('worker.js')\n\nworker.onmessage = function (message) {\n  alert(JSON.stringify(message.data))\n})\n\nworker.postMessage('hello!')\n
\n\n

Messages can be anything that can be serialized into JSON (objects, arrays, strings, numbers, booleans). See: structured clone

\n\n

Worker

\n\n
self.onmessage = function (message) {\n  ···\n}\n\nself.postMessage({ msg: 'hello' })\n
\n\n

Message data

\n\n

[MessageEvent]

\n\n
bubbles: false\ncancelBubble: false\ncancelable: false\nclipboardData: undefined\ncurrentTarget: Worker\ndata: \"Hello\"             ← the data\ndefaultPrevented: false\neventPhase: 0\nlastEventId: \"\"\norigin: \"\"\nports: Array[0]\nreturnValue: true\nsource: null\nsrcElement: Worker\ntarget: Worker\ntimeStamp: 1344821022383\ntype: \"message\"\n
\n\n

These are the contents of message on onmessage.

", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-10-30" },{ "id": "webpack", "title": "Webpack", "url": "/webpack", "category": "JavaScript libraries", "keywords": null, "content_html": "

Basic config

\n\n

webpack.config.js

\n\n
module.exports = {\n  context: __dirname,\n  entry: 'src/app.js',\n  output: {\n    path: __dirname + '/public',\n    filename: 'app.js'\n  }\n}\n
\n\n

Terminal

\n\n
npm install --save-dev webpack\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
webpackbuild
webpack -- -pbuild production
webpack -- --watchcompile continuously
\n\n

This compiles src/app.js into public/app.js. (Note: you may need to use ./node_modules/.bin/webpack as a command if you’re not invoking Webpack via npm scripts.)

\n\n

Multiple files

\n\n

webpack.config.js

\n\n
module.exports = {\n  entry: {\n    app: 'src/app.js',\n    vendor: 'src/vendor.js'\n  },\n  output: {\n    path: __dirname + '/public',\n    filename: '[name].js'\n  }\n}\n
\n\n

This creates app.js and vendor.js.

\n\n

Loaders

\n\n

Babel

\n\n

Terminal

\n\n
npm install --save-dev \\\n  babel-loader \\\n  babel-preset-env \\\n  babel-preset-react\n
\n\n

webpack.config.js

\n\n
module.exports = {\n  ···\n  module: {\n    rules: [\n      { test: /\\.js$/,\n        exclude: /node_modules/,\n        use: [\n          { loader: 'babel-loader' }\n        ]\n      }\n    ]\n  }\n}\n
\n\n

.babelrc

\n\n
{\n  \"presets\": [ \"env\", \"react\" ]\n}\n
\n\n

Adds support for Babel.

\n\n

CSS

\n\n

Terminal

\n\n
npm install --save-dev \\\n  css-loader \\\n  style-loader\n
\n\n

webpack.config.js

\n\n
module.exports = {\n  ···\n  module: {\n    rules: [\n     { test: /\\.css$/,\n       exclude: /node_modules/,\n       use: [\n         { loader: 'style-loader' },\n         { loader: 'css-loader' }\n       ]\n      }\n    ]\n  }\n}\n
\n\n

Your JavaScript

\n\n
import './styles.css'\n// or:\nrequire('./styles.css')\n
\n\n

This allows you to use CSS inside your JavaScript. This packages your CSS inside your JavaScript bundle.

\n\n

PostCSS

\n\n

Terminal

\n\n
npm install --save-dev \\\n  postcss-loader \\\n  postcss-cssnext\n
\n\n

webpack.config.js

\n\n
···\n// Inside module.rules[]:\n{ test: /\\.css$/,\n  exclude: /node_modules/,\n  use: [\n    { loader: 'style-loader' },\n    { loader: 'css-loader' },\n    { loader: 'postcss-loader' }\n···\n
\n\n

postcss.config.js

\n\n
module.exports = {\n  plugins: [\n    require('postcss-cssnext')()\n  ]\n}\n
\n\n

This example adds postcss-cssnext support to your CSS files.

\n\n

Other features

\n\n

Dev server

\n\n

package.json

\n\n
{ ···\n  \"scripts\": {\n    \"dev\": \"webpack-dev-server\"\n  }\n}\n
\n\n

Terminal

\n\n
npm install --save-dev \\\n  webpack-dev-server\n
\n\n
npm run dev\n
\n\n

This starts an HTTP server for development (port 8080 by default).

", "intro_html": "

This is a very basic “getting started with Webpack” guide for use with Webpack v3. This doesn’t cover all features, but it should get you started in understanding the config file format.

", "description_html": "", "tags": null, "updated": "2017-09-26" },{ "id": "weechat", "title": "Weechat", "url": "/weechat", "category": "Apps", "keywords": null, "content_html": "

Keys

\n\n

Buffers

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
^s / ^uSet unread marker on all windows
^p, A-leftSwitch buffer left
^n, A-rightSwitch buffer right
A-aNext buffer with activity
A-0...9Switch buffers
F9 / F10Scroll buffer title
F11 / F12Scroll nick list
A-w A-LeftSwitch windows
A-w A-bBalance windows
\n\n

(A- is alt.)

\n\n

Window commands

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ShortcutDescription
/window splithSplit horizontal
/window splitvSplit vertical
/window zoomZoom
\n\n

Search

\n\n\n \n \n \n \n \n \n \n \n \n \n
^rSearch
Enter ^j ^mStop search
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "weinre", "title": "Weinre", "url": "/weinre", "category": "JavaScript libraries", "keywords": null, "content_html": "

Usage

\n\n

Install:

\n\n
$ npm install -g weinre\n
\n\n

Start the server:

\n\n
$ weinre --boundHost 0.0.0.0\n$ open http://localhost:8080\n
\n\n

HTML to inject

\n\n\n
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.async=1;js.src='http://'+location.hostname+':8080/target/target-script-min.js#anonymous';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','weinre');</script>\n
\n\n

References

\n\n", "intro_html": "

weinre is a remote Web inspector. Note that it has been deprecated since 2016.

", "description_html": "", "tags": ["Archived"], "updated": null },{ "id": "xpath", "title": "Xpath", "url": "/xpath", "category": "HTML", "keywords": null, "content_html": "

Testing

\n\n

Xpath test bed

\n\n

Test queries in the Xpath test bed:

\n\n\n\n

Browser console

\n\n
$x(\"//div\")\n
\n\n

Works in Firefox and Chrome.

\n\n

Selectors

\n\n

Descendant selectors

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CSSXpath?
h1//h1?
div p//div//p?
ul > li//ul/li?
ul > li > a//ul/li/a 
div > *//div/* 
:root/?
:root > body/body 
\n\n

Attribute selectors

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CSSXpath?
#id//*[@id=\"id\"]?
.class//*[@class=\"class\"] kinda 
input[type=\"submit\"]//input[@type=\"submit\"] 
a#abc[for=\"xyz\"]//a[@id=\"abc\"][@for=\"xyz\"]?
a[rel]//a[@rel] 
a[href^='/']//a[starts-with(@href, '/')]?
a[href$='pdf']//a[ends-with(@href, '.pdf')] 
a[href*='://']//a[contains(@href, '://')] 
a[rel~='help']//a[contains(@rel, 'help')] kinda 
\n\n

Order selectors

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CSSXpath?
ul > li:first-child//ul/li[1]?
ul > li:nth-child(2)//ul/li[2] 
ul > li:last-child//ul/li[last()] 
li#id:first-child//li[@id=\"id\"][1] 
a:first-child//a[1] 
a:last-child//a[last()] 
\n\n

Siblings

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CSSXpath?
h1 ~ ul//h1/following-sibling::ul?
h1 + ul//h1/following-sibling::ul[1] 
h1 ~ #id//h1/following-sibling::[@id=\"id\"] 
\n\n

jQuery

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CSSXpath?
$('ul > li').parent()//ul/li/..?
$('li').closest('section')//li/ancestor-or-self::section 
$('a').attr('href')//a/@href?
$('span').text()//span/text() 
\n\n

Other things

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CSSXpath?
h1:not([id])//h1[not(@id)]?
Text match//button[text()=\"Submit\"]?
Text match (substring)//button[contains(text(),\"Go\")] 
Arithmetic//product[@price > 2.50] 
Has children//ul[*] 
Has children (specific)//ul[li] 
Or logic//a[@name or @href]?
Union (joins results)//a | //div?
\n\n\n\n

Class check

\n\n
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]\n
\n\n

Xpath doesn’t have the “check if part of space-separated list” operator, so this is the workaround (source).

\n\n

Expressions

\n\n

Steps and axes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
//ul/a[@id='link']
AxisStepAxisStep
\n\n

Prefixes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PrefixExampleWhat
////hr[@class='edge']Anywhere
././aRelative
//html/body/divRoot
\n\n

Begin your expression with any of these.

\n\n

Axes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AxisExampleWhat
///ul/li/aChild
////[@id=\"list\"]//aDescendant
\n\n

Separate your steps with /. Use two (//) if you don’t want to select direct children.

\n\n

Steps

\n\n
//div\n//div[@name='box']\n//[@id='link']\n
\n\n

A step may have an element name (div) and predicates ([...]). Both are optional.\nThey can also be these other things:

\n\n
//a/text()     #=> \"Go home\"\n//a/@href      #=> \"index.html\"\n//a/*          #=> All a's child elements\n
\n\n

Predicates

\n\n

Predicates

\n\n
//div[true()]\n//div[@class=\"head\"]\n//div[@class=\"head\"][@id=\"top\"]\n
\n\n

Restricts a nodeset only if some condition is true. They can be chained.

\n\n

Operators

\n\n
# Comparison\n//a[@id = \"xyz\"]\n//a[@id != \"xyz\"]\n//a[@price > 25]\n
\n\n
# Logic (and/or)\n//div[@id=\"head\" and position()=2]\n//div[(x and y) or not(z)]\n
\n\n

Use comparison and logic operators to make conditionals.

\n\n

Using nodes

\n\n
# Use them inside functions\n//ul[count(li) > 2]\n//ul[count(li[@class='hide']) > 0]\n
\n\n
# This returns `<ul>` that has a `<li>` child\n//ul[li]\n
\n\n

You can use nodes inside predicates.

\n\n

Indexing

\n\n
//a[1]                  # first <a>\n//a[last()]             # last <a>\n//ol/li[2]              # second <li>\n//ol/li[position()=2]   # same as above\n//ol/li[position()>1]   # :not(:first-child)\n
\n\n

Use [] with a number, or last() or position().

\n\n

Chaining order

\n\n
a[1][@href='/']\na[@href='/'][1]\n
\n\n

Order is significant, these two are different.

\n\n

Nesting predicates

\n\n
//section[//h1[@id='hi']]\n
\n\n

This returns <section> if it has an <h1> descendant with id='hi'.

\n\n

Functions

\n\n

Node functions

\n\n
name()                     # //[starts-with(name(), 'h')]\ntext()                     # //button[text()=\"Submit\"]\n                           # //button/text()\nlang(str)\nnamespace-uri()\n
\n\n
count()                    # //table[count(tr)=1]\nposition()                 # //ol/li[position()=2]\n
\n\n

Boolean functions

\n\n
not(expr)                  # button[not(starts-with(text(),\"Submit\"))]\n
\n\n

String functions

\n\n
contains()                 # font[contains(@class,\"head\")]\nstarts-with()              # font[starts-with(@class,\"head\")]\nends-with()                # font[ends-with(@class,\"head\")]\n
\n\n
concat(x,y)\nsubstring(str, start, len)\nsubstring-before(\"01/02\", \"/\")  #=> 01\nsubstring-after(\"01/02\", \"/\")   #=> 02\ntranslate()\nnormalize-space()\nstring-length()\n
\n\n

Type conversion

\n\n
string()\nnumber()\nboolean()\n
\n\n

Axes

\n\n

Using axes

\n\n
//ul/li                       # ul > li\n//ul/child::li                # ul > li (same)\n//ul/following-sibling::li    # ul ~ li\n//ul/descendant-or-self::li   # ul li\n//ul/ancestor-or-self::li     # $('ul').closest('li')\n
\n\n

Steps of an expression are separated by /, usually used to pick child nodes. That’s not always true: you can specify a different “axis” with ::.

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
//ul/child::li
AxisStepAxisStep
\n\n

Child axis

\n\n
# both the same\n//ul/li/a\n//child::ul/child::li/child::a\n
\n\n

child:: is the default axis. This makes //a/b/c work.

\n\n
# both the same\n# this works because `child::li` is truthy, so the predicate succeeds\n//ul[li]\n//ul[child::li]\n
\n\n
# both the same\n//ul[count(li) > 2]\n//ul[count(child::li) > 2]\n
\n\n

Descendant-or-self axis

\n\n
# both the same\n//div//h4\n//div/descendant-or-self::h4\n
\n\n

// is short for the descendant-or-self:: axis.

\n\n
# both the same\n//ul//[last()]\n//ul/descendant-or-self::[last()]\n
\n\n

Other axes

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AxisAbbrevNotes
ancestor  
ancestor-or-self  
attribute@@href is short for attribute::href
child div is short for child::div
descendant  
descendant-or-self//// is short for /descendant-or-self::node()/
namespace  
self.. is short for self::node()
parent.... is short for parent::node()
following  
following-sibling  
preceding  
preceding-sibling  
\n\n

There are other axes you can use.

\n\n

Unions

\n\n
//a | //span\n
\n\n

Use | to join two expressions.

\n\n

More examples

\n\n

Examples

\n\n
//*                 # all elements\ncount(//*)          # count all elements\n(//h1)[1]/text()    # text of the first h1 heading\n//li[span]          # find a <li> with an <span> inside it\n                    # ...expands to //li[child::span]\n//ul/li/..          # use .. to select a parent\n
\n\n

Find a parent

\n\n
//section[h1[@id='section-name']]\n
\n

Finds a <section> that directly contains h1#section-name

\n\n
//section[//h1[@id='section-name']]\n
\n\n

Finds a <section> that contains h1#section-name.\n(Same as above, but uses descendant-or-self instead of child)

\n\n

Closest

\n\n
./ancestor-or-self::[@class=\"box\"]\n
\n\n

Works like jQuery’s $().closest('.box').

\n\n

Attributes

\n\n
//item[@price > 2*@discount]\n
\n\n

Finds <item> and check its attributes

\n\n

References

\n\n", "intro_html": "", "description_html": "

$x(‘//div//p//*’) == $(‘div p *’), $x(‘//[@id=”item”]’) == $(‘#item’), and many other Xpath examples.

", "tags": ["Featured"], "updated": null },{ "id": "yaml", "title": "Yaml", "url": "/yaml", "category": "Markup", "keywords": null, "content_html": "

Multiline strings

\n\n
Multiline: |\n  hello\n  world\n
\n\n

Inheritance

\n\n
parent: &defaults\n  a: 2\n  b: 3\n\nchild:\n  <<: *defaults\n  b: 4\n
\n\n

Reference content

\n\n
values: &ref\n  - These values\n  - will be reused below\n  \nother_values:\n  <<: *ref\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "yargs", "title": "Yargs", "url": "/yargs", "category": "JavaScript libraries", "keywords": null, "content_html": "

Basic usage

\n\n
var argv = require('yargs').argv;\n\nargv._         // [ ... ]\nargv.$0        // \"node bin/mybin\"\nargv.verbose   // --verbose\n
\n\n

Help and version

\n\n
var argv = require('yargs')\n\n  // version\n  .alias('v', 'version')\n  .version(function() { return require('../package').version; })\n  .describe('v', 'show version information')\n\n  // help text\n  .alias('h', 'help')\n  .help('help')\n  .usage('Usage: $0 -x [num]')\n  .showHelpOnFail(false, \"Specify --help for available options\")\n
\n\n

Options

\n\n
  .option('f', {\n      alias : 'file',\n      describe: 'x marks the spot',\n      type: 'string', /* array | boolean | string */\n      nargs: 1,\n      demand: true,\n      demand: 'file is required',\n      default: '/etc/passwd'\n      // also: count:true, requiresArg:true\n  })\n\n  .options({\n    f: { ... }\n  })\n
\n\n

Examples and more help stuff

\n\n
  // more help\n  .example('...')\n  .epilog('copyright 2015')\n  .command('start', 'start a server')\n
\n\n

Stacking

\n\n
  .count('verbose')\n\nargv.verbose // -vvv => 3\n
\n\n

Reject non explicits

\n\n
  .strict()\n
\n\n

Methods

\n\n
yargs.showHelp()\nyargs.help() //=>string\n
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "yarn", "title": "Yarn", "url": "/yarn", "category": "JavaScript libraries", "keywords": null, "content_html": "

npm equivalents

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
npmyarn
npm inityarn init
npm installyarn
npm install gulp --saveyarn add gulp
npm install gulp --save-dev --save-exactyarn add gulp --dev --exact
npm install -g gulpyarn global add gulp
npm updateyarn upgrade
./node_modules/.bin/gulpyarn run gulp
\n\n

yarn install

\n\n
--no-lockfile\n--pure-lockfile\n--frozen-lockfile\n--silent\n--offline\n--update-checksums\n--check-files\n--flat\n--force\n--ignore-scripts\n--modules-folder <path>\n--production[=true|false]\n
\n\n

These options are available for yarn install.

\n\n

yarn add

\n\n
--dev\n--peer\n--optional\n--exact\n--tilde\n
\n\n

These options are available for yarn add.

\n\n

Workspaces

\n\n

In package.json:

\n\n
\"workspaces\": [\n  \"packages/*\"\n]\n
\n\n
jest/\n├─ package.json\n└─ packages/\n   ├─ jest-matcher-utils/\n   │  └─ package.json\n   └─ jest-diff/\n      └─ package.json\n
\n\n

(New in 1.0) Allows monorepos to share packages with each other. See: Introducing workspaces

\n\n

Selective version resolution

\n\n

In package.json:

\n\n
\"resolutions\": {\n  \"**/sass-brunch/node-sass\": \"4.5.2\"\n}\n
\n\n

(New in 1.0) Allows you to specify versions for sub-dependencies. See: Selective version resolutions

\n\n

Create

\n\n
yarn create react-app hello\n
\n\n

Install create-react-app and runs it. See: yarn create

", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2019-09-30" },{ "id": "znc", "title": "ZNC bouncer", "url": "/znc", "category": "Others", "keywords": null, "content_html": "

Start

\n\n
/msg *status addserver irc.undernet.org [6667]\n/msg *status connect\n\n/msg *status loadmod webadmin\n/msg *status loadmod admin\n/msg *status loadmod away\n/msg *status loadmod awaynick\n/msg *status loadmod clientnotify    # Notifies when another client logs\n/msg *status loadmod keepnick\n/msg *status loadmod kickrejoin\n
\n\n

Away

\n\n
/msg *status loadmod away\n/msg *away away\n/msg *away back\n/msg *away show   #=> Show messages\n/msg *away delete all\n
\n\n

Watch

\n\n
/msg *status loadmod watch\n/msg *watch list\n/msg *watch add * *watch *rico*\n/msg *watch add * *watch *%nick%*\n
", "intro_html": "

A quick reference to the ZNC IRC bouncer’s common commands.

", "description_html": "", "tags": null, "updated": null },{ "id": "zombie", "title": "Zombie", "url": "/zombie", "category": "JavaScript libraries", "keywords": null, "content_html": "

Zombie

\n\n

Examples

\n\n
browser\n  .visit(\"http://.../\", ->)\n  .fill(\"email\", \"zombie@underworld.dead\")\n  .fill(\"password\", \"eat-the-living\")\n  .select(\"Born\", \"1985\")\n  .uncheck(\"Send newsletter\")\n  .clickLink(\"Link name\")\n  .pressButton(\"Sign\", () => { ... })\n  .text(\"H1\")\n
\n\n

Expectations

\n\n
expect(browser.query(\"#brains\"))\n\nexpect(browser.body.queryAll(\".hand\")).length 2\n\nconsole.log(browser.html())\nconsole.log(browser.html(\"table.parts\"))\n\nexpect(Browser.text(\".card-nopad small\"), \"A better way to get around!\")\n
", "intro_html": "

Zombie is a full-stack testing solution for Node.js.

", "description_html": "", "tags": null, "updated": null },{ "id": "zsh", "title": "zsh", "url": "/zsh", "category": "CLI", "keywords": null, "content_html": "

Expressions

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExpressionExampleDescription
!!sudo !!Last command (sudo !!)
!*vim !*Last command’s parameters (vim !*)
!^ Last command’s first parameter
!$ Last command’s last parameter
!?ls <tab>sudo !?mv <tab>Command and params of last ls command
!?ls?:* <tab> Params of last ls command
*(m0)rm *(m0)Last modified today
*(m-4) Last modified <4 days ago
\n\n

Change default shell

\n\n
chsh -s `which zsh`\n
\n\n

Process Substitution

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ExpressionExampleDescription
<(COMMAND)grep \"needle\" <(curl \"https://haystack.io\")Replace argument with named pipe/FIFO (read-only) with command output
=(COMMAND)vim =(curl \"https://haystack.io\")Replace argument with file (writable) containing command output
\n\n

Also see

\n\n\n\n

Zsh is mostly compatible with Bash, so most everything in Bash’s cheatsheet also applies.

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "assets/css/style.css", "title": null, "url": "/assets/css/style.css", "category": "Others", "keywords": null, "content_html": "

@import “jekyll-theme-primer”;

", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "redirects.json", "title": null, "url": "/redirects.json", "category": "Others", "keywords": null, "content_html": "

{“/jade.html”:”https://devhints.io/pug”,”/package.html”:”https://devhints.io/package.json”,”/phoenix-ecto@1.3.html”:”https://devhints.io/phoenix-ecto”,”/sh.html”:”https://devhints.io/bash”}

", "intro_html": "", "description_html": "", "tags": null, "updated": null } ]