# record_sheet

id: pm2
git_filename: ./pm2.md
format: md
field_title: pm2
field_category: CLI
field_updated: 2020-05-08
field_updated___timezone: UTC
data:
{"title": "pm2", "category": "CLI", "authors": {"github": "Dr-Dino"}, "updated": "2020-05-08", "body": "### Fork mode\n\n| Command                          | Description              |\n| ---                              | ---                      |\n| `pm2 start app.js --name my-api` | Start and name a process |\n\n### Cluster mode\n\n| Command                 | Description                                                        |\n| ---                     | ---                                                                |\n| `pm2 start app.js -i 0` | Will start maximum processes with LB depending on available CPUs\t |\n\n### Listing\n\n| Command          | Description                                         |\n| ---              | ---                                                 |\n| `pm2 list`       | Display all processes status                        |\n| `pm2 jlist`      | Print process list in raw JSON                      |\n| `pm2 prettylist` | Print process list in beautified JSON               |\n| ---              | ---                                                 |\n| `pm2 describe 0` | Display all information about a specific process\t |\n| ---              | ---                                                 |\n| `pm2 monit`      | Monitor all processes                               |\n\n### Logs\n\n| Command            | Description                               |\n| ---                | ---                                       |\n| `pm2 logs [--raw]` | Display all processes logs in streaming\t |\n| `pm2 flush`        | Empty all log files                       |\n| `pm2 reloadLogs`\t | Reload all logs                           |\n\n### Actions\n\n| Command           | Description                                    |\n| ---               | ---                                            |\n| `pm2 stop all`    | Stop all processes                             |\n| `pm2 restart all` | Restart all processes                          |\n| ---               | ---                                            |\n| `pm2 reload all`  | Will 0s downtime reload (for NETWORKED apps)\t |\n| ---               | ---                                            |\n| `pm2 stop 0`      | Stop specific process id                       |\n| `pm2 restart 0`   | Restart specific process id                    |\n| ---               | ---                                            |\n| `pm2 delete 0`    | Will remove process from pm2 list              |\n| `pm2 delete all`  | Will remove all processes from pm2 list        |\n| ---               | ---                                            |\n| `pm2 save`        | Save processes list to respawn at reboot       |\n| ---               | ---                                            |\n| `pm2 reset`       | reset the restart counter                      |\n| `pm2 reset all`   | reset all restart counters                     |\n\n### Misc\n\n| Command                             | Description                                                    |\n| ---                                 | ---                                                            |\n| `pm2 reset <process>`               | Reset meta data (restarted time...)                            |\n| `pm2 updatePM2`                     | Update in memory pm2                                           |\n| `pm2 ping`                          | Ensure pm2 daemon has been launched                            |\n| `pm2 sendSignal SIGUSR2 my-app`     | Send system signal to script                                   |\n| ---                                 | ---                                                            |\n| `pm2 start app.js --no-daemon`      | Run pm2 daemon in the foreground if it doesn't exist already\t |\n| `pm2 start app.js --no-vizion`      | Skip vizion features (versioning control)                      |\n| `pm2 start app.js --no-autorestart` | Do not automatically restart app                               |"}

field_body:
### Fork mode

| Command                          | Description              |
| ---                              | ---                      |
| `pm2 start app.js --name my-api` | Start and name a process |

### Cluster mode

| Command                 | Description                                                        |
| ---                     | ---                                                                |
| `pm2 start app.js -i 0` | Will start maximum processes with LB depending on available CPUs	 |

### Listing

| Command          | Description                                         |
| ---              | ---                                                 |
| `pm2 list`       | Display all processes status                        |
| `pm2 jlist`      | Print process list in raw JSON                      |
| `pm2 prettylist` | Print process list in beautified JSON               |
| ---              | ---                                                 |
| `pm2 describe 0` | Display all information about a specific process	 |
| ---              | ---                                                 |
| `pm2 monit`      | Monitor all processes                               |

### Logs

| Command            | Description                               |
| ---                | ---                                       |
| `pm2 logs [--raw]` | Display all processes logs in streaming	 |
| `pm2 flush`        | Empty all log files                       |
| `pm2 reloadLogs`	 | Reload all logs                           |

### Actions

| Command           | Description                                    |
| ---               | ---                                            |
| `pm2 stop all`    | Stop all processes                             |
| `pm2 restart all` | Restart all processes                          |
| ---               | ---                                            |
| `pm2 reload all`  | Will 0s downtime reload (for NETWORKED apps)	 |
| ---               | ---                                            |
| `pm2 stop 0`      | Stop specific process id                       |
| `pm2 restart 0`   | Restart specific process id                    |
| ---               | ---                                            |
| `pm2 delete 0`    | Will remove process from pm2 list              |
| `pm2 delete all`  | Will remove all processes from pm2 list        |
| ---               | ---                                            |
| `pm2 save`        | Save processes list to respawn at reboot       |
| ---               | ---                                            |
| `pm2 reset`       | reset the restart counter                      |
| `pm2 reset all`   | reset all restart counters                     |

### Misc

| Command                             | Description                                                    |
| ---                                 | ---                                                            |
| `pm2 reset <process>`               | Reset meta data (restarted time...)                            |
| `pm2 updatePM2`                     | Update in memory pm2                                           |
| `pm2 ping`                          | Ensure pm2 daemon has been launched                            |
| `pm2 sendSignal SIGUSR2 my-app`     | Send system signal to script                                   |
| ---                                 | ---                                                            |
| `pm2 start app.js --no-daemon`      | Run pm2 daemon in the foreground if it doesn't exist already	 |
| `pm2 start app.js --no-vizion`      | Skip vizion features (versioning control)                      |
| `pm2 start app.js --no-autorestart` | Do not automatically restart app                               |


id: plantuml
git_filename: ./plantuml.md
format: md
field_title: PlantUML
data:
{"title": "PlantUML", "body": "### About\n{: .-intro}\n\nPlantUML is a markup language for creating diagrams.\n\n- <https://plantuml.com/>\n\n### Format\n\n    @startuml\n    Car : drive()\n    Dog : bark()\n    @enduml\n\n    # plantuml file.uml && open file.png\n\n## Classes\n\n * http://plantuml.sourceforge.net/classes.html\n\n### Methods\n\n    Car : drive()\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### 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### Associations\n\n    Car <|-- SmallCar      # extension\n    Car *-- Engine         # composition\n    Cars o-- Car           # aggregation\n    Car <|.. SmallCar      # dotted line (use .. instead of --)\n    Car <|--* Car\n\n    -left->\n    -right->\n\n### Relations\n\n    Driver - Car : drives >\n    Car -- Owner : < owns\n    Car *-- Wheel : has 4 >\n\n### Notes\n\n    class Car {\n    }\n    note left: Something something\n\n    note top of Car : This is a car.\n\n### Namespaces\n\n    namespace Client {\n      class Driver {\n      }\n    }\n\n    Car -- Client.Driver : owns >\n\n\n## Activities\n\n    (*) --> \"First Activity\"\n    -->[You can put also labels] \"Second Activity\"\n    --> (*)"}

field_body:
### About
{: .-intro}

PlantUML is a markup language for creating diagrams.

- <https://plantuml.com/>

### Format

    @startuml
    Car : drive()
    Dog : bark()
    @enduml

    # plantuml file.uml && open file.png

## Classes

 * http://plantuml.sourceforge.net/classes.html

### Methods

    Car : drive()

### Methods (alt)

    class Car {
      String make
      year : Integer
      void drive()

      -private()
      #protected()
      ~package private()
      +public()

      {static} String id
      {abstract} void methods()
    }

### Lines

    class Car {
      These are separated by lines.
      The next line is a dotted line
      ..
      Next is a double-stroke
      ==
      Next is a plain line
      --
      Next is a strong line
      __
      You can make headers with it
      .. header ..
    }

### Associations

    Car <|-- SmallCar      # extension
    Car *-- Engine         # composition
    Cars o-- Car           # aggregation
    Car <|.. SmallCar      # dotted line (use .. instead of --)
    Car <|--* Car

    -left->
    -right->

### Relations

    Driver - Car : drives >
    Car -- Owner : < owns
    Car *-- Wheel : has 4 >

### Notes

    class Car {
    }
    note left: Something something

    note top of Car : This is a car.

### Namespaces

    namespace Client {
      class Driver {
      }
    }

    Car -- Client.Driver : owns >


## Activities

    (*) --> "First Activity"
    -->[You can put also labels] "Second Activity"
    --> (*)


id: phoenix@1.2
git_filename: ./phoenix@1.2.md
format: md
field_title: Phoenix 1.2
field_category: Elixir
field_updated: 2018-03-06
field_updated___timezone: UTC
data:
{"title": "Phoenix 1.2", "category": "Elixir", "weight": -1, "updated": "2018-03-06", "body": "See [Phoenix](./phoenix) for a more updated cheatsheet.\n\n### Directory structure (Legacy 1.2)\n\n```\n\u251c\u2500\u2500 _build\n\u251c\u2500\u2500 config/\n\u251c\u2500\u2500 deps/\n\u251c\u2500\u2500 lib/\n\u2502   \u251c\u2500\u2500 hello/\n\u2502   \u251c\u2500\u2500 hello.ex\n\u251c\u2500\u2500 node_modules/\n\u251c\u2500\u2500 priv/\n\u251c\u2500\u2500 test/\n\u2514\u2500\u2500 web/\n\u2502   \u251c\u2500\u2500 channels/\n\u2502   \u251c\u2500\u2500 controllers/\n\u2502   \u251c\u2500\u2500 models/\n\u2502   \u251c\u2500\u2500 static/\n\u2502   \u251c\u2500\u2500 templates/\n\u2502   \u251c\u2500\u2500 views/\n\u2502   \u251c\u2500\u2500 gettext.ex\n\u2502   \u251c\u2500\u2500 router.ex\n\u2502   \u251c\u2500\u2500 web.ex\n\u251c\u2500\u2500 mix.exs\n```\n\nThis is Phoenix 1.2's structure. Phoenix 1.3 has no `models`."}

field_body:
See [Phoenix](./phoenix) for a more updated cheatsheet.

### Directory structure (Legacy 1.2)

```
├── _build
├── config/
├── deps/
├── lib/
│   ├── hello/
│   ├── hello.ex
├── node_modules/
├── priv/
├── test/
└── web/
│   ├── channels/
│   ├── controllers/
│   ├── models/
│   ├── static/
│   ├── templates/
│   ├── views/
│   ├── gettext.ex
│   ├── router.ex
│   ├── web.ex
├── mix.exs
```

This is Phoenix 1.2's structure. Phoenix 1.3 has no `models`.


id: phoenix
git_filename: ./phoenix.md
format: md
field_title: Phoenix
field_category: Elixir
field_updated: 2018-03-06
field_updated___timezone: UTC
data:
{"title": "Phoenix", "category": "Elixir", "weight": -1, "updated": "2018-03-06", "body": "### Quick start\n\n```bash\n# Install Phoenix\nmix local.hex\nmix archive.install https://github.com/phoenixframework/archives/raw/master/phx_new.ez\n```\n\n```bash\n# Create a new project\nmix phx.new hello\n```\n\n```bash\n# Start the application\nmix phx.server\n```\n\nInstall Erlang, Elixir, Node.js, PostgreSQL first.\nSee: [Installation](https://hexdocs.pm/phoenix/installation.html) _(hexdocs.pm)_\n\n### Directory structure\n\n```\n./\n\u251c\u2500\u2500 _build\n\u251c\u2500\u2500 assets/\n\u2502   \u251c\u2500\u2500 css/\n\u2502   \u251c\u2500\u2500 js/\n\u2502   \u251c\u2500\u2500 static/\n\u2502   \u2514\u2500\u2500 node_modules/\n\u251c\u2500\u2500 config/\n\u251c\u2500\u2500 deps/\n\u251c\u2500\u2500 lib/\n\u2502   \u251c\u2500\u2500 hello/\n\u2502   \u251c\u2500\u2500 hello.ex\n\u2502   \u251c\u2500\u2500 hello_web/\n\u2502   \u2502   \u251c\u2500\u2500 channels/\n\u2502   \u2502   \u251c\u2500\u2500 controllers/\n\u2502   \u2502   \u251c\u2500\u2500 templates/\n\u2502   \u2502   \u251c\u2500\u2500 views/\n\u2502   \u2502   \u251c\u2500\u2500 router.ex\n\u2502   \u2502   \u2514\u2500\u2500 gettext.ex\n\u2502   \u2514\u2500\u2500 hello_web.ex\n\u251c\u2500\u2500 priv/\n\u2514\u2500\u2500 test/\n```\n{: .-box-chars}\n\nSee: [Adding pages](https://hexdocs.pm/phoenix/adding_pages.html) _(hexdocs.pm)_\n\n### Migrations\n\n```bash\n$ mix ecto.gen.migration update_posts_table\n  creating priv/repo/migrations/20160602085927_update_posts_table.exs\n  \u00b7\u00b7\u00b7\n```\n\n```elixir\ncreate 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](./phoenix-migrations)\n{: .-crosslink}\n\n### Routing\n\n```elixir\nget \"/\", PageController, :index\n\nresources \"/users\", UserController do\n  resources \"/posts\", PostController\nend\n```\n\n```elixir\nuser_post_path(conn, :index, 17)     # \u2192 /users/17/posts\nuser_post_path(conn, :show, 17, 12)  # \u2192 /users/17/posts/12\n```\n\n[Phoenix routing cheatsheet](./phoenix-routing)\n{: .-crosslink}\n\n### Conn\n\n```elixir\nconn.host          # \u2192 \"example.com\"\nconn.method        # \u2192 \"GET\"\nconn.path_info     # \u2192 [\"posts\", \"1\"]\nconn.request_path  # \u2192 \"/posts/1\"\n```\n\n```elixir\nconn\n|> put_status(202)\n|> html(\"<html><head>\u00b7\u00b7\u00b7\")\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](./phoenix-conn)\n{: .-crosslink}\n\n### Ecto\n\n```bash\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](./phoenix-ecto)\n{: .-crosslink}\n\n### Also see\n\n- [Phoenix framework site](http://phoenixframework.org/) _(phoenixframework.org)_\n- [Phoenix: getting started](https://hexdocs.pm/phoenix/overview.html) _(hexdocs.pm)_"}

field_body:
### Quick start

```bash
# Install Phoenix
mix local.hex
mix archive.install https://github.com/phoenixframework/archives/raw/master/phx_new.ez
```

```bash
# Create a new project
mix phx.new hello
```

```bash
# Start the application
mix phx.server
```

Install Erlang, Elixir, Node.js, PostgreSQL first.
See: [Installation](https://hexdocs.pm/phoenix/installation.html) _(hexdocs.pm)_

### Directory structure

```
./
├── _build
├── assets/
│   ├── css/
│   ├── js/
│   ├── static/
│   └── node_modules/
├── config/
├── deps/
├── lib/
│   ├── hello/
│   ├── hello.ex
│   ├── hello_web/
│   │   ├── channels/
│   │   ├── controllers/
│   │   ├── templates/
│   │   ├── views/
│   │   ├── router.ex
│   │   └── gettext.ex
│   └── hello_web.ex
├── priv/
└── test/
```
{: .-box-chars}

See: [Adding pages](https://hexdocs.pm/phoenix/adding_pages.html) _(hexdocs.pm)_

### Migrations

```bash
$ mix ecto.gen.migration update_posts_table
  creating priv/repo/migrations/20160602085927_update_posts_table.exs
  ···
```

```elixir
create table(:documents) do
  add :title, :string
  add :title, :string, default: "Hello"
  add :body, :text
  add :age, :integer
  add :price, :float, precision: 10, scale: 2
  timestamps
end
```

[Ecto migrations cheatsheet](./phoenix-migrations)
{: .-crosslink}

### Routing

```elixir
get "/", PageController, :index

resources "/users", UserController do
  resources "/posts", PostController
end
```

```elixir
user_post_path(conn, :index, 17)     # → /users/17/posts
user_post_path(conn, :show, 17, 12)  # → /users/17/posts/12
```

[Phoenix routing cheatsheet](./phoenix-routing)
{: .-crosslink}

### Conn

```elixir
conn.host          # → "example.com"
conn.method        # → "GET"
conn.path_info     # → ["posts", "1"]
conn.request_path  # → "/posts/1"
```

```elixir
conn
|> put_status(202)
|> html("<html><head>···")
|> json(%{ message: "Hello" })
|> text("Hello")
|> redirect(to: "/foo")
|> render("index.html")
|> render("index.html", hello: "world")
|> render(MyApp.ErrorView, "404.html")
```

[Phoenix conn cheatsheet](./phoenix-conn)
{: .-crosslink}

### Ecto

```bash
$ mix phx.gen.html \
    Accounts \       # domain
    Profile \        # schema
    profiles \       # table name
    email:string \
    age:integer
```

[Ecto cheatsheet](./phoenix-ecto)
{: .-crosslink}

### Also see

- [Phoenix framework site](http://phoenixframework.org/) _(phoenixframework.org)_
- [Phoenix: getting started](https://hexdocs.pm/phoenix/overview.html) _(hexdocs.pm)_


id: phoenix-routing
git_filename: ./phoenix-routing.md
format: md
field_title: Phoenix: Routing
field_category: Elixir
data:
{"title": "Phoenix: Routing", "category": "Elixir", "weight": -1, "body": "### Showing routes\n\n```sh\nmix phx.routes        # 1.3+\nmix phoenix.routes    # 1.2 and below\n```\n\nSee: [Mix.Tasks.Phoenix.Routes](https://hexdocs.pm/phoenix/Mix.Tasks.Phoenix.Routes.html) _(hexdocs.pm)_\n\n### Single routes\n\n```elixir\nget \"/\", PageController, :index\n```\n\nAlso: `put` `post` `patch` `options` `delete` `head`\n\n### Resources\n\n```elixir\nresources \"/users\", UserController\nresources \"/users\", UserController, only: [:index, :show]\nresources \"/users\", UserController, except: [:delete]\n```\n\n```elixir\nresources \"/users\", UserController,\n  as: :person    # helper name (person_path)\n  name: :person  # ...?\n  param: :id     # name of parameter for this resource\n```\n\nGenerates these routes:\n\n| Method    | Path              | Helper                     |\n| ----      | ----              | ----                       |\n| GET       | `/users`          | `user_path(:index)`        |\n| GET       | `/users/new`      | `user_path(:new)`          |\n| GET       | `/users/:id`      | `user_path(:show, user)`   |\n| GET       | `/users/:id/edit` | `user_path(:edit, user)`   |\n| POST      | `/users`          | `user_path(:create, user)` |\n| PATCH/PUT | `/users/:id`      | `user_path(:update, user)` |\n| DELETE    | `/users/:id`      | `user_path(:delete, user)` |\n{: .-left-align}\n\nSee: [resources/4](https://hexdocs.pm/phoenix/Phoenix.Router.html#resources/4) _(hexdocs.pm)_\n\n### Path helpers\n\n```elixir\nuser_path(conn, :index)                 # \u2192 /users\nuser_path(conn, :show, 17)              # \u2192 /users/17\nuser_path(conn, :show, %User{id: 17})   # \u2192 /users/17\nuser_path(conn, :show, 17, admin: true) # \u2192 /users/17?admin=true\n```\n\n```elixir\nuser_url(conn, :index) # \u2192 \"http://localhost:4000/users\"\n```\n\n```elixir\nMyApp.Router.Helpers.user_path(MyApp.Endpoint, :index)\n```\n\nSee: [Helpers](https://hexdocs.pm/phoenix/Phoenix.Router.html#module-helpers) _(hexdocs.pm)_\n\n### Nested resources\n\n```elixir\nresources \"/users\", UserController do\n  resources \"/posts\", PostController\nend\n```\n\n```elixir\nuser_post_path(:index, 17)     # \u2192 /users/17/posts\nuser_post_path(:show, 17, 12)  # \u2192 /users/17/posts/12\n```\n\nSee: [Scopes and resources](https://hexdocs.pm/phoenix/Phoenix.Router.html#module-scopes-and-resources) _(hexdocs.pm)_\n\n### Scoped routes\n\n```elixir\nscope \"/admin\" do\n  pipe_through :browser\n  resources \"/reviews\", MyApp.Admin.ReviewController\nend\n# reviews_path() -> /admin/reviews\n```\n\n```elixir\nscope \"/admin\", as: :admin do: ... end\n# admin_reviews_path() -> /admin/reviews\n```\n\nSee: [scope/2](https://hexdocs.pm/phoenix/Phoenix.Router.html#scope/2) _(hexdocs.pm)_"}

field_body:
### Showing routes

```sh
mix phx.routes        # 1.3+
mix phoenix.routes    # 1.2 and below
```

See: [Mix.Tasks.Phoenix.Routes](https://hexdocs.pm/phoenix/Mix.Tasks.Phoenix.Routes.html) _(hexdocs.pm)_

### Single routes

```elixir
get "/", PageController, :index
```

Also: `put` `post` `patch` `options` `delete` `head`

### Resources

```elixir
resources "/users", UserController
resources "/users", UserController, only: [:index, :show]
resources "/users", UserController, except: [:delete]
```

```elixir
resources "/users", UserController,
  as: :person    # helper name (person_path)
  name: :person  # ...?
  param: :id     # name of parameter for this resource
```

Generates these routes:

| Method    | Path              | Helper                     |
| ----      | ----              | ----                       |
| GET       | `/users`          | `user_path(:index)`        |
| GET       | `/users/new`      | `user_path(:new)`          |
| GET       | `/users/:id`      | `user_path(:show, user)`   |
| GET       | `/users/:id/edit` | `user_path(:edit, user)`   |
| POST      | `/users`          | `user_path(:create, user)` |
| PATCH/PUT | `/users/:id`      | `user_path(:update, user)` |
| DELETE    | `/users/:id`      | `user_path(:delete, user)` |
{: .-left-align}

See: [resources/4](https://hexdocs.pm/phoenix/Phoenix.Router.html#resources/4) _(hexdocs.pm)_

### Path helpers

```elixir
user_path(conn, :index)                 # → /users
user_path(conn, :show, 17)              # → /users/17
user_path(conn, :show, %User{id: 17})   # → /users/17
user_path(conn, :show, 17, admin: true) # → /users/17?admin=true
```

```elixir
user_url(conn, :index) # → "http://localhost:4000/users"
```

```elixir
MyApp.Router.Helpers.user_path(MyApp.Endpoint, :index)
```

See: [Helpers](https://hexdocs.pm/phoenix/Phoenix.Router.html#module-helpers) _(hexdocs.pm)_

### Nested resources

```elixir
resources "/users", UserController do
  resources "/posts", PostController
end
```

```elixir
user_post_path(:index, 17)     # → /users/17/posts
user_post_path(:show, 17, 12)  # → /users/17/posts/12
```

See: [Scopes and resources](https://hexdocs.pm/phoenix/Phoenix.Router.html#module-scopes-and-resources) _(hexdocs.pm)_

### Scoped routes

```elixir
scope "/admin" do
  pipe_through :browser
  resources "/reviews", MyApp.Admin.ReviewController
end
# reviews_path() -> /admin/reviews
```

```elixir
scope "/admin", as: :admin do: ... end
# admin_reviews_path() -> /admin/reviews
```

See: [scope/2](https://hexdocs.pm/phoenix/Phoenix.Router.html#scope/2) _(hexdocs.pm)_


id: phoenix-migrations
git_filename: ./phoenix-migrations.md
format: md
field_title: Phoenix: Ecto migrations
field_category: Elixir
field_updated: 2020-02-23
field_updated___timezone: UTC
data:
{"title": "Phoenix: Ecto migrations", "category": "Elixir", "weight": -1, "updated": "2020-02-23", "body": "### Creating\n\n```bash\n$ mix ecto.gen.migration update_posts_table\n  creating priv/repo/migrations/20160602085927_update_posts_table.exs\n  \u00b7\u00b7\u00b7\n```\n\n```bash\n$ mix ecto.migrate\n$ mix ecto.rollback\n```\n\nCreates a migration (no models).\n\n### Creating models\n\n```bash\n$ mix phoenix.gen.model Message messages user_id:integer content:text\n```\n\nThis is only for Phoenix 1.2 or older; models aren't available in Phoenix 1.3+.\n\n### Creating context\n\n```bash\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```elixir\ncreate 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```elixir\nalter table(:posts) do\n  add :summary, :text\n  modify :title, :text\n  remove :views\nend\n```\n\n```elixir\nrename table(:posts), :title, to: :summary\nrename table(:posts), to: table(:new_posts)\n```\n\n```elixir\ndrop table(:documents)\ndrop_if_exists table(:documents)\n```\n\n```elixir\ntable(:documents)\ntable(:weather, prefix: :north_america)\n```\n\n### Indices\n\n```elixir\ncreate index(:posts, [:slug], concurrently: true)\ncreate unique_index(:posts, [:slug])\ndrop index(:posts, [:name])\n```\n\n### Execute SQL\n\n```elixir\nexecute \"UPDATE posts SET published_at = NULL\"\nexecute create: \"posts\", capped: true, size: 1024\n```\n\n## References\n\n- [Ecto.Migration](http://devdocs.io/phoenix/ecto/ecto.migration)"}

field_body:
### Creating

```bash
$ mix ecto.gen.migration update_posts_table
  creating priv/repo/migrations/20160602085927_update_posts_table.exs
  ···
```

```bash
$ mix ecto.migrate
$ mix ecto.rollback
```

Creates a migration (no models).

### Creating models

```bash
$ mix phoenix.gen.model Message messages user_id:integer content:text
```

This is only for Phoenix 1.2 or older; models aren't available in Phoenix 1.3+.

### Creating context

```bash
$ mix phx.gen.context Images Album albums title:string subtitle:string privacy:string
```
 
## Migration functions

### Creating tables

```elixir
create table(:documents) do
  add :title, :string
  add :title, :string, size: 40
  add :title, :string, default: "Hello"
  add :title, :string, default: fragment("now()")
  add :title, :string, null: false
  add :body, :text
  add :age, :integer
  add :price, :float
  add :price, :float
  add :price, :decimal, precision: 10, scale: 2
  add :published_at, :utc_datetime
  add :group_id, references(:groups)
  add :object, :json

  timestamps  # inserted_at and updated_at
end

create_if_not_exists table(:documents) do: ... end
```

### Other operations

```elixir
alter table(:posts) do
  add :summary, :text
  modify :title, :text
  remove :views
end
```

```elixir
rename table(:posts), :title, to: :summary
rename table(:posts), to: table(:new_posts)
```

```elixir
drop table(:documents)
drop_if_exists table(:documents)
```

```elixir
table(:documents)
table(:weather, prefix: :north_america)
```

### Indices

```elixir
create index(:posts, [:slug], concurrently: true)
create unique_index(:posts, [:slug])
drop index(:posts, [:name])
```

### Execute SQL

```elixir
execute "UPDATE posts SET published_at = NULL"
execute create: "posts", capped: true, size: 1024
```

## References

- [Ecto.Migration](http://devdocs.io/phoenix/ecto/ecto.migration)


id: phoenix-ecto@1.3
git_filename: ./phoenix-ecto@1.3.md
format: md
field_title: Phoenix: Ecto models
field_category: Hidden
data:
{"title": "Phoenix: Ecto models", "category": "Hidden", "redirect_to": "/phoenix-ecto", "deprecated": true, "body": ""}


id: phoenix-ecto@1.2
git_filename: ./phoenix-ecto@1.2.md
format: md
field_title: Phoenix: Ecto models
field_category: Elixir
field_tags: Archived
data:
{"title": "Phoenix: Ecto models", "category": "Elixir", "deprecated": true, "tags": ["Archived"], "archived": "This is for Phoenix 1.2 and below. [Phoenix 1.3 has a new API.](./phoenix-ecto@1.3).", "body": "### About\n\nThis is for Phoenix 1.2 and below. [Phoenix 1.3 has a new API.](./phoenix-ecto@1.3).\n\n### Generating\n\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```elixir\ndefmodule 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```elixir\ndef 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```elixir\nchangeset.valid?\nchangeset.errors     #=> [title: \"empty\"]\n\nchangeset.changes    #=> %{}\nchangeset.params[:title]\n\nchangeset.required   #=> [:title]\nchangeset.optional   #=> [:body]\n```\n\n### Updating\n\n```elixir\nchangeset #(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```elixir\nget_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```elixir\nRepo.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```elixir\nchangeset |> Repo.update\nchangeset |> Repo.insert\nchangeset |> Repo.insert_or_update\n```\n\n```\nUser\n|> Ecto.Changeset.change(%{name: \"hi\"})\n|> Repo.insert\n```\n\n## Many\n\n### Queries\n\n```elixir\nfrom 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```elixir\nRepo.all(User)\n```\n\n### Update many\n\n```elixir\nRepo.update_all(Post, set: [title: \"Title\"])\nRepo.update_all(Post, inc: [views: 1])\n```\n\n### Chaining `_all` with queries\n\n```elixir\nfrom(p in Post, where: p.id < 10)\n|> Repo.update_all(...)\n\nfrom(p in Post, where: p.id < 10)\n|> Repo.all()\n```"}

field_body:
### About

This is for Phoenix 1.2 and below. [Phoenix 1.3 has a new API.](./phoenix-ecto@1.3).

### Generating

```
$ mix phoenix.gen.html Profile profiles email:string age:integer
$ mix phoenix.gen.html User users email:string hashed_password:string
```

### Schema

```elixir
defmodule User do
  use Ecto.Schema

  schema "users" do
    field :name
    field :age, :integer
    # :id :binary :integer :float :boolean :string :binary
    # {:array, inner_type} :decimal :map

    field :password, virtual: true
  end
end
```

### Changesets

```elixir
def changeset(user, params \\ :empty) do
  %User{}
  |> Ecto.Changeset.change   # basic casting to changeset

  user
  |> cast(params, ~w(name email), ~w(age)) # params to Changeset

  |> validate_format(:email, ~r/@/)

  |> validate_inclusion(:age, 18..100)
  |> validate_exclusion(:role, ~w(admin superadmin))
  |> validate_subset(:pets, ~w(cat dog parrot whale))

  |> validate_length(:body, min: 1)
  |> validate_length(:body, min: 1, max: 160)
  |> validate_length(:partners, is: 2)

  |> validate_number(:pi, greater_than: 3)
  |> validate_number(:pi, less_than: 4)
  |> validate_number(:pi, equal_to: 42)

  |> validate_change(:title, fn _, _ -> [])
  |> validate_confirmation(:password, message: "does not match")

  |> unique_constraint(:email)
  |> foreign_key_constraint(:post_id)
  |> assoc_constraint(:post)      # ensure post_id exists
  |> no_assoc_constraint(:post)   # negative (useful for deletions)
end
```

```elixir
changeset.valid?
changeset.errors     #=> [title: "empty"]

changeset.changes    #=> %{}
changeset.params[:title]

changeset.required   #=> [:title]
changeset.optional   #=> [:body]
```

### Updating

```elixir
changeset #(or model)
|> change(title: "New title")
|> change(%{ title: "New title" })
|> put_change(:title, "New title")
|> force_change(:title, "New title")
|> update_change(:title, &(&1 <> "..."))

|> delete_change(:title)
|> merge(other_changeset)

|> add_error(:title, "empty")
```

### Getting

```elixir
get_change(changeset, :title)    #=> "hi" (if changed)
get_field(changeset, :title)     #=> "hi" (even if unchanged)

fetch_change(changeset, :title)  #=> {:ok, "hi"} | :error
fetch_field(changeset, :title)   #=> {:changes | :model, "value"} | :error
```

## Ecto

### Get one

```elixir
Repo.get(User, id)
Repo.get_by(User, email: "john@hello.com")  #=> %User{} | nil

# also get! get_by!
```

### Create/update

```elixir
changeset |> Repo.update
changeset |> Repo.insert
changeset |> Repo.insert_or_update
```

```
User
|> Ecto.Changeset.change(%{name: "hi"})
|> Repo.insert
```

## Many

### Queries

```elixir
from p in Post,
  where: p.title == "Hello",
  where: [state: "Sweden"],

  limit: 1,
  offset: 10,

  order_by: c.name,
  order_by: [c.name, c.title],
  order_by: [asc: c.name, desc: c.title],

  preload: [:comments],
  preload: [comments: {c, likes: l}],

  join: c in assoc(c, :comments),
  join: p in Post, on: c.post_id == p.id,
  group_by: p,

  select: p,
  select: {p.title, p.description},
  select: [p.title, p.description],
```

### Get many

```elixir
Repo.all(User)
```

### Update many

```elixir
Repo.update_all(Post, set: [title: "Title"])
Repo.update_all(Post, inc: [views: 1])
```

### Chaining `_all` with queries

```elixir
from(p in Post, where: p.id < 10)
|> Repo.update_all(...)

from(p in Post, where: p.id < 10)
|> Repo.all()
```


id: phoenix-ecto
git_filename: ./phoenix-ecto.md
format: md
field_title: Phoenix: Ecto
field_category: Elixir
field_tags: WIP
field_updated: 2017-08-30
field_updated___timezone: UTC
data:
{"title": "Phoenix: Ecto", "category": "Elixir", "tags": ["WIP"], "updated": "2017-08-30", "body": "## Schemas\n{: .-three-column}\n\n### Generating\n\n```bash\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```elixir\ndefmodule 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| Field |\n| --- |\n| `:id` |\n| `:binary` |\n| `:boolean` |\n| `:string` |\n| --- |\n| `:integer` |\n| `:float` |\n| `:decimal` |\n| --- |\n| `{:array, inner_type}` |\n| `:map` |\n{: .-left-align}\n\n## Changesets\n\n### Changesets\n\n```elixir\ndef 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```elixir\nchangeset.valid?\nchangeset.errors     #=> [title: \"empty\"]\n\nchangeset.changes    #=> %{}\nchangeset.params[:title]\n\nchangeset.required   #=> [:title]\nchangeset.optional   #=> [:body]\n```\n\n### Updating\n\n```elixir\nchangeset #(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```elixir\nget_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```elixir\nRepo.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```elixir\nchangeset |> Repo.update\nchangeset |> Repo.insert\nchangeset |> Repo.insert_or_update\n```\n\n```\nUser\n|> Ecto.Changeset.change(%{name: \"hi\"})\n|> Repo.insert\n```\n\n## Many\n\n### Queries\n\n```elixir\nfrom 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```elixir\nRepo.all(User)\n```\n\n### Update many\n\n```elixir\nRepo.update_all(Post, set: [title: \"Title\"])\nRepo.update_all(Post, inc: [views: 1])\n```\n\n### Chaining `_all` with queries\n\n```elixir\nfrom(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{: .-one-column}\n\n- Based on Ecto 1.3."}

field_body:
## Schemas
{: .-three-column}

### Generating

```bash
$ mix phx.gen.html \
    Accounts \       # domain
    Profile \        # schema
    profiles \       # table name
    email:string \
    age:integer
```

### Schema

```elixir
defmodule Myapp.Accounts.User do
  use Ecto.Schema

  schema "users" do
    field :name
    field :age, :integer
    field :password, virtual: true

    timestamps()
  end
end
```

### Field types

| Field |
| --- |
| `:id` |
| `:binary` |
| `:boolean` |
| `:string` |
| --- |
| `:integer` |
| `:float` |
| `:decimal` |
| --- |
| `{:array, inner_type}` |
| `:map` |
{: .-left-align}

## Changesets

### Changesets

```elixir
def changeset(user, params \\ :empty) do
  %User{}
  |> Ecto.Changeset.change   # basic casting to changeset

  user
  |> cast(params, ~w(name email), ~w(age)) # params to Changeset

  |> validate_format(:email, ~r/@/)

  |> validate_inclusion(:age, 18..100)
  |> validate_exclusion(:role, ~w(admin superadmin))
  |> validate_subset(:pets, ~w(cat dog parrot whale))

  |> validate_length(:body, min: 1)
  |> validate_length(:body, min: 1, max: 160)
  |> validate_length(:partners, is: 2)

  |> validate_number(:pi, greater_than: 3)
  |> validate_number(:pi, less_than: 4)
  |> validate_number(:pi, equal_to: 42)

  |> validate_change(:title, fn _, _ -> [])
  |> validate_confirmation(:password, message: "does not match")

  |> unique_constraint(:email)
  |> foreign_key_constraint(:post_id)
  |> assoc_constraint(:post)      # ensure post_id exists
  |> no_assoc_constraint(:post)   # negative (useful for deletions)
end
```

### Changeset fields

```elixir
changeset.valid?
changeset.errors     #=> [title: "empty"]

changeset.changes    #=> %{}
changeset.params[:title]

changeset.required   #=> [:title]
changeset.optional   #=> [:body]
```

### Updating

```elixir
changeset #(or model)
|> change(title: "New title")
|> change(%{ title: "New title" })
|> put_change(:title, "New title")
|> force_change(:title, "New title")
|> update_change(:title, &(&1 <> "..."))

|> delete_change(:title)
|> merge(other_changeset)

|> add_error(:title, "empty")
```

### Getting

```elixir
get_change(changeset, :title)    #=> "hi" (if changed)
get_field(changeset, :title)     #=> "hi" (even if unchanged)

fetch_change(changeset, :title)  #=> {:ok, "hi"} | :error
fetch_field(changeset, :title)   #=> {:changes | :model, "value"} | :error
```

## Repo

### Get one

```elixir
Repo.get(User, id)
Repo.get_by(User, email: "john@hello.com")  #=> %User{} | nil

# also get! get_by!
```

### Create/update

```elixir
changeset |> Repo.update
changeset |> Repo.insert
changeset |> Repo.insert_or_update
```

```
User
|> Ecto.Changeset.change(%{name: "hi"})
|> Repo.insert
```

## Many

### Queries

```elixir
from p in Post,
  where: p.title == "Hello",
  where: [state: "Sweden"],

  limit: 1,
  offset: 10,

  order_by: c.name,
  order_by: [c.name, c.title],
  order_by: [asc: c.name, desc: c.title],

  preload: [:comments],
  preload: [comments: {c, likes: l}],

  join: c in assoc(c, :comments),
  join: p in Post, on: c.post_id == p.id,
  group_by: p,

  select: p,
  select: {p.title, p.description},
  select: [p.title, p.description],
```

### Get many

```elixir
Repo.all(User)
```

### Update many

```elixir
Repo.update_all(Post, set: [title: "Title"])
Repo.update_all(Post, inc: [views: 1])
```

### Chaining `_all` with queries

```elixir
from(p in Post, where: p.id < 10)
|> Repo.update_all(...)

from(p in Post, where: p.id < 10)
|> Repo.all()
```

## References
{: .-one-column}

- Based on Ecto 1.3.


id: phoenix-conn
git_filename: ./phoenix-conn.md
format: md
field_title: Phoenix: Plug.Conn
field_category: Elixir
field_updated: 2018-01-19
field_updated___timezone: UTC
data:
{"title": "Phoenix: Plug.Conn", "category": "Elixir", "updated": "2018-01-19", "weight": -5, "body": "Request\n-------\n\n### Request\n{: .-prime}\n\n```elixir\nconn.host          # \u2192 \"example.com\"\nconn.method        # \u2192 \"GET\"\nconn.path_info     # \u2192 [\"posts\", \"1\"]\nconn.request_path  # \u2192 \"/posts/1\"\nconn.query_string  # \u2192 \"utm_source=twitter\"\nconn.port          # \u2192 80\nconn.scheme        # \u2192 :http\nconn.peer          # \u2192 { {127, 0, 0, 1}, 12345 }\nconn.remote_ip     # \u2192 { 151, 236, 219, 228 }\nconn.req_headers   # \u2192 [{\"content-type\", \"text/plain\"}]\n```\n\n```elixir\nconn |> get_req_header(\"content-type\")\n# \u2192 [\"text/plain\"]\n```\n\n### Updating conn\n\n```elixir\nconn\n|> put_req_header(\"accept\", \"application/json\")\n```\n\nUsually only useful for tests.\n\nResponse\n--------\n\n### Response\n{: .-prime}\n\n```elixir\nconn.resp_body     # \u2192 \"...\"\nconn.resp_charset  # \u2192 \"utf-8\"\nconn.resp_cookies  # \u2192 ...\nconn.resp_headers  # \u2192 ...\nconn.status        # \u2192 ...\n```\n\n### Sending responses\n\n```elixir\n# Plug.Conn\nconn\n|> html(\"<html><head>...\")\n|> json(%{ message: \"Hello\" })\n|> text(\"Hello\")\n```\n\n```elixir\n|> redirect(to: \"/foo\")\n|> redirect(external: \"http://www.google.com/\")\n|> halt()\n```\n\n```elixir\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```elixir\n|> put_private(:plug_foo, \"...\")  # reserved for libraries\n```\n\n```elixir\n|> send_resp(201, \"\")\n```\n\n### Phoenix views\n\n```elixir\n# Phoenix.Controller\nconn\n|> render(\"index.html\")\n|> render(\"index.html\", hello: \"world\")\n|> render(MyApp.ErrorView, \"404.html\")\n```\n\n```elixir\n|> put_layout(:foo)\n|> put_layout(false)\n|> put_view(ErrorView)\n```\n\n```elixir\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```elixir\n|> put_new_view(ErrorView)  # if not set yet\n|> put_new_layout(:foo)\n```\n\n```elixir\nlayout(conn)\n```\n\nOther features\n--------------\n\n### Other fields\n{: .-prime}\n\n```elixir\nconn.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```js\nplug :accepts, [\"html\", \"json\"]\nconn |> accepts([\"html\", \"json\"])\nget_format(conn)  # \u2192 \"html\"\nconn.accepts\n```\n\n### Assigns\n\n```elixir\nconn.assigns[:hello]\nconn |> assign(:user_id, 100)\n```\n\n```elixir\nconn = async_assign(conn, :location, fn -> geoip_lookup() end)\nawait_assign(conn, :location)\n```\n\n### Session\n\n```elixir\nconn = 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```elixir\nconn\n|> put_flash(:info, \"Success\")\n|> put_flash(:error, \"Oh no\")\n```\n\nAlso available: `flash` `cookie` `params`"}

field_body:
Request
-------

### Request
{: .-prime}

```elixir
conn.host          # → "example.com"
conn.method        # → "GET"
conn.path_info     # → ["posts", "1"]
conn.request_path  # → "/posts/1"
conn.query_string  # → "utm_source=twitter"
conn.port          # → 80
conn.scheme        # → :http
conn.peer          # → { {127, 0, 0, 1}, 12345 }
conn.remote_ip     # → { 151, 236, 219, 228 }
conn.req_headers   # → [{"content-type", "text/plain"}]
```

```elixir
conn |> get_req_header("content-type")
# → ["text/plain"]
```

### Updating conn

```elixir
conn
|> put_req_header("accept", "application/json")
```

Usually only useful for tests.

Response
--------

### Response
{: .-prime}

```elixir
conn.resp_body     # → "..."
conn.resp_charset  # → "utf-8"
conn.resp_cookies  # → ...
conn.resp_headers  # → ...
conn.status        # → ...
```

### Sending responses

```elixir
# Plug.Conn
conn
|> html("<html><head>...")
|> json(%{ message: "Hello" })
|> text("Hello")
```

```elixir
|> redirect(to: "/foo")
|> redirect(external: "http://www.google.com/")
|> halt()
```

```elixir
|> put_resp_content_type("text/plain")
|> put_resp_cookie("abc", "def")
|> put_resp_header("X-Delivered-By", "myapp")
|> put_status(202)
|> put_status(:not_found)
```

```elixir
|> put_private(:plug_foo, "...")  # reserved for libraries
```

```elixir
|> send_resp(201, "")
```

### Phoenix views

```elixir
# Phoenix.Controller
conn
|> render("index.html")
|> render("index.html", hello: "world")
|> render(MyApp.ErrorView, "404.html")
```

```elixir
|> put_layout(:foo)
|> put_layout(false)
|> put_view(ErrorView)
```

```elixir
|> put_secure_browser_headers()
# prevent clickjacking, nosniff, and xss protection
# x-frame-options, x-content-type-options, x-xss-protection
```

```elixir
|> put_new_view(ErrorView)  # if not set yet
|> put_new_layout(:foo)
```

```elixir
layout(conn)
```

Other features
--------------

### Other fields
{: .-prime}

```elixir
conn.assigns          # storage of crap
conn.owner            # process
conn.halted           # if pipeline was halted
conn.secret_key_base  # ...
conn.state            # :unset, :set, :file, :sent, :chunked
```

### Accepts

```js
plug :accepts, ["html", "json"]
conn |> accepts(["html", "json"])
get_format(conn)  # → "html"
conn.accepts
```

### Assigns

```elixir
conn.assigns[:hello]
conn |> assign(:user_id, 100)
```

```elixir
conn = async_assign(conn, :location, fn -> geoip_lookup() end)
await_assign(conn, :location)
```

### Session

```elixir
conn = fetch_session(conn)   # or plug :fetch_session

conn = put_session(conn, :message, "new stuff we just set in the session")
get_session(conn, :message)
conn = clear_session(conn)
```

```elixir
conn
|> put_flash(:info, "Success")
|> put_flash(:error, "Oh no")
```

Also available: `flash` `cookie` `params`


id: ph-food-delivery
git_filename: ./ph-food-delivery.md
format: md
field_title: Food delivery (Philippines)
data:
{"title": "Food delivery (Philippines)", "intro": "Food delivery numbers & sites for top restaurant chains in Metro Manila. For numbers outside Metro Manila, check their websites.\n", "body": "## Numbers\n{: .-two-column}\n\n### Western\n\n| Restaurant    | Online order                                                        | Phone                                                                                                       |\n| ---           | ---                                                                 | ---                                                                                                         |\n| Army Navy     | [armynavy.com.ph](http://www.armynavy.com.ph/)                      | `331-3131`                                                                                                  |\n| Burger King   | [burgerkingdelivery.com.ph](https://www.burgerkingdelivery.com.ph/) | <abbr class='hint-mark hint--bottom' data-hint='Yes, you need to dial the # sign'><i></i></abbr> `#2-22-22` |\n| KFC           | [kfc.com.ph](https://www.kfc.com.ph)                                | `887-8888`                                                                                                  |\n| Kenny Rogers  | [kennys.com.ph](http://kennys.com.ph/)                              | `555-9000`                                                                                                  |\n| McDonald's    | [mcdonalds.com.ph](http://www.mcdonalds.com.ph/mcdelivery)          | `8-6236`                                                                                                    |\n| Pancake House | [pancakehouse.com.ph](https://www.pancakehouse.com.ph/)             | `7-9000`                                                                                                    |\n| Wendy's       | [wendys.com.ph](https://wendys.com.ph/delivery/)                    | `533-3333`                                                                                                  |\n{: .-bold-first.-headers.-no-wrap}\n\n### Pizza\n\n| Restaurant    | Online order                                              | Phone      |\n| ---           | ---                                                       | ---        |\n| Angel's Pizza | [angelspizza.com.ph](http://angelspizza.com.ph/)          | `922-2222` |\n| Domino's      | [dominospizza.ph](https://www.dominospizza.ph/)           | `997-3030` |\n| Greenwich     | [greenwichdelivery.com](http://greenwichdelivery.com/)    | `5-5555`   |\n| Papa John's   | [papajohns.com.ph](http://papajohns.com.ph/)              | `887-7272` |\n| Pizza Hut     | [pizzahut.com.ph](https://order.pizzahut.com.ph)          | `911-1111` |\n| Shakey's      | [shakeyspizza.ph](http://order.shakeyspizza.ph/)          | `77-7777`  |\n| Yellow Cab    | [yellowcabpizza.com](http://delivery.yellowcabpizza.com/) | `789-9999` |\n{: .-bold-first.-headers.-no-wrap}\n\n### Asian\n\n| Restaurant    | Online order                                                        | Phone       |\n| ---           | ---                                                                 | ---         |\n| Bonchon       | [bonchon.com.ph](http://bonchon.com.ph/food/main-menu/) _(menu)_    | `633-1818`  |\n| Chowking      | [chowkingdelivery.com](http://www.chowkingdelivery.com)             | `9-8888`    |\n| North Park    | [northparkdelivery.com](http://northparkdelivery.com/)              | `7-3737`    |\n| Yoshinoya     | [yoshinoya.ph](http://www.yoshinoya.ph/ordeonline.html/)            | `288-2888`  |\n{: .-bold-first.-headers.-no-wrap}\n\n### Filipino\n\n| Restaurant    | Online order                                                        | Phone       |\n| ---           | ---                                                                 | ---         |\n| Amber's       | [amber.com.ph](http://onlineordering.amber.com.ph/)                 | `884-8888`  |\n| Goldilock's   | [goldilocksdelivery.com.ph](http://www.goldilocksdelivery.com.ph/)  | `888-1-999` |\n| Jollibee      | [jollibeedelivery.com](http://jollibeedelivery.com)                 | `#8-7000`   |\n| Mang Inasal   | [manginasal.com](http://www.manginasal.com/menu/) _(menu)_          | `733-1111`  |\n| Max's         | [maxschicken.com](http://delivery.maxschicken.com/)                 | `7-9000`    |\n{: .-bold-first.-headers.-no-wrap}\n\n### Dessert\n\n| Restaurant    | Online order                                                        | Phone       |\n| ---           | ---                                                                 | ---         |\n| Krispy Kreme  | [now.krispykreme.com.ph](http://now.krispykreme.com.ph/)            | `7-9000`    |\n| Red Ribbon    | [redribbononlinestore.com](http://redribbononlinestore.com/)        | `8-7777`    |\n{: .-bold-first.-headers.-no-wrap}\n\n## -\n\nHint: you can get to this page via [devhints.io/gutom](https://devhints.io/gutom) \ud83c\udf45\ud83c\udf5f"}

field_intro:
Food delivery numbers & sites for top restaurant chains in Metro Manila. For numbers outside Metro Manila, check their websites.

field_body:
## Numbers
{: .-two-column}

### Western

| Restaurant    | Online order                                                        | Phone                                                                                                       |
| ---           | ---                                                                 | ---                                                                                                         |
| Army Navy     | [armynavy.com.ph](http://www.armynavy.com.ph/)                      | `331-3131`                                                                                                  |
| Burger King   | [burgerkingdelivery.com.ph](https://www.burgerkingdelivery.com.ph/) | <abbr class='hint-mark hint--bottom' data-hint='Yes, you need to dial the # sign'><i></i></abbr> `#2-22-22` |
| KFC           | [kfc.com.ph](https://www.kfc.com.ph)                                | `887-8888`                                                                                                  |
| Kenny Rogers  | [kennys.com.ph](http://kennys.com.ph/)                              | `555-9000`                                                                                                  |
| McDonald's    | [mcdonalds.com.ph](http://www.mcdonalds.com.ph/mcdelivery)          | `8-6236`                                                                                                    |
| Pancake House | [pancakehouse.com.ph](https://www.pancakehouse.com.ph/)             | `7-9000`                                                                                                    |
| Wendy's       | [wendys.com.ph](https://wendys.com.ph/delivery/)                    | `533-3333`                                                                                                  |
{: .-bold-first.-headers.-no-wrap}

### Pizza

| Restaurant    | Online order                                              | Phone      |
| ---           | ---                                                       | ---        |
| Angel's Pizza | [angelspizza.com.ph](http://angelspizza.com.ph/)          | `922-2222` |
| Domino's      | [dominospizza.ph](https://www.dominospizza.ph/)           | `997-3030` |
| Greenwich     | [greenwichdelivery.com](http://greenwichdelivery.com/)    | `5-5555`   |
| Papa John's   | [papajohns.com.ph](http://papajohns.com.ph/)              | `887-7272` |
| Pizza Hut     | [pizzahut.com.ph](https://order.pizzahut.com.ph)          | `911-1111` |
| Shakey's      | [shakeyspizza.ph](http://order.shakeyspizza.ph/)          | `77-7777`  |
| Yellow Cab    | [yellowcabpizza.com](http://delivery.yellowcabpizza.com/) | `789-9999` |
{: .-bold-first.-headers.-no-wrap}

### Asian

| Restaurant    | Online order                                                        | Phone       |
| ---           | ---                                                                 | ---         |
| Bonchon       | [bonchon.com.ph](http://bonchon.com.ph/food/main-menu/) _(menu)_    | `633-1818`  |
| Chowking      | [chowkingdelivery.com](http://www.chowkingdelivery.com)             | `9-8888`    |
| North Park    | [northparkdelivery.com](http://northparkdelivery.com/)              | `7-3737`    |
| Yoshinoya     | [yoshinoya.ph](http://www.yoshinoya.ph/ordeonline.html/)            | `288-2888`  |
{: .-bold-first.-headers.-no-wrap}

### Filipino

| Restaurant    | Online order                                                        | Phone       |
| ---           | ---                                                                 | ---         |
| Amber's       | [amber.com.ph](http://onlineordering.amber.com.ph/)                 | `884-8888`  |
| Goldilock's   | [goldilocksdelivery.com.ph](http://www.goldilocksdelivery.com.ph/)  | `888-1-999` |
| Jollibee      | [jollibeedelivery.com](http://jollibeedelivery.com)                 | `#8-7000`   |
| Mang Inasal   | [manginasal.com](http://www.manginasal.com/menu/) _(menu)_          | `733-1111`  |
| Max's         | [maxschicken.com](http://delivery.maxschicken.com/)                 | `7-9000`    |
{: .-bold-first.-headers.-no-wrap}

### Dessert

| Restaurant    | Online order                                                        | Phone       |
| ---           | ---                                                                 | ---         |
| Krispy Kreme  | [now.krispykreme.com.ph](http://now.krispykreme.com.ph/)            | `7-9000`    |
| Red Ribbon    | [redribbononlinestore.com](http://redribbononlinestore.com/)        | `8-7777`    |
{: .-bold-first.-headers.-no-wrap}

## -

Hint: you can get to this page via [devhints.io/gutom](https://devhints.io/gutom) 🍅🍟


id: perl-pie
git_filename: ./perl-pie.md
format: md
field_title: Perl-pie
field_category: Development
data:
{"title": "Perl-pie", "category": "Development", "body": "### About\n{: .-intro}\n\nUse `perl` to search and replace across many files.\n\n### Search and replace\n\n```sh\nperl -p -i -e 's/hello/hola/g' *.txt\n```\n\n### Back-referencing\n\nUse `\\1` et al.\n\n```sh\n# '@include align-items(center);' => 'align-items: center;'\nperl -p -i -e \"s/\\@include (align-items)\\((.*)\\);/\\1: \\2;/g\"\n```"}

field_body:
### About
{: .-intro}

Use `perl` to search and replace across many files.

### Search and replace

```sh
perl -p -i -e 's/hello/hola/g' *.txt
```

### Back-referencing

Use `\1` et al.

```sh
# '@include align-items(center);' => 'align-items: center;'
perl -p -i -e "s/\@include (align-items)\((.*)\);/\1: \2;/g"
```


id: passenger
git_filename: ./passenger.md
format: md
field_title: Phusion Passenger
field_tags: WIP
data:
{"title": "Phusion Passenger", "tags": ["WIP"], "body": "### Enabling Phusion passenger\n\n```\nserver {\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\nThis is an example nginx configuration."}

field_body:
### Enabling Phusion passenger

```
server {
   listen 80;
   server_name www.yourhost.com;
   root /somewhere/public;   # <--- be sure to point to 'public'!
   passenger_enabled on;
   autoindex on; # Show directory listings
}
```

This is an example nginx configuration.


id: pass
git_filename: ./pass.md
format: md
field_title: Pass
field_category: CLI
data:
{"title": "Pass", "category": "CLI", "body": "Reference\n---------\n\n### Create\n\n```sh\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```sh\n$ pass insert [-m] twitter.com/rsc\n$ pass generate [-n] twitter.com/rsc length\n```\n\n### Retrieve\n\n```sh\n$ pass ls twitter.com/\n$ pass show twitter.com/rsc\n$ pass -c twitter.com/rsc\n```\n\n### Search\n\n```sh\n$ pass find twitter.com\n```\n\n### Management\n\n```sh\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```sh\n$ pass edit twitter.com/rsc\n```\n\n### Synchronize\n\n```sh\n$ pass git push\n$ pass git pull\n```\n\n## References\n\n* <https://passwordstore.org>"}

field_body:
Reference
---------

### Create

```sh
$ pass init [-p] <gpg-id>
$ pass git init
$ pass git remote add origin <your.git:repository>
$ pass git push -u --all
```

### Store

```sh
$ pass insert [-m] twitter.com/rsc
$ pass generate [-n] twitter.com/rsc length
```

### Retrieve

```sh
$ pass ls twitter.com/
$ pass show twitter.com/rsc
$ pass -c twitter.com/rsc
```

### Search

```sh
$ pass find twitter.com
```

### Management

```sh
$ pass mv twitter.com twitter.com/rsc
$ pass rm [-rf] twitter.com
$ pass cp twitter.com/rsc twitter.com/ricosc
```

```sh
$ pass edit twitter.com/rsc
```

### Synchronize

```sh
$ pass git push
$ pass git pull
```

## References

* <https://passwordstore.org>


id: parsley
git_filename: ./parsley.md
format: md
field_title: Parsley.js
field_category: JavaScript libraries
field_intro: [Parsley](http://parsleyjs.org/doc/) provides frontend form validation.
field_updated: 2018-12-06
field_updated___timezone: UTC
data:
{"title": "Parsley.js", "updated": "2018-12-06", "weight": -1, "category": "JavaScript libraries", "keywords": ["data-parsley-validate", "$('#form').parsley()", "errorClass", "successClass", "classHandler", "errorsContainer", "errorsWrapper", "errorTemplate"], "intro": "[Parsley](http://parsleyjs.org/doc/) provides frontend form validation.\n", "body": "## Parsley\n{: .-three-column}\n\n### Installing via NPM\n\n```\nnpm install --save parsleyjs\n```\n\n[parsleyjs](https://www.npmjs.com/package/parsleyjs) is the Parsley form validator. ('parsley' is a different package)\n\n### Enabling\n\n#### via HTML\n\n```html\n<form data-parsley-validate>\n<!-- \u2717 not preferred -->\n```\n\n#### via JavaScript\n\n```js\n$('#form').parsley(/* options */)\n```\n\nIt's preferable to explicitly call `$.fn.parsley()`.\n\n### API\n\n#### Form\n\n```js\n$('#myform').parsley()\n  .isValid()  // \u2192 true | null\n  .validate()\n  .reset()\n  .destroy()\n```\n\n#### Input\n\n```js\n$('#myform input').parsley()\n  .isValid()\n  .validate() // returns errors\n```\n\n### Validators\n\n```html\n<input ...>\n```\n\n#### Required\n\n```html\n  required\n```\n\n#### Types\n\n```html\n  type='email'\n```\n\n```html\n  type='url'\n  data-parsley-type='url'\n```\n\n#### Length\n\n```html\n  maxlength='6'\n  data-parsley-maxlength='6'\n  minlength='10'\n  data-parsley-minlength='10'\n```\n\n#### Numeric\n\n```html\n  pattern='\\d+'\n  data-parsley-pattern='\\d+'\n```\n\n```html\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```html\n  type='range'\n  data-parsley=range='[6, 10]'\n```\n\n```html\n  max='10'\n  data-parsley-max='10'\n  min='6'\n  data-parsley-min='6'\n```\n\n#### Checkboxes\n\n```html\n  data-parsley-mincheck='1'\n  data-parsley-maxcheck='3'\n  data-parsley-check='[1, 3]'\n```\n\n#### Confirmation\n\n```html\n  data-parsley-equalto='#confirm'\n```\n\n## Options\n\n### Form options\n\n```js\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```js\n// Stop validating field on highest priority failing constraint\n  priorityEnabled: true\n```\n\nSee: [Options](http://parsleyjs.org/doc/annotated-source/defaults.html)\n\n### Field options\n\n```js\n// identifier used to group together inputs\n// (e.g. radio buttons\u2026)\n  multiple: null\n```\n\n```js\n// identifier (or array of identifiers) used to\n// validate only a select group of inputs\n  group: null\n```\n\nThese options are only available for fields.\n\n### UI Options\n\n```js\n// Enable/disable error messages\n  uiEnabled: true\n```\n\n```js\n// Key events threshold before validation\n  validationThreshold: 3\n```\n\n```js\n// Focused field on form validation error. \u2018first\u2019|\u2019last\u2019|\u2019none\u2019\n  focus: 'first'\n```\n\n```js\n// $.Event() that will trigger validation. eg: keyup, change\u2026\n  trigger: false\n```\n\n```js\n// Class that would be added on every failing validation\n// Parsley field\n  errorClass: 'parsley-error'\n  successClass: 'parsley-success'\n```\n\n```js\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```js\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```js\n// ul elem that would receive errors\u2019 list\n  errorsWrapper: '<ul class=\"parsley-errors-list\"></ul>'\n```\n\n```js\n// li elem that would receive error message\n  errorTemplate: '<li></li>'\n```\n\n## Examples\n\n### Custom container\n\n```js\n$('[data-parsley]').parsley({\n  errorsContainer (field) {\n    return field.$element.closest('.block, .control')\n  }\n})\n```\n\nAppends the error to the closest `.block` or `.control`.\n\n### Custom markup\n\n```js\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\nUses custom markup.\n\n### Custom fields\n\n```js\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\nApplies the `errorClass` and `successClass` to the closest `.input-group`, if available.\n\n### Custom validator\n\n#### HTML\n\n```html\n<input type='text' data-parsley-multiple-of='3' />\n```\n\n#### JavaScript\n\n```js\nwindow.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\nSee: [Custom validators](http://parsleyjs.org/doc/index.html#custom)\n\n## Also see\n\n- [Parsley documentation](http://parsleyjs.org/doc/) _(parsleyjs.org)_"}

field_body:
## Parsley
{: .-three-column}

### Installing via NPM

```
npm install --save parsleyjs
```

[parsleyjs](https://www.npmjs.com/package/parsleyjs) is the Parsley form validator. ('parsley' is a different package)

### Enabling

#### via HTML

```html
<form data-parsley-validate>
<!-- ✗ not preferred -->
```

#### via JavaScript

```js
$('#form').parsley(/* options */)
```

It's preferable to explicitly call `$.fn.parsley()`.

### API

#### Form

```js
$('#myform').parsley()
  .isValid()  // → true | null
  .validate()
  .reset()
  .destroy()
```

#### Input

```js
$('#myform input').parsley()
  .isValid()
  .validate() // returns errors
```

### Validators

```html
<input ...>
```

#### Required

```html
  required
```

#### Types

```html
  type='email'
```

```html
  type='url'
  data-parsley-type='url'
```

#### Length

```html
  maxlength='6'
  data-parsley-maxlength='6'
  minlength='10'
  data-parsley-minlength='10'
```

#### Numeric

```html
  pattern='\d+'
  data-parsley-pattern='\d+'
```

```html
  type='number'
  data-parsley-type='number'
  data-parsley-type='integer'
  data-parsley-type='digits'
  data-parsley-type='alphanum'
```

#### Range

```html
  type='range'
  data-parsley=range='[6, 10]'
```

```html
  max='10'
  data-parsley-max='10'
  min='6'
  data-parsley-min='6'
```

#### Checkboxes

```html
  data-parsley-mincheck='1'
  data-parsley-maxcheck='3'
  data-parsley-check='[1, 3]'
```

#### Confirmation

```html
  data-parsley-equalto='#confirm'
```

## Options

### Form options

```js
// Supported & excluded inputs by default
  inputs: 'input, textarea, select'
  excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]'
```

```js
// Stop validating field on highest priority failing constraint
  priorityEnabled: true
```

See: [Options](http://parsleyjs.org/doc/annotated-source/defaults.html)

### Field options

```js
// identifier used to group together inputs
// (e.g. radio buttons…)
  multiple: null
```

```js
// identifier (or array of identifiers) used to
// validate only a select group of inputs
  group: null
```

These options are only available for fields.

### UI Options

```js
// Enable/disable error messages
  uiEnabled: true
```

```js
// Key events threshold before validation
  validationThreshold: 3
```

```js
// Focused field on form validation error. ‘first’|’last’|’none’
  focus: 'first'
```

```js
// $.Event() that will trigger validation. eg: keyup, change…
  trigger: false
```

```js
// Class that would be added on every failing validation
// Parsley field
  errorClass: 'parsley-error'
  successClass: 'parsley-success'
```

```js
// Return the $element that will receive these above
// success or error classes. Could also be (and given
// directly from DOM) a valid selector like '#div'
  classHandler: function (ParsleyField) {}
```

```js
// Return the $element where errors will be appended.
// Could also be (and given directly from DOM) a valid
// selector like '#div'
  errorsContainer: function (ParsleyField) {}
```

```js
// ul elem that would receive errors’ list
  errorsWrapper: '<ul class="parsley-errors-list"></ul>'
```

```js
// li elem that would receive error message
  errorTemplate: '<li></li>'
```

## Examples

### Custom container

```js
$('[data-parsley]').parsley({
  errorsContainer (field) {
    return field.$element.closest('.block, .control')
  }
})
```

Appends the error to the closest `.block` or `.control`.

### Custom markup

```js
$('[data-parsley]').parsley({
  errorClass: '-error',
  successClass: '-success',

  errorsWrapper: '<ul class="parsley-error-list"></ul>',
  errorTemplate: '<li class="parsley-error"></li>'
})
```

Uses custom markup.

### Custom fields

```js
$('[data-parsley]').parsley({
  classHandler (field) {
    const $parent = field.$element.closest('.input-group')
    if ($parent.length) return $parent

    return field.$element
  }
})
```

Applies the `errorClass` and `successClass` to the closest `.input-group`, if available.

### Custom validator

#### HTML

```html
<input type='text' data-parsley-multiple-of='3' />
```

#### JavaScript

```js
window.Parsley
  .addValidator('multipleOf', {
    // string | number | integer | date | regexp | boolean
    requirementType: 'integer',

    // validateString | validateDate | validateMultiple
    validateNumber (value, requirement) {
      return 0 === value % requirement
    },

    messages: {
      en: 'This value should be a multiple of %s'
    }
  })
```

See: [Custom validators](http://parsleyjs.org/doc/index.html#custom)

## Also see

- [Parsley documentation](http://parsleyjs.org/doc/) _(parsleyjs.org)_


id: parsimmon
git_filename: ./parsimmon.md
format: md
field_title: Parsimmon
field_category: JavaScript libraries
data:
{"title": "Parsimmon", "category": "JavaScript libraries", "body": "### Basic usage\n```js\nconst P = require('parsimmon')\n\nP.regexp(/[a-z]+/)\n.parse('hello')\n//=> { status: true, value: ['hello'] }\n```\n\n### Atoms\n\n```js\nP.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```js\nP.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```js\nP.seq(P.number, P.oneOf('+-*/'), P.number)\n.map(([left, oper, right]) => ({ oper, left, right }))\n```\n\n### Reference\n\n- <https://github.com/jneen/parsimmon/blob/master/API.md>"}

field_body:
### Basic usage
```js
const P = require('parsimmon')

P.regexp(/[a-z]+/)
.parse('hello')
//=> { status: true, value: ['hello'] }
```

### Atoms

```js
P.regexp(/[a-z]+/)
P.string('hello')
P.oneOf('abc')             // like P.regexp(/[abc]/)

P.whitespace
P.optWhitespace
P.eof
```

### Combinators

```js
P.seq(a, b, c)             // sequence of these
P.alt(a, b)                // any of these
P.sepBy(a, P.string(','))  // sequence of `a`, separated by ','
P.sepBy1(a, P.string(',')) // same, at least once

a.or(b)                    // like P.alt(a, b)
a.skip(b)                  // parses `b` but discards it

a.many()
a.times(3)
a.times(1, 4)              // 1 <= x <= 4
a.atMost(10)
a.atLeast(10)
```

### Formatting

```js
P.seq(P.number, P.oneOf('+-*/'), P.number)
.map(([left, oper, right]) => ({ oper, left, right }))
```

### Reference

- <https://github.com/jneen/parsimmon/blob/master/API.md>


id: pacman
git_filename: ./pacman.md
format: md
field_title: Pacman
field_category: Linux
field_updated: 2018-07-07
field_updated___timezone: UTC
data:
{"title": "Pacman", "category": "Linux", "updated": "2018-07-07", "body": "## Commands\n{: .-three-column}\n\n### About\n{: .-intro}\n\nPacman is the package manager for Arch Linux and its derivatives.\n\n- <https://wiki.archlinux.org/title/pacman>\n\n### Common commands\n\n| Command                 | Description                       |\n| ----------------------- | --------------------------------- |\n| `pacman -Syu <pkg>`     | Install (and update package list) |\n| `pacman -S <pkg>`       | Install only                      |\n| `pacman -Rsc <pkg>`     | Uninstall                         |\n| `pacman -Ss <keywords>` | Search                            |\n| `pacman -Syu`           | Upgrade everything                |\n{: .-prime}\n\n### Query\n\n| Command              | Description                            |\n| -------------------- | -------------------------------------- |\n| `pacman -Qe`         | List explictly-installed packages      |\n| ---                  | ---                                    |\n| `pacman -Ql <pkg>`   | What files does this package have?     |\n| `pacman -Qii <pkg>`  | List information on package            |\n| ---                  | ---                                    |\n| `pacman -Qo <file>`  | Who owns this file?                    |\n| ---                  | ---                                    |\n| `pacman -Qs <query>` | Search installed packages for keywords |\n\n### Orphans\n\n| Command                       | Description                 |\n| ----------------------------- | --------------------------- |\n| `pacman -Qdt`                 | List unneeded packages      |\n| `pacman -Rns $(pacman -Qdtq)` | Uninstall unneeded packages |\n\nAvoid orphans by using `pacman -Rsc` to remove packages, which will remove unneeded dependencies.\n\n### Other\n\n| Command            | Description                |\n| ------------------ | -------------------------- |\n| `pactree <pkg>`    | What does _pkg_ depend on? |\n| `pactree -r <pkg>` | What depends on _pkg_?     |\n\n### References\n\n* [Pacman tips and tricks](https://wiki.archlinux.org/index.php/Pacman/Tips_and_tricks) _(wiki.archlinux.org)_"}

field_body:
## Commands
{: .-three-column}

### About
{: .-intro}

Pacman is the package manager for Arch Linux and its derivatives.

- <https://wiki.archlinux.org/title/pacman>

### Common commands

| Command                 | Description                       |
| ----------------------- | --------------------------------- |
| `pacman -Syu <pkg>`     | Install (and update package list) |
| `pacman -S <pkg>`       | Install only                      |
| `pacman -Rsc <pkg>`     | Uninstall                         |
| `pacman -Ss <keywords>` | Search                            |
| `pacman -Syu`           | Upgrade everything                |
{: .-prime}

### Query

| Command              | Description                            |
| -------------------- | -------------------------------------- |
| `pacman -Qe`         | List 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 |

### Orphans

| Command                       | Description                 |
| ----------------------------- | --------------------------- |
| `pacman -Qdt`                 | List unneeded packages      |
| `pacman -Rns $(pacman -Qdtq)` | Uninstall unneeded packages |

Avoid orphans by using `pacman -Rsc` to remove packages, which will remove unneeded dependencies.

### Other

| Command            | Description                |
| ------------------ | -------------------------- |
| `pactree <pkg>`    | What does _pkg_ depend on? |
| `pactree -r <pkg>` | What depends on _pkg_?     |

### References

* [Pacman tips and tricks](https://wiki.archlinux.org/index.php/Pacman/Tips_and_tricks) _(wiki.archlinux.org)_


id: packs
git_filename: ./packs.md
format: md
field_title: Packs (ruby)
field_category: Ruby libraries
field_intro: Packs are a specification for an extensible packaging system to help modularize Ruby applications.
field_updated: 2024-07-05
field_updated___timezone: UTC
data:
{"title": "Packs (ruby)", "category": "Ruby libraries", "updated": "2024-07-05", "intro": "Packs are a specification for an extensible packaging system to help modularize Ruby applications.", "body": "## Manage packs\n\n### Create pack\n\n```bash\n$ bin/packs create packs/pack_name\n```\n\n#### Example\n\n```bash\n$ bin/packs create packs/profiles\n```\n\nCreate new pack named `profiles`.\n\n### Make a file or directory public\n\n```bash\n$ bin/packs make_public path/to/file.rb\n$ bin/packs make_public path/to/directory\n```\n\nMake file or directory public API, meaning that classes outside the package can call this logic.\n\n#### Example\n\n```bash\n$ bin/packs make_public packs/profiles/app/services/create_profile_service.rb\n```\n\nAllow external code to call the class `CreateProfileService`.\n\nThis command will mainly move that file in `packs/profiles/app/public/create_profile_service.rb`\n\n### Move a pack\n\n```bash\n$ bin/packs move packs/destination_pack path/to/file.rb\n$ bin/packs move packs/destination_pack path/to/directory\n```\n\nMove file or directory from one pack to another pack.\n\n```bash\n$ bin/packs move_to_folder packs/foo path/to/directory\n```\n\nMove `packs/foo` to the `path/to/directory` folder, where `path/to/directory` does not contain a `package.yml` file.\n\n```bash\n$ bin/packs move_to_parent packs/child_pack packs/parent_pack\n```\n\nSet `packs/child_pack` as a child of `packs/parent_pack`.\n\n### Add dependency to a pack\n\n```bash\n$ bin/packs add_dependency packs/from_pack packs/to_pack\n```\n\n## Packs validity\n\n### All packs are valid?\n\n```bash\n$ bin/packs validate\n```\n\nRuns `bin/packwerk validate` under the hood (detects cycles).\n\n### A specific pack is valid?\n\n```bash\n$ bin/packs check packs/pack_name\n```\n\nRuns `bin/packwerk check` under the hood.\n\n### Update `package.yml`\n\n```bash\n$ bin/packs update\n```\n\nRuns `bin/packwerk update-todo` under the hood.\n\n## Lints\n\n```bash\n$ bin/packs lint_package_todo_yml_files\n```\n\nLint `package_todo.yml` files to check for formatting issues.\n\n```bash\n$ bin/packs lint_package_yml_files [ packs/my_pack packs/my_other_pack ]\n```\n\nLint `package.yml` files.\n\n```bash\n$ bin/packs list_top_violations type [ packs/your_pack ]\n```\n\nList the top violations of a specific type for `packs/your_pack`.\n\n## Also see\n\n- [Documentation](https://github.com/rubyatscale/packs) _(`packs` github repository)_"}

field_body:
## Manage packs

### Create pack

```bash
$ bin/packs create packs/pack_name
```

#### Example

```bash
$ bin/packs create packs/profiles
```

Create new pack named `profiles`.

### Make a file or directory public

```bash
$ bin/packs make_public path/to/file.rb
$ bin/packs make_public path/to/directory
```

Make file or directory public API, meaning that classes outside the package can call this logic.

#### Example

```bash
$ bin/packs make_public packs/profiles/app/services/create_profile_service.rb
```

Allow external code to call the class `CreateProfileService`.

This command will mainly move that file in `packs/profiles/app/public/create_profile_service.rb`

### Move a pack

```bash
$ bin/packs move packs/destination_pack path/to/file.rb
$ bin/packs move packs/destination_pack path/to/directory
```

Move file or directory from one pack to another pack.

```bash
$ bin/packs move_to_folder packs/foo path/to/directory
```

Move `packs/foo` to the `path/to/directory` folder, where `path/to/directory` does not contain a `package.yml` file.

```bash
$ bin/packs move_to_parent packs/child_pack packs/parent_pack
```

Set `packs/child_pack` as a child of `packs/parent_pack`.

### Add dependency to a pack

```bash
$ bin/packs add_dependency packs/from_pack packs/to_pack
```

## Packs validity

### All packs are valid?

```bash
$ bin/packs validate
```

Runs `bin/packwerk validate` under the hood (detects cycles).

### A specific pack is valid?

```bash
$ bin/packs check packs/pack_name
```

Runs `bin/packwerk check` under the hood.

### Update `package.yml`

```bash
$ bin/packs update
```

Runs `bin/packwerk update-todo` under the hood.

## Lints

```bash
$ bin/packs lint_package_todo_yml_files
```

Lint `package_todo.yml` files to check for formatting issues.

```bash
$ bin/packs lint_package_yml_files [ packs/my_pack packs/my_other_pack ]
```

Lint `package.yml` files.

```bash
$ bin/packs list_top_violations type [ packs/your_pack ]
```

List the top violations of a specific type for `packs/your_pack`.

## Also see

- [Documentation](https://github.com/rubyatscale/packs) _(`packs` github repository)_


id: package-json
git_filename: ./package-json.md
format: md
field_title: package.json
field_category: Node.js
field_prism_languages: json
field_updated: 2020-06-23
field_updated___timezone: UTC
data:
{"title": "package.json", "category": "Node.js", "prism_languages": ["json"], "updated": "2020-06-23", "weight": -3, "body": "### Basic\n\n```json\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{: data-line=\"2,3,4,5\"}\n\nHighlighted lines are required.\n\n### Dependencies\n\n```json\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```json\n\"devDependencies\": { \u00b7\u00b7\u00b7 },\n\"peerDependencies\": { \u00b7\u00b7\u00b7 },\n\"optionalDependencies\": { \u00b7\u00b7\u00b7 },\n```\n\nSee [Semver cheatsheet](./semver) for explanation of version ranges.\n\n### Scripts\n\n```json\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```json\n\"private\": true,\n\"preferGlobal\": true\n```\n\n### Config\n\n```json\n{\n  \"config\": {\n    \"foobar\": \"hello\"\n  },\n  \"scripts\": {\n    \"run\": \"echo $npm_package_config_foobar\"\n  }\n}\n```\n\nKeys in `config` are exposed as env vars to scripts.\n\n## References\n{: .-one-column}\n\n * <http://package.json.nodejitsu.com/>\n * `npm help package.json`\n{: .-also-see}"}

field_body:
### Basic

```json
{
  "name": "expo",
  "description": "My package",
  "version": "0.1.0",
  "license": "MIT",
  "keywords": ["http", "server"],
  "author": "Rico Sta. Cruz <rstacruz@users.noreply.github.com>",
  "engines": {
    "node": ">=0.8.0"
  },
  "main": "index",
  "bin": {
    "command": "./bin/command"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/rstacruz/___.git"
  },
}
```
{: data-line="2,3,4,5"}

Highlighted lines are required.

### Dependencies

```json
"dependencies": {
  "colors":   "*",
  "flatiron": "0.1.x",
  "flatiron": "~0.1.0",
  "plates":   "https://github.com/user/project/tarball/branch",
  "stuff":    "git://github.com/user/project.git#commit-ish"
},
```

```json
"devDependencies": { ··· },
"peerDependencies": { ··· },
"optionalDependencies": { ··· },
```

See [Semver cheatsheet](./semver) for explanation of version ranges.

### Scripts

```json
"scripts": {
  "start": "node ./bin/xxx",       /* npm start */
  "test": "vows --spec --isolate", /* npm test */
  "postinstall": "...",
  "prepublish": "grunt build",     /* after 'npm install' and before 'npm 
                                      publish' */
}
```

### Misc

```json
"private": true,
"preferGlobal": true
```

### Config

```json
{
  "config": {
    "foobar": "hello"
  },
  "scripts": {
    "run": "echo $npm_package_config_foobar"
  }
}
```

Keys in `config` are exposed as env vars to scripts.

## References
{: .-one-column}

 * <http://package.json.nodejitsu.com/>
 * `npm help package.json`
{: .-also-see}


id: osx
git_filename: ./osx.md
format: md
field_title: OS X
field_category: macOS
data:
{"title": "OS X", "category": "macOS", "body": "### 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### Hide desktop icons\n\n    defaults write com.apple.finder CreateDesktop -bool false\n    killall Finder\n\n### Auto-hide other windows on dock switch\n\n    defaults write com.apple.dock single-app -bool TRUE\n    killall Dock\n\n    defaults delete com.apple.dock single-app\n    killall Dock\n\n### Flush DNS\n\n    killall -HUP mDNSResponder   # 10.8+\n    dscacheutil -flushcache      # 10.7 below\n\n### Disable spotlight indexing\n\n    mdutil -a -i off                    # disable indexing for all volumes\n    mdutil -i off MOUNT_POINT           # disable for specific volume\n    touch FOLDER/.metadata_never_index  # disable for FOLDER\n                                        \n\n### Turn on/off proxy\n\n    sudo networksetup -setsocksfirewallproxystate Wi-Fi off\n    sudo networksetup -setsocksfirewallproxystate Ethernet off\n    sudo networksetup -setsocksfirewallproxy Wi-Fi 127.0.0.1 9999\n    sudo networksetup -setsocksfirewallproxy Ethernet 127.0.0.1 9999\n    sudo networksetup -setsocksfirewallproxystate Wi-Fi on\n    sudo networksetup -setsocksfirewallproxystate Ethernet on\n\n### System utils\n\n - `networksetup` - Configure network (ip, dns, proxy, etc)\n - `tmutil` - Configure Time Machine (enable/disable, exclude path, delete snapshots, etc)\n - `mdutil` - Manage Spotlight (enable/disable, exclude, etc)\n - `diskutil` - Control disk (format, eject, unmount, etc)\n - `launchctl` - Control running \"agents\"\n\n### Useful utils\n\n - `open` - open files and directories ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/open.1.html))\n - `textutil` - manipulate text files of various formats ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/textutil.1.html))\n - `pbcopy` / `pbpaste` - provide copying and pasting to the pasteboard ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/pbcopy.1.html))\n - `sips` - scriptable image processing system ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/sips.1.html))\n - `mdfind` - finds files matching a given query ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/mdfind.1.html))\n - `screencapture` - capture images from the screen ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/screencapture.1.html))\n - `defaults` - access the Mac OS X user defaults system ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/defaults.1.html))\n - `/usr/libexec/airportd`\n - `scutil`\n\n __INFO: `brew` ([link](https://brew.sh)) is highly recommended utility__"}

field_body:
### Locations of startup items

    ~/Library/LaunchAgents
    /System/Library/LaunchAgents/
    /System/Library/LaunchDaemons/
    /Library/LaunchAgents/
    /Library/LaunchDaemons/

    __Running `launchctl list` show you what launch scripts are currently loaded.__

### Hide desktop icons

    defaults write com.apple.finder CreateDesktop -bool false
    killall Finder

### Auto-hide other windows on dock switch

    defaults write com.apple.dock single-app -bool TRUE
    killall Dock

    defaults delete com.apple.dock single-app
    killall Dock

### Flush DNS

    killall -HUP mDNSResponder   # 10.8+
    dscacheutil -flushcache      # 10.7 below

### Disable spotlight indexing

    mdutil -a -i off                    # disable indexing for all volumes
    mdutil -i off MOUNT_POINT           # disable for specific volume
    touch FOLDER/.metadata_never_index  # disable for FOLDER
                                        

### Turn on/off proxy

    sudo networksetup -setsocksfirewallproxystate Wi-Fi off
    sudo networksetup -setsocksfirewallproxystate Ethernet off
    sudo networksetup -setsocksfirewallproxy Wi-Fi 127.0.0.1 9999
    sudo networksetup -setsocksfirewallproxy Ethernet 127.0.0.1 9999
    sudo networksetup -setsocksfirewallproxystate Wi-Fi on
    sudo networksetup -setsocksfirewallproxystate Ethernet on

### System utils

 - `networksetup` - Configure network (ip, dns, proxy, etc)
 - `tmutil` - Configure Time Machine (enable/disable, exclude path, delete snapshots, etc)
 - `mdutil` - Manage Spotlight (enable/disable, exclude, etc)
 - `diskutil` - Control disk (format, eject, unmount, etc)
 - `launchctl` - Control running "agents"

### Useful utils

 - `open` - open files and directories ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/open.1.html))
 - `textutil` - manipulate text files of various formats ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/textutil.1.html))
 - `pbcopy` / `pbpaste` - provide copying and pasting to the pasteboard ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/pbcopy.1.html))
 - `sips` - scriptable image processing system ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/sips.1.html))
 - `mdfind` - finds files matching a given query ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/mdfind.1.html))
 - `screencapture` - capture images from the screen ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/screencapture.1.html))
 - `defaults` - access the Mac OS X user defaults system ([man](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/defaults.1.html))
 - `/usr/libexec/airportd`
 - `scutil`

 __INFO: `brew` ([link](https://brew.sh)) is highly recommended utility__


id: org-mode
git_filename: ./org-mode.md
format: md
field_title: Org Mode
field_category: Apps
field_tags: WIP
field_intro: [Org mode](https://orgmode.org/) is for keeping hierarchal notes (and more) in Emacs.
field_updated: 2018-02-19
field_updated___timezone: UTC
data:
{"title": "Org Mode", "tags": ["WIP"], "category": "Apps", "updated": "2018-02-19", "intro": "[Org mode](https://orgmode.org/) is for keeping hierarchal notes (and more) in Emacs.\n", "body": "## Syntax\n{: .-three-column}\n\n### Headings\n\n```org\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```org\n* Lists\n\nTo buy:\n1. Milk\n2. Eggs\n   - Organic\n3. Cheese\n   + Parmesan\n   + Mozarella\n```\n\n### Inline styles\n\n```org\n*bold*\n/italic/\n_underline_\n=verbatim=\n~code~\n+strike-through+\n```\n\n### To do\n\n```org\n* TODO buy airplane\n```\n\nCycle by using `S-LEFT` / `S-RIGHT`. List all TODO's via `C-c C-v`.\n\n## Shortcuts\n{: .-three-column}\n\n### Basic shortcuts\n\n| Description    | Shortcut             |\n| ---            | ---                  |\n| (Un) fold      | `TAB` / `S-TAB`      |\n| Move up        | `M-UP` / `M-DOWN`    |\n| New headline   | `M-RET`              |\n| Cycle workflow | `S-LEFT` / `S-RIGHT` |\n| Cycle priority | `S-UP` / `S-DOWN` |\n{:.-shortcuts-right}\n\n### Timer\n\n| Description     | Shortcut        |\n| ---             | ---             |\n| Start timer     | `C-c` `C-x` `0` |\n| Stop timer      | `C-c` `C-x` `_` |\n| Pause timer     | `C-c` `C-x` `,` |\n| ---             | ---             |\n| Start countdown | `C-c` `C-x` `;` |\n{:.-shortcuts-right}\n\nYou can use this for Pomodoro!\n\n### Agenda\n\n| Description     | Shortcut        |\n| ---             | ---             |\n| Agenda menu     | `C-c` `a`       |\n| ---             | ---             |\n| Add document    | `C-c` `[`       |\n| Remove document | `C-c` `]`       |\n| ---             | ---             |\n| Add date        | `C-c` `.`       |\n| Add time & date | `C-u` `C-c` `.` |\n{:.-shortcuts-right}\n\nStart by adding the current file to the agenda (`C-c [`), then use the agenda menu to navigate.\n\n### Export\n\n| Description | Shortcut    |\n| ---         | ---         |\n| Export menu | `C-c` `C-e` |\n\nLets you export the document as Markdown, HTML, and others.\n\n## References\n\n- [Org for beginners](https://orgmode.org/worg/org-tutorials/org4beginners.html) _(orgmode.org)_\n- [Org mode website](https://orgmode.org/) _(orgmode.org)_"}

field_body:
## Syntax
{: .-three-column}

### Headings

```org
* Welcome to Org mode

  Lines starting with * are headings.
  These lines without are notes.

** Sub-heading

   Two stars mark a 2nd-level subheading (h2).
```

### Lists

```org
* Lists

To buy:
1. Milk
2. Eggs
   - Organic
3. Cheese
   + Parmesan
   + Mozarella
```

### Inline styles

```org
*bold*
/italic/
_underline_
=verbatim=
~code~
+strike-through+
```

### To do

```org
* TODO buy airplane
```

Cycle by using `S-LEFT` / `S-RIGHT`. List all TODO's via `C-c C-v`.

## Shortcuts
{: .-three-column}

### Basic shortcuts

| Description    | Shortcut             |
| ---            | ---                  |
| (Un) fold      | `TAB` / `S-TAB`      |
| Move up        | `M-UP` / `M-DOWN`    |
| New headline   | `M-RET`              |
| Cycle workflow | `S-LEFT` / `S-RIGHT` |
| Cycle priority | `S-UP` / `S-DOWN` |
{:.-shortcuts-right}

### Timer

| Description     | Shortcut        |
| ---             | ---             |
| Start timer     | `C-c` `C-x` `0` |
| Stop timer      | `C-c` `C-x` `_` |
| Pause timer     | `C-c` `C-x` `,` |
| ---             | ---             |
| Start countdown | `C-c` `C-x` `;` |
{:.-shortcuts-right}

You can use this for Pomodoro!

### Agenda

| Description     | Shortcut        |
| ---             | ---             |
| Agenda menu     | `C-c` `a`       |
| ---             | ---             |
| Add document    | `C-c` `[`       |
| Remove document | `C-c` `]`       |
| ---             | ---             |
| Add date        | `C-c` `.`       |
| Add time & date | `C-u` `C-c` `.` |
{:.-shortcuts-right}

Start by adding the current file to the agenda (`C-c [`), then use the agenda menu to navigate.

### Export

| Description | Shortcut    |
| ---         | ---         |
| Export menu | `C-c` `C-e` |

Lets you export the document as Markdown, HTML, and others.

## References

- [Org for beginners](https://orgmode.org/worg/org-tutorials/org4beginners.html) _(orgmode.org)_
- [Org mode website](https://orgmode.org/) _(orgmode.org)_


id: npm
git_filename: ./npm.md
format: md
field_title: npm
field_category: JavaScript
field_updated: 2019-12-24
field_updated___timezone: UTC
data:
{"title": "npm", "category": "JavaScript", "weight": -1, "updated": "2019-12-24", "body": "### Package management\n\n| Command                           | Description                                               |\n| ---                               | ---                                                       |\n| `npm i`                           | Alias for `npm install`                                   |\n| `npm install`                     | Install everything in package.json                        |\n| `npm install --production`        | Install everything in package.json, except devDependecies |\n\n### Adding packages\n\n| Command                           | Description                                               |\n| ---                               | ---                                                       |  \n| `npm install lodash`              | Install a package                                         |\n| `npm install --save-dev lodash`   | Install as devDependency                                  |\n| `npm install --save-exact lodash` | Install with exact                                        |\n\n### Listing\n\n| Command                 | Description                                                         |\n| ---                     | ---                                                                 |\n| `npm list`              | Lists the installed versions of all dependencies in this software   | \n| `npm list -g --depth 0` | Lists the installed versions of all globally installed packages     | \n| `npm view`              | Lists the latest versions of all dependencies in this software      | \n| `npm outdated`          | Lists only the dependencies in this software which are outdated     |\n\n### Updating\n\n| Command             | Description                |\n| ---                 | ---                        |\n| `npm update`        | Update production packages |\n| `npm update --dev`  | Update dev packages        |\n| `npm update -g`     | Update global packages     |\n| ---                 | ---                        |\n| `npm update lodash` | Update a package           |\n\n\n### Removing\n\n| Command             | Description                        |\n| ---                 | ---                                |\n| `npm rm lodash`     | Remove package production packages |\n\n## More features\n\n### Install names\n\n| Command                              | Description             |\n| ---                                  | ---                     |\n| `npm i sax`                          | NPM package             |\n| `npm i sax@latest`                   | Specify tag `latest`    |\n| `npm i sax@3.0.0`                    | Specify version `3.0.0` |\n| `npm i sax@\">=1 <2.0\"`               | Specify version range   |\n| ---                                  | ---                     |\n| `npm i @org/sax`                     | Scoped NPM package      |\n| ---                                  | ---                     |\n| `npm i user/repo`                    | GitHub                  |\n| `npm i user/repo#master`             | GitHub                  |\n| `npm i github:user/repo`             | GitHub                  |\n| `npm i gitlab:user/repo`             | GitLab                  |\n| ---                                  | ---                     |\n| `npm i /path/to/repo`                | Absolute path           |\n| `npm i ./archive.tgz`                | Tarball                 |\n| `npm i https://site.com/archive.tgz` | Tarball via HTTP        |\n\n### Bumping versions\n\n| Command                           | Description                                               |\n| ---                               | ---                                                       |\n| `npm version 1.2.3`               | Bump the package version to 1.2.3                         |\n| `npm version major`               | Bump the major package version by 1 (1.2.3 \u2192 2.0.0)       |\n| `npm version minor`               | Bump the minor package version by 1 (1.2.3 \u2192 1.3.0)       |\n| `npm version patch`               | Bump the patch package version by 1 (1.2.3 \u2192 1.2.4)       |\n\n### Misc features\n\n```bash\n# Add someone as an owner\nnpm owner add USERNAME PACKAGENAME\n```\n\n```bash\n# list packages\nnpm ls\n```\n\n```bash\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```bash\n# update all packages, or selected packages\nnpm update [-g] PACKAGE\n```\n\n```bash\n# Check for outdated packages\nnpm outdated [PACKAGE]\n```"}

field_body:
### Package management

| Command                           | Description                                               |
| ---                               | ---                                                       |
| `npm i`                           | Alias for `npm install`                                   |
| `npm install`                     | Install everything in package.json                        |
| `npm install --production`        | Install everything in package.json, except devDependecies |

### Adding packages

| Command                           | Description                                               |
| ---                               | ---                                                       |  
| `npm install lodash`              | Install a package                                         |
| `npm install --save-dev lodash`   | Install as devDependency                                  |
| `npm install --save-exact lodash` | Install with exact                                        |

### Listing

| Command                 | Description                                                         |
| ---                     | ---                                                                 |
| `npm list`              | Lists the installed versions of all dependencies in this software   | 
| `npm list -g --depth 0` | Lists the installed versions of all globally installed packages     | 
| `npm view`              | Lists the latest versions of all dependencies in this software      | 
| `npm outdated`          | Lists only the dependencies in this software which are outdated     |

### Updating

| Command             | Description                |
| ---                 | ---                        |
| `npm update`        | Update production packages |
| `npm update --dev`  | Update dev packages        |
| `npm update -g`     | Update global packages     |
| ---                 | ---                        |
| `npm update lodash` | Update a package           |


### Removing

| Command             | Description                        |
| ---                 | ---                                |
| `npm rm lodash`     | Remove package production packages |

## More features

### Install names

| Command                              | Description             |
| ---                                  | ---                     |
| `npm i sax`                          | NPM package             |
| `npm i sax@latest`                   | Specify tag `latest`    |
| `npm i sax@3.0.0`                    | Specify version `3.0.0` |
| `npm i sax@">=1 <2.0"`               | Specify version range   |
| ---                                  | ---                     |
| `npm i @org/sax`                     | Scoped NPM package      |
| ---                                  | ---                     |
| `npm i user/repo`                    | GitHub                  |
| `npm i user/repo#master`             | GitHub                  |
| `npm i github:user/repo`             | GitHub                  |
| `npm i gitlab:user/repo`             | GitLab                  |
| ---                                  | ---                     |
| `npm i /path/to/repo`                | Absolute path           |
| `npm i ./archive.tgz`                | Tarball                 |
| `npm i https://site.com/archive.tgz` | Tarball via HTTP        |

### Bumping versions

| Command                           | Description                                               |
| ---                               | ---                                                       |
| `npm version 1.2.3`               | Bump the package version to 1.2.3                         |
| `npm version major`               | Bump the major package version by 1 (1.2.3 → 2.0.0)       |
| `npm version minor`               | Bump the minor package version by 1 (1.2.3 → 1.3.0)       |
| `npm version patch`               | Bump the patch package version by 1 (1.2.3 → 1.2.4)       |

### Misc features

```bash
# Add someone as an owner
npm owner add USERNAME PACKAGENAME
```

```bash
# list packages
npm ls
```

```bash
# Adds warning to those that install a package of old versions
npm deprecate PACKAGE@"< 0.2.0" "critical bug fixed in v0.2.0"
```

```bash
# update all packages, or selected packages
npm update [-g] PACKAGE
```

```bash
# Check for outdated packages
npm outdated [PACKAGE]
```


id: nopt
git_filename: ./nopt.md
format: md
field_title: Nopt
field_category: JavaScript libraries
data:
{"title": "Nopt", "category": "JavaScript libraries", "body": "### About\n{: .-intro}\n\n- <https://www.npmjs.org/package/nopt>\n\n### Example\n\n```js\nvar 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```js\nif (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```"}

field_body:
### About
{: .-intro}

- <https://www.npmjs.org/package/nopt>

### Example

```js
var args = require('nopt')({
  foo: [String, null],
  size: ['big', 'medium', 'small'],
  many: [String, Array],
  debug: Boolean,
  version: Boolean,
  help: Boolean
}, {
  h: '--help',
  v: '--version'
}, process.argv);

args == {
  debug: true,
  version: true,
  size: 'big',
  argv: {
    remain: ['...', '...'],
    cooked: ...,
    original: ...
  }
}
```

```js
if (args.help) {
  console.log([
      'Usage:',
      '  hicat [options] [file]',
      '',
      'Options:',
      '  -h, --help         print usage information',
      '  -v, --version      show version info and exit',
  ].join('\n'));
  process.exit(0);
}

if (args.version) {
  console.log(require('../package.json').version);
  process.exit(0);
}
```


id: nodejs
git_filename: ./nodejs.md
format: md
field_title: Node.js API
field_category: Node.js
data:
{"title": "Node.js API", "category": "Node.js", "body": "### Globals\n\n    __filename\n    __dirname\n\n### exec\n\n    var exec = require('child_process').exec,\n\n    var 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### Snippets\n\n    info = require('../package.json')\n    info.version\n\n    process.stdout.write(util.inspect(objekt, false, Infinity, true) + '\\n');\n\n### Spawn - passthru the in/out\n\n    var spawn = require('child_process').spawn;\n    var proc = spawn(bin, argv, { stdio: 'inherit' });\n    proc.on('error', function(err) {\n      if (err.code == \"ENOENT\") { \"does not exist\" }\n      if (err.code == \"EACCES\") { \"not executable\" }\n    });\n    proc.on('exit', function(code) { ... });\n\n    // also { stdio: ['pipe', 'pipe', process.stdout] }\n    // also { stdio: [process.stdin, process.stderr, process.stdout] }\n\n    proc.stdout.on('data', function (data) {\n    });\n    proc.stderr.on('data', function (data) {\n    });\n\n[all]: http://nodejs.org/api/all.html"}

field_body:
### Globals

    __filename
    __dirname

### exec

    var exec = require('child_process').exec,

    var child = exec('cat *.js bad_file | wc -l',
      function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
          console.log('exec error: ' + error);
        }
    });

### Snippets

    info = require('../package.json')
    info.version

    process.stdout.write(util.inspect(objekt, false, Infinity, true) + '\n');

### Spawn - passthru the in/out

    var spawn = require('child_process').spawn;
    var proc = spawn(bin, argv, { stdio: 'inherit' });
    proc.on('error', function(err) {
      if (err.code == "ENOENT") { "does not exist" }
      if (err.code == "EACCES") { "not executable" }
    });
    proc.on('exit', function(code) { ... });

    // also { stdio: ['pipe', 'pipe', process.stdout] }
    // also { stdio: [process.stdin, process.stderr, process.stdout] }

    proc.stdout.on('data', function (data) {
    });
    proc.stderr.on('data', function (data) {
    });

[all]: http://nodejs.org/api/all.html


id: nodejs-stream
git_filename: ./nodejs-stream.md
format: md
field_title: Node.js streams
field_category: Node.js
field_updated: 2017-08-30
field_updated___timezone: UTC
data:
{"title": "Node.js streams", "category": "Node.js", "weight": -1, "updated": "2017-08-30", "body": "### Types\n\n| Stream      | Description                        |\n| ---         | ---                                |\n| `Readable`  | Data emitter                       |\n| `Writable`  | Data receiver                      |\n| `Transform` | Emitter and receiver               |\n| `Duplex`    | Emitter and receiver (independent) |\n\nSee: [Stream](https://nodejs.org/api/stream.html#stream_stream) _(nodejs.org)_\n\n### Streams\n\n```js\nconst Readable = require('stream').Readable\nconst Writable = require('stream').Writable\nconst Transform = require('stream').Transform\n```\n\n### Piping\n\n```js\nclock()              // Readable stream\n  .pipe(xformer())   // Transform stream\n  .pipe(renderer())  // Writable stream\n```\n\n### Methods\n\n```js\nstream.push(/*...*/)         // Emit a chunk\nstream.emit('error', error)  // Raise an error\nstream.push(null)            // Close a stream\n```\n\n### Events\n\n```js\nconst 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\nAssuming `source()` is a readable stream.\n\n### Flowing mode\n\n```js\n// Toggle flowing mode\nst.resume()\nst.pause()\n```\n\n```js\n// Automatically turns on flowing mode\nst.on('data', /*...*/)\n```\n\nStream types\n------------\n{: .-three-column}\n\n### Readable\n\n```js\nfunction 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\nReadable streams are generators of data. Write data using `stream.push()`.\n\n### Transform\n\n```js\nfunction 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\nPass the updated chunk to `done(null, chunk)`.\n\n### Writable\n\n```js\nfunction 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```js\nclock()              // Readable stream\n  .pipe(xformer())   // Transform stream\n  .pipe(renderer())  // Writable stream\n```\n\n## Also see\n{: .-one-column}\n\n- <https://nodejs.org/api/stream.html>\n- <https://github.com/substack/stream-handbook>"}

field_body:
### Types

| Stream      | Description                        |
| ---         | ---                                |
| `Readable`  | Data emitter                       |
| `Writable`  | Data receiver                      |
| `Transform` | Emitter and receiver               |
| `Duplex`    | Emitter and receiver (independent) |

See: [Stream](https://nodejs.org/api/stream.html#stream_stream) _(nodejs.org)_

### Streams

```js
const Readable = require('stream').Readable
const Writable = require('stream').Writable
const Transform = require('stream').Transform
```

### Piping

```js
clock()              // Readable stream
  .pipe(xformer())   // Transform stream
  .pipe(renderer())  // Writable stream
```

### Methods

```js
stream.push(/*...*/)         // Emit a chunk
stream.emit('error', error)  // Raise an error
stream.push(null)            // Close a stream
```

### Events

```js
const st = source()
st.on('data', (data) => { console.log('<-', data) })
st.on('error', (err) => { console.log('!', err.message) })
st.on('close', () => { console.log('** bye') })
st.on('finish', () => { console.log('** bye') })
```

Assuming `source()` is a readable stream.

### Flowing mode

```js
// Toggle flowing mode
st.resume()
st.pause()
```

```js
// Automatically turns on flowing mode
st.on('data', /*...*/)
```

Stream types
------------
{: .-three-column}

### Readable

```js
function clock () {
  const stream = new Readable({
    objectMode: true,
    read() {}
  })

  setInterval(() => {
    stream.push({ time: new Date() })
  }, 1000)

  return stream
}

// Implement read() if you
// need on-demand reading.
```

Readable streams are generators of data. Write data using `stream.push()`.

### Transform

```js
function xformer () {
  let count = 0

  return new Transform({
    objectMode: true,
    transform: (data, _, done) => {
      done(null, { ...data, index: count++ })
    }
  })
}
```

Pass the updated chunk to `done(null, chunk)`.

### Writable

```js
function renderer () {
  return new Writable({
    objectMode: true,
    write: (data, _, done) => {
      console.log('<-', data)
      done()
    }
  })
}
```

### All together now

```js
clock()              // Readable stream
  .pipe(xformer())   // Transform stream
  .pipe(renderer())  // Writable stream
```

## Also see
{: .-one-column}

- <https://nodejs.org/api/stream.html>
- <https://github.com/substack/stream-handbook>


id: nodejs-process
git_filename: ./nodejs-process.md
format: md
field_title: process
field_category: Node.js
data:
{"title": "process", "category": "Node.js", "body": "### Streams\n\n    process.stdout.write('...');\n    process.stderr.write('...');\n\n    function 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### stuff\n\n    process.argv; //=> ['node', 'file.js', 'one', 'two']\n    process.env; //=> {TERM: 'screen-256color', SHELL: '/bin/bash', ...}\n\n    process.exit();\n    process.exit(1);\n\n### Directories\n    \n    process.cwd(); //=> \"/tmp\"\n    process.chdir('dir');\n\n### References\n\n- http://nodejs.org/api/process.html"}

field_body:
### Streams

    process.stdout.write('...');
    process.stderr.write('...');

    function stdin(fn) {
      var data = '';

      process.stdin.setEncoding('utf8');
      process.stdin.on('readable', function() {
        var chunk = process.stdin.read();
        if (chunk !== null) data += chunk;
      });

      process.stdin.on('end', function() {
        fn(null, data);
      });
    }

### stuff

    process.argv; //=> ['node', 'file.js', 'one', 'two']
    process.env; //=> {TERM: 'screen-256color', SHELL: '/bin/bash', ...}

    process.exit();
    process.exit(1);

### Directories
    
    process.cwd(); //=> "/tmp"
    process.chdir('dir');

### References

- http://nodejs.org/api/process.html


id: nodejs-path
git_filename: ./nodejs-path.md
format: md
field_title: Node.js path API
field_category: Node.js
field_intro: Quick reference to the [Node.js path API](https://nodejs.org/api/path.html).
data:
{"title": "Node.js path API", "category": "Node.js", "intro": "Quick reference to the [Node.js path API](https://nodejs.org/api/path.html).\n", "body": "### Functions\n\n```js\nconst fs = require('fs')\n\nfs.realpath('/etc/passwd', function (err, path) {\n  path // => \"/private/etc/passwd\"\n})\n```\n\n```js\nconst path = require('path')\ndir = path.join('etc', 'passwd')\ndir = path.resolve('/etc', 'passwd', '..', 'var')\n```\n\n```js\npath.dirname('/etc/passwd') //      => \"/etc\"\npath.basename('/etc/passwd') //     => \"passwd\"\npath.basename('/etc/rc.d', '.d') // => \"rc\"\n```\n\n### References\n\n- https://nodejs.org/api/path.html"}

field_body:
### Functions

```js
const fs = require('fs')

fs.realpath('/etc/passwd', function (err, path) {
  path // => "/private/etc/passwd"
})
```

```js
const path = require('path')
dir = path.join('etc', 'passwd')
dir = path.resolve('/etc', 'passwd', '..', 'var')
```

```js
path.dirname('/etc/passwd') //      => "/etc"
path.basename('/etc/passwd') //     => "passwd"
path.basename('/etc/rc.d', '.d') // => "rc"
```

### References

- https://nodejs.org/api/path.html


id: nodejs-fs
git_filename: ./nodejs-fs.md
format: md
field_title: fs
field_category: Node.js
data:
{"title": "fs", "category": "Node.js", "body": "### Reading\n\n    fs.readFile('file.txt', function(err, data) { .. });\n    fs.readFile('file.txt', {encoding: 'utf-8'}, function(err, data) { .. });\n\n### Writing\n\n    fs.writeFile('output.txt', function(err) { .. });\n    fs.appendFile('output.txt', function(err) { .. });\n\n### Watch\n\n    fs.watch('dir OR file.txt', { persistent: true }, function(event, file) {\n      event; /* rename | change */\n    });\n\n### Getting info\n\n    fs.exists('file.txt', function(exists /*bool*/) { ... });\n\n    fs.stat('file.txt', function(stats) {\n      stats.isFile();\n      stats.isDirectory();\n      stats.isSymbolicLink();\n    });\n\n### File operations\n\n    fs.rename('old.txt', 'new.txt', function(){});\n    fs.chown('file.txt', uid, gid, function(){});\n    fs.symlink('src', 'dest', function(){});\n    fs.unlink('path', function(){});\n    fs.rmdir('path', function(){});\n\n    fs.readdir('path', function(err, files) { .. }); /* `files` = array of names */\n\n### Path\n\n    fs.realpath('/etc/passwd', function(err, path) { /* \"/private/etc/passwd\" */ });\n\n### Sync\n\n    data = fs.readFileSync('input.txt');\n    fs.writeFileSync('output.txt', data);\n    fs.appendFileSync('output.txt', data);\n    fs.existsSync('file.txt');\n\n### References\n\n- https://nodejs.org/api/fs.html"}

field_body:
### Reading

    fs.readFile('file.txt', function(err, data) { .. });
    fs.readFile('file.txt', {encoding: 'utf-8'}, function(err, data) { .. });

### Writing

    fs.writeFile('output.txt', function(err) { .. });
    fs.appendFile('output.txt', function(err) { .. });

### Watch

    fs.watch('dir OR file.txt', { persistent: true }, function(event, file) {
      event; /* rename | change */
    });

### Getting info

    fs.exists('file.txt', function(exists /*bool*/) { ... });

    fs.stat('file.txt', function(stats) {
      stats.isFile();
      stats.isDirectory();
      stats.isSymbolicLink();
    });

### File operations

    fs.rename('old.txt', 'new.txt', function(){});
    fs.chown('file.txt', uid, gid, function(){});
    fs.symlink('src', 'dest', function(){});
    fs.unlink('path', function(){});
    fs.rmdir('path', function(){});

    fs.readdir('path', function(err, files) { .. }); /* `files` = array of names */

### Path

    fs.realpath('/etc/passwd', function(err, path) { /* "/private/etc/passwd" */ });

### Sync

    data = fs.readFileSync('input.txt');
    fs.writeFileSync('output.txt', data);
    fs.appendFileSync('output.txt', data);
    fs.existsSync('file.txt');

### References

- https://nodejs.org/api/fs.html


id: nodejs-assert
git_filename: ./nodejs-assert.md
format: md
field_title: assert
field_category: Node.js
data:
{"title": "assert", "category": "Node.js", "body": "### Assertions\n\n```js\nassert(val)\nassert.equal(actual, expected)\nassert.notEqual(a, e)\n```\n\n```js\nassert.deepEqual(a, e)\nassert.notDeepEqual(a, e)\n```\n\n```js\nassert.throws(fn)\n```\n\n### References\n\n- http://nodejs.org/api/assert.html"}

field_body:
### Assertions

```js
assert(val)
assert.equal(actual, expected)
assert.notEqual(a, e)
```

```js
assert.deepEqual(a, e)
assert.notDeepEqual(a, e)
```

```js
assert.throws(fn)
```

### References

- http://nodejs.org/api/assert.html


id: nocode
git_filename: ./nocode.md
format: md
field_title: Nocode
field_updated: 2018-03-17
field_updated___timezone: UTC
data:
{"title": "Nocode", "updated": "2018-03-17", "intro": "[Nocode](https://github.com/kelseyhightower/nocode) is the best way to write secure and reliable applications. Write nothing; deploy nowhere.\n", "body": "## Nothing\n{: .-one-column}\n\n<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>"}

field_intro:
[Nocode](https://github.com/kelseyhightower/nocode) is the best way to write secure and reliable applications. Write nothing; deploy nowhere.

field_body:
## Nothing
{: .-one-column}

<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>


id: nock
git_filename: ./nock.md
format: md
field_title: Nock
field_category: JavaScript libraries
data:
{"title": "Nock", "category": "JavaScript libraries", "body": "### Nock\n\n```js\nscope = nock('http://foo.com')\nscope = nock('http://foo.com', { allowUnmocked: true })\n```\n\n```js\nnock('http://foo.com')\n  .get('/user')\n  .reply(200, { id: 1234 })\n```\n\n### Filtering\n\n```js\nnock('http://foo.com')\n  .filteringPath(/[&\\?]token=[^&]*/g, '')\n  .get('/user')\n\n// catches \"/user?token=...\" as well\n```"}

field_body:
### Nock

```js
scope = nock('http://foo.com')
scope = nock('http://foo.com', { allowUnmocked: true })
```

```js
nock('http://foo.com')
  .get('/user')
  .reply(200, { id: 1234 })
```

### Filtering

```js
nock('http://foo.com')
  .filteringPath(/[&\?]token=[^&]*/g, '')
  .get('/user')

// catches "/user?token=..." as well
```


id: ncftp
git_filename: ./ncftp.md
format: md
field_title: ncftp
field_category: CLI
data:
{"title": "ncftp", "category": "CLI", "body": "### Bookmarking\n\n```bash\n$ ncftp\n$ open -u username ftp.host.com\n$ bookmark bookmarkname\n```\n\n### Mass download\n\n```bash\n$ ncftpget -R bookmarkname /www/ .\n```\n\n### Mass upload\n\n```bash\n$ ncftpput -R bookmarkname /www/ .\n```\n\n### Upload just the changed files\n\n```bash\n$ git show --pretty=\"format:\" --name-only HEAD~1\n$ ncftpget -R -C log bookmarkname /www/ .\n```"}

field_body:
### Bookmarking

```bash
$ ncftp
$ open -u username ftp.host.com
$ bookmark bookmarkname
```

### Mass download

```bash
$ ncftpget -R bookmarkname /www/ .
```

### Mass upload

```bash
$ ncftpput -R bookmarkname /www/ .
```

### Upload just the changed files

```bash
$ git show --pretty="format:" --name-only HEAD~1
$ ncftpget -R -C log bookmarkname /www/ .
```


id: mysql
git_filename: ./mysql.md
format: md
field_title: MySQL
field_category: Databases
field_updated: 2020-07-05
field_updated___timezone: UTC
data:
{"title": "MySQL", "updated": "2020-07-05", "category": "Databases", "body": "### Browsing\n\n```sql\nSHOW DATABASES;\nSHOW TABLES;\nSHOW FIELDS FROM table / DESCRIBE table;\nSHOW CREATE TABLE table;\nSHOW PROCESSLIST;\nKILL process_number;\n```\n\n### Select\n\n```sql\nSELECT * FROM table;\nSELECT * FROM table1, table2;\nSELECT field1, field2 FROM table1, table2;\nSELECT ... FROM ... WHERE condition\nSELECT ... FROM ... WHERE condition GROUP BY field;\nSELECT ... FROM ... WHERE condition GROUP BY 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```sql\nSELECT ... 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```sql\nfield1 = 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```sql\nCREATE 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```bash\nmysqldump -u Username -p dbNameYouWant > databasename_backup.sql\n```\n\n### Restore from backup SQL File\n\n```bash\nmysql -u Username -p dbNameYouWant < databasename_backup.sql;\n```\n\n### Repair Tables After Unclean Shutdown\n\n```bash\nmysqlcheck --all-databases;\nmysqlcheck --all-databases --fast;\n```\n\n### Insert\n\n```sql\nINSERT INTO table1 (field1, field2) VALUES (value1, value2);\n```\n\n### Delete\n\n```sql\nDELETE FROM table1 / TRUNCATE table1\nDELETE FROM table1 WHERE condition\nDELETE FROM table1, table2 WHERE table1.id1 =\n  table2.id2 AND condition\n```\n\n### Update\n\n```sql\nUPDATE 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```sql\nCREATE 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```sql\nCREATE 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```sql\nCREATE TABLE table1 (fk_field1 type1, fk_field2 type2, ...,\n FOREIGN KEY (fk_field1, fk_field2) REFERENCES table2 (t2_fieldA, t2_fieldB))\n```\n\n```sql\nCREATE TABLE table IF NOT EXISTS;\n```\n\n```sql\nCREATE TEMPORARY TABLE table;\n```\n\n#### Drop\n\n```sql\nDROP TABLE table;\nDROP TABLE IF EXISTS table;\nDROP TABLE table1, table2, ...\n```\n\n#### Alter\n\n```sql\nALTER 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```sql\nALTER 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```sql\nCREATE 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```sql\nCREATE 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```sql\nSET PASSWORD = PASSWORD('new_pass');\nSET PASSWORD FOR 'user'@'host' = PASSWORD('new_pass');\nSET PASSWORD = OLD_PASSWORD('new_pass');\n```\n\n```sql\nDROP USER 'user'@'host';\n```\n\nHost \u2018%\u2019 indicates any host.\n\n### Main Data Types\n\n```sql\nTINYINT (1o: -128 to +127)\nSMALLINT (2o: +-65 000)\nMEDIUMINT (3o: +-16 000 000)\nINT (4o: +- 2 000 000 000)\nBIGINT (8o: +-9.10^18)\n```\n\n```sql\nPrecise interval: -(2^(8*N-1)) -> (2^8*N)-1\n```\n\n\u26a0 INT(2) = \"2 digits displayed\" -- NOT \"number with 2 digits max\"\n\n```sql\nFLOAT(M,D)\nDOUBLE(M,D)\nFLOAT(D=0->53)\n```\n\n\u26a0 8,3 -> 12345,678 -- NOT 12345678,123!\n\n```sql\nTIME (HH:MM)\nYEAR (AAAA)\nDATE (AAAA-MM-JJ)\nDATETIME (AAAA-MM-JJ HH:MM; ann\u00e9es 1000->9999)\nTIMESTAMP (like DATETIME, but 1970->2038, compatible with Unix)\n```\n\n```sql\nVARCHAR (single-line; explicit size)\nTEXT (multi-lines; max size=65535)\nBLOB (binary; max size=65535)\n```\n\nVariants for TEXT&BLOB: `TINY` (max=255), `MEDIUM` (max=~16000), and `LONG` (max=4Go). Ex: `VARCHAR(32)`, `TINYTEXT`, `LONGBLOB`, `MEDIUMTEXT`\n\n```sql\nENUM ('value1', 'value2', ...) -- (default NULL, or '' if NOT NULL)\n```\n\n### Reset Root Password\n\n```bash\n$ /etc/init.d/mysql stop\n```\n\n```bash\n$ mysqld_safe --skip-grant-tables\n```\n\n```bash\n$ mysql # on another terminal\nmysql> UPDATE mysql.user SET password=PASSWORD('new_pass') WHERE user='root';\n```\n\n```bash\n## Switch back to the mysqld_safe terminal and kill the process using Control + \\\n$ /etc/init.d/mysql start\n```\n\nYour commands may vary depending on your OS."}

field_body:
### Browsing

```sql
SHOW DATABASES;
SHOW TABLES;
SHOW FIELDS FROM table / DESCRIBE table;
SHOW CREATE TABLE table;
SHOW PROCESSLIST;
KILL process_number;
```

### Select

```sql
SELECT * FROM table;
SELECT * FROM table1, table2;
SELECT field1, field2 FROM table1, table2;
SELECT ... FROM ... WHERE condition
SELECT ... FROM ... WHERE condition GROUP BY field;
SELECT ... FROM ... WHERE condition GROUP BY field HAVING condition2;
SELECT ... FROM ... WHERE condition ORDER BY field1, field2;
SELECT ... FROM ... WHERE condition ORDER BY field1, field2 DESC;
SELECT ... FROM ... WHERE condition LIMIT 10;
SELECT DISTINCT field1 FROM ...
SELECT DISTINCT field1, field2 FROM ...
```

### Select - Join

```sql
SELECT ... FROM t1 JOIN t2 ON t1.id1 = t2.id2 WHERE condition;
SELECT ... FROM t1 LEFT JOIN t2 ON t1.id1 = t2.id2 WHERE condition;
SELECT ... FROM t1 JOIN (t2 JOIN t3 ON ...) ON ...
```

### Conditions

```sql
field1 = value1
field1 <> value1
field1 LIKE 'value _ %'
field1 IS NULL
field1 IS NOT NULL
field1 IS IN (value1, value2)
field1 IS NOT IN (value1, value2)
condition1 AND condition2
condition1 OR condition2
```

### Create / Open / Delete Database

```sql
CREATE DATABASE DatabaseName;
CREATE DATABASE DatabaseName CHARACTER SET utf8;
USE DatabaseName;
DROP DATABASE DatabaseName;
ALTER DATABASE DatabaseName CHARACTER SET utf8;
```

### Backup Database to SQL File

```bash
mysqldump -u Username -p dbNameYouWant > databasename_backup.sql
```

### Restore from backup SQL File

```bash
mysql -u Username -p dbNameYouWant < databasename_backup.sql;
```

### Repair Tables After Unclean Shutdown

```bash
mysqlcheck --all-databases;
mysqlcheck --all-databases --fast;
```

### Insert

```sql
INSERT INTO table1 (field1, field2) VALUES (value1, value2);
```

### Delete

```sql
DELETE FROM table1 / TRUNCATE table1
DELETE FROM table1 WHERE condition
DELETE FROM table1, table2 WHERE table1.id1 =
  table2.id2 AND condition
```

### Update

```sql
UPDATE table1 SET field1=new_value1 WHERE condition;
UPDATE table1, table2 SET field1=new_value1, field2=new_value2, ... WHERE
  table1.id1 = table2.id2 AND condition;
```

### Create / Delete / Modify Table

#### Create

```sql
CREATE TABLE table (field1 type1, field2 type2);
CREATE TABLE table (field1 type1, field2 type2, INDEX (field));
CREATE TABLE table (field1 type1, field2 type2, PRIMARY KEY (field1));
CREATE TABLE table (field1 type1, field2 type2, PRIMARY KEY (field1,field2));
```

```sql
CREATE TABLE table1 (fk_field1 type1, field2 type2, ...,
  FOREIGN KEY (fk_field1) REFERENCES table2 (t2_fieldA))
    [ON UPDATE|ON DELETE] [CASCADE|SET NULL]
```

```sql
CREATE TABLE table1 (fk_field1 type1, fk_field2 type2, ...,
 FOREIGN KEY (fk_field1, fk_field2) REFERENCES table2 (t2_fieldA, t2_fieldB))
```

```sql
CREATE TABLE table IF NOT EXISTS;
```

```sql
CREATE TEMPORARY TABLE table;
```

#### Drop

```sql
DROP TABLE table;
DROP TABLE IF EXISTS table;
DROP TABLE table1, table2, ...
```

#### Alter

```sql
ALTER TABLE table MODIFY field1 type1
ALTER TABLE table MODIFY field1 type1 NOT NULL ...
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 NOT NULL ...
ALTER TABLE table ALTER field1 SET DEFAULT ...
ALTER TABLE table ALTER field1 DROP DEFAULT
ALTER TABLE table ADD new_name_field1 type1
ALTER TABLE table ADD new_name_field1 type1 FIRST
ALTER TABLE table ADD new_name_field1 type1 AFTER another_field
ALTER TABLE table DROP field1
ALTER TABLE table ADD INDEX (field);
```

#### Change field order

```sql
ALTER TABLE table MODIFY field1 type1 FIRST
ALTER TABLE table MODIFY field1 type1 AFTER another_field
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 FIRST
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 AFTER
  another_field
```

### Keys

```sql
CREATE TABLE table (..., PRIMARY KEY (field1, field2))
CREATE TABLE table (..., FOREIGN KEY (field1, field2) REFERENCES table2
(t2_field1, t2_field2))
```

### Users and Privileges

```sql
CREATE USER 'user'@'localhost';
GRANT ALL PRIVILEGES ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT, INSERT, DELETE ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
REVOKE ALL PRIVILEGES ON base.* FROM 'user'@'host'; -- one permission only
REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'user'@'host'; -- all permissions
FLUSH PRIVILEGES;
```

```sql
SET PASSWORD = PASSWORD('new_pass');
SET PASSWORD FOR 'user'@'host' = PASSWORD('new_pass');
SET PASSWORD = OLD_PASSWORD('new_pass');
```

```sql
DROP USER 'user'@'host';
```

Host ‘%’ indicates any host.

### Main Data Types

```sql
TINYINT (1o: -128 to +127)
SMALLINT (2o: +-65 000)
MEDIUMINT (3o: +-16 000 000)
INT (4o: +- 2 000 000 000)
BIGINT (8o: +-9.10^18)
```

```sql
Precise interval: -(2^(8*N-1)) -> (2^8*N)-1
```

⚠ INT(2) = "2 digits displayed" -- NOT "number with 2 digits max"

```sql
FLOAT(M,D)
DOUBLE(M,D)
FLOAT(D=0->53)
```

⚠ 8,3 -> 12345,678 -- NOT 12345678,123!

```sql
TIME (HH:MM)
YEAR (AAAA)
DATE (AAAA-MM-JJ)
DATETIME (AAAA-MM-JJ HH:MM; années 1000->9999)
TIMESTAMP (like DATETIME, but 1970->2038, compatible with Unix)
```

```sql
VARCHAR (single-line; explicit size)
TEXT (multi-lines; max size=65535)
BLOB (binary; max size=65535)
```

Variants for TEXT&BLOB: `TINY` (max=255), `MEDIUM` (max=~16000), and `LONG` (max=4Go). Ex: `VARCHAR(32)`, `TINYTEXT`, `LONGBLOB`, `MEDIUMTEXT`

```sql
ENUM ('value1', 'value2', ...) -- (default NULL, or '' if NOT NULL)
```

### Reset Root Password

```bash
$ /etc/init.d/mysql stop
```

```bash
$ mysqld_safe --skip-grant-tables
```

```bash
$ mysql # on another terminal
mysql> UPDATE mysql.user SET password=PASSWORD('new_pass') WHERE user='root';
```

```bash
## Switch back to the mysqld_safe terminal and kill the process using Control + \
$ /etc/init.d/mysql start
```

Your commands may vary depending on your OS.


id: moment
git_filename: ./moment.md
format: md
field_title: Moment.js
field_category: JavaScript libraries
field_tags: Featurable
field_updated: 2018-09-15
field_updated___timezone: UTC
data:
{"title": "Moment.js", "category": "JavaScript libraries", "updated": "2018-09-15", "tags": ["Featurable"], "body": "### Parsing\n\n```js\nm = moment('2013-03-01', 'YYYY-MM-DD')\n```\n\nThis parses the given date using the given format. Returns a moment object.\n\n### Formatting\n\n```js\nm.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```js\nm.add(1, 'day')\nm.subtract(2, 'days')\n```\n\n```js\nm.startOf('day')\nm.endOf('day')\nm.startOf('hour')\n```\n\n### Internationalization\n\n```js\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\nSee [datetime](./datetime) for more.\n\n{% include common/moment_format.md title=\"Formatting\" %}\n\n## References\n\n### Alternatives\n\n* [You don't need Moment.js](https://github.com/you-dont-need/You-Dont-Need-Momentjs) _(github.com)_\n\n### Also see\n\n* [Datetime cheatsheet](./datetime) _(devhints.io)_\n* [Moment website](http://momentjs.com/) _(momentjs.com)_\n* [Moment docs](http://momentjs.com/docs/) _(momentjs.com)_"}

field_body:
### Parsing

```js
m = moment('2013-03-01', 'YYYY-MM-DD')
```

This parses the given date using the given format. Returns a moment object.

### Formatting

```js
m.format()            // "2013-03-01T00:00:00+01:00"
m.format('dddd')      // "Friday"
m.format('MMM Do YY') // "Mar 1st 13"
m.fromNow()           // "7 years ago"
m.calendar()          // "03/01/2013"
```

### Add

```js
m.add(1, 'day')
m.subtract(2, 'days')
```

```js
m.startOf('day')
m.endOf('day')
m.startOf('hour')
```

### Internationalization

```js
.format('L')      // 06/09/2014
.format('l')      // 6/9/2014
.format('LL')     // June 9 2014
.format('ll')     // Jun 9 2014
.format('LLL')    // June 9 2014 9:32 PM
.format('lll')    // Jun 9 2014 9:32 PM
.format('LLLL')   // Monday, June 9 2014 9:32 PM
.format('llll')   // Mon, Jun 9 2014 9:32 PM
```

See [datetime](./datetime) for more.

{% include common/moment_format.md title="Formatting" %}

## References

### Alternatives

* [You don't need Moment.js](https://github.com/you-dont-need/You-Dont-Need-Momentjs) _(github.com)_

### Also see

* [Datetime cheatsheet](./datetime) _(devhints.io)_
* [Moment website](http://momentjs.com/) _(momentjs.com)_
* [Moment docs](http://momentjs.com/docs/) _(momentjs.com)_


id: modernizr
git_filename: ./modernizr.md
format: md
field_title: Modernizr
field_category: JavaScript libraries
field_tags: Archived
data:
{"title": "Modernizr", "category": "JavaScript libraries", "tags": ["Archived"], "archived": "Modernizr is no longer in active development.", "body": "### Script\n\n    <script src='//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js'></script>\n\n### Detections\n\nJavaScript\n\n * js\n\nCSS\n\n * flexbox\n * rgba\n * hsla\n * multiplebgs\n * backgroundsize\n * borderimage\n * borderradius\n * boxshadow\n * textshadow\n * opacity\n * cssanimations\n * csscolumns\n * cssgradients\n * cssreflections\n * csstransforms\n * csstransforms3d\n * csstransitions\n * fontface\n * generatedcontent\n\nHTML5\n\n * canvas\n * canvastext\n * webgl\n * touch\n * geolocation\n * postmessage\n * websqldatabase\n * indexeddb\n * hashchange\n * history\n * draganddrop\n * websockets\n * video\n * audio\n * localstorage\n * sessionstorage\n * webworkers\n * applicationcache\n * svg\n * inlinesvg\n * smil\n * svgclippaths"}

field_body:
### Script

    <script src='//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js'></script>

### Detections

JavaScript

 * js

CSS

 * flexbox
 * rgba
 * hsla
 * multiplebgs
 * backgroundsize
 * borderimage
 * borderradius
 * boxshadow
 * textshadow
 * opacity
 * cssanimations
 * csscolumns
 * cssgradients
 * cssreflections
 * csstransforms
 * csstransforms3d
 * csstransitions
 * fontface
 * generatedcontent

HTML5

 * canvas
 * canvastext
 * webgl
 * touch
 * geolocation
 * postmessage
 * websqldatabase
 * indexeddb
 * hashchange
 * history
 * draganddrop
 * websockets
 * video
 * audio
 * localstorage
 * sessionstorage
 * webworkers
 * applicationcache
 * svg
 * inlinesvg
 * smil
 * svgclippaths


id: modella
git_filename: ./modella.md
format: md
field_title: Modella
field_category: JavaScript libraries
field_prism_languages: coffeescript
data:
{"title": "Modella", "category": "JavaScript libraries", "prism_languages": ["coffeescript"], "intro": "[Modella](https://www.npmjs.com/package/modella) allows you to create simple models in JavaScript. This is a guide on basic usage of Modella in CoffeeScript.\n", "body": "### Defining models\n\n```coffeescript\nUser = Modella('User')\n```\n\n```coffeescript\n  .attr('name')\n  .attr('email', { required: true })\n  .use(require('modella-validators'))\n```\n\n```coffeescript\n  .validator (u) ->\n    u.error('username', 'is required')  unless u.has('username')\n```\n\n### Instances\n\n```coffeescript\nuser\n  .name()\n  .name('John')\n  .set(name: 'John')\n```\n\n```coffeescript\n  .has('name')   # \u2192 true\n  .isNew()\n  .isValid()\n```\n\n```coffeescript\n  .save (err) ->\n  .remove (err) ->\n  .removed\n  .model         # === User\n```\n\n## Events\n\n### Emitting\n\n```coffeescript\nModel.emit('event', [data...])\n```\n\n```coffeescript\nrecord.emit('event', [data...])\n```\n\n### List of events\n\n```coffeescript\nuser\n  .on 'save', ->\n  .on 'create', ->\n  .on 'saving', (data, done) -> done()\n```\n\n```coffeescript\n  .on 'remove', ->\n  .on 'removing', (data, done) -> done()\n```\n\n```coffeescript\n  .on 'valid', ->\n  .on 'invalid', ->\n```\n\n```coffeescript\n  .on 'change', ->\n  .on 'change email', ->\n```\n\n```coffeescript\n  .on 'initializing', (instance, attrs) ->\n  .on 'initialize', ->\n```\n\n```coffeescript\n  .on 'error', -> failed to save model\n```\n\n```coffeescript\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```coffeescript\nMyPlugin = ->\n  return (Model) ->\n\n    Model.method = ...\n    Model.prototype.method = ...\n    Model.attr(...)\n\n    Model\n```\n\nA 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```coffeescript\nUser\n  .all (err, users) ->\n  .find id, (err, user) ->\n```\n\n```coffeescript\n  .remove ->\n  .save ->\n  .update ->\n```"}

field_intro:
[Modella](https://www.npmjs.com/package/modella) allows you to create simple models in JavaScript. This is a guide on basic usage of Modella in CoffeeScript.

field_body:
### Defining models

```coffeescript
User = Modella('User')
```

```coffeescript
  .attr('name')
  .attr('email', { required: true })
  .use(require('modella-validators'))
```

```coffeescript
  .validator (u) ->
    u.error('username', 'is required')  unless u.has('username')
```

### Instances

```coffeescript
user
  .name()
  .name('John')
  .set(name: 'John')
```

```coffeescript
  .has('name')   # → true
  .isNew()
  .isValid()
```

```coffeescript
  .save (err) ->
  .remove (err) ->
  .removed
  .model         # === User
```

## Events

### Emitting

```coffeescript
Model.emit('event', [data...])
```

```coffeescript
record.emit('event', [data...])
```

### List of events

```coffeescript
user
  .on 'save', ->
  .on 'create', ->
  .on 'saving', (data, done) -> done()
```

```coffeescript
  .on 'remove', ->
  .on 'removing', (data, done) -> done()
```

```coffeescript
  .on 'valid', ->
  .on 'invalid', ->
```

```coffeescript
  .on 'change', ->
  .on 'change email', ->
```

```coffeescript
  .on 'initializing', (instance, attrs) ->
  .on 'initialize', ->
```

```coffeescript
  .on 'error', -> failed to save model
```

```coffeescript
  .on 'setting', (instance, attrs) ->  # on Model#set()
  .on 'attr', -> # new attr via Model.attr()
```

## Misc

### Plugins

```coffeescript
MyPlugin = ->
  return (Model) ->

    Model.method = ...
    Model.prototype.method = ...
    Model.attr(...)

    Model
```

A plugin is a function that returns a model decorator (ie, a function that takes in a model and returns a model).

### Memory

```coffeescript
User
  .all (err, users) ->
  .find id, (err, user) ->
```

```coffeescript
  .remove ->
  .save ->
  .update ->
```


id: mocha
git_filename: ./mocha.md
format: md
field_title: Mocha.js
field_category: JavaScript libraries
data:
{"title": "Mocha.js", "category": "JavaScript libraries", "body": "### BDD\n\n    mocha.setup('bdd');\n\n    describe('something', function() {\n      beforeEach(function() {\n      });\n\n      it('should work', function() {\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### Chai: Shoulds\n\n    chai.should();\n\n    foo.should.be.a('string');\n    foo.should.equal('bar');\n    foo.should.have.length(3);\n    tea.should.have.property('flavors').with.length(3);\n\n### See also\n\n * [Mocha TDD](mocha-tdd.html)\n * [Mocha HTML](mocha-html.html)\n * [Chai](chai.html)\n * [Sinon](sinon.html)\n * [Sinon Chai](sinon-chai.html)"}

field_body:
### BDD

    mocha.setup('bdd');

    describe('something', function() {
      beforeEach(function() {
      });

      it('should work', function() {
      });
    });

### Async

    it('should save', function(done) {
      var user = new User();
      user.save(function(err) {
        if (err) throw err;
        done();
      });
    });

### Chai: Shoulds

    chai.should();

    foo.should.be.a('string');
    foo.should.equal('bar');
    foo.should.have.length(3);
    tea.should.have.property('flavors').with.length(3);

### See also

 * [Mocha TDD](mocha-tdd.html)
 * [Mocha HTML](mocha-html.html)
 * [Chai](chai.html)
 * [Sinon](sinon.html)
 * [Sinon Chai](sinon-chai.html)


id: mocha-tdd
git_filename: ./mocha-tdd.md
format: md
field_title: Mocha.js TDD interface
field_category: JavaScript libraries
data:
{"title": "Mocha.js TDD interface", "category": "JavaScript libraries", "body": "### TDD\n\n    mocha.setup('tdd');\n\n    suite('something', function() {\n      setup(function() {\n      });\n\n      test('should work', function() {\n      });\n\n      teardown(function() {\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### Chai: Expect\n\n    var expect = chai.expect;\n\n    expect(foo).to.be.a('string');\n    expect(foo).to.equal('bar');\n    expect(foo).to.have.length(3);\n    expect(tea).to.have.property('flavors').with.length(3);\n\n### See also\n\n * [Mocha BDD](mocha.html)\n * [Mocha HTML](mocha-html.html)\n * [Chai](chai.html)\n * [Sinon](sinon.html)\n * [Sinon Chai](sinon-chai.html)"}

field_body:
### TDD

    mocha.setup('tdd');

    suite('something', function() {
      setup(function() {
      });

      test('should work', function() {
      });

      teardown(function() {
      });
    });

### Async

    test('should save', function(done) {
      var user = new User();
      user.save(function(err) {
        if (err) throw err;
        done();
      });
    });

### Chai: Expect

    var expect = chai.expect;

    expect(foo).to.be.a('string');
    expect(foo).to.equal('bar');
    expect(foo).to.have.length(3);
    expect(tea).to.have.property('flavors').with.length(3);

### See also

 * [Mocha BDD](mocha.html)
 * [Mocha HTML](mocha-html.html)
 * [Chai](chai.html)
 * [Sinon](sinon.html)
 * [Sinon Chai](sinon-chai.html)


id: mocha-html
git_filename: ./mocha-html.md
format: md
field_title: Mocha HTML
field_category: JavaScript libraries
data:
{"title": "Mocha HTML", "category": "JavaScript libraries", "body": "### About\n\nThis is a mocha template that loads js/css from cdn.\n\n### Template\n\n```html\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```"}

field_body:
### About

This is a mocha template that loads js/css from cdn.

### Template

```html
<!doctype html>
<html>
<head>
  <meta charset='utf-8'>
  <title>Mocha</title>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <link href='https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css' rel='stylesheet' />
</head>
<body>
  <div id='mocha'></div>
  <script src='https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js'></script>
  <script src='https://cdn.rawgit.com/chaijs/chai/2.3.0/chai.js'></script>
  <script>window.onerror=function(msg,url,line){document.getElementById('mocha').innerHTML+='<h1>'+msg+'</'+'h1>'+'<h2>'+url+':'+line+'</'+'h2>';return false}</script>
  <script>mocha.setup('bdd')</script>
  <!-- what to test: -->
  <script src='../index.js'></script>
  <!-- tests to run: -->
  <script src='first_test.js'></script>
  <script src='second_test.js'></script>
  <script>mocha.run()</script>
</body>
</html>
```


id: mocha-blanket
git_filename: ./mocha-blanket.md
format: md
field_title: Mocha blanket
field_category: JavaScript libraries
data:
{"title": "Mocha blanket", "category": "JavaScript libraries", "intro": "Use [blanket](https://npmjs.com/package/blanket) for easy coverage reporting for Mocha JavaScript tests.\n", "body": "### Quickstart guide\n\nInstall blanket:\n{: .-setup}\n\n```bash\nnpm i --save-dev blanket\n```\n\nIn your test helpers, use Blanket before `require`ing:\n\n```js\nif (process.env.COVERAGE) {\n  require('blanket')({\n    pattern: require('path').resolve('./index.js')\n  });\n}\nthing = require('../index');\n```\n\nAdd to `package.json`:\n\n```json\n\"scripts\": {\n  \"coverage\": \"env COVERAGE=1 mocha -R html-cov > coverage.html && open coverage.html\"\n}\n```\n\nBe sure to ignore it:\n\n```bash\necho \"coverage.html\" >> .gitignore\n```\n\nThen run:\n\n```bash\nnpm run coverage\n```\n\n### Travis + coveralls.io support\n\nVisit [coveralls.io] then activate your repo. Then install the appropriate packages:\n{: .-setup}\n\n```bash\nnpm i --save-dev mocha-lcov-reporter coveralls\n```\n\nAdd this to `.travis.yml`:\n\n```yml\nafter_success:\n  - ./node_modules/.bin/mocha -R mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js\n```\n\nCommit, push, wait for Travis to finish.\n\n[blanket]: https://www.npmjs.org/package/blanket\n[coveralls.io]: http://coveralls.io"}

field_intro:
Use [blanket](https://npmjs.com/package/blanket) for easy coverage reporting for Mocha JavaScript tests.

field_body:
### Quickstart guide

Install blanket:
{: .-setup}

```bash
npm i --save-dev blanket
```

In your test helpers, use Blanket before `require`ing:

```js
if (process.env.COVERAGE) {
  require('blanket')({
    pattern: require('path').resolve('./index.js')
  });
}
thing = require('../index');
```

Add to `package.json`:

```json
"scripts": {
  "coverage": "env COVERAGE=1 mocha -R html-cov > coverage.html && open coverage.html"
}
```

Be sure to ignore it:

```bash
echo "coverage.html" >> .gitignore
```

Then run:

```bash
npm run coverage
```

### Travis + coveralls.io support

Visit [coveralls.io] then activate your repo. Then install the appropriate packages:
{: .-setup}

```bash
npm i --save-dev mocha-lcov-reporter coveralls
```

Add this to `.travis.yml`:

```yml
after_success:
  - ./node_modules/.bin/mocha -R mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js
```

Commit, push, wait for Travis to finish.

[blanket]: https://www.npmjs.org/package/blanket
[coveralls.io]: http://coveralls.io


id: mobx
git_filename: ./mobx.md
format: md
field_title: Mobx
field_category: JavaScript libraries
field_updated: 2018-05-14
field_updated___timezone: UTC
data:
{"title": "Mobx", "category": "JavaScript libraries", "updated": "2018-05-14", "body": "### Properties\n\n```js\nimport {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```js\nclass 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```js\nconst person = observable({\n  name: 'Ella Fitzgerald'\n})\n```\n\n```js\nconst temp = observable(23)\ntemp.get()\ntemp.set(25)\ntemp.observe(...)\n```\n\n## Reactions\n\n### Importing\n\n```js\nimport {autorun, autorunAsync, when} from 'mobx'\n```\n\n### autorun()\n\n```js\n// Runs it, finds out what it accessed, then observe those\nautorun(() => {\n  console.log(page.title)\n})\n```\n\n### when()\n\n```js\nclass Foo {\n  constructor () {\n    when(\n      () => !this.isVisible,\n      () => this.doSomething())\n  }\n}\n```\n\n### expr()\n\n```js\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](http://mobxjs.github.io/mobx/refguide/modifiers.html)\n\n- `asMap(obj)` - JS map (dynamic keys)\n- `asReference(fn)` - don't observe me\n- `asStructure(obj)` - JS object (observe as deepEqual)\n- `asFlat(array)` - JS array (observe its children)\n\n## React\n\n### mobx-react\n\n```js\nimport { 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```js\nimport { 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- <https://github.com/mobxjs/mobx>"}

field_body:
### Properties

```js
import {observable, computed} from 'mobx'

class Page {
  @observable title = ''
  @observable published = false
  @observable author = null

  @computed get authorName () {
    return this.author || 'Anonymous'
  }
}
```

### Actions

```js
class Page {
  @action publish () {
    this.published = true
    // do ajax/async here if you like
  }
}
```

### Plain objects

```js
const person = observable({
  name: 'Ella Fitzgerald'
})
```

```js
const temp = observable(23)
temp.get()
temp.set(25)
temp.observe(...)
```

## Reactions

### Importing

```js
import {autorun, autorunAsync, when} from 'mobx'
```

### autorun()

```js
// Runs it, finds out what it accessed, then observe those
autorun(() => {
  console.log(page.title)
})
```

### when()

```js
class Foo {
  constructor () {
    when(
      () => !this.isVisible,
      () => this.doSomething())
  }
}
```

### expr()

```js
// A temporary computed value. Its result is cached.
render () {
  const isPublished = expr(() => page.published === true)
  if (isPublished) { ... }
}
```

## [Modifiers](http://mobxjs.github.io/mobx/refguide/modifiers.html)

- `asMap(obj)` - JS map (dynamic keys)
- `asReference(fn)` - don't observe me
- `asStructure(obj)` - JS object (observe as deepEqual)
- `asFlat(array)` - JS array (observe its children)

## React

### mobx-react

```js
import { observer } from 'mobx-react'

@observer
class PageView extends React.Component {
  render () {
    return <div>{this.props.page.title}</div>
  }
}

<PageView page={page} />
```

### Functional components

```js
import { observer } from 'mobx-react'

const PageView = observer(({page}) => {
  <div>{page.title}</div>
})

<PageView page={page} />
```

## References

- <https://github.com/mobxjs/mobx>


id: mixpanel
git_filename: ./mixpanel.md
format: md
field_title: Mixpanel
field_category: Analytics
data:
{"title": "Mixpanel", "category": "Analytics", "body": "### Identify\n\n```js\nmixpanel.identify('284')\nmixpanel.people.set({ $email: 'hi@gmail.com' })\n```\n\n```js\n// Set common properties\nmixpanel.register({ age: 28, gender: 'male' })\n```\n\n### Track events\n\n```js\nmixpanel.track('Login success')\nmixpanel.track('Search', { query: 'cheese' })\n```\n\n### References\n\n* <https://mixpanel.com/help/reference/javascript>"}

field_body:
### Identify

```js
mixpanel.identify('284')
mixpanel.people.set({ $email: 'hi@gmail.com' })
```

```js
// Set common properties
mixpanel.register({ age: 28, gender: 'male' })
```

### Track events

```js
mixpanel.track('Login success')
mixpanel.track('Search', { query: 'cheese' })
```

### References

* <https://mixpanel.com/help/reference/javascript>


id: minitest
git_filename: ./minitest.md
format: md
field_title: Minitest
field_category: Ruby
data:
{"title": "Minitest", "category": "Ruby", "body": "### Usage\n\n    require 'minitest/autorun'\n\n    describe \"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\n    end\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\n    proc { ... }.must_output out_or_nil [, err]\n    proc { ... }.must_raise exception\n    proc { ... }.must_throw sym\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\n    end\n\n### Assertions\n\n    assert\n    assert_block { ... }\n    assert_empty\n    assert_equal 2, @size\n    assert_in_delta @size, 1, 1\n    assert_in_epsilon\n    assert_includes @list, \"item\"\n    assert_instance_of Array, @list\n    assert_kind_of Enumerable, @list\n    assert_match @str, /regex/\n    assert_nil\n    assert_operator @n, :==, 0\n    assert_output\n    assert_raises\n    assert_respond_to\n    assert_same\n    assert_send\n    assert_silent\n    assert_throws\n\n### Minitest::Mock\n\nA simple and clean mock system. There two essential methods at our disposal: expect and verify.\n\n    require 'minitest/autorun'\n\n    describe 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\n    end\n\n### Reporters\n\n    gem 'minitest-reporters'\n\n    require 'minitest/reporters'\n    Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new\n\n    [Default, Spec, Progress, RubyMate, RubyMine, JUnit]"}

field_body:
### Usage

    require 'minitest/autorun'

    describe "X" do
      before do .. end
      after do .. end
      subject { .. }
      let(:list) { Array.new }

      it "should work" do
        assert true
      end
    end

### Specs (.must/.wont)

    expect(x)
    .must_be :==, 0
    .must_equal b
    .must_be_close_to 2.99999
    .must_be_same_as b

    .must_include needle
    .must_be_empty

    .must_be_kind_of
    .must_be_instance_of
    .must_be_nil
    .must_match /regex/
    .must_be :<=, 42
    .must_respond_to msg

    .must_be_silent  ( proc { "no stdout or stderr" }.must_be_silent)
    .must_output "hi"

    proc { ... }.must_output out_or_nil [, err]
    proc { ... }.must_raise exception
    proc { ... }.must_throw sym

### Test

    class TestHipster < Minitest::Test
      def setup
        @subject = ["silly hats", "skinny jeans"]
      end

      def teardown
        @hipster.destroy!
      end

      def test_for_helvetica_font
        assert_equal "helvetica!", @hipster.preferred_font
      end

      def test_not_mainstream
        refute @hipster.mainstream?
      end
    end

### Assertions

    assert
    assert_block { ... }
    assert_empty
    assert_equal 2, @size
    assert_in_delta @size, 1, 1
    assert_in_epsilon
    assert_includes @list, "item"
    assert_instance_of Array, @list
    assert_kind_of Enumerable, @list
    assert_match @str, /regex/
    assert_nil
    assert_operator @n, :==, 0
    assert_output
    assert_raises
    assert_respond_to
    assert_same
    assert_send
    assert_silent
    assert_throws

### Minitest::Mock

A simple and clean mock system. There two essential methods at our disposal: expect and verify.

    require 'minitest/autorun'

    describe Twipster, "Make every tweet a hipster tweet." do
      before do
        @twitter  = Minitest::Mock.new
        @twipster = Twipster.new(@twitter)
      end

      it "should append a #lolhipster hashtag and update Twitter with our status" do
        tweet = "Skyrim? Too mainstream."
        @twitter.expect :update, true, ["#{tweet} #lolhipster"]
        @twipster.submit(tweet)
        assert @twitter.verify # verifies tweet and hashtag was passed to `@twitter.update`
      end
    end

### Reporters

    gem 'minitest-reporters'

    require 'minitest/reporters'
    Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new

    [Default, Spec, Progress, RubyMate, RubyMine, JUnit]


id: minimist
git_filename: ./minimist.md
format: md
field_title: minimist
field_category: JavaScript libraries
data:
{"title": "minimist", "category": "JavaScript libraries", "body": "### Usage\n\n```js\nvar minimist = require('minimist')\n```\n{: .-setup}\n\n```js\nvar args = minimist(process.argv.slice(2), {\n  string: 'lang',           // --lang xml\n  boolean: ['version'],     // --version\n  alias: { v: 'version' }\n})\n```\n\n```js\nconsole.log(args)\n```\n\nAll options are optional, but it's recommended you set `string` and `boolean` at least.\n\n### All options\n\n```js\nvar 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\nAll options are optional.\n\n### Result\n\nWith `--lang xml --no-pager -h index.js package.json`, you get:\n{: .-setup}\n\n```\nargs == {\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\nUse [meow](https://www.npmjs.com/package/meow) to automatically add support for `--help`, `--version` and more.\n{: .-setup}\n\n```js\nmeow(`\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 * <https://www.npmjs.org/package/minimist>\n * <https://github.com/substack/minimist>"}

field_body:
### Usage

```js
var minimist = require('minimist')
```
{: .-setup}

```js
var args = minimist(process.argv.slice(2), {
  string: 'lang',           // --lang xml
  boolean: ['version'],     // --version
  alias: { v: 'version' }
})
```

```js
console.log(args)
```

All options are optional, but it's recommended you set `string` and `boolean` at least.

### All options

```js
var args = minimist(process.argv.slice(2), {
  string: [ 'lang' ],
  boolean: [ 'pager' ],
  alias: { h: 'help', v: 'version' },
  default: { lang: 'en' },
  '--': true,
  stopEarly: true, /* populate _ with first non-option */
  unknown: function () { ... } /* invoked on unknown param */
})
```

All options are optional.

### Result

With `--lang xml --no-pager -h index.js package.json`, you get:
{: .-setup}

```
args == {
  lang: 'xml',
  version: false,
  h: true,
  help: true,
  _: [ 'index.js', 'package.json' ]
}
```

## Meow

### Help and version

Use [meow](https://www.npmjs.com/package/meow) to automatically add support for `--help`, `--version` and more.
{: .-setup}

```js
meow(`
    Usage:
        $0 FILES [options]

    Options:
        -h, --help         print usage information
        -v, --version      show version info and exit
`, {
  alias: { h: 'help', v: 'version' }
  /* minimist options */
})
```

### Reference

 * <https://www.npmjs.org/package/minimist>
 * <https://github.com/substack/minimist>


id: middleman
git_filename: ./middleman.md
format: md
field_title: Middleman 3
field_category: JavaScript libraries
field_tags: Archived
data:
{"title": "Middleman 3", "category": "JavaScript libraries", "tags": ["Archived"], "archived": "This guide is for Middleman v3.", "body": "### About\n\n**NB:** This is for Middleman 3, not Middleman 4+.\n\n### Compass config\n\n    compass_config do |config|\n      config.output_style = :compact\n    end\n\n### Config\n\n    # Automatic image dimensions on image_tag helper\n    activate :automatic_image_sizes\n\n### Gems\n\n    # Susy grids in Compass\n    # First: gem install compass-susy-plugin\n    require 'susy'\n\n    # CodeRay syntax highlighting in Haml\n    # First: gem install haml-coderay\n    require 'haml-coderay'\n\n    # CoffeeScript filters in Haml\n    # First: gem install coffee-filter\n    require 'coffee-filter'\n\n\n### Page command\n\n    # With no layout\n    page \"/path/to/file.html\", :layout => false\n\n    # With alternative layout\n    page \"/path/to/file.html\", :layout => :otherlayout\n\n    # A path which all have the same layout\n    with_layout :admin do\n      page \"/admin/*\"\n    end\n\n    # Proxy (fake) files\n    page \"/this-page-has-no-template.html\", :proxy => \"/template-file.html\" do\n      @which_fake_page = \"Rendering a fake page with a variable\"\n    end\n\n### Helpers\n\n    helpers do\n      def some_helper\n        \"Helping\"\n      end\n    end\n\n### Directories\n\n    set :css_dir, \"alternative_css_directory\"\n    set :js_dir, \"alternative_js_directory\"\n    set :images_dir, \"alternative_image_directory\"\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/\"\n    end"}

field_body:
### About

**NB:** This is for Middleman 3, not Middleman 4+.

### Compass config

    compass_config do |config|
      config.output_style = :compact
    end

### Config

    # Automatic image dimensions on image_tag helper
    activate :automatic_image_sizes

### Gems

    # Susy grids in Compass
    # First: gem install compass-susy-plugin
    require 'susy'

    # CodeRay syntax highlighting in Haml
    # First: gem install haml-coderay
    require 'haml-coderay'

    # CoffeeScript filters in Haml
    # First: gem install coffee-filter
    require 'coffee-filter'


### Page command

    # With no layout
    page "/path/to/file.html", :layout => false

    # With alternative layout
    page "/path/to/file.html", :layout => :otherlayout

    # A path which all have the same layout
    with_layout :admin do
      page "/admin/*"
    end

    # Proxy (fake) files
    page "/this-page-has-no-template.html", :proxy => "/template-file.html" do
      @which_fake_page = "Rendering a fake page with a variable"
    end

### Helpers

    helpers do
      def some_helper
        "Helping"
      end
    end

### Directories

    set :css_dir, "alternative_css_directory"
    set :js_dir, "alternative_js_directory"
    set :images_dir, "alternative_image_directory"

# Build-specific configuration

    configure :build do
      activate :minify_css
      activate :minify_javascript

      # Enable cache buster
      activate :cache_buster

      # Use relative URLs
      activate :relative_assets

      # Compress PNGs after build
      # First: gem install middleman-smusher
      # require "middleman-smusher"
      activate :smusher

      # Or use a different image path
      set :http_path, "/Content/images/"
    end


id: meta-tags
git_filename: ./meta-tags.md
format: md
field_title: Meta-tags gem
field_category: Ruby libraries
field_updated: 2017-09-08
field_updated___timezone: UTC
data:
{"title": "Meta-tags gem", "category": "Ruby libraries", "weight": -1, "updated": "2017-09-08", "body": "### Titles\n\n```ruby\nset_meta_tags title: 'Member Login'\n# <title>Some Page Title</title>\n```\n\n```ruby\nset_meta_tags site: 'Site Title', title: 'Member Login'\n# <title>Site Title | Page Title</title>\n```\n\n```ruby\nset_meta_tags(\n  site: 'Site Title',\n  title: 'Member Login',\n  reverse: true,\n  separator: '&middot;'.html_safe\n)\n# <title>Page Title \u00b7 Site Title</title>\n```\n\nWorks in a controller or a view.\n\n### Setting defaults\n\n```\nrails generate meta_tags:install\n```\n\nThis creates `config/initializers/meta_tags.rb` that you can edit.\n\n### Others\n\n```ruby\nset_meta_tags site: 'Site name'\nset_meta_tags title: 'Title'\nset_meta_tags description: \"All text about keywords\"\n```\n\n```ruby\nset_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```ruby\nset_meta_tags noindex: true\nset_meta_tags nofollow: true\nset_meta_tags follow: true\n```\n\n```ruby\nset_meta_tags og: { image: ['...'] }\nset_meta_tags twitter: { description: '...' }\n```\n```ruby\nset_meta_tags separator: '\u00b7'   # Site \u00b7 Page title\nset_meta_tags prefix: ' '      # Around the separator\nset_meta_tags suffix: ' '\n```\n\n```ruby\nset_meta_tags lowercase: true  # Lowercase page title\nset_meta_tags reverse: true    # Site name last\n```\n\n### In views\n\n```ruby\n# Displaying tags\n<%= display_meta_tags %>\n```\n\n```ruby\n# Displaying tags individually\n<h1><%= title %></h1>\n```\n\n```ruby\n# Setting tags\n<% title 'Member Login' %>\n<% description 'My page' %>\n<% keywords '..' %>\n```\n\n### Reference\n\n- Accurate as of 2.1.0. See: <https://github.com/kpumuk/meta-tags>"}

field_body:
### Titles

```ruby
set_meta_tags title: 'Member Login'
# <title>Some Page Title</title>
```

```ruby
set_meta_tags site: 'Site Title', title: 'Member Login'
# <title>Site Title | Page Title</title>
```

```ruby
set_meta_tags(
  site: 'Site Title',
  title: 'Member Login',
  reverse: true,
  separator: '&middot;'.html_safe
)
# <title>Page Title · Site Title</title>
```

Works in a controller or a view.

### Setting defaults

```
rails generate meta_tags:install
```

This creates `config/initializers/meta_tags.rb` that you can edit.

### Others

```ruby
set_meta_tags site: 'Site name'
set_meta_tags title: 'Title'
set_meta_tags description: "All text about keywords"
```

```ruby
set_meta_tags keywords: %w[abc def ghi]
set_meta_tags canonical: 'http://...'
set_meta_tags icon: 'favicon.ico'
set_meta_tags author: 'http://...'
set_meta_tags alternate: { 'fr' => 'http://...' }
set_meta_tags prev: 'http://...'
set_meta_tags next: 'http://...'
set_meta_tags image_src: 'http://...'
```

```ruby
set_meta_tags noindex: true
set_meta_tags nofollow: true
set_meta_tags follow: true
```

```ruby
set_meta_tags og: { image: ['...'] }
set_meta_tags twitter: { description: '...' }
```
```ruby
set_meta_tags separator: '·'   # Site · Page title
set_meta_tags prefix: ' '      # Around the separator
set_meta_tags suffix: ' '
```

```ruby
set_meta_tags lowercase: true  # Lowercase page title
set_meta_tags reverse: true    # Site name last
```

### In views

```ruby
# Displaying tags
<%= display_meta_tags %>
```

```ruby
# Displaying tags individually
<h1><%= title %></h1>
```

```ruby
# Setting tags
<% title 'Member Login' %>
<% description 'My page' %>
<% keywords '..' %>
```

### Reference

- Accurate as of 2.1.0. See: <https://github.com/kpumuk/meta-tags>


id: meow
git_filename: ./meow.md
format: md
field_title: Meow
field_category: JavaScript libraries
field_intro: [meow](https://npmjs.com/package/meow) is the easiest way to write command line apps for Node.js.
field_updated: 2017-10-30
field_updated___timezone: UTC
data:
{"title": "Meow", "category": "JavaScript libraries", "updated": "2017-10-30", "weight": -1, "intro": "[meow](https://npmjs.com/package/meow) is the easiest way to write command line apps for Node.js.\n", "body": "### Typical settings\n\n```js\nconst 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```js\ncli.flags   // { lang: 'en' }\ncli.input   // []\n```\n\nYes, flags are automatically camelCased!\n\n### Lesser-used settings\n\n```js\nmeow(`...`, {\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\nAlso see [minimist](minimist.html)."}

field_body:
### Typical settings

```js
const cli = require('meow')(`
  Usage: appname [options]

  Options:
        --lang LANG    set the language

  Other options:
    -h, --help         show usage information
    -v, --version      print version info and exit
`, {
  string: ['lang'],
  boolean: ['help', 'version'],
  alias: { h: 'help', v: 'version' }
})
```

`string` and `boolean` lets meow/minimist know which flags expect arguments (`string`) and which don't (`boolean`).

### Using the result

```js
cli.flags   // { lang: 'en' }
cli.input   // []
```

Yes, flags are automatically camelCased!

### Lesser-used settings

```js
meow(`...`, {
  // Default values if flags are not specified
  default: { lang: 'en' },

  // allow using -- to stop processing flags
  '--': true,

  // Populate `_` with first non-option
  stopEarly: true,

  // Invoked on unknown param
  unknown: function () { ... }
})
```

Also see [minimist](minimist.html).


id: markdown
git_filename: ./markdown.md
format: md
field_title: Markdown
field_category: Markup
field_prism_languages: markdown
field_updated: 2020-07-01
field_updated___timezone: UTC
data:
{"title": "Markdown", "category": "Markup", "prism_languages": ["markdown"], "updated": "2020-07-01", "weight": -1, "body": "## Reference\n{:.-three-column}\n\n### Headers\n\n```markdown\n# h1\n## h2\n### h3\n#### h4\n##### h5\n###### h6\n```\n\n```markdown\nHeader 1\n========\n```\n\n```markdown\nHeader 2\n--------\n```\n\n### Emphasis\n\n```markdown\n*italic*\n_italic_\n```\n\n```markdown\n**bold**\n__bold__\n```\n\n```markdown\n***bold italic***\n___bold italic___\n```\n\n```markdown\n~~strikethrough~~\n```\n\n```markdown\n`code`\n```\n\n### Lists\n\n```markdown\n* Item 1\n  * Nested Item 1\n* Item 2\n```\n\n```markdown\n- Item 1\n  - Nested Item 1\n- Item 2\n```\n\n```markdown\n- [ ] Checkbox off\n- [x] Checkbox on\n```\n\n```markdown\n1. Item 1\n2. Item 2\n```\n\n### Links\n\n```markdown\n[link](http://google.com)\n```\n\n```markdown\n[link][google]\n[google]: http://google.com\n```\n\n```markdown\n<http://google.com>\n```\n\n### Images\n\n```markdown\n![Image alt text](/path/to/img.jpg)\n![Image alt text](/path/to/img.jpg \"title\")\n```\n\n```markdown\n![Image alt text][img]\n[img]: http://foo.com/img.jpg\n```\n\n```markdown\n![Image alt text][img_base64]\n[img_base64]: <data:image/png;base64,...>\n```\n\n### Code\n\n```markdown\n`inline code`\n```\n\n```\n    4 space indent\n    makes a code block\n```\n\n~~~markdown\n```\ncode fences\n```\n~~~\n\n\n~~~markdown\n```js\ncodeFences.withLanguage()\n```\n~~~\n\n### Blockquotes\n\n```markdown\n> This is\n> a blockquote\n>\n> > Nested\n> > Blockquote\n```\n\n### Horizontal line\n\n```markdown\n----\n```\n\n```markdown\n****\n```\n\n### Tables\n\n```markdown\n| Column 1 Heading | Column 2 Heading |\n| ---------------- | ---------------- |\n| Some content     | Other content    |\n```\n\n```markdown\nColumn 1 Heading | Column 2 Heading\n--- | ---\nSome content | Other content\n```"}

field_body:
## Reference
{:.-three-column}

### Headers

```markdown
# h1
## h2
### h3
#### h4
##### h5
###### h6
```

```markdown
Header 1
========
```

```markdown
Header 2
--------
```

### Emphasis

```markdown
*italic*
_italic_
```

```markdown
**bold**
__bold__
```

```markdown
***bold italic***
___bold italic___
```

```markdown
~~strikethrough~~
```

```markdown
`code`
```

### Lists

```markdown
* Item 1
  * Nested Item 1
* Item 2
```

```markdown
- Item 1
  - Nested Item 1
- Item 2
```

```markdown
- [ ] Checkbox off
- [x] Checkbox on
```

```markdown
1. Item 1
2. Item 2
```

### Links

```markdown
[link](http://google.com)
```

```markdown
[link][google]
[google]: http://google.com
```

```markdown
<http://google.com>
```

### Images

```markdown
![Image alt text](/path/to/img.jpg)
![Image alt text](/path/to/img.jpg "title")
```

```markdown
![Image alt text][img]
[img]: http://foo.com/img.jpg
```

```markdown
![Image alt text][img_base64]
[img_base64]: <data:image/png;base64,...>
```

### Code

```markdown
`inline code`
```

```
    4 space indent
    makes a code block
```

~~~markdown
```
code fences
```
~~~


~~~markdown
```js
codeFences.withLanguage()
```
~~~

### Blockquotes

```markdown
> This is
> a blockquote
>
> > Nested
> > Blockquote
```

### Horizontal line

```markdown
----
```

```markdown
****
```

### Tables

```markdown
| Column 1 Heading | Column 2 Heading |
| ---------------- | ---------------- |
| Some content     | Other content    |
```

```markdown
Column 1 Heading | Column 2 Heading
--- | ---
Some content | Other content
```


id: man
git_filename: ./man.md
format: md
field_title: Man
field_category: CLI
data:
{"title": "Man", "category": "CLI", "body": "### Man paths\n\n| `1` | General User Commands |\n| `2` | System Calls |\n| `3` | Library Routines |\n| `4` | Special Files and Sockets |\n| `5` | File formats and Conventions |\n| `6` | Games and Fun Stuff |\n| `7` | Miscellaneous Documentation |\n| `8` | System Administration |\n| `9` | Kernel and Programming Style |\n| `n` | Tcl/Tk |"}

field_body:
### Man paths

| `1` | General User Commands |
| `2` | System Calls |
| `3` | Library Routines |
| `4` | Special Files and Sockets |
| `5` | File formats and Conventions |
| `6` | Games and Fun Stuff |
| `7` | Miscellaneous Documentation |
| `8` | System Administration |
| `9` | Kernel and Programming Style |
| `n` | Tcl/Tk |


id: mako
git_filename: ./mako.md
format: md
field_title: Mako
field_category: Python
data:
{"title": "Mako", "category": "Python", "body": "### Basic usage\n\n```\nVariable x has content: ${x}\nExpression: ${x + 1}\nEscaped for HTML: ${x | h}\n```\n\n### Control structures\n\n```\n% for x in range(5):\n    % if x % 2 == 0:\n    ${x} is even!\n    % else:\n    ${x} is odd!\n    % endif\n% endfor\n```\n\n### Including Python code\n\n```python\n<%\n    greeting = \"Hello world!\"\n    # arbitrary python code\n%>\n\n<%!\n# arbitrary python code run at toplevel\n# cannot access variables!\n\ndef sign_string(number):\n    if number > 0:\n        return \"positive\"\n    elif number < 0:\n        return \"negative\"\n    else:\n        return \"zero\"\n%>\n```\n\n### Special blocks\n\n```html\n<%text filter=\"h\">\n    This is a raw block where ${nothing is evaluated}\n    <%\n        not even this\n    %>\n    and <html is escaped> too with \"h\" filter\n</%text>\n\n<%def name=\"myfunc(x)\">\n    this is a reusable macro, with arguments: ${x}\n</%def>\n\n${myfunc(42)}\n\n<%doc>\n    this is a comment\n</%doc>\n```\n\n### Inheritance\n\n#### shared.html\n\n```html\n<html>\n  <head>\n    <title><%block name=\"title\" /></title>\n  </head>\n  <body>\n    <header><h1><%block name=\"title\" /></h1></header>\n    <main>${self.body()}</main>\n  </body>\n</html>\n```\n\n#### home.html\n\n```html\n<%inherit file=\"shared.html\" />\n<%block name=\"title\">Welcome to my site</%block>\n\nThis is the body\n```\n\n#### article.html\n\n```html\n<%inherit file=\"shared.html\" />\n<%block name=\"title\">${post.title}</%block>\n\n${post.content}\n```\n\n## Library\n\n### Basic usage\n\n```python\nfrom mako.template import Template\n\nmytemplate = Template(\"hello, ${name}!\")\nprint(mytemplate.render(name=\"jack\"))\n```"}

field_body:
### Basic usage

```
Variable x has content: ${x}
Expression: ${x + 1}
Escaped for HTML: ${x | h}
```

### Control structures

```
% for x in range(5):
    % if x % 2 == 0:
    ${x} is even!
    % else:
    ${x} is odd!
    % endif
% endfor
```

### Including Python code

```python
<%
    greeting = "Hello world!"
    # arbitrary python code
%>

<%!
# arbitrary python code run at toplevel
# cannot access variables!

def sign_string(number):
    if number > 0:
        return "positive"
    elif number < 0:
        return "negative"
    else:
        return "zero"
%>
```

### Special blocks

```html
<%text filter="h">
    This is a raw block where ${nothing is evaluated}
    <%
        not even this
    %>
    and <html is escaped> too with "h" filter
</%text>

<%def name="myfunc(x)">
    this is a reusable macro, with arguments: ${x}
</%def>

${myfunc(42)}

<%doc>
    this is a comment
</%doc>
```

### Inheritance

#### shared.html

```html
<html>
  <head>
    <title><%block name="title" /></title>
  </head>
  <body>
    <header><h1><%block name="title" /></h1></header>
    <main>${self.body()}</main>
  </body>
</html>
```

#### home.html

```html
<%inherit file="shared.html" />
<%block name="title">Welcome to my site</%block>

This is the body
```

#### article.html

```html
<%inherit file="shared.html" />
<%block name="title">${post.title}</%block>

${post.content}
```

## Library

### Basic usage

```python
from mako.template import Template

mytemplate = Template("hello, ${name}!")
print(mytemplate.render(name="jack"))
```


id: makefile
git_filename: ./makefile.md
format: md
field_title: Makefile
field_category: CLI
field_prism_languages: makefile
data:
{"title": "Makefile", "prism_languages": ["makefile"], "category": "CLI", "body": "### Var assignment\n\n```makefile\nfoo  = \"bar\"\nbar  = $(foo) foo  # dynamic (renewing) assignment\nfoo := \"boo\"       # one time assignment, $(bar) now is \"boo foo\"\nfoo ?= /usr/local  # safe assignment, $(foo) and $(bar) still the same\nbar += world       # append, \"boo foo world\"\nfoo != echo fooo   # exec shell command and assign to foo\n# $(bar) now is \"fooo foo world\"\n```\n\n`=` expressions are only evaluated when they're being used.\n\n### Magic variables\n\n```makefile\nout.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| Prefix | Description                                 |\n| ------ | ------------------------------------------- |\n| `-`    | Ignore errors                               |\n| `@`    | Don't print command                         |\n| `+`    | Run even if Make is in 'don't execute' mode |\n\n```makefile\nbuild:\n    @echo \"compiling\"\n    -gcc $< $@\n\n-include .depend\n```\n\n### Find files\n\n```makefile\njs_files  := $(wildcard test/*.js)\nall_files := $(shell find images -name \"*\")\n```\n\n### Substitutions\n\n```makefile\nfile     = $(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```makefile\n$(strip $(string_var))\n\n$(filter %.less, $(files))\n$(filter-out %.less, $(files))\n```\n\n### Building files\n\n```makefile\n%.o: %.c\n  ffmpeg -i $< > $@   # Input and output\n  foo $^\n```\n\n### Includes\n\n```makefile\n-include foo.make\n```\n\n### Options\n\n```sh\nmake\n  -e, --environment-overrides\n  -B, --always-make\n  -s, --silent\n  -j, --jobs=N   # parallel processing\n```\n\n### Conditionals\n\n```makefile\nfoo: $(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```makefile\ndeploy:\n  $(MAKE) deploy2\n```\n\n### Further reading\n\n- [isaacs's Makefile](https://gist.github.com/isaacs/62a2d1825d04437c6f08)\n- [Your Makefiles are wrong](https://tech.davis-hansson.com/p/make/)\n- [Manual](https://www.gnu.org/software/make/manual/html_node/index.html)"}

field_body:
### Var assignment

```makefile
foo  = "bar"
bar  = $(foo) foo  # dynamic (renewing) assignment
foo := "boo"       # one time assignment, $(bar) now is "boo foo"
foo ?= /usr/local  # safe assignment, $(foo) and $(bar) still the same
bar += world       # append, "boo foo world"
foo != echo fooo   # exec shell command and assign to foo
# $(bar) now is "fooo foo world"
```

`=` expressions are only evaluated when they're being used.

### Magic variables

```makefile
out.o: src.c src.h
  $@   # "out.o" (target)
  $<   # "src.c" (first prerequisite)
  $^   # "src.c src.h" (all prerequisites)

%.o: %.c
  $*   # the 'stem' with which an implicit rule matches ("foo" in "foo.c")

also:
  $+   # prerequisites (all, with duplication)
  $?   # prerequisites (new ones)
  $|   # prerequisites (order-only?)

  $(@D) # target directory
```

### Command prefixes

| Prefix | Description                                 |
| ------ | ------------------------------------------- |
| `-`    | Ignore errors                               |
| `@`    | Don't print command                         |
| `+`    | Run even if Make is in 'don't execute' mode |

```makefile
build:
    @echo "compiling"
    -gcc $< $@

-include .depend
```

### Find files

```makefile
js_files  := $(wildcard test/*.js)
all_files := $(shell find images -name "*")
```

### Substitutions

```makefile
file     = $(SOURCE:.cpp=.o)   # foo.cpp => foo.o
outputs  = $(files:src/%.coffee=lib/%.js)

outputs  = $(patsubst %.c, %.o, $(wildcard *.c))
assets   = $(patsubst images/%, assets/%, $(wildcard images/*))
```

### More functions

```makefile
$(strip $(string_var))

$(filter %.less, $(files))
$(filter-out %.less, $(files))
```

### Building files

```makefile
%.o: %.c
  ffmpeg -i $< > $@   # Input and output
  foo $^
```

### Includes

```makefile
-include foo.make
```

### Options

```sh
make
  -e, --environment-overrides
  -B, --always-make
  -s, --silent
  -j, --jobs=N   # parallel processing
```

### Conditionals

```makefile
foo: $(objects)
ifeq ($(CC),gcc)
  $(CC) -o foo $(objects) $(libs_for_gcc)
else
  $(CC) -o foo $(objects) $(normal_libs)
endif
```

### Recursive

```makefile
deploy:
  $(MAKE) deploy2
```

### Further reading

- [isaacs's Makefile](https://gist.github.com/isaacs/62a2d1825d04437c6f08)
- [Your Makefiles are wrong](https://tech.davis-hansson.com/p/make/)
- [Manual](https://www.gnu.org/software/make/manual/html_node/index.html)


id: make-assets
git_filename: ./make-assets.md
format: md
field_title: Make for assets
field_tags: Archived
data:
{"title": "Make for assets", "tags": ["Archived"], "archived": "This sheet may be listing practices that are outdated.", "body": "### Basic compiling\n\n```makefile\nbin := ./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\n    stylus := $(bin)/stylus\n    autoprefixer := $(bin)/autoprefixer\n    styl_files := $(shell find web/ -name \"*.styl\")\n\n    all: public/app.css\n\n    public/app.css: css/app.styl\n\n    %.css: %.styl $(styl_files)\n        @$(stylus) $< | $(autoprefixer) -b \"> 1%\" > $@\n\n### Hint\n\n    hint:\n       $(js_files)\n\n### Watching\n\n    watch:\n        @echo \"... watching for changes\"\n        @while true; do make -s; sleep 1; done\n\n### Browserify\n\n    js_files := $(shell find web/ -name \"*.js\")\n\n    public/app.js: web/app.js\n    public/vendor.js: web/vendor.js\n\n    public/%.js: web/%.js $(js_files)\n        $(browserify) -t [ cssify -x .css ] $< > $@"}

field_body:
### Basic compiling

```makefile
bin := ./node_modules/.bin

all: build/foo.js

build/%.js: src/%.coffee
    @$(bin)/coffee < $^ > $@
```

### Stylus + Autoprefixer

    bin := ./node_modules/.bin
    stylus := $(bin)/stylus
    autoprefixer := $(bin)/autoprefixer
    styl_files := $(shell find web/ -name "*.styl")

    all: public/app.css

    public/app.css: css/app.styl

    %.css: %.styl $(styl_files)
        @$(stylus) $< | $(autoprefixer) -b "> 1%" > $@

### Hint

    hint:
       $(js_files)

### Watching

    watch:
        @echo "... watching for changes"
        @while true; do make -s; sleep 1; done

### Browserify

    js_files := $(shell find web/ -name "*.js")

    public/app.js: web/app.js
    public/vendor.js: web/vendor.js

    public/%.js: web/%.js $(js_files)
        $(browserify) -t [ cssify -x .css ] $< > $@


id: macos-mouse-acceleration
git_filename: ./macos-mouse-acceleration.md
format: md
field_title: Mouse Acceleration
field_category: macOS
field_intro: Disable mouse acceleration with this one weird trick.
field_updated: 2018-03-20
field_updated___timezone: UTC
data:
{"title": "Mouse Acceleration", "category": "macOS", "updated": "2018-03-20", "weight": -1, "keywords": ["defaults write .GlobalPreferences com.apple.mouse.scaling -1"], "intro": "Disable mouse acceleration with this one weird trick.\n", "body": "## Acceleration\n\n\n### Disabling\n\n```bash\ndefaults write .GlobalPreferences com.apple.mouse.scaling -1\n```\n\nNote: 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\nUnder *System Preferences* \u2192 *Mouse*, change *Tracking Speed*.\n\n### Trackpad acceleration\n\n```bash\ndefaults write .GlobalPreferences com.apple.trackpad.scaling -1\n```\n\nWorks the same way, but only affects trackpads.\n\n## References\n\n- [Disabling mouse acceleration](https://stackoverflow.com/questions/5782884/disabling-mouse-acceleration-in-mac-os-x) _(stackoverflow.com)_"}

field_body:
## Acceleration


### Disabling

```bash
defaults write .GlobalPreferences com.apple.mouse.scaling -1
```

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.

### Re-enabling

Under *System Preferences* → *Mouse*, change *Tracking Speed*.

### Trackpad acceleration

```bash
defaults write .GlobalPreferences com.apple.trackpad.scaling -1
```

Works the same way, but only affects trackpads.

## References

- [Disabling mouse acceleration](https://stackoverflow.com/questions/5782884/disabling-mouse-acceleration-in-mac-os-x) _(stackoverflow.com)_


id: machinist
git_filename: ./machinist.md
format: md
field_title: Machinist
field_category: Ruby libraries
field_tags: Archived
data:
{"title": "Machinist", "category": "Ruby libraries", "tags": ["Archived"], "archived": "Machinist has not been in active development since 2013.", "body": "### About\n\nMachinist is a fixture management library for Ruby.\n\n- <https://github.com/notahat/machinist>\n\n### Installing\n\n    # Gemfile\n    gem 'machinist', '>= 2.0.0.beta2', group: 'test'\n\n    # ~$ bundle\n    # ~$ rails generate machinist:install\n\n### Building objects\n\n    User.make\n\n    # `make` builds it, and `make!` builds+saves it\n    User.make!\n    User.make! name: \"David\"\n    User.make!(:admin)\n\n### Defining blueprints\n\n    User.blueprint do\n      name  { \"User #{sn}\" }\n      email { \"user-#{sn}@example.com\" }\n    end\n\n    User.blueprint(:admin) do\n      name  { \"Admin User #{sn}\" }\n      admin { true }\n    end\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\n    end\n\n### References\n\n * [https://github.com/notahat/machinist](https://github.com/notahat/machinist)"}

field_body:
### About

Machinist is a fixture management library for Ruby.

- <https://github.com/notahat/machinist>

### Installing

    # Gemfile
    gem 'machinist', '>= 2.0.0.beta2', group: 'test'

    # ~$ bundle
    # ~$ rails generate machinist:install

### Building objects

    User.make

    # `make` builds it, and `make!` builds+saves it
    User.make!
    User.make! name: "David"
    User.make!(:admin)

### Defining blueprints

    User.blueprint do
      name  { "User #{sn}" }
      email { "user-#{sn}@example.com" }
    end

    User.blueprint(:admin) do
      name  { "Admin User #{sn}" }
      admin { true }
    end

### Associations

    Post.blueprint do
      author { User.make }

      comments(3)    # Makes 3 comments (has_many / habtm)

      author         # autodetect (Assumes there's User.blueprint)

    end

### References

 * [https://github.com/notahat/machinist](https://github.com/notahat/machinist)


id: lua
git_filename: ./lua.md
format: md
field_title: Lua
data:
{"title": "Lua", "body": "## Basic examples\n\n### References\n\n- <https://www.lua.org/pil/13.html>\n- <http://lua-users.org/wiki/ObjectOrientedProgramming>\n\n### Comments\n\n    -- comment\n    --[[ Multiline\n         comment ]]\n\n### Invoking functions\n\n    print()\n    print(\"Hi\")\n\n    -- You can omit parentheses if the argument is one string or table literal\n    print \"Hello World\"     <-->     print(\"Hello World\")\n    dofile 'a.lua'          <-->     dofile ('a.lua')\n    print [[a multi-line    <-->     print([[a multi-line\n     message]]                        message]])\n    f{x=10, y=20}           <-->     f({x=10, y=20})\n    type{}                  <-->     type({})\n\n### Tables / arrays\n\n    t = {}\n    t = { a = 1, b = 2 }\n    t.a = function() ... end\n\n    t = { [\"hello\"] = 200 }\n    t.hello\n\n    -- Remember, arrays are also tables\n    array = { \"a\", \"b\", \"c\", \"d\" }\n    print(array[2])       -- \"b\" (one-indexed)\n    print(#array)         -- 4 (length)\n\n### Loops\n\n    while condition do\n    end\n\n    for i = 1,5 do\n    end\n\n    for i = start,finish,delta do\n    end\n\n    for k,v in pairs(tab) do\n    end\n\n    repeat\n    until condition\n\n    -- Breaking out:\n    while x do\n      if condition then break end\n    end\n\n### Conditionals\n\n    if condition then\n      print(\"yes\")\n    elseif condition then\n      print(\"maybe\")\n    else\n      print(\"no\")\n    end\n\n### Variables\n\n    local x = 2\n    two, four = 2, 4\n\n### Functions\n\n    function myFunction()\n      return 1\n    end\n\n    function myFunctionWithArgs(a, b)\n      -- ...\n    end\n\n    myFunction()\n\n    anonymousFunctions(function()\n      -- ...\n    end)\n\n    -- Not exported in the module\n    local function myPrivateFunction()\n    end\n\n    -- Splats\n    function doAction(action, ...)\n      print(\"Doing '\"..action..\"' to\", ...)\n      --> print(\"Doing 'write' to\", \"Shirley\", \"Abed\")\n    end\n\n    doAction('write', \"Shirley\", \"Abed\")\n\n### Lookups\n\n    mytable = { x = 2, y = function() .. end }\n\n    -- The same:\n    mytable.x\n    mytable['x']\n\n    -- Syntactic sugar, these are equivalent:\n    mytable.y(mytable)\n    mytable:y()\n\n    mytable.y(mytable, a, b)\n    mytable:y(a, b)\n\n    function X:y(z) .. end\n    function X.y(self, z) .. end\n\n## More concepts\n\n### Metatables\n\n    mt = {}\n\n    -- A metatable is simply a table with functions in it.\n    mt.__tostring = function() return \"lol\" end\n    mt.__add      = function(b) ... end       -- a + b\n    mt.__mul      = function(b) ... end       -- a * b\n    mt.__index    = function(k) ... end       -- Lookups (a[k] or a.k)\n    mt.__newindex = function(k, v) ... end    -- Setters (a[k] = v)\n\n    -- Metatables allow you to override behavior of another table.\n    mytable = {}\n    setmetatable(mytable, mt)\n\n    print(myobject)\n\n### Classes\n\n    Account = {}\n\n    function Account:new(balance)\n      local t = setmetatable({}, { __index = Account })\n\n      -- Your constructor stuff\n      t.balance = (balance or 0)\n      return t\n    end\n\n    function Account:withdraw(amount)\n      print(\"Withdrawing \"..amount..\"...\")\n      self.balance = self.balance - amount\n      self:report()\n    end\n\n    function Account:report()\n      print(\"Your current balance is: \"..self.balance)\n    end\n\n    a = Account:new(9000)\n    a:withdraw(200)    -- method call\n\n### Constants\n\n    nil\n    false\n    true\n\n## Operators (and their metatable names)\n\n### Relational\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\n\n    -- Logic (and/or)\n    nil and false  --> nil\n    false and nil  --> false\n    not true       --> false\n    0 and 20       --> 20\n    10 and 20      --> 20\n\n### Tables\n\n    -- Length\n    -- __len(array)\n    #array\n\n\n    -- Indexing\n    -- __index(table, key)\n    t[key]\n    t.key\n\n    -- __newindex(table, key, value)\n    t[key]=value\n\n    -- String concat\n    -- __concat(left, right)\n    \"hello, \"..name\n\n    -- Call\n    -- __call(func, ...)\n\n## API\n\n### API: Global Functions\n\n    dofile(\"hello.lua\")\n    loadfile(\"hello.lua\")\n\n    assert(x)    -- x or (raise an error)\n    assert(x, \"failed\")\n\n    type(var)   -- \"nil\" | \"number\" | \"string\" | \"boolean\" | \"table\" | \"function\" | \"thread\" | \"userdata\"\n\n    -- Does /not/ invoke meta methods (__index and __newindex)\n    rawset(t, index, value)    -- Like t[index] = value\n    rawget(t, index)           -- Like t[index]\n\n    _G  -- Global context\n    setfenv(1, {})  -- 1: current function, 2: caller, and so on -- {}: the new _G\n\n    pairs(t)     -- iterable list of {key, value}\n    ipairs(t)    -- iterable list of {index, value}\n\n    tonumber(\"34\")\n    tonumber(\"8f\", 16)\n\n### API: Strings\n\n    'string'..'concatenation'\n\n    s = \"Hello\"\n    s:upper()\n    s:lower()\n    s:len()    -- Just like #s\n\n    s:find()\n    s:gfind()\n\n    s:match()\n    s:gmatch()\n\n    s:sub()\n    s:gsub()\n\n    s:rep()\n    s:char()\n    s:dump()\n    s:reverse()\n    s:byte()\n    s:format()\n\n### API: Tables\n\n    table.foreach(t, function(row) ... end)\n    table.setn\n    table.insert(t, 21)          -- append (--> t[#t+1] = 21)\n    table.insert(t, 4, 99)\n    table.getn\n    table.concat\n    table.sort\n    table.remove(t, 4)\n\n### API: Math\n\n    math.abs     math.acos    math.asin       math.atan    math.atan2\n    math.ceil    math.cos     math.cosh       math.deg     math.exp\n    math.floor   math.fmod    math.frexp      math.ldexp   math.log\n    math.log10   math.max     math.min        math.modf    math.pow\n    math.rad     math.random  math.randomseed math.sin     math.sinh\n    math.sqrt    math.tan     math.tanh\n\n    math.sqrt(144)\n    math\n\n### API: Misc\n\n    io.output(io.open(\"file.txt\", \"w\"))\n    io.write(x)\n    io.close()\n\n    for line in io.lines(\"file.txt\")\n\n    file = assert(io.open(\"file.txt\", \"r\"))\n    file:read()\n    file:lines()\n    file:close()"}

field_body:
## Basic examples

### References

- <https://www.lua.org/pil/13.html>
- <http://lua-users.org/wiki/ObjectOrientedProgramming>

### Comments

    -- comment
    --[[ Multiline
         comment ]]

### Invoking functions

    print()
    print("Hi")

    -- You can omit parentheses if the argument is one string or table literal
    print "Hello World"     <-->     print("Hello World")
    dofile 'a.lua'          <-->     dofile ('a.lua')
    print [[a multi-line    <-->     print([[a multi-line
     message]]                        message]])
    f{x=10, y=20}           <-->     f({x=10, y=20})
    type{}                  <-->     type({})

### Tables / arrays

    t = {}
    t = { a = 1, b = 2 }
    t.a = function() ... end

    t = { ["hello"] = 200 }
    t.hello

    -- Remember, arrays are also tables
    array = { "a", "b", "c", "d" }
    print(array[2])       -- "b" (one-indexed)
    print(#array)         -- 4 (length)

### Loops

    while condition do
    end

    for i = 1,5 do
    end

    for i = start,finish,delta do
    end

    for k,v in pairs(tab) do
    end

    repeat
    until condition

    -- Breaking out:
    while x do
      if condition then break end
    end

### Conditionals

    if condition then
      print("yes")
    elseif condition then
      print("maybe")
    else
      print("no")
    end

### Variables

    local x = 2
    two, four = 2, 4

### Functions

    function myFunction()
      return 1
    end

    function myFunctionWithArgs(a, b)
      -- ...
    end

    myFunction()

    anonymousFunctions(function()
      -- ...
    end)

    -- Not exported in the module
    local function myPrivateFunction()
    end

    -- Splats
    function doAction(action, ...)
      print("Doing '"..action.."' to", ...)
      --> print("Doing 'write' to", "Shirley", "Abed")
    end

    doAction('write', "Shirley", "Abed")

### Lookups

    mytable = { x = 2, y = function() .. end }

    -- The same:
    mytable.x
    mytable['x']

    -- Syntactic sugar, these are equivalent:
    mytable.y(mytable)
    mytable:y()

    mytable.y(mytable, a, b)
    mytable:y(a, b)

    function X:y(z) .. end
    function X.y(self, z) .. end

## More concepts

### Metatables

    mt = {}

    -- A metatable is simply a table with functions in it.
    mt.__tostring = function() return "lol" end
    mt.__add      = function(b) ... end       -- a + b
    mt.__mul      = function(b) ... end       -- a * b
    mt.__index    = function(k) ... end       -- Lookups (a[k] or a.k)
    mt.__newindex = function(k, v) ... end    -- Setters (a[k] = v)

    -- Metatables allow you to override behavior of another table.
    mytable = {}
    setmetatable(mytable, mt)

    print(myobject)

### Classes

    Account = {}

    function Account:new(balance)
      local t = setmetatable({}, { __index = Account })

      -- Your constructor stuff
      t.balance = (balance or 0)
      return t
    end

    function Account:withdraw(amount)
      print("Withdrawing "..amount.."...")
      self.balance = self.balance - amount
      self:report()
    end

    function Account:report()
      print("Your current balance is: "..self.balance)
    end

    a = Account:new(9000)
    a:withdraw(200)    -- method call

### Constants

    nil
    false
    true

## Operators (and their metatable names)

### Relational

    -- Relational (binary)
    -- __eq  __lt  __gt  __le  __ge
       ==    <     >     <=    >=
    ~=   -- Not equal, just like !=

    -- Arithmetic (binary)
    -- __add  __sub  __muv  __div  __mod  __pow
       +      -      *      /      %      ^

    -- Arithmetic (unary)
    -- __unm (unary minus)
       -

### Logic

    -- Logic (and/or)
    nil and false  --> nil
    false and nil  --> false
    not true       --> false
    0 and 20       --> 20
    10 and 20      --> 20

### Tables

    -- Length
    -- __len(array)
    #array


    -- Indexing
    -- __index(table, key)
    t[key]
    t.key

    -- __newindex(table, key, value)
    t[key]=value

    -- String concat
    -- __concat(left, right)
    "hello, "..name

    -- Call
    -- __call(func, ...)

## API

### API: Global Functions

    dofile("hello.lua")
    loadfile("hello.lua")

    assert(x)    -- x or (raise an error)
    assert(x, "failed")

    type(var)   -- "nil" | "number" | "string" | "boolean" | "table" | "function" | "thread" | "userdata"

    -- Does /not/ invoke meta methods (__index and __newindex)
    rawset(t, index, value)    -- Like t[index] = value
    rawget(t, index)           -- Like t[index]

    _G  -- Global context
    setfenv(1, {})  -- 1: current function, 2: caller, and so on -- {}: the new _G

    pairs(t)     -- iterable list of {key, value}
    ipairs(t)    -- iterable list of {index, value}

    tonumber("34")
    tonumber("8f", 16)

### API: Strings

    'string'..'concatenation'

    s = "Hello"
    s:upper()
    s:lower()
    s:len()    -- Just like #s

    s:find()
    s:gfind()

    s:match()
    s:gmatch()

    s:sub()
    s:gsub()

    s:rep()
    s:char()
    s:dump()
    s:reverse()
    s:byte()
    s:format()

### API: Tables

    table.foreach(t, function(row) ... end)
    table.setn
    table.insert(t, 21)          -- append (--> t[#t+1] = 21)
    table.insert(t, 4, 99)
    table.getn
    table.concat
    table.sort
    table.remove(t, 4)

### API: Math

    math.abs     math.acos    math.asin       math.atan    math.atan2
    math.ceil    math.cos     math.cosh       math.deg     math.exp
    math.floor   math.fmod    math.frexp      math.ldexp   math.log
    math.log10   math.max     math.min        math.modf    math.pow
    math.rad     math.random  math.randomseed math.sin     math.sinh
    math.sqrt    math.tan     math.tanh

    math.sqrt(144)
    math

### API: Misc

    io.output(io.open("file.txt", "w"))
    io.write(x)
    io.close()

    for line in io.lines("file.txt")

    file = assert(io.open("file.txt", "r"))
    file:read()
    file:lines()
    file:close()


id: lodash
git_filename: ./lodash.md
format: md
field_title: Lodash
field_category: JavaScript libraries
field_updated: 2020-06-24
field_updated___timezone: UTC
data:
{"title": "Lodash", "category": "JavaScript libraries", "weight": -3, "updated": "2020-06-24", "description": "This is not a complete list.\n", "body": "## Collections\n\n### Finding\n\n```js\n_.filter(list, (n) => n % 2)    // \u2192 Array\n_.find(list, (n) => n % 2)      // \u2192 item\n_.findLast(list, ...)           // \u2192 item\n```\n\nWorks for both arrays and objects.\n\n### Accessing\n\n```js\n_.at([ abcd ], 0)               // \u2192 [ a ] - same as list[0]\n_.at([ abcd ], [ 0, 1 ])        // \u2192 [ ab ]\n```\n\n### Set/get\n\n```js\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```js\n_.forEach(list, (item, i) => ...)\n_.forEachRight(list, ...)\n\n_.map(list, ...)\n```\n\n```js\n_.every(users, (u) => u.active)  // \u2192 true|false (aka _.all)\n_.any(users, ...)                // \u2192 true|false (aka _.some)\n```\n\n## Array\n\n### Arrays\n\n```js\n_.chunk([ abcd ], 2)           // \u2192 [ [ab], [cd] ]\n_.compact(list)\n\n_.fill(Array(4), 'x')          // \u2192 [ 'x', 'x', 'x', 'x' ]\n_.flatten\n_.flattenDeep\n```\n\n### Filtering\n\n```js\n_.drop([ abcdef ], 2)          // \u2192 [   cdef ]\n_.dropRight([ abcdef ], 2)     // \u2192 [ abcd   ]\n_.take([ abcdef ], 2)          // \u2192 [ ab     ]\n_.takeRight([ abcdef ], 2)     // \u2192 [     de ]\n_.slice([ abcdef ], 2, 4)      // \u2192 [   cd   ]\n```\n\n```js\n_.initial([ abcdef ])          // \u2192 [ abcde  ] - dropRight(list, 1)\n_.rest([ abcdef ])             // \u2192 [  bcdef ] - takeRight(list, 1)\n```\n\n```js\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```js\n_.without([ abcde ], b)        // \u2192 [ acde ]\n```\n\n```js\n_.remove(list, (n) => n % 2)\n```\n\n### Accessing\n\n```js\n_.first([ abcdef ])            // \u2192 a\n_.last([ abcdef ])             // \u2192 f\n```\n\n### Sets\n\n```js\n_.uniq()\n_.difference([ abc ], [ bc ])       // \u2192 [ a    ]\n_.intersection([ abc ], [ bcd ])    // \u2192 [  bc  ]\n_.union([ abc ], [ bcd ])           // \u2192 [ abcd ] (unique)\n```\n\n```js\nArray#concat()\n```\n\n### Indexes\n\n```js\n_.findIndex(list, fn)\n_.findLastIndex(list, fn)\n```\n\n```js\n_.sortedIndex(list, val)\n_.sortedLastIndex(list, val)\n```\n\n```js\n_.indexOf(list, val)\n```\n\n## Functions\n\n### Currying\n\n```js\ngreet = (greeting, name) => `${greeting}, ${name}!`\n```\n{: .-setup}\n\n```js\nfn = _.partial(fn, 'hi')\nfn('joe')    // \u2192 'hi, joe!'\n\nfn = _.partial(fn, 'joe')\nfn('yo')     // \u2192 'yo, joe!'\n```\n\n```js\n_.curry(greet)('hi')         // \u2192 function(name)\n_.curryRight(greet)('joe')   // \u2192 function(greet)\n```\n\n## Decorating functions\n\n### Throttling\n\n```js\n_.throttle(fn)\n_.debounce(fn)\n```\n\n### Limiting\n\n```js\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```js\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```js\n_.capitalize('hello world')   // \u2192 'Hello world'\n_.startCase('hello_world')    // \u2192 'Hello World'\n_.snakeCase('hello world')    // \u2192 'hello_world'\n_.kebabCase('hello world')    // \u2192 'hello-world'\n_.camelCase('hello world')    // \u2192 'helloWorld'\n```\n\n### Padding\n\n```js\n_.pad('abc', 3)           // \u2192 'abc'\n_.pad('abc', 8)           // \u2192 '   abc  '\n_.pad('abc', 8, '_-')     // \u2192 '_-abc_-_'\n_.padStart('abc', 3)      // \u2192 'abc'\n_.padStart('abc', 6)      // \u2192 '   abc'\n_.padStart('abc', 6, '_-')// \u2192 '_-_abc'\n_.padEnd('abc', 3)        // \u2192 'abc'\n_.padEnd('abc', 6)        // \u2192 'abc   '\n_.padEnd('abc', 6, '_-')  // \u2192 'abc_-_'\n```\n\n### Trim\n\n```js\n_.trim('  str  ')         // \u2192 'str' \n_.trimLeft('  str  ')     // \u2192 'str  '\n_.trimRight('  str  ')    // \u2192 '  str'\n```\n\n### Etc\n\n```js\n_.repeat('-', 2)              // \u2192 '--'\n_.deburr('d\u00e9j\u00e0 vu')           // \u2192 'deja vu'\n_.trunc('hello world', 5)     // \u2192 'hello...'\n```\n\n```js\n_.startsWith('abc', 'a')   // \u2192 true\n_.endsWith('abc', 'c')     // \u2192 true\n```\n\n## Objects\n\n### Keys and values\n\n```js\n_.keys(obj)\n_.values(obj)\n```\n\n## Chaining\n\n### Chain and value\n\n```js\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```"}

field_body:
## Collections

### Finding

```js
_.filter(list, (n) => n % 2)    // → Array
_.find(list, (n) => n % 2)      // → item
_.findLast(list, ...)           // → item
```

Works for both arrays and objects.

### Accessing

```js
_.at([ abcd ], 0)               // → [ a ] - same as list[0]
_.at([ abcd ], [ 0, 1 ])        // → [ ab ]
```

### Set/get

```js
_.set(object, 'users[0].name', value)
_.get(object, 'users[0].name')
_.get(object, ['users', 0, 'name'])
```

### Iteration

```js
_.forEach(list, (item, i) => ...)
_.forEachRight(list, ...)

_.map(list, ...)
```

```js
_.every(users, (u) => u.active)  // → true|false (aka _.all)
_.any(users, ...)                // → true|false (aka _.some)
```

## Array

### Arrays

```js
_.chunk([ abcd ], 2)           // → [ [ab], [cd] ]
_.compact(list)

_.fill(Array(4), 'x')          // → [ 'x', 'x', 'x', 'x' ]
_.flatten
_.flattenDeep
```

### Filtering

```js
_.drop([ abcdef ], 2)          // → [   cdef ]
_.dropRight([ abcdef ], 2)     // → [ abcd   ]
_.take([ abcdef ], 2)          // → [ ab     ]
_.takeRight([ abcdef ], 2)     // → [     de ]
_.slice([ abcdef ], 2, 4)      // → [   cd   ]
```

```js
_.initial([ abcdef ])          // → [ abcde  ] - dropRight(list, 1)
_.rest([ abcdef ])             // → [  bcdef ] - takeRight(list, 1)
```

```js
_.dropWhile(list, 'active')            // works like filter
_.dropWhile(list, 'active', true)
_.dropWhile(list, { active: true })
_.dropWhile(list, (n) => ...)
_.dropRightWhile(list, ...)
```

```js
_.without([ abcde ], b)        // → [ acde ]
```

```js
_.remove(list, (n) => n % 2)
```

### Accessing

```js
_.first([ abcdef ])            // → a
_.last([ abcdef ])             // → f
```

### Sets

```js
_.uniq()
_.difference([ abc ], [ bc ])       // → [ a    ]
_.intersection([ abc ], [ bcd ])    // → [  bc  ]
_.union([ abc ], [ bcd ])           // → [ abcd ] (unique)
```

```js
Array#concat()
```

### Indexes

```js
_.findIndex(list, fn)
_.findLastIndex(list, fn)
```

```js
_.sortedIndex(list, val)
_.sortedLastIndex(list, val)
```

```js
_.indexOf(list, val)
```

## Functions

### Currying

```js
greet = (greeting, name) => `${greeting}, ${name}!`
```
{: .-setup}

```js
fn = _.partial(fn, 'hi')
fn('joe')    // → 'hi, joe!'

fn = _.partial(fn, 'joe')
fn('yo')     // → 'yo, joe!'
```

```js
_.curry(greet)('hi')         // → function(name)
_.curryRight(greet)('joe')   // → function(greet)
```

## Decorating functions

### Throttling

```js
_.throttle(fn)
_.debounce(fn)
```

### Limiting

```js
_.before(5, fn)         // only works 5 times
_.after(5, fn)          // works only after 5 times
_.once(fn)              // like _.before(fn, 1)
```

### Etc

```js
_.wrap(_.escape, (name) => `hi ${name}`)
// same as doing `name = _.escape(name)`

_.delay(fn, 2000)

_.negate(fn)

_.memoize(fn)
_.memoize(fn, ...)
```

## Strings

### Capitalization

```js
_.capitalize('hello world')   // → 'Hello world'
_.startCase('hello_world')    // → 'Hello World'
_.snakeCase('hello world')    // → 'hello_world'
_.kebabCase('hello world')    // → 'hello-world'
_.camelCase('hello world')    // → 'helloWorld'
```

### Padding

```js
_.pad('abc', 3)           // → 'abc'
_.pad('abc', 8)           // → '   abc  '
_.pad('abc', 8, '_-')     // → '_-abc_-_'
_.padStart('abc', 3)      // → 'abc'
_.padStart('abc', 6)      // → '   abc'
_.padStart('abc', 6, '_-')// → '_-_abc'
_.padEnd('abc', 3)        // → 'abc'
_.padEnd('abc', 6)        // → 'abc   '
_.padEnd('abc', 6, '_-')  // → 'abc_-_'
```

### Trim

```js
_.trim('  str  ')         // → 'str' 
_.trimLeft('  str  ')     // → 'str  '
_.trimRight('  str  ')    // → '  str'
```

### Etc

```js
_.repeat('-', 2)              // → '--'
_.deburr('déjà vu')           // → 'deja vu'
_.trunc('hello world', 5)     // → 'hello...'
```

```js
_.startsWith('abc', 'a')   // → true
_.endsWith('abc', 'c')     // → true
```

## Objects

### Keys and values

```js
_.keys(obj)
_.values(obj)
```

## Chaining

### Chain and value

```js
_([1, 2, 3])
  .reduce((total, n) => total + n)
  .map((n) => n * n)
  .tap(console.log)
  .thru((n) => n.reverse())
  .value()
```


id: linux
git_filename: ./linux.md
format: md
field_title: Linux
data:
{"title": "Linux", "body": "### Read/Write/Execute a file\n\n    $ chmod +rwx App\n    $ ./App\n\n### Remove\n\n    $ rm namefile\n    $ rm -d Directory\n    $ rm -rf Directory_with_files\n\n### Copy file to a folder\n\n    $ cp namefile Downloads\n    $ ls\n    namefile  Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos\n    $ cd Downloads\n    ~/Downloads$ ls\n    namefile\n\n\n### Create empty file\n\n    $ touch namefile\n    $ touch --help\n\n### Show in the terminal the file\n\n    $ cat namefile\n    $ cat --help\n\n\n### Create new directory\n\n    $ mkdir name\n    $ mkdir --help\n\n### list files from directory\n\n    $ ls\n    Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos\n    $ ls --help\n\n### Mounting a RAM drive\n\n    $ mount -t tmpfs -o size=5G,nr_inodes=5k,mode=700 tmpfs /tmp\n\n### Visudo\n\n    sudo visudo\n\n    username ALL=(ALL) NOPASSWD:/sbin/restart whatever\n\n### Display the amount of available disk space\n\n```sh\ndf\ndf -h   # human-readable format\ndf -a   # all filesystems\n```\n\n### Display disk usage\n\n```sh\ndu\ndu -hsx * | sort -rh | head -10    # largest 10 folders\n```\n\n### Answer yes in a bash script\n\n```bash\nyes | /your/command\n```"}

field_body:
### Read/Write/Execute a file

    $ chmod +rwx App
    $ ./App

### Remove

    $ rm namefile
    $ rm -d Directory
    $ rm -rf Directory_with_files

### Copy file to a folder

    $ cp namefile Downloads
    $ ls
    namefile  Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos
    $ cd Downloads
    ~/Downloads$ ls
    namefile


### Create empty file

    $ touch namefile
    $ touch --help

### Show in the terminal the file

    $ cat namefile
    $ cat --help


### Create new directory

    $ mkdir name
    $ mkdir --help

### list files from directory

    $ ls
    Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos
    $ ls --help

### Mounting a RAM drive

    $ mount -t tmpfs -o size=5G,nr_inodes=5k,mode=700 tmpfs /tmp

### Visudo

    sudo visudo

    username ALL=(ALL) NOPASSWD:/sbin/restart whatever

### Display the amount of available disk space

```sh
df
df -h   # human-readable format
df -a   # all filesystems
```

### Display disk usage

```sh
du
du -hsx * | sort -rh | head -10    # largest 10 folders
```

### Answer yes in a bash script

```bash
yes | /your/command
```


id: licenses
git_filename: ./licenses.md
format: md
field_title: Licenses
field_updated: 2017-08-30
field_updated___timezone: UTC
data:
{"title": "Licenses", "section": "Development", "updated": "2017-08-30", "body": "## Licenses\n\n### MIT License\n\n```\nThe 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```\nCopyright (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```\nCopyright (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```\nCopyright (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```"}

field_body:
## Licenses

### MIT License

```
The MIT License (MIT)

Copyright (c) 2015 $NAME

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

### ISC

```
Copyright (c) 2015, $NAME

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
```

### BSD 2C

```
Copyright (c) 2015, $NAME
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```

### BSD 3C

```
Copyright (c) 2015, $NAME
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of simpler-extend nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```


id: less
git_filename: ./less.md
format: md
field_title: Less.js
data:
{"title": "Less.js", "body": "### Functions\n\n    unit(30px / 5px)  #=> 6\n    unit(5, px)       #=> 5px\n\n    e(\"ms:stuff()\")   #=> ms:stuff() (unquote)\n\n    %(\"count: %d\", 1+2) #=> \"count: 3\"\n\n    iscolor(@x)\n    isstring(@x)\n    isnumber(@x)\n    iskeyword(@x)\n    isurl(url(...))\n    ispixel()\n    isem()\n    ispercentage()\n    isunit()\n\n    hue(@color)\n    saturation(@color)\n    lightness(@color)\n    luma(@color)\n    luminance(@color)\n\n    fade(@color, amount)\n    fadein(@color, amount)\n    fadeout(@color, amount)\n    spin(@color, degrees)\n    mix(@a, @b, amount)\n\n### Conditionals\n\n    .image when (luma(@color) > 50%) { }\n    .image when (not(...)) { }\n    .image when (default()) {}\n    .image when (e(@shape) = 'circle') { }"}

field_body:
### Functions

    unit(30px / 5px)  #=> 6
    unit(5, px)       #=> 5px

    e("ms:stuff()")   #=> ms:stuff() (unquote)

    %("count: %d", 1+2) #=> "count: 3"

    iscolor(@x)
    isstring(@x)
    isnumber(@x)
    iskeyword(@x)
    isurl(url(...))
    ispixel()
    isem()
    ispercentage()
    isunit()

    hue(@color)
    saturation(@color)
    lightness(@color)
    luma(@color)
    luminance(@color)

    fade(@color, amount)
    fadein(@color, amount)
    fadeout(@color, amount)
    spin(@color, degrees)
    mix(@a, @b, amount)

### Conditionals

    .image when (luma(@color) > 50%) { }
    .image when (not(...)) { }
    .image when (default()) {}
    .image when (e(@shape) = 'circle') { }


id: ledger
git_filename: ./ledger.md
format: md
field_title: Ledger CLI
field_category: Ledger
field_updated: 2020-05-23
field_updated___timezone: UTC
data:
{"title": "Ledger CLI", "category": "Ledger", "updated": "2020-05-23", "weight": -5, "body": "### Basic usage\n\n```bash\n$ ledger bal\n$ ledger reg\n```\n\n```bash\n$ ledger reg grocery  # show entries for 'grocery'\n$ ledger bal assets   # check if i'm broke\n```\n\n```bash\n  -b 01/01   # --begin\n  -e 01/31   # --end\n  -S date    # --sort\n  -S amount\n```\n\n### Examples\n\n```bash\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```bash\n# what did I spend on most? (--sorted)\n  ledger reg Expenses -S amount\n```\n\n```bash\n# how much did I have at this date? (--end)\n  ledger bal -e 01/15 ^Assets ^Liabilities\n```\n\n```bash\n# how much did I spend and earn this month?\n  ledger bal ^Expenses ^Income --invert\n```\n\n```bash\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\nFormat\n------\n\n### Basic format\n\n```\n2013/01/03 * Rent for January\n  Expenses:Rent   $600.00\n  Assets:Savings\n```\n\n`*` = cleared, `!` = pending\n\n### Secondary dates\n\n```\n2008/01/01=2008/01/14 Client invoice\n```\n\nIt can mean anything you want, eg, for the estimated date you'll be paid.\n\n### Balance assertions\n\n```\n2008/01/01 * KFC\n  Expenses:Food    $20\n  Assets:Cash     $-20  = $500\n```\n{: data-line=\"3\"}\n\n`Cash $X = $500` ensures Cash is at $500 after the transaction.\n\n### Balance assignment\n\n```bash\n2008/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{: data-line=\"2,7\"}\n\n`ACCOUNT = $500` figures out what's needed to make it $500.\n\n### Payables\n\n```bash\n2008/04/25 * Rent\n  (Assets:Checking)  -$200\n  Expenses:Rent\n```\n{: data-line=\"2\"}\n\n### Commodities\n\n```bash\n; cost per item\n2010/05/31 * Market\n  Assets:Fridge                35 apples @ $0.42\n  Assets:Cash\n```\n{: data-line=\"3\"}\n\n```bash\n; total cost\n2010/05/31 * Market\n  Assets:Fridge                35 apples @@ $14.70\n  Assets:Cash\n```\n{: data-line=\"3\"}\n\n```bash\n; fixed lot prices\n2010/05/31 * Gas\n  Expenses:Gasoline             11 GAL {=$2.299}\n  Assets:Cash\n```\n{: data-line=\"3\"}\n\n### Commodity definitions\n\n```\ncommodity $\n  note American Dollars\n  format $1,000.00\n  nomarket\n  default\n```\n\n### Budgeting\n\n```\n~ Monthly\n  Expenses:Rent  $500\n  Expenses:Food  $100\n  Expenses        $40 ; everything else\n  Assets\n\n~ Yearly\n```\n\n```bash\nledger bal --budget Expenses\nledger bal --unbudgeted Expenses\n```\n{: .-setup}\n\n### Comments\n\n    ; line comment\n    # also line comment\n    % also line comment\n    | also line comment\n    * also line comment\n\nQuerying\n--------\n\n### Periods\n\n```\n[interval] [begin] [end]\n```\n\n```\ninterval:\n  every day|week|month|quarter|year\n  every N days|weeks|...\n  daily|weekly|...\n```\n\n```\nbegin:\n  from <spec>\nend:\n  to <spec>\n```\n\n```\nspec:\n  2004\n  2004/10/1\n```\n\n```bash\n$ ledger bal|reg --period \"until aug\"\n$ ledger bal|reg --period \"last oct\"\n$ ledger bal|reg --period \"every week\"\n```\n{: .-setup}\n\n### Register\n\n```bash\n$ ledger reg\n```\n{: .-setup}\n\n```bash\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```bash\n  -S, --sort date\n  -S, --sort amount\n```\n\n### Filters\n\n```bash\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\n    term and term\n    term or term\n    not term\n    \\( term \\)\n\nExample:\n\n    ledger r ^expenses and @Denny's\n    ledger r food and @Starbucks and not dining\n\n### Display\n\n```bash\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```bash\n2008/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{: data-line=\"1\"}\n\nSay 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```bash\n2008/01/01=2008/01/15 Client invoice ;  actual date money received\n  Assets:Accounts Receivable            $100.00\n  Income: Client name\n```\n{: data-line=\"1\"}\n\n## References\n{: .-one-column}\n\n* <http://ledger-cli.org/3.0/doc/ledger3.html>\n* <https://gist.github.com/agaviria/3317397>\n{: .-also-see}"}

field_body:
### Basic usage

```bash
$ ledger bal
$ ledger reg
```

```bash
$ ledger reg grocery  # show entries for 'grocery'
$ ledger bal assets   # check if i'm broke
```

```bash
  -b 01/01   # --begin
  -e 01/31   # --end
  -S date    # --sort
  -S amount
```

### Examples

```bash
# any/all matches
  ledger bal Rent Transportation  # any
  ledger bal Income and Job       # all
  ledger bal Expenses and not (Drinks or Food)
```

```bash
# what did I spend on most? (--sorted)
  ledger reg Expenses -S amount
```

```bash
# how much did I have at this date? (--end)
  ledger bal -e 01/15 ^Assets ^Liabilities
```

```bash
# how much did I spend and earn this month?
  ledger bal ^Expenses ^Income --invert
```

```bash
# how much was spent over the course of 3 days? (totalled)
  ledger reg -b 01/25 -e 01/27 --subtotal
  ledger reg -b 01/25 -e 01/27 --subtotal grocery
```

Format
------

### Basic format

```
2013/01/03 * Rent for January
  Expenses:Rent   $600.00
  Assets:Savings
```

`*` = cleared, `!` = pending

### Secondary dates

```
2008/01/01=2008/01/14 Client invoice
```

It can mean anything you want, eg, for the estimated date you'll be paid.

### Balance assertions

```
2008/01/01 * KFC
  Expenses:Food    $20
  Assets:Cash     $-20  = $500
```
{: data-line="3"}

`Cash $X = $500` ensures Cash is at $500 after the transaction.

### Balance assignment

```bash
2008/01/01 * Cash balance
  Assets:Cash              = $500
  Equity:Adjustments

2008/01/01 * KFC
  Expenses:Food            $20
  Assets:Cash              = $500
```
{: data-line="2,7"}

`ACCOUNT = $500` figures out what's needed to make it $500.

### Payables

```bash
2008/04/25 * Rent
  (Assets:Checking)  -$200
  Expenses:Rent
```
{: data-line="2"}

### Commodities

```bash
; cost per item
2010/05/31 * Market
  Assets:Fridge                35 apples @ $0.42
  Assets:Cash
```
{: data-line="3"}

```bash
; total cost
2010/05/31 * Market
  Assets:Fridge                35 apples @@ $14.70
  Assets:Cash
```
{: data-line="3"}

```bash
; fixed lot prices
2010/05/31 * Gas
  Expenses:Gasoline             11 GAL {=$2.299}
  Assets:Cash
```
{: data-line="3"}

### Commodity definitions

```
commodity $
  note American Dollars
  format $1,000.00
  nomarket
  default
```

### Budgeting

```
~ Monthly
  Expenses:Rent  $500
  Expenses:Food  $100
  Expenses        $40 ; everything else
  Assets

~ Yearly
```

```bash
ledger bal --budget Expenses
ledger bal --unbudgeted Expenses
```
{: .-setup}

### Comments

    ; line comment
    # also line comment
    % also line comment
    | also line comment
    * also line comment

Querying
--------

### Periods

```
[interval] [begin] [end]
```

```
interval:
  every day|week|month|quarter|year
  every N days|weeks|...
  daily|weekly|...
```

```
begin:
  from <spec>
end:
  to <spec>
```

```
spec:
  2004
  2004/10/1
```

```bash
$ ledger bal|reg --period "until aug"
$ ledger bal|reg --period "last oct"
$ ledger bal|reg --period "every week"
```
{: .-setup}

### Register

```bash
$ ledger reg
```
{: .-setup}

```bash
  -D, --daily
  -W, --weekly
  -M, --monthly
      --quarterly
  -Y, --yearly
  -s, --subtotal
  --start-of-week monday
```

```bash
  -S, --sort date
  -S, --sort amount
```

### Filters

```bash
-b, --begin DATE
-e, --end DATE

-d payee =~ /pioneer/

-C, --cleared    # (with *)
-U, --uncleared  # (no *)
    --pending    # (with !)

-R, --real       # ignore virtual postings (eg: "(Cash)  $-400")
-L, --actual     # no automated postings (eg: "= /^Income/")

-r, --related   # show the other side
                # "reg -r savings" shows where it comes from)
```

### Queries

    ^regex$
    @payee
    %tag
    %tag=value
    =note
    #code
    term and term
    term or term
    not term
    \( term \)

Example:

    ledger r ^expenses and @Denny's
    ledger r food and @Starbucks and not dining

### Display

```bash
-n, --collapse       # [register] collapse entries
                     # [balance] no grand total
-s, --subtotal       # [balance] show sub-accounts
                     # [other] show subtotals
--flat
```

### Effective dates

```bash
2008/01/01=2008/01/14 Client invoice  ;  estimated date you'll be paid
  Assets:Accounts Receivable            $100.00
  Income: Client name
```
{: data-line="1"}

Say you're in business. If you bill a customer, you can enter something like above.
Then, when you receive the payment, you change it to:

```bash
2008/01/01=2008/01/15 Client invoice ;  actual date money received
  Assets:Accounts Receivable            $100.00
  Income: Client name
```
{: data-line="1"}

## References
{: .-one-column}

* <http://ledger-cli.org/3.0/doc/ledger3.html>
* <https://gist.github.com/agaviria/3317397>
{: .-also-see}


id: ledger-query
git_filename: ./ledger-query.md
format: md
field_title: Ledger queries
field_category: Ledger
data:
{"title": "Ledger queries", "category": "Ledger", "body": "### About\n\n- <https://ledger-cli.org/3.0/doc/ledger3.html#Complex-expressions>\n\n### Query characters\n\n| Query           | Description |\n| ---             | ---         |\n| `@payee`        | Payee       |\n| `%tag`          | Tag         |\n| `=note`         | Note        |\n| `#code`         | Code        |\n| ---             | ---         |\n| `TERM and TERM` | Boolean and |\n| `TERM or TERM`  | Boolean or  |\n| `not TERM`      | Boolean not |\n\n### Examples\n\n```sh\nledger r @taco\nledger r comment =~ /landline/\n```"}

field_body:
### About

- <https://ledger-cli.org/3.0/doc/ledger3.html#Complex-expressions>

### Query characters

| Query           | Description |
| ---             | ---         |
| `@payee`        | Payee       |
| `%tag`          | Tag         |
| `=note`         | Note        |
| `#code`         | Code        |
| ---             | ---         |
| `TERM and TERM` | Boolean and |
| `TERM or TERM`  | Boolean or  |
| `not TERM`      | Boolean not |

### Examples

```sh
ledger r @taco
ledger r comment =~ /landline/
```


id: ledger-periods
git_filename: ./ledger-periods.md
format: md
field_title: Ledger periods
field_category: Ledger
data:
{"title": "Ledger periods", "category": "Ledger", "body": "### About\n{: .-intro}\n\n- <https://ledger-cli.org/3.0/doc/ledger3.html#Period-Expressions>\n\n### Usage\n\n    [INTERVAL] [BEGIN] [END]\n\n#### Intervals\n\n    every day\n    every week\n    every month\n    every quarter\n    every year\n    every N days     # N is any integer\n    every N weeks\n    every N months\n    every N quarters\n    every N years\n    daily\n    weekly\n    biweekly\n    monthly\n    bimonthly\n    quarterly\n    yearly\n\n#### Begin\n\n    from <SPEC>\n    since <SPEC>\n\n#### End\n\n    to <SPEC>\n    until <SPEC>\n\n### Spec\n\n    2004\n    2004/10\n    2004/10/1\n    10/1\n    october\n    oct\n    this week  # or day, month, quarter, year\n    next week\n    last week\n\n### Examples\n\n    $ ledger r -p \"since last month\""}

field_body:
### About
{: .-intro}

- <https://ledger-cli.org/3.0/doc/ledger3.html#Period-Expressions>

### Usage

    [INTERVAL] [BEGIN] [END]

#### Intervals

    every day
    every week
    every month
    every quarter
    every year
    every N days     # N is any integer
    every N weeks
    every N months
    every N quarters
    every N years
    daily
    weekly
    biweekly
    monthly
    bimonthly
    quarterly
    yearly

#### Begin

    from <SPEC>
    since <SPEC>

#### End

    to <SPEC>
    until <SPEC>

### Spec

    2004
    2004/10
    2004/10/1
    10/1
    october
    oct
    this week  # or day, month, quarter, year
    next week
    last week

### Examples

    $ ledger r -p "since last month"


id: ledger-format
git_filename: ./ledger-format.md
format: md
field_title: Ledger format
field_category: Ledger
data:
{"title": "Ledger format", "category": "Ledger", "body": "### Example\n```\n2015/01/01 Pay rent\n  Assets:Savings     -$300\n  Expenses:Rent\n```\n\n### First line\n\n```\n2015/01/01 *       Pay rent       ; tagname:\n^          ^       ^\nDate       Flag    Description    ^ comment/tag\n```\n\n### Balance assertion\n\n```\n2015/01/01 Pay rent\n  Assets:Savings     -$300 = $1200  ; assert there's $1200 left after\n  Expenses:Rent\n```\nFlags:\n\n```\n* cleared\n! pending\n```\n\n## Accounts\n\n### Accounts\n\nOnly relevant with `--strict` or `--pedantic`\n\n```\naccount 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### Others\n\n```\nD $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```\naccount Home\ninclude home.journal\nend\n```"}

field_body:
### Example
```
2015/01/01 Pay rent
  Assets:Savings     -$300
  Expenses:Rent
```

### First line

```
2015/01/01 *       Pay rent       ; tagname:
^          ^       ^
Date       Flag    Description    ^ comment/tag
```

### Balance assertion

```
2015/01/01 Pay rent
  Assets:Savings     -$300 = $1200  ; assert there's $1200 left after
  Expenses:Rent
```
Flags:

```
* cleared
! pending
```

## Accounts

### Accounts

Only relevant with `--strict` or `--pedantic`

```
account Expenses:Food
    note This account is all about the chicken!
    alias food
    payee ^(KFC|Popeyes)$
    check commodity == "$"
    assert commodity == "$"
    eval print("Hello!")
    default
```

## Others

### Others

```
D $1,000.00     ; set default commodity

alias Cash = Assets:Cash

Y2015           ; set default year (you can use 01/25 as date after)
```

### Prefix all transactions with an account

```
account Home
include home.journal
end
```


id: ledger-examples
git_filename: ./ledger-examples.md
format: md
field_title: Ledger examples
field_category: Ledger
data:
{"title": "Ledger examples", "category": "Ledger", "body": "### 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### 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### 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### Switches\n\n    # what's everything I got in USD? (--exchange)\n      ledger b Assets -X USD"}

field_body:
### Inspecting transactions

    # show me expenses for october (--period)
      ledger r Expenses -p oct

    # what's the most expensive? (--sorted)
      ledger r Expenses -S amount --tail 10

    # how much was spent on grocery? (--weekly, --monthly)
      ledger r Grocery
      ledger r Grocery -W
      ledger r Grocery -M

    # what did I spend my Mastercard on? (--period, --begin, --end)
      ledger r mastercard
      ledger r mastercard -p "january"
      ledger r mastercard -b 01/25 -e 01/31

### Graphing

    # Graph my bank account balance, monthly
      ledger r Savings -M

    # Graph my expenses, monthly (-n = --collapse)
      ledger r Expenses -M -n

    # ...what's the average per month?
      ledger r Expenses -M -n --average

### Simple

    # what did I do yesterday?
    # ..list transactions on this day
      ledger r -p 01/26
      ledger r -p yesterday

### Switches

    # what's everything I got in USD? (--exchange)
      ledger b Assets -X USD


id: ledger-csv
git_filename: ./ledger-csv.md
format: md
field_title: Ledger CSV format
field_category: Ledger
data:
{"title": "Ledger CSV format", "category": "Ledger", "body": "## Ledger CSV format\n{: .-one-column}\n\n```\n$ ledger csv\n```\n{: .-setup}\n\n```csv\ndate         , code  , desc     , account            , currency , amt     , pending/cleared , notes\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\"  , \"Expenses:Others\"  , \"P\"      , \"20\"    , \"*\"             , \"\"\n```"}

field_body:
## Ledger CSV format
{: .-one-column}

```
$ ledger csv
```
{: .-setup}

```csv
date         , code  , desc     , account            , currency , amt     , pending/cleared , notes
"2013/09/02" , ""    , "things" , "Assets:Cash"      , "P"      , "-2000" , "*"             , ""
"2013/09/02" , ""    , "things" , "Liabilities:Card" , "P"      , "-200"  , "*"             , ""
"2013/09/02" , ""    , "things" , "Expenses:Things"  , "P"      , "2200"  , "*"             , ""
"2013/09/04" , ""    , "stuff"  , "Assets:Cash"      , "P"      , "-20"   , "*"             , ""
"2013/09/04" , ""    , "stuff"  , "Expenses:Others"  , "P"      , "20"    , "*"             , ""
```


id: layout-thrashing
git_filename: ./layout-thrashing.md
format: md
field_title: Layout thrashing
field_category: HTML
field_updated: 2017-10-19
field_updated___timezone: UTC
data:
{"title": "Layout thrashing", "category": "HTML", "description": "", "updated": "2017-10-19", "weight": -1, "intro": "These are CSS properties that will cause \"layout thrashing\". Avoid changing them to prevent bottlenecks in your UI performance.\n", "body": "## Layout thrashing\n{: .-one-column}\n\n### Things that cause invalidation\n\n#### Element\n\n  - clientHeight\n  - clientLeft\n  - clientTop\n  - clientWidth\n  - focus\n  - getBoundingClientRect\n  - getClientRects\n  - innerText\n  - offsetHeight\n  - offsetLeft\n  - offsetParent\n  - offsetTop\n  - offsetWidth\n  - outerText\n  - scrollByLines\n  - scrollByPages\n  - scrollHeight\n  - scrollIntoView\n  - scrollIntoViewIfNeeded\n  - scrollLeft\n  - scrollTop\n  - scrollWidth\n{: .-six-column}\n\n#### MouseEvent\n\n  - layerX\n  - layerY\n  - offsetX\n  - offsetY\n{: .-six-column}\n\n#### Window\n\n  - getComputedStyle\n  - scrollBy\n  - scrollTo\n  - scrollX\n  - scrollY\n{: .-six-column}\n\n#### Frame, Document & Image\n\n  - height\n  - width\n{: .-six-column}\n\n#### jQuery\n\n  - $.fn.offset\n  - $.fn.offsetParent\n  - $.fn.position\n  - $.fn.scrollLeft\n  - $.fn.scrollTop\n  - $.fn.css('...')\n  - $.fn.text('...')\n  - $(':hidden')\n  - $(':contains')\n{: .-six-column}\n\n## Also see\n\n * <http://www.kellegous.com/j/2013/01/26/layout-performance/>\n * <https://gist.github.com/desandro/4657744>\n * <http://stackoverflow.com/questions/17199958/why-does-setting-textcontent-cause-layout-thrashing>"}

field_intro:
These are CSS properties that will cause "layout thrashing". Avoid changing them to prevent bottlenecks in your UI performance.

field_body:
## Layout thrashing
{: .-one-column}

### Things that cause invalidation

#### Element

  - clientHeight
  - clientLeft
  - clientTop
  - clientWidth
  - focus
  - getBoundingClientRect
  - getClientRects
  - innerText
  - offsetHeight
  - offsetLeft
  - offsetParent
  - offsetTop
  - offsetWidth
  - outerText
  - scrollByLines
  - scrollByPages
  - scrollHeight
  - scrollIntoView
  - scrollIntoViewIfNeeded
  - scrollLeft
  - scrollTop
  - scrollWidth
{: .-six-column}

#### MouseEvent

  - layerX
  - layerY
  - offsetX
  - offsetY
{: .-six-column}

#### Window

  - getComputedStyle
  - scrollBy
  - scrollTo
  - scrollX
  - scrollY
{: .-six-column}

#### Frame, Document & Image

  - height
  - width
{: .-six-column}

#### jQuery

  - $.fn.offset
  - $.fn.offsetParent
  - $.fn.position
  - $.fn.scrollLeft
  - $.fn.scrollTop
  - $.fn.css('...')
  - $.fn.text('...')
  - $(':hidden')
  - $(':contains')
{: .-six-column}

## Also see

 * <http://www.kellegous.com/j/2013/01/26/layout-performance/>
 * <https://gist.github.com/desandro/4657744>
 * <http://stackoverflow.com/questions/17199958/why-does-setting-textcontent-cause-layout-thrashing>


id: kramdown
git_filename: ./kramdown.md
format: md
field_title: Kramdown
field_category: Markup
data:
{"title": "Kramdown", "category": "Markup", "body": "### About\n{: .-intro}\n\nKramdown is a Markdown parser in Ruby.\n\n- <https://kramdown.gettalong.org/>\n\n### Configuration\n\n * `parse_block_html` - process kramdown syntax inside blocks\n * `parse_span_html` - process kramdown syntax inside inlines\n * `html_to_native` - convert html elements to native elements\n\n    {::options parse_block_html=\"true\" /}\n\nFor the GFM parser:\n\n * `hard_wrap`\n\nhttp://kramdown.gettalong.org/parser/gfm.html\n\n### For jekyll (gh-pages)\n\n    # _config.yml\n    markdown: kramdown\n    kramdown:\n      input: GFM\n\n### Footnotes (Kramdown)\n\n    This is some text.[^1]. Other text.[^footnote].\n\n    [^1]: Some *crazy* footnote definition.\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### 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### References\n\n * http://kramdown.gettalong.org/syntax.html\n * http://kramdown.gettalong.org/parser/kramdown.html"}

field_body:
### About
{: .-intro}

Kramdown is a Markdown parser in Ruby.

- <https://kramdown.gettalong.org/>

### Configuration

 * `parse_block_html` - process kramdown syntax inside blocks
 * `parse_span_html` - process kramdown syntax inside inlines
 * `html_to_native` - convert html elements to native elements

    {::options parse_block_html="true" /}

For the GFM parser:

 * `hard_wrap`

http://kramdown.gettalong.org/parser/gfm.html

### For jekyll (gh-pages)

    # _config.yml
    markdown: kramdown
    kramdown:
      input: GFM

### Footnotes (Kramdown)

    This is some text.[^1]. Other text.[^footnote].

    [^1]: Some *crazy* footnote definition.

### Abbreviations (Kramdown)

    This is some text not written in HTML but in another language!

    *[another language]: It's called Markdown
    *[HTML]: HyperTextMarkupLanguage

### Classes and IDs (Kramdown)

    A simple paragraph with an ID attribute.
    {: #para-one}

    > A blockquote with a title
    {:title="The blockquote title"}
    {: #myid}

    * {:.cls} This item has the class "cls"

    {:.ruby}
        Some code here

### References

 * http://kramdown.gettalong.org/syntax.html
 * http://kramdown.gettalong.org/parser/kramdown.html


id: kotlin
git_filename: ./kotlin.md
format: md
field_title: Kotlin
field_category: Java & JVM
field_prism_languages: kotlin
field_updated: 2018-12-06
field_updated___timezone: UTC
data:
{"title": "Kotlin", "updated": "2018-12-06", "category": "Java & JVM", "prism_languages": ["kotlin"], "intro": "[Kotlin](http://kotlinlang.org/) is a statically typed programming language for modern multiplatform applications.\n", "body": "Variables\n---------\n{: .-three-column}\n\n### Mutability\n\n```kotlin\nvar mutableString: String = \"Adam\"\nval immutableString: String = \"Adam\"\nval inferredString = \"Adam\"\n```\n\n### Strings\n\n```kotlin\nval name = \"Adam\"\nval greeting = \"Hello, \" + name\nval greetingTemplate = \"Hello, $name\"\nval interpolated = \"Hello, ${name.toUpperCase()}\"\n```\n\n### Numbers\n\n```kotlin\nval intNum = 10\nval doubleNum = 10.0\nval longNum = 10L\nval floatNum = 10.0F\n```\n\n### Booleans\n\n```kotlin\nval trueBoolean = true\nval falseBoolean = false\nval andCondition = trueBoolean && falseBoolean\nval orCondition = trueBoolean || falseBoolean\n```\n\n### Static Fields\n\n```kotlin\nclass Person {\n    companion object {\n        val NAME_KEY = \"name_key\"\n    }\n}\n\nval key = Person.NAME_KEY\n```\n\nNull Safety\n-----------\n{: .-two-column}\n\n### Nullable properties\n\n```kotlin\nval 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```kotlin\nval 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```kotlin\nval nullableStringLength: Int? = nullableString?.length\nval nullableDepartmentHead: String? = person?.department?.head?.name\n```\n\n### Elvis Operator\n\n```kotlin\nval 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```kotlin\n// Will not throw ClassCastException\nval nullableCar: Car? = (input as? Car)\n```\n\nCollections\n-----------\n{: .-two-column}\n\n### Creation\n\n```kotlin\nval numArray = arrayOf(1, 2, 3)\nval numList = listOf(1, 2, 3)\nval mutableNumList = mutableListOf(1, 2, 3)\n```\n\n### Accessing\n\n```kotlin\nval firstItem = numList[0]\nval firstItem = numList.first()\nval firstItem = numList.firstOrNull()\n```\n\n### Maps\n\n```kotlin\nval 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```kotlin\nval 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```kotlin\nfor (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```kotlin\nval 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 }\nval fullMenu = objList.map { \"${it.name} - $${it.detail}\" }\n```\n\nNote: `it` is the [implicit name for a single parameter](https://kotlinlang.org/docs/reference/lambdas.html#it-implicit-name-of-a-single-parameter).\n\nFunctions\n---------\n{: .-two-column}\n\n### Parameters & Return Types\n\n```kotlin\nfun 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```kotlin\nfun 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```kotlin\nfun Int.timesTwo(): Int {\n    return this * 2\n}\n\nval four = 2.timesTwo()\n```\n\n### Default Parameters\n\n```kotlin\nfun getGreeting(person: Person, intro: String = \"Hello,\"): String {\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```kotlin\nclass 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```kotlin\nclass 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* [Companion Objects](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects)\n\nClasses\n-------\n{: .-two-column}\n\n### Primary Constructor\n\n```kotlin\nclass Person(val name: String, val age: Int)\nval adam = Person(\"Adam\", 100)\n```\n\n### Secondary Constructors\n\n```kotlin\nclass 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```kotlin\nopen 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\nControl Flow\n------------\n{: .-two-column}\n\n### If Statements\n\n```kotlin\nif (someBoolean) {\n    doThing()\n} else {\n    doOtherThing()\n}\n```\n\n### For Loops\n\n```kotlin\nfor (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```kotlin\nwhen (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```kotlin\nwhile (x > 0) {\n    x--\n}\n\ndo {\n    x--\n} while (x > 0)\n```\n\nDestructuring Declarations\n--------------------------\n{: .-two-column}\n\n### Objects & Lists\n\n```kotlin\nval 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```kotlin\nclass 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\nReferences\n----------\n{: .-one-column}\n\n* [Defining Variables](https://kotlinlang.org/docs/reference/basic-syntax.html#defining-variables) _(kotlinlang.org)_\n* [Strings Documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html) _(kotlinlang.org)_\n* [String Templates](https://kotlinlang.org/docs/reference/basic-types.html#string-templates) _(kotlinlang.org)_\n* [Basic Types](https://kotlinlang.org/docs/reference/basic-types.html) _(kotlinlang.org)_\n* [Companion Objects](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects) _(kotlinlang.org)_\n* [Null Safety](https://kotlinlang.org/docs/reference/null-safety.html) _(kotlinlang.org)_\n* [Collections Overview](https://kotlinlang.org/docs/reference/collections.html) _(kotlinlang.org)_\n* [Collections Documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html) _(kotlinlang.org)_\n* [Functions Documentation](https://kotlinlang.org/docs/reference/functions.html) _(kotlinlang.org)_\n* [Classes Documentation](https://kotlinlang.org/docs/reference/classes.html) _(kotlinlang.org)_\n* [Destructuring Declarations](https://kotlinlang.org/docs/reference/multi-declarations.html) _(kotlinlang.org)_"}

field_intro:
[Kotlin](http://kotlinlang.org/) is a statically typed programming language for modern multiplatform applications.

field_body:
Variables
---------
{: .-three-column}

### Mutability

```kotlin
var mutableString: String = "Adam"
val immutableString: String = "Adam"
val inferredString = "Adam"
```

### Strings

```kotlin
val name = "Adam"
val greeting = "Hello, " + name
val greetingTemplate = "Hello, $name"
val interpolated = "Hello, ${name.toUpperCase()}"
```

### Numbers

```kotlin
val intNum = 10
val doubleNum = 10.0
val longNum = 10L
val floatNum = 10.0F
```

### Booleans

```kotlin
val trueBoolean = true
val falseBoolean = false
val andCondition = trueBoolean && falseBoolean
val orCondition = trueBoolean || falseBoolean
```

### Static Fields

```kotlin
class Person {
    companion object {
        val NAME_KEY = "name_key"
    }
}

val key = Person.NAME_KEY
```

Null Safety
-----------
{: .-two-column}

### Nullable properties

```kotlin
val cannotBeNull: String = null // Invalid
val canBeNull: String? = null // Valid

val cannotBeNull: Int = null // Invalid
val canBeNull: Int? = null // Valid
```

### Checking for null

```kotlin
val name: String? = "Adam"

if (name != null && name.length > 0) {
    print("String length is ${name.length}")
} else {
    print("String is empty.")
}
```

### Safe Operator

```kotlin
val nullableStringLength: Int? = nullableString?.length
val nullableDepartmentHead: String? = person?.department?.head?.name
```

### Elvis Operator

```kotlin
val nonNullStringLength: Int = nullableString?.length ?: 0
val nonNullDepartmentHead: String = person?.department?.head?.name ?: ""
val nonNullDepartmentHead: String = person?.department?.head?.name.orEmpty()
```

### Safe Casts
```kotlin
// Will not throw ClassCastException
val nullableCar: Car? = (input as? Car)
```

Collections
-----------
{: .-two-column}

### Creation

```kotlin
val numArray = arrayOf(1, 2, 3)
val numList = listOf(1, 2, 3)
val mutableNumList = mutableListOf(1, 2, 3)
```

### Accessing

```kotlin
val firstItem = numList[0]
val firstItem = numList.first()
val firstItem = numList.firstOrNull()
```

### Maps

```kotlin
val faceCards = mutableMapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val jackValue = faceCards["Jack"] // 11
faceCards["Ace"] = 1
```

### Mutability

```kotlin
val immutableList = listOf(1, 2, 3)
val mutableList = immutableList.toMutableList()

val immutableMap = mapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val mutableMap = immutableMap.toMutableMap()
```

### Iterating

```kotlin
for (item in myList) {
    print(item)
}

myList.forEach {
    print(it)
}

myList.forEachIndexed { index, item -> 
    print("Item at $index is: $item")
}
```

### Filtering & Searching

```kotlin
val evenNumbers = numList.filter { it % 2 == 0 }
val containsEven = numList.any { it % 2 == 0 }
val containsNoEvens = numList.none { it % 2 == 0 }
val containsNoEvens = numList.all { it % 2 == 1 }
val firstEvenNumber: Int = numList.first { it % 2 == 0 }
val firstEvenOrNull: Int? = numList.firstOrNull { it % 2 == 0 }
val fullMenu = objList.map { "${it.name} - $${it.detail}" }
```

Note: `it` is the [implicit name for a single parameter](https://kotlinlang.org/docs/reference/lambdas.html#it-implicit-name-of-a-single-parameter).

Functions
---------
{: .-two-column}

### Parameters & Return Types

```kotlin
fun printName() {
    print("Adam")
}

fun printName(person: Person) {
    print(person.name)
}

fun getGreeting(person: Person): String {
    return "Hello, ${person.name}"
}

fun getGreeting(person: Person): String = "Hello, ${person.name}"
fun getGreeting(person: Person) = "Hello, ${person.name}"
```

### Higher Order Functions

```kotlin
fun callbackIfTrue(condition: Boolean, callback: () -> Unit) {
    if (condition) {
        callback()
    }
}

callbackIfTrue(someBoolean) {
    print("Condition was true")
}
```

### Extension Functions

```kotlin
fun Int.timesTwo(): Int {
    return this * 2
}

val four = 2.timesTwo()
```

### Default Parameters

```kotlin
fun getGreeting(person: Person, intro: String = "Hello,"): String {
    return "$intro ${person.name}"
}

// Returns "Hello, Adam"
val hello = getGreeting(Person("Adam"))

// Returns "Welcome, Adam"
val welcome = getGreeting(Person("Adam"), "Welcome,")
```

### Named Parameters

```kotlin
class Person(val name: String = "", age: Int = 0)

// All valid
val person = Person()
val person = Person("Adam", 100)
val person = Person(name = "Adam", age = 100)
val person = Person(age = 100)
val person = Person(age = 100, name = "Adam")
```

### Static Functions

```kotlin
class Fragment(val args: Bundle) {
    companion object {
        fun newInstance(args: Bundle): Fragment {
            return Fragment(args)
        }
    }
}

val fragment = Fragment.newInstance(args)
```

* [Companion Objects](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects)

Classes
-------
{: .-two-column}

### Primary Constructor

```kotlin
class Person(val name: String, val age: Int)
val adam = Person("Adam", 100)
```

### Secondary Constructors

```kotlin
class Person(val name: String) {
    private var age: Int? = null

    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }
}

// Above can be replaced with default params
class Person(val name: String, val age: Int? = null)
```

### Inheritance & Implementation

```kotlin
open class Vehicle
class Car : Vehicle()

interface Runner {
    fun run()
}

class Machine : Runner {
    override fun run() {
        // ...
    }
}
```

Control Flow
------------
{: .-two-column}

### If Statements

```kotlin
if (someBoolean) {
    doThing()
} else {
    doOtherThing()
}
```

### For Loops

```kotlin
for (i in 0..10) { } // 1 - 10
for (i in 0 until 10) // 1 - 9
(0..10).forEach { }
for (i in 0 until 10 step 2) // 0, 2, 4, 6, 8
```

### When Statements

```kotlin
when (direction) {
    NORTH -> {
        print("North")
    }
    SOUTH -> print("South")
    EAST, WEST -> print("East or West")
    "N/A" -> print("Unavailable")
    else -> print("Invalid Direction")
}
```

### While Loops

```kotlin
while (x > 0) {
    x--
}

do {
    x--
} while (x > 0)
```

Destructuring Declarations
--------------------------
{: .-two-column}

### Objects & Lists

```kotlin
val person = Person("Adam", 100)
val (name, age) = person

val pair = Pair(1, 2)
val (first, second) = pair

val coordinates = arrayOf(1, 2, 3)
val (x, y, z) = coordinates
```

### ComponentN Functions

```kotlin
class Person(val name: String, val age: Int) {
	operator fun component1(): String {
		return name
	}

	operator fun component2(): Int {
		return age
	}
}
```

References
----------
{: .-one-column}

* [Defining Variables](https://kotlinlang.org/docs/reference/basic-syntax.html#defining-variables) _(kotlinlang.org)_
* [Strings Documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html) _(kotlinlang.org)_
* [String Templates](https://kotlinlang.org/docs/reference/basic-types.html#string-templates) _(kotlinlang.org)_
* [Basic Types](https://kotlinlang.org/docs/reference/basic-types.html) _(kotlinlang.org)_
* [Companion Objects](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects) _(kotlinlang.org)_
* [Null Safety](https://kotlinlang.org/docs/reference/null-safety.html) _(kotlinlang.org)_
* [Collections Overview](https://kotlinlang.org/docs/reference/collections.html) _(kotlinlang.org)_
* [Collections Documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html) _(kotlinlang.org)_
* [Functions Documentation](https://kotlinlang.org/docs/reference/functions.html) _(kotlinlang.org)_
* [Classes Documentation](https://kotlinlang.org/docs/reference/classes.html) _(kotlinlang.org)_
* [Destructuring Declarations](https://kotlinlang.org/docs/reference/multi-declarations.html) _(kotlinlang.org)_


id: koa
git_filename: ./koa.md
format: md
field_title: Koa
field_category: JavaScript libraries
data:
{"title": "Koa", "category": "JavaScript libraries", "body": "### About\n{: .-intro}\n\nKoa is a web framework for Node.js.\n\n- <https://koajs.com/>\n\n### Reference\n\n```js\napp.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```js\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```js\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```js\nexports.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```"}

field_body:
### About
{: .-intro}

Koa is a web framework for Node.js.

- <https://koajs.com/>

### Reference

```js
app.use(function * (next) {
  var ctx = this

  ctx.request
  ctx.response

  ctx.body = 'hello'

  ctx.state.user = yield User.find(id).fetch()

  ctx.cookies.set('foo', 'hello', { signed: true })
  ctx.cookies.get('foo')

  ctx.throw(403)
```

### Request

```js
  ctx.header        // ctx.headers
  ctx.method        // and =
  ctx.url           // and =
  ctx.originalUrl
  ctx.origin        // => 'http://example.com'
  ctx.href          // => 'http://example.com/foo?q=hello'
  ctx.path          // and =
  ctx.query         // { q: 'hello' }
  ctx.query         // and =
  ctx.querystring
  ctx.querystring   // and =
  ctx.host
  ctx.hostname
  ctx.fresh
  ctx.stale
  ctx.socket
  ctx.protocol
  ctx.secure
  ctx.ip
  ctx.ips
  ctx.subdomains
  ctx.is()                  // .is('html') .is('text/html')
  ctx.accepts()             // .accepts('html') .accepts('html', 'json')
  ctx.acceptsEncodings()    // .acceptsEncodings('gzip')
  ctx.acceptsCharsets()
  ctx.acceptsLanguages()
  ctx.get()

  ctx.request.type          // => 'image/jpg'
  ctx.request.charset       // => 'utf-8'
  ctx.request.protocol      // => 'https'
  ctx.request.secure        // => true
  ctx.request.ip            // (supports X-Forwarded-For if app.proxy)
  ctx.request.ips
  ctx.request.subdomains

  ctx.request.fresh
  ctx.request.stale
```

### Response

```js
  ctx.body = 'hello'

  ctx.throw(403)
  ctx.throw('name required', 403)
  ctx.throw(403, 'name required')
  ctx.throw('oops')
  ctx.assert(ctx.state.user, 401, 'You must log in')
```

### Middlewares

```js
exports.conditionalGet = require('koa-conditional-get');
exports.responseTime = require('koa-response-time');
exports.ratelimit = require('koa-ratelimit');
exports.compress = require('koa-compress');
exports.rewrite = require('koa-rewrite');
exports.favicon = require('koa-favicon');
exports.session = require('koa-session');
exports.static = require('koa-static');
exports.logger = require('koa-logger');
exports.mount = require('koa-mount');
exports.etag = require('koa-etag');
```


id: knex
git_filename: ./knex.md
format: md
field_title: Knex
field_category: Databases
field_intro: [Knex](http://knexjs.org/) is an SQL query builder for Node.js. This guide targets v0.13.0.
field_updated: 2020-06-03
field_updated___timezone: UTC
data:
{"title": "Knex", "updated": "2020-06-03", "category": "Databases", "intro": "[Knex](http://knexjs.org/) is an SQL query builder for Node.js.\nThis guide targets v0.13.0.\n", "body": "## Getting started\n{: .-three-column}\n\n### Connect\n\n```js\nrequire('knex')({\n  client: 'pg',\n  connection: 'postgres://user:pass@localhost:5432/dbname'\n})\n```\n\nSee: [Connect](#connect-1)\n\n### Create table\n\n```js\nknex.schema.createTable('user', (table) => {\n  table.increments('id')\n  table.string('name')\n  table.integer('age')\n})\n.then(() => \u00b7\u00b7\u00b7)\n```\n\nSee: [Schema](#schema)\n\n### Select\n\n```js\nknex('users')\n  .where({ email: 'hi@example.com' })\n  .then(rows => \u00b7\u00b7\u00b7)\n```\n{: data-line=\"2\"}\n\nSee: [Select](#select-1)\n\n### Insert\n\n```js\nknex('users')\n  .insert({ email: 'hi@example.com' })\n```\n{: data-line=\"2\"}\n\nSee: [Insert](#insert-1)\n\n### Update\n\n```js\nknex('users')\n  .where({ id: 135 })\n  .update({ email: 'hi@example.com' })\n```\n{: data-line=\"2,3\"}\n\nSee: [Update](#update-1)\n\n### Migrations\n\n```bash\nknex 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\nSee: [Migrations](#migrations-1)\n\n### Seeds\n\n```bash\nknex 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\nSee: [Seeds](http://knexjs.org/#Seeds)\n\n## Connect\n{: .-three-column}\n\n### Libraries\n\n| `pg` | PostgreSQL |\n| `mysql` | MySQL or MariaDB |\n| `sqlite3` | Sqlite3 |\n| `mssql` | MSSQL |\n\nInstall any of these packages along with `knex`.\n\nSee: [Node.js installation](http://knexjs.org/#Installation-node)\n\n### Connect via host\n\n```js\nvar 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{: data-line=\"2,3\"}\n\nSee: [Initializing the library](http://knexjs.org/#Installation-client)\n\n### Connect via URL\n\n```js\nvar 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{: data-line=\"2,3\"}\n\n### Connect via Sqlite\n\n```js\nvar knex = require('knex')({\n  client: 'sqlite3',\n  connection: { filename: './mydb.sqlite' }\n})\n```\n{: data-line=\"2,3\"}\n\n## Select\n\n### Where\n\n```js\nknex\n  .from('books')\n  .select('title', 'author', 'year')\n```\n\n#### Where\n\n```js\n  .where('title', 'Hello')\n  .where({ title: 'Hello' })\n  .whereIn('id', [1, 2, 3])\n  .whereNot(\u00b7\u00b7\u00b7)\n  .whereNotIn('id', [1, 2, 3])\n```\n\n#### Where conditions\n\n```js\n  .whereNull('updated_at')\n  .whereNotNull(\u00b7\u00b7\u00b7)\n```\n\n```js\n  .whereExists('updated_at')\n  .whereNotExists(\u00b7\u00b7\u00b7)\n```\n\n```js\n  .whereBetween('votes', [1, 100])\n  .whereNotBetween(\u00b7\u00b7\u00b7)\n```\n\n```js\n  .whereRaw('id = ?', [1])\n```\n\n#### Where grouping\n\n```js\n  .where(function () {\n    this\n      .where('id', 1)\n      .orWhere('id', '>', 10)\n  })\n```\n\nSee: [Where clauses](http://knexjs.org/#Builder-wheres)\n\n### Join\n\n```js\nknex('users')\n```\n\n#### Basic join\n\n```js\n  .join('contacts', 'users.id', '=', 'contacts.id')\n  .join('contacts', {'users.id': 'contacts.id'})\n```\n\n#### Strings\n\n```js\n  .join('accounts', 'accounts.type', '=', knex.raw('?', ['admin']))\n```\n\n#### Directions\n\n```js\n  .leftJoin(\u00b7\u00b7\u00b7)\n  .leftOuterJoin(\u00b7\u00b7\u00b7)\n  .rightJoin(\u00b7\u00b7\u00b7)\n  .rightOuterJoin(\u00b7\u00b7\u00b7)\n  .outerJoin(\u00b7\u00b7\u00b7)\n  .fullOuterJoin(\u00b7\u00b7\u00b7)\n  .crossJoin(\u00b7\u00b7\u00b7)\n```\n\n#### Raw\n\n```js\n  .joinRaw('natural full join table1')\n```\n\n#### Grouping\n\n```js\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(\u00b7\u00b7\u00b7)\n\n      .onNull('accounts.email')\n      .onNotNull(\u00b7\u00b7\u00b7)\n\n      .onExists(function () {\n        this.select(\u00b7\u00b7\u00b7)\n      })\n      .onNotExists(\u00b7\u00b7\u00b7)\n  })\n```\n\nSee: [Join methods](http://knexjs.org/#Builder-join)\n\n### Others\n\n```js\nknex('users')\n  .distinct()\n```\n\n#### Group\n\n```js\n  .groupBy('count')\n  .groupByRaw('year WITH ROLLUP')\n```\n\n#### Order\n```js\n  .orderBy('name', 'desc')\n  .orderByRaw('name DESC')\n```\n\n#### Offset/limit\n\n```js\n  .offset(10)\n  .limit(20)\n```\n\n#### Having\n\n```js\n  .having('count', '>', 100)\n  .havingIn('count', [1, 100])\n```\n\n#### Union\n\n```js\n  .union(function() {\n    this.select(\u00b7\u00b7\u00b7)\n  })\n  .unionAll(\u00b7\u00b7\u00b7)\n```\n\nSee: [Query builder](http://knexjs.org/#Builder)\n\n### Etc\n\n```js\nknex('users')\n  .pluck('id')\n  .then(ids => { \u00b7\u00b7\u00b7 })\n```\n```js\nknex('users')\n  .first()\n  .then(user => { \u00b7\u00b7\u00b7 })\n```\n\n#### Booleans\n\n```js\n  .count('active')\n  .count('active as is_active')\n```\n\n#### Numbers\n\n```js\n  .min('age')\n  .max('age')\n  .sum('age')\n  .sumDistinct('age')\n  .avg('age')\n```\n\nSee: [Query builder](http://knexjs.org/#Builder)\n\n## Schema\n\n### Create table\n\n```js\nknex.schema.createTable('accounts', table => {\n```\n\n#### Columns\n\n```js\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```js\n  table.unique('email')\n  table.unique(['email', 'company_id'])\n  table.dropUnique(\u00b7\u00b7\u00b7)\n```\n\n#### Indices\n\n```js\n  table.foreign('company_id')\n    .references('companies.id')\n  table.dropForeign(\u00b7\u00b7\u00b7)\n```\n\n#### Variations\n\n```js\n  table.integer('user_id')\n    .unsigned()\n    .references('users.id')\n```\n\n```js\n})\n.then(() => \u00b7\u00b7\u00b7)\n```\n{: .-setup}\n\nSee: [Schema builder](http://knexjs.org/#Schema)\n\n### Alter table\n\n```js\nknex.schema.table('accounts', table => {\n```\n\n#### Create\n\n```js\n  table.string('first_name')\n```\n\n#### Alter\n\n```js\n  table.string('first_name').alter()\n  table.renameColumn('admin', 'is_admin')\n```\n\n#### Drop\n\n```js\n  table.dropColumn('admin')\n  table.dropTimestamps('created_at')\n```\n\n```js\n})\n```\n{: .-setup}\n\nSee: [Schema builder](http://knexjs.org/#Schema)\n\n### Other methods\n\n```js\nknex.schema\n  .renameTable('persons', 'people')\n  .dropTable('persons')\n```\n\n```js\n  .hasTable('users').then(exists => \u00b7\u00b7\u00b7)\n  .hasColumn('users', 'id').then(exists => \u00b7\u00b7\u00b7)\n```\n\nSee: [Schema builder](http://knexjs.org/#Schema)\n\n## Modifying\n{: .-three-column}\n\n### Insert\n\n```js\nknex('users')\n```\n\n#### Insert one\n\n```js\n  .insert({ name: 'John' })\n```\n\n#### Insert many\n\n```js\n  .insert([\n    { name: 'Starsky' },\n    { name: 'Hutch' }\n  ])\n```\n\nSee: [Insert](http://knexjs.org/#Builder-insert)\n\n### Update\n\n```js\nknex('users')\n  .where({ id: 2 })\n  .update({ name: 'Homer' })\n```\n\nSee: [Update](http://knexjs.org/#Builder-update)\n\n### Delete\n\n```js\nknex('users')\n  .where({ id: 2 })\n  .del()\n```\n\nSee: [Delete](http://knexjs.org/#Builder-del)\n\n## Migrations\n\n### Setting up\n\n#### Create knexfile.js\n\n```\n./node_modules/.bin/knex init\n```\n\n#### Create a migration\n\n```\nknex migrate:make migration_name\nknex migrate:make migration_name --env production\n```\n\n#### Run migrations\n\n```\nknex migrate:latest\nknex migrate:latest --env production\n```\n\n#### Rollback\n\n```\nknex migrate:rollback\nknex migrate:rollback --env production\n```\n\nSee: [Migrations](http://knexjs.org/#Migrations)"}

field_body:
## Getting started
{: .-three-column}

### Connect

```js
require('knex')({
  client: 'pg',
  connection: 'postgres://user:pass@localhost:5432/dbname'
})
```

See: [Connect](#connect-1)

### Create table

```js
knex.schema.createTable('user', (table) => {
  table.increments('id')
  table.string('name')
  table.integer('age')
})
.then(() => ···)
```

See: [Schema](#schema)

### Select

```js
knex('users')
  .where({ email: 'hi@example.com' })
  .then(rows => ···)
```
{: data-line="2"}

See: [Select](#select-1)

### Insert

```js
knex('users')
  .insert({ email: 'hi@example.com' })
```
{: data-line="2"}

See: [Insert](#insert-1)

### Update

```js
knex('users')
  .where({ id: 135 })
  .update({ email: 'hi@example.com' })
```
{: data-line="2,3"}

See: [Update](#update-1)

### Migrations

```bash
knex init
knex migrate:make migration_name
knex migrate:make migration_name -x ts # Generates a TypeScript migration file
knex migrate:latest
knex migrate:rollback
```

See: [Migrations](#migrations-1)

### Seeds

```bash
knex seed:make seed_name
knex seed:make seed_name -x ts # Generates a TypeScript seed file
knex seed:run # Runs all seed files
knex seed:run --specific=seed-filename.js # Runs a specific seed file
```

See: [Seeds](http://knexjs.org/#Seeds)

## Connect
{: .-three-column}

### Libraries

| `pg` | PostgreSQL |
| `mysql` | MySQL or MariaDB |
| `sqlite3` | Sqlite3 |
| `mssql` | MSSQL |

Install any of these packages along with `knex`.

See: [Node.js installation](http://knexjs.org/#Installation-node)

### Connect via host

```js
var knex = require('knex')({
  client: 'mysql',
  connection: {
    host: '127.0.0.1',
    user: 'your_database_user',
    password: 'your_database_password',
    database: 'myapp_test'
  },
  pool: { min: 0, max: 7 }
})
```
{: data-line="2,3"}

See: [Initializing the library](http://knexjs.org/#Installation-client)

### Connect via URL

```js
var pg = require('knex')({
  client: 'pg',
  connection: process.env.DATABASE_URL,
  searchPath: 'knex,public',
  pool: { min: 0, max: 7 }
})
```
{: data-line="2,3"}

### Connect via Sqlite

```js
var knex = require('knex')({
  client: 'sqlite3',
  connection: { filename: './mydb.sqlite' }
})
```
{: data-line="2,3"}

## Select

### Where

```js
knex
  .from('books')
  .select('title', 'author', 'year')
```

#### Where

```js
  .where('title', 'Hello')
  .where({ title: 'Hello' })
  .whereIn('id', [1, 2, 3])
  .whereNot(···)
  .whereNotIn('id', [1, 2, 3])
```

#### Where conditions

```js
  .whereNull('updated_at')
  .whereNotNull(···)
```

```js
  .whereExists('updated_at')
  .whereNotExists(···)
```

```js
  .whereBetween('votes', [1, 100])
  .whereNotBetween(···)
```

```js
  .whereRaw('id = ?', [1])
```

#### Where grouping

```js
  .where(function () {
    this
      .where('id', 1)
      .orWhere('id', '>', 10)
  })
```

See: [Where clauses](http://knexjs.org/#Builder-wheres)

### Join

```js
knex('users')
```

#### Basic join

```js
  .join('contacts', 'users.id', '=', 'contacts.id')
  .join('contacts', {'users.id': 'contacts.id'})
```

#### Strings

```js
  .join('accounts', 'accounts.type', '=', knex.raw('?', ['admin']))
```

#### Directions

```js
  .leftJoin(···)
  .leftOuterJoin(···)
  .rightJoin(···)
  .rightOuterJoin(···)
  .outerJoin(···)
  .fullOuterJoin(···)
  .crossJoin(···)
```

#### Raw

```js
  .joinRaw('natural full join table1')
```

#### Grouping

```js
  .join('accounts', function () {
    this
      .on('accounts.id', '=', 'users.account_id')
      .orOn('accounts.owner_id', '=', 'users.id')

      .onIn('accounts.id', [1, 2, 3, 5, 8])
      .onNotIn(···)

      .onNull('accounts.email')
      .onNotNull(···)

      .onExists(function () {
        this.select(···)
      })
      .onNotExists(···)
  })
```

See: [Join methods](http://knexjs.org/#Builder-join)

### Others

```js
knex('users')
  .distinct()
```

#### Group

```js
  .groupBy('count')
  .groupByRaw('year WITH ROLLUP')
```

#### Order
```js
  .orderBy('name', 'desc')
  .orderByRaw('name DESC')
```

#### Offset/limit

```js
  .offset(10)
  .limit(20)
```

#### Having

```js
  .having('count', '>', 100)
  .havingIn('count', [1, 100])
```

#### Union

```js
  .union(function() {
    this.select(···)
  })
  .unionAll(···)
```

See: [Query builder](http://knexjs.org/#Builder)

### Etc

```js
knex('users')
  .pluck('id')
  .then(ids => { ··· })
```
```js
knex('users')
  .first()
  .then(user => { ··· })
```

#### Booleans

```js
  .count('active')
  .count('active as is_active')
```

#### Numbers

```js
  .min('age')
  .max('age')
  .sum('age')
  .sumDistinct('age')
  .avg('age')
```

See: [Query builder](http://knexjs.org/#Builder)

## Schema

### Create table

```js
knex.schema.createTable('accounts', table => {
```

#### Columns

```js
  table.increments('id')
  table.string('account_name')
  table.integer('age')
  table.float('age')
  table.decimal('balance', 8, 2)
  table.boolean('is_admin')
  table.date('birthday')
  table.time('created_at')
  table.timestamp('created_at').defaultTo(knex.fn.now())
  table.json('profile')
  table.jsonb('profile')
  table.uuid('id').primary()
```

#### Constraints

```js
  table.unique('email')
  table.unique(['email', 'company_id'])
  table.dropUnique(···)
```

#### Indices

```js
  table.foreign('company_id')
    .references('companies.id')
  table.dropForeign(···)
```

#### Variations

```js
  table.integer('user_id')
    .unsigned()
    .references('users.id')
```

```js
})
.then(() => ···)
```
{: .-setup}

See: [Schema builder](http://knexjs.org/#Schema)

### Alter table

```js
knex.schema.table('accounts', table => {
```

#### Create

```js
  table.string('first_name')
```

#### Alter

```js
  table.string('first_name').alter()
  table.renameColumn('admin', 'is_admin')
```

#### Drop

```js
  table.dropColumn('admin')
  table.dropTimestamps('created_at')
```

```js
})
```
{: .-setup}

See: [Schema builder](http://knexjs.org/#Schema)

### Other methods

```js
knex.schema
  .renameTable('persons', 'people')
  .dropTable('persons')
```

```js
  .hasTable('users').then(exists => ···)
  .hasColumn('users', 'id').then(exists => ···)
```

See: [Schema builder](http://knexjs.org/#Schema)

## Modifying
{: .-three-column}

### Insert

```js
knex('users')
```

#### Insert one

```js
  .insert({ name: 'John' })
```

#### Insert many

```js
  .insert([
    { name: 'Starsky' },
    { name: 'Hutch' }
  ])
```

See: [Insert](http://knexjs.org/#Builder-insert)

### Update

```js
knex('users')
  .where({ id: 2 })
  .update({ name: 'Homer' })
```

See: [Update](http://knexjs.org/#Builder-update)

### Delete

```js
knex('users')
  .where({ id: 2 })
  .del()
```

See: [Delete](http://knexjs.org/#Builder-del)

## Migrations

### Setting up

#### Create knexfile.js

```
./node_modules/.bin/knex init
```

#### Create a migration

```
knex migrate:make migration_name
knex migrate:make migration_name --env production
```

#### Run migrations

```
knex migrate:latest
knex migrate:latest --env production
```

#### Rollback

```
knex migrate:rollback
knex migrate:rollback --env production
```

See: [Migrations](http://knexjs.org/#Migrations)


id: jshint
git_filename: ./jshint.md
format: md
field_title: Jshint
field_category: JavaScript libraries
field_updated: 2017-09-12
field_updated___timezone: UTC
data:
{"title": "Jshint", "category": "JavaScript libraries", "updated": "2017-09-12", "body": "### Relaxing\n\nEnable these options to *not* throw errors in these conditions.\nSee: [Relaxing](https://www.jshint.com/docs/options/#relaxing-options)\n{: .-setup}\n\n```js\n/* jshint asi: true */\nallow()\nmissing_semicolons()\n```\n\n```js\n/* jshint boss: true */\nif (m = str.match(/.../))\n```\n\n```js\n/* jshint debug: true */\ndebugger;\n```\n\n```js\n/* jshint eqnull: true */\nif (x == null)\n```\n\n```js\n/* jshint evil: true */\neval('...')\n```\n\n```js\n/* jshint expr: true */\nproduction && minify = true;\ndiv.innerWidth;\nexpect(x).be.true;\n```\n\n```js\n/* jshint laxcomma: true */\nvar one = 1\n  , two = 2;\n```\n\n```js\n/* jshint loopfunc: true */\nfor (i=0; i<10; x++) {\n  (function(i) { ... })(i);\n}\n```\n\n```js\n/* jshint sub: true */\nprocess.env['name_here']\n```\n\n```js\n/* jshint strict: \"global\" */\n\"use strict\";\n```\n\n### Enforcing\n\nEnable these options to catch more errors.\nSee: [Enforcing](https://www.jshint.com/docs/options/#enforcing-options)\n{: .-setup}\n\n```js\n/* jshint curly: true */\nwhile (day)                     // err: use { }'s\n  shuffle();\n```\n\n```js\n/* jshint eqeqeq: true */\nif (a == null)                  // err: use ===\n```\n\n```js\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```js\n/* jshint forin: true */\nfor (key in obj) { ... }        // err: check obj.hasOwnProperty(key)\n```\n\n```js\n/* jshint freeze: true */\nArray.prototype.count = ...;    // err: don't modify native prototypes\n```\n\n```js\n/* jshint indent: 4 */\nif (x) {                        // err: expected indent of 4, found 2\n  ...;\n}\n```\n\n```js\n/* jshint quotmark: single */\n/* jshint quotmark: double */\nalert(\"hi\");                    // err: only single allowed\n```\n\n```js\n/* jshint strict: true */\nfunction() { ... }              // err: need \"use strict\"\n```\n\n```js\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```js\n/* jshint ignore:start */\n/* jshint ignore:end */\n```\n\n### Globals and Environments\n\n```js\n/* jshint undef: true */\n/* global jQuery */\n/* global -BAD_LIB */\n```\n\n```js\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\nSee: [Environments](https://www.jshint.com/docs/options/#environments)\n\n### Also see\n\n* <https://www.jshint.com/docs/options/>\n* <https://gist.github.com/haschek/2595796>"}

field_body:
### Relaxing

Enable these options to *not* throw errors in these conditions.
See: [Relaxing](https://www.jshint.com/docs/options/#relaxing-options)
{: .-setup}

```js
/* jshint asi: true */
allow()
missing_semicolons()
```

```js
/* jshint boss: true */
if (m = str.match(/.../))
```

```js
/* jshint debug: true */
debugger;
```

```js
/* jshint eqnull: true */
if (x == null)
```

```js
/* jshint evil: true */
eval('...')
```

```js
/* jshint expr: true */
production && minify = true;
div.innerWidth;
expect(x).be.true;
```

```js
/* jshint laxcomma: true */
var one = 1
  , two = 2;
```

```js
/* jshint loopfunc: true */
for (i=0; i<10; x++) {
  (function(i) { ... })(i);
}
```

```js
/* jshint sub: true */
process.env['name_here']
```

```js
/* jshint strict: "global" */
"use strict";
```

### Enforcing

Enable these options to catch more errors.
See: [Enforcing](https://www.jshint.com/docs/options/#enforcing-options)
{: .-setup}

```js
/* jshint curly: true */
while (day)                     // err: use { }'s
  shuffle();
```

```js
/* jshint eqeqeq: true */
if (a == null)                  // err: use ===
```

```js
/* jshint es3: true */
// ...for legacy IE compatibility
a.default = function() { ... }; // err: reserved word
array = [ 1, 2, 3, ];           // err: extra comma
```

```js
/* jshint forin: true */
for (key in obj) { ... }        // err: check obj.hasOwnProperty(key)
```

```js
/* jshint freeze: true */
Array.prototype.count = ...;    // err: don't modify native prototypes
```

```js
/* jshint indent: 4 */
if (x) {                        // err: expected indent of 4, found 2
  ...;
}
```

```js
/* jshint quotmark: single */
/* jshint quotmark: double */
alert("hi");                    // err: only single allowed
```

```js
/* jshint strict: true */
function() { ... }              // err: need "use strict"
```

```js
/* jshint white: true, indent: 4 */
/* jshint maxdepth: 2 */
/* jshint maxparams: 3 */
/* jshint maxstatements: 4 */
/* jshint maxcomplexity: 5 */
/* jshint maxlen: 80 */
```

### Ignore

```js
/* jshint ignore:start */
/* jshint ignore:end */
```

### Globals and Environments

```js
/* jshint undef: true */
/* global jQuery */
/* global -BAD_LIB */
```

```js
/* jshint devel: true */   console, alert, ...
/* jshint browser: true */ window, document, location, ...
/* jshint node: true */    module, exports, console, process, ...
/* jshint jquery: true */  jQuery, $
```

See: [Environments](https://www.jshint.com/docs/options/#environments)

### Also see

* <https://www.jshint.com/docs/options/>
* <https://gist.github.com/haschek/2595796>


id: jsdoc
git_filename: ./jsdoc.md
format: md
field_title: Jsdoc
field_category: JavaScript
field_updated: 2024-07-26
field_updated___timezone: UTC
data:
{"title": "Jsdoc", "category": "JavaScript", "updated": "2024-07-26", "weight": -1, "body": "### Functions\n\n```js\n/**\n * This is a function.\n *\n * @param {string} n - A string param\n * @param {string} [o] - A optional string param\n * @param {string} [d=DefaultValue] - A optional string param\n * @return {string} A good string\n *\n * @example\n *\n *     foo('hello')\n */\n\nfunction foo(n, o, d) {\n  return n\n}\n```\n\nSee: <https://jsdoc.app/index.html>\n\n### Types\n\n| Type                            | Description                           |\n| ------------------------------- | ------------------------------------- |\n| `@param {string=} n`            | Optional                              |\n| `@param {string} [n]`           | Optional                              |\n| `@param {(string|number)} n`    | Multiple types                        |\n| `@param {*} n`                  | Any type                              |\n| `@param {...string} n`          | Repeatable arguments                  |\n| `@param {string} [n=\"hi\"]`      | Optional with default                 |\n| `@param {string[]} n`           | Array of strings                      |\n| `@return {Promise<string[]>} n` | Promise fulfilled by array of strings |\n\nSee: <https://jsdoc.app/tags-type.html>\n\n### Variables\n\n```js\n/**\n * @type {number}\n */\nvar FOO = 1\n```\n\n```js\n/**\n * @const {number}\n */\nconst FOO = 1\n```\n\n### Typedef\n\n```js\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```js\n/**\n * Plays a song\n * @param {Song} song - The {@link Song} to be played\n */\n\nfunction play(song) {}\n```\n\nSee: <https://jsdoc.app/tags-typedef.html>\n\n### Typedef Shorthand\n\n{% raw %}\n\n```js\n/**\n * A song\n * @typedef {{title: string, artist: string, year: number}} Song\n */\n```\n\n{% endraw %}\n\n```js\n/**\n * Plays a song\n * @param {Song} song - The {@link Song} to be played\n */\n\nfunction play(song) {}\n```\n\nSee: <https://jsdoc.app/tags-typedef.html>\n\n### Importing types\n\n```js\n/**\n * @typedef {import('./Foo').default} Bar\n */\n\n// or\n\n/** @import { Bar } from \"./Foo.js\" */\n\n/**\n * @param {Bar} x\n */\n\nfunction test(x) {}\n```\n\nThis syntax is [TypeScript-specific](https://github.com/Microsoft/TypeScript/wiki/JsDoc-support-in-JavaScript#import-types).\n\n### Other keywords\n\n```js\n/**\n * @throws {FooException}\n * @async\n * @private\n * @deprecated\n * @see\n * @example\n * @todo\n *\n * @function\n * @class\n */\n```\n\nSee the full list: <https://jsdoc.app/index.html#block-tags>\n\n### Renaming\n\n```js\n/**\n * @alias Foo.bar\n * @name Foo.bar\n */\n```\n\nPrefer `alias` over `name`. See: <https://jsdoc.app/tags-alias.html>"}

field_body:
### Functions

```js
/**
 * This is a function.
 *
 * @param {string} n - A string param
 * @param {string} [o] - A optional string param
 * @param {string} [d=DefaultValue] - A optional string param
 * @return {string} A good string
 *
 * @example
 *
 *     foo('hello')
 */

function foo(n, o, d) {
  return n
}
```

See: <https://jsdoc.app/index.html>

### Types

| Type                            | Description                           |
| ------------------------------- | ------------------------------------- |
| `@param {string=} n`            | Optional                              |
| `@param {string} [n]`           | Optional                              |
| `@param {(string|number)} n`    | Multiple types                        |
| `@param {*} n`                  | Any type                              |
| `@param {...string} n`          | Repeatable arguments                  |
| `@param {string} [n="hi"]`      | Optional with default                 |
| `@param {string[]} n`           | Array of strings                      |
| `@return {Promise<string[]>} n` | Promise fulfilled by array of strings |

See: <https://jsdoc.app/tags-type.html>

### Variables

```js
/**
 * @type {number}
 */
var FOO = 1
```

```js
/**
 * @const {number}
 */
const FOO = 1
```

### Typedef

```js
/**
 * A song
 * @typedef {Object} Song
 * @property {string} title - The title
 * @property {string} artist - The artist
 * @property {number} year - The year
 */
```

```js
/**
 * Plays a song
 * @param {Song} song - The {@link Song} to be played
 */

function play(song) {}
```

See: <https://jsdoc.app/tags-typedef.html>

### Typedef Shorthand

{% raw %}

```js
/**
 * A song
 * @typedef {{title: string, artist: string, year: number}} Song
 */
```

{% endraw %}

```js
/**
 * Plays a song
 * @param {Song} song - The {@link Song} to be played
 */

function play(song) {}
```

See: <https://jsdoc.app/tags-typedef.html>

### Importing types

```js
/**
 * @typedef {import('./Foo').default} Bar
 */

// or

/** @import { Bar } from "./Foo.js" */

/**
 * @param {Bar} x
 */

function test(x) {}
```

This syntax is [TypeScript-specific](https://github.com/Microsoft/TypeScript/wiki/JsDoc-support-in-JavaScript#import-types).

### Other keywords

```js
/**
 * @throws {FooException}
 * @async
 * @private
 * @deprecated
 * @see
 * @example
 * @todo
 *
 * @function
 * @class
 */
```

See the full list: <https://jsdoc.app/index.html#block-tags>

### Renaming

```js
/**
 * @alias Foo.bar
 * @name Foo.bar
 */
```

Prefer `alias` over `name`. See: <https://jsdoc.app/tags-alias.html>


id: jscoverage
git_filename: ./jscoverage.md
format: md
field_title: jscoverage
field_category: JavaScript libraries
data:
{"title": "jscoverage", "category": "JavaScript libraries", "intro": "A small guide into installing [jscoverage](https://npmjs.com/package./jscoverage). Also see [mocha-blanket](./mocha-blanket).\n", "body": "### Install\n\n#### Install via npm\n\n```bash\nnpm install --save-dev jscoverage\n```\n\n#### Ignore output\n\n```bash\necho coverage.html >> .gitignore\n```\n\n### package.json\n\nThe `coverage` task injects your source files (`lib`) with jscoverage hooks, runs `mocha -R html-cov`, then restores later.\n{: .-setup}\n\n```bash\n/* directory */\n\"coverage\": \"mv lib lib~; (jscoverage lib~ lib; mocha -R html-cov > coverage.html); rm -rf lib; mv lib~ lib\"\n```\n{: .-hard-wrap}\n\n```bash\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{: .-hard-wrap}\n\n### Run\n\n```bash\nnpm run coverage\n```\n\n```bash\nopen coverage.html\n```\n\n### Caveats\n\nIf you're using jsdom, be sure to expose the `window._$jscoverage` variable into \nthe `global` scope."}

field_intro:
A small guide into installing [jscoverage](https://npmjs.com/package./jscoverage). Also see [mocha-blanket](./mocha-blanket).

field_body:
### Install

#### Install via npm

```bash
npm install --save-dev jscoverage
```

#### Ignore output

```bash
echo coverage.html >> .gitignore
```

### package.json

The `coverage` task injects your source files (`lib`) with jscoverage hooks, runs `mocha -R html-cov`, then restores later.
{: .-setup}

```bash
/* directory */
"coverage": "mv lib lib~; (jscoverage lib~ lib; mocha -R html-cov > coverage.html); rm -rf lib; mv lib~ lib"
```
{: .-hard-wrap}

```bash
/* single file */
"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"
```
{: .-hard-wrap}

### Run

```bash
npm run coverage
```

```bash
open coverage.html
```

### Caveats

If you're using jsdom, be sure to expose the `window._$jscoverage` variable into 
the `global` scope.


id: js-speech
git_filename: ./js-speech.md
format: md
field_title: JavaScript speech synthesis
field_category: JavaScript
data:
{"title": "JavaScript speech synthesis", "category": "JavaScript", "weight": -1, "body": "## SpeechSynthesisUtterance\n{: .-one-column}\n\n```js\nfunction 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```js\nspeak('Hello, world')\n```\n\nSee: [SpeechSynthesisUtterance](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance) _(developer.mozilla.org)_"}

field_body:
## SpeechSynthesisUtterance
{: .-one-column}

```js
function speak (message) {
  var msg = new SpeechSynthesisUtterance(message)
  var voices = window.speechSynthesis.getVoices()
  msg.voice = voices[0]
  window.speechSynthesis.speak(msg)
}
```

```js
speak('Hello, world')
```

See: [SpeechSynthesisUtterance](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance) _(developer.mozilla.org)_


id: js-model
git_filename: ./js-model.md
format: md
field_title: js-model
field_category: JavaScript libraries
data:
{"title": "js-model", "category": "JavaScript libraries", "body": "### Example\n\n```bash\nProject = Model \"project\", ->\n  @extend\n    findByTitle: (title) -> ...\n\n  @include\n    markAsDone: -> ...\n\n  # ActiveRecord::Base.include_root_in_json = false\n```\n\n```bash\nproject = Project.find(1)\nproject = Project.findByTitle(\"hello\")\n\nproject.markAsDone()\n```\n\n### Persistence\n\n```bash\nProject \"hi\", ->\n  @persistence Model.REST, \"/projects\"\n  @persistence Model.localStorage\n```\n\n```bash\nProject.load ->\n  # loaded\n```\n\n### Attrs\n\n```bash\nproject = new Project(name: \"Hello\")\n\nproject.attr('name', \"Hey\")\nproject.attr('name')\n\nproject.save()\nproject.destroy()\n```\n\n### Collection\n\n```bash\nFood.add(egg)\nFood.all()\nFood.select (food) -> ...\nFood.first()\n```\n\n```bash\nFood.find(id)\n```\n\n### Events\n\n```bash\n# Classes\nProject.bind \"add\", (obj) ->\nProject.bind \"remove\", (obj) ->\n```\n\n```bash\n# Instances\nproject.bind \"update\", ->\nproject.bind \"destroy\", ->\n```\n\n```bash\nproject.trigger \"turn_blue\"\n```\n\n## References\n{: .-one-column}\n\n- <http://benpickles.github.io/js-model/>"}

field_body:
### Example

```bash
Project = Model "project", ->
  @extend
    findByTitle: (title) -> ...

  @include
    markAsDone: -> ...

  # ActiveRecord::Base.include_root_in_json = false
```

```bash
project = Project.find(1)
project = Project.findByTitle("hello")

project.markAsDone()
```

### Persistence

```bash
Project "hi", ->
  @persistence Model.REST, "/projects"
  @persistence Model.localStorage
```

```bash
Project.load ->
  # loaded
```

### Attrs

```bash
project = new Project(name: "Hello")

project.attr('name', "Hey")
project.attr('name')

project.save()
project.destroy()
```

### Collection

```bash
Food.add(egg)
Food.all()
Food.select (food) -> ...
Food.first()
```

```bash
Food.find(id)
```

### Events

```bash
# Classes
Project.bind "add", (obj) ->
Project.bind "remove", (obj) ->
```

```bash
# Instances
project.bind "update", ->
project.bind "destroy", ->
```

```bash
project.trigger "turn_blue"
```

## References
{: .-one-column}

- <http://benpickles.github.io/js-model/>


id: js-lazy
git_filename: ./js-lazy.md
format: md
field_title: JavaScript lazy shortcuts
field_category: JavaScript
data:
{"title": "JavaScript lazy shortcuts", "category": "JavaScript", "body": "## Shortcuts\n{: .-left-reference}\n\n### Examples\n\n```js\nn = +'4096'    // n === 4096\ns = '' + 200   // s === '200'\n```\n\n```js\nnow = +new Date()\nisPublished = !!post.publishedAt\n```\n\n### Shortcuts\n\n| What | Lazy mode | \"The right way\" |\n| --- | --- | --- |\n| String to number | `+str` | `parseInt(str, 10)` _or_ `parseFloat()` |\n| Math floor | `num | 0` | `Math.floor(num)` |\n| Number to string | `'' + num` | `num.toString()` |\n| Date to UNIX timestamp | `+new Date()` | `new Date().getTime()` |\n| Any to boolean | `!!value` | `Boolean(value)` |\n| Check array contents | `if (~arr.indexOf(v))` | `if (arr.includes(v))` |\n{: .-left-align.-headers}\n\n`.includes` is ES6-only, otherwise use `.indexOf(val) !== -1` if you don't polyfill."}

field_body:
## Shortcuts
{: .-left-reference}

### Examples

```js
n = +'4096'    // n === 4096
s = '' + 200   // s === '200'
```

```js
now = +new Date()
isPublished = !!post.publishedAt
```

### Shortcuts

| What | Lazy mode | "The right way" |
| --- | --- | --- |
| String to number | `+str` | `parseInt(str, 10)` _or_ `parseFloat()` |
| Math floor | `num | 0` | `Math.floor(num)` |
| Number to string | `'' + num` | `num.toString()` |
| Date to UNIX timestamp | `+new Date()` | `new Date().getTime()` |
| Any to boolean | `!!value` | `Boolean(value)` |
| Check array contents | `if (~arr.indexOf(v))` | `if (arr.includes(v))` |
{: .-left-align.-headers}

`.includes` is ES6-only, otherwise use `.indexOf(val) !== -1` if you don't polyfill.


id: js-fetch
git_filename: ./js-fetch.md
format: md
field_title: fetch()
field_category: JavaScript
data:
{"title": "fetch()", "category": "JavaScript", "weight": -3, "body": "### Fetch\n{: .-prime}\n\n```js\nfetch('/data.json')\n  .then(response => response.json())\n  .then(data => {\n    console.log(data)\n  })\n  .catch(err => ...)\n```\n{: data-line=\"4\"}\n\n### Response\n\n```js\nfetch('/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```js\nfetch('/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```js\nfetch('/data.json')\n  .then(checkStatus)\n```\n\n```js\nfunction 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\nNon-2xx responses are still successful requests. Use another function to turn them to errors.\n\n### Using with node.js\n\n```js\nconst fetch = require('isomorphic-fetch')\n```\n\nSee: [isomorphic-fetch](https://npmjs.com/package/isomorphic-fetch) _(npmjs.com)_\n\n## References\n{: .-one-column}\n\n- <https://fetch.spec.whatwg.org/>\n- <https://www.npmjs.com/package/whatwg-fetch>"}

field_body:
### Fetch
{: .-prime}

```js
fetch('/data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  .catch(err => ...)
```
{: data-line="4"}

### Response

```js
fetch('/data.json')
.then(res => {
  res.text()       // response body (=> Promise)
  res.json()       // parse via JSON (=> Promise)
  res.status       //=> 200
  res.statusText   //=> 'OK'
  res.redirected   //=> false
  res.ok           //=> true
  res.url          //=> 'http://site.com/data.json'
  res.type         //=> 'basic'
                   //   ('cors' 'default' 'error'
                   //    'opaque' 'opaqueredirect')

  res.headers.get('Content-Type')
})
```

### Request options

```js
fetch('/data.json', {
  method: 'post',
  body: new FormData(form), // post body
  body: JSON.stringify(...),

  headers: {
    'Accept': 'application/json'
  },

  credentials: 'same-origin', // send cookies
  credentials: 'include',     // send cookies, even in CORS

})
```

### Catching errors

```js
fetch('/data.json')
  .then(checkStatus)
```

```js
function checkStatus (res) {
  if (res.status >= 200 && res.status < 300) {
    return res
  } else {
    let err = new Error(res.statusText)
    err.response = res
    throw err
  }
}
```

Non-2xx responses are still successful requests. Use another function to turn them to errors.

### Using with node.js

```js
const fetch = require('isomorphic-fetch')
```

See: [isomorphic-fetch](https://npmjs.com/package/isomorphic-fetch) _(npmjs.com)_

## References
{: .-one-column}

- <https://fetch.spec.whatwg.org/>
- <https://www.npmjs.com/package/whatwg-fetch>


id: js-date
git_filename: ./js-date.md
format: md
field_title: JavaScript Date
field_category: JavaScript
data:
{"title": "JavaScript Date", "category": "JavaScript", "weight": -3, "body": "## Date\n{: .-left-reference}\n\n### Constructor\n\n```js\n// Now\nnew Date()\n```\n\n```js\n// ms since epoch\nnew Date(1393678859000)\n```\n\n```js\n// Date format\nnew Date(\"March 1, 2014 13:00:59\")\n```\n\n```js\n// ISO date format\nnew Date(\"2014-03-01T13:00:59\")\n```\n\n```js\nnew Date(2014, 2, 1, 13, 0, 59, 0)\n```\n\n### Constructor\n\n| `new Date(` | `2014,` | `2,`  | `1,` | `13,` | `0,` | `59,` | `0)`  |\n| Date        | Year    | Month | Day  | Hour  | Min  | Sec   | Milli |\n{: .-css-breakdown}\n\nMonths are zero-indexed (eg, January is `0`).\n\n### Conversion\n\n| Method                   | Result                                      |\n| ---                      | ---                                         |\n| `d.toString()`           | `\"Sat Mar 01 2014 13:00:59 GMT+0000 (GMT)\"` |\n| `d.toTimeString()`       | `\"13:00:59 GMT+0000 (GMT)\"`                 |\n| `d.toUTCString()`        | `\"Sat, 01 Mar 2014 13:00:59 GMT\"`           |\n| ---                      | ---                                         |\n| `d.toDateString()`       | `\"Sat Mar 01 2014\"`                         |\n| `d.toISOString()`        | `\"2014-03-01T13:00:59.000Z\"`                |\n| `d.toLocaleString()`     | `\"3/1/2014, 1:00:59 PM\"`                    |\n| `d.toLocaleTimeString()` | `\"1:00:59 PM\"`                              |\n| ---                      | ---                                         |\n| `d.getTime()`            | `1393678859000`                             |\n\nAccessing\n---------\n\n### Getters\n\n| Method                 | Result            |\n| ---                    | ---               |\n| `.getDate()`           | `1..31`           |\n| `.getDay()`            | `0..6` (sun..sat) |\n| `.getFullYear()`       | `2014`            |\n| `.getMonth()`          | `0..11`           |\n| ---                    | ---               |\n| `.getHours()`          |                   |\n| `.getMinutes()`        |                   |\n| `.getSeconds()`        |                   |\n| `.getMilliseconds()`   |                   |\n| ---                    | ---               |\n| `.getTime()`           | ms since epoch    |\n| `.getTimezoneOffset()` |                   |\n\nUTC versions are also available (eg, `.getUTCDate()`, `.getUTCDay()`, etc).\n\n### Setters\n\n| Method                       | Result |\n| ---                          | ---    |\n| `.setDate` _(val)_           |        |\n| `.setDay` _(val)_            |        |\n| `.setFullYear` _(val)_       |        |\n| `.setMonth` _(val)_          |        |\n| ---                          | ---    |\n| `.setHours` _(val)_          |        |\n| `.setMinutes` _(val)_        |        |\n| `.setSeconds` _(val)_        |        |\n| `.setMilliseconds` _(val)_   |        |\n| ---                          | ---    |\n| `.setTime` _(val)_           |        |\n| `.setTimezoneOffset` _(val)_ |        |\n\nSee the getters list."}

field_body:
## Date
{: .-left-reference}

### Constructor

```js
// Now
new Date()
```

```js
// ms since epoch
new Date(1393678859000)
```

```js
// Date format
new Date("March 1, 2014 13:00:59")
```

```js
// ISO date format
new Date("2014-03-01T13:00:59")
```

```js
new Date(2014, 2, 1, 13, 0, 59, 0)
```

### Constructor

| `new Date(` | `2014,` | `2,`  | `1,` | `13,` | `0,` | `59,` | `0)`  |
| Date        | Year    | Month | Day  | Hour  | Min  | Sec   | Milli |
{: .-css-breakdown}

Months are zero-indexed (eg, January is `0`).

### Conversion

| Method                   | Result                                      |
| ---                      | ---                                         |
| `d.toString()`           | `"Sat Mar 01 2014 13:00:59 GMT+0000 (GMT)"` |
| `d.toTimeString()`       | `"13:00:59 GMT+0000 (GMT)"`                 |
| `d.toUTCString()`        | `"Sat, 01 Mar 2014 13:00:59 GMT"`           |
| ---                      | ---                                         |
| `d.toDateString()`       | `"Sat Mar 01 2014"`                         |
| `d.toISOString()`        | `"2014-03-01T13:00:59.000Z"`                |
| `d.toLocaleString()`     | `"3/1/2014, 1:00:59 PM"`                    |
| `d.toLocaleTimeString()` | `"1:00:59 PM"`                              |
| ---                      | ---                                         |
| `d.getTime()`            | `1393678859000`                             |

Accessing
---------

### Getters

| Method                 | Result            |
| ---                    | ---               |
| `.getDate()`           | `1..31`           |
| `.getDay()`            | `0..6` (sun..sat) |
| `.getFullYear()`       | `2014`            |
| `.getMonth()`          | `0..11`           |
| ---                    | ---               |
| `.getHours()`          |                   |
| `.getMinutes()`        |                   |
| `.getSeconds()`        |                   |
| `.getMilliseconds()`   |                   |
| ---                    | ---               |
| `.getTime()`           | ms since epoch    |
| `.getTimezoneOffset()` |                   |

UTC versions are also available (eg, `.getUTCDate()`, `.getUTCDay()`, etc).

### Setters

| Method                       | Result |
| ---                          | ---    |
| `.setDate` _(val)_           |        |
| `.setDay` _(val)_            |        |
| `.setFullYear` _(val)_       |        |
| `.setMonth` _(val)_          |        |
| ---                          | ---    |
| `.setHours` _(val)_          |        |
| `.setMinutes` _(val)_        |        |
| `.setSeconds` _(val)_        |        |
| `.setMilliseconds` _(val)_   |        |
| ---                          | ---    |
| `.setTime` _(val)_           |        |
| `.setTimezoneOffset` _(val)_ |        |

See the getters list.


id: js-array
git_filename: ./js-array.md
format: md
field_title: JavaScript Arrays
field_category: JavaScript
data:
{"title": "JavaScript Arrays", "category": "JavaScript", "body": "### Arrays\n\n```bash\nlist = [a,b,c,d,e]\n```\n{: .-setup}\n\n```bash\nlist[1]                 // \u2192 b\nlist.indexOf(b)         // \u2192 1\nlist.lastIndexOf(b)     // \u2192 1\nlist.includes(b)        // \u2192 true\n```\n\n### Subsets\n\n#### Immutable\n\n```bash\nlist.slice(0,1)         // \u2192 [a        ]\nlist.slice(1)           // \u2192 [  b,c,d,e]\nlist.slice(1,2)         // \u2192 [  b      ]\n```\n\n#### Mutative\n\n```bash\nre = 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```bash\nlist.concat([X,Y])      // \u2192 [_,_,_,_,_,X,Y]\n```\n\n#### Mutative\n\n```bash\nlist.push(X)            // list == [_,_,_,_,_,X]\nlist.unshift(X)         // list == [X,_,_,_,_,_]\nlist.splice(2, 0, X)    // list == [_,_,X,_,_,_]\n```\n\n### Inserting\n\n```bash\n// after -- [_,_,REF,NEW,_,_]\nlist.splice(list.indexOf(REF)+1, 0, NEW))\n```\n\n```bash\n// before -- [_,_,NEW,REF,_,_]\nlist.splice(list.indexOf(REF), 0, NEW))\n```\n\n### Replace items\n\n```bash\nlist.splice(2, 1, X)    // list == [a,b,X,d,e]\n```\n\n### Removing items\n\n```bash\nlist.pop()              // \u2192 e    list == [a,b,c,d]\nlist.shift()            // \u2192 a    list == [b,c,d,e]\nlist.splice(2, 1)       // \u2192 [c]  list == [a,b,d,e]\n```\n\n### Iterables\n\n```bash\n.filter(n => ...) => array\n```\n\n```bash\n.forEach(n => ...)\n```\n\n```bash\n.find(n => ...)  // es6\n.findIndex(...)  // es6\n```\n\n```bash\n.every(n => ...) => Boolean // ie9+\n.some(n => ..) => Boolean   // ie9+\n```\n\n```bash\n.map(n => ...)   // ie9+\n.reduce((total, n) => total) // ie9+\n.reduceRight(...)\n```"}

field_body:
### Arrays

```bash
list = [a,b,c,d,e]
```
{: .-setup}

```bash
list[1]                 // → b
list.indexOf(b)         // → 1
list.lastIndexOf(b)     // → 1
list.includes(b)        // → true
```

### Subsets

#### Immutable

```bash
list.slice(0,1)         // → [a        ]
list.slice(1)           // → [  b,c,d,e]
list.slice(1,2)         // → [  b      ]
```

#### Mutative

```bash
re = list.splice(1)     // re = [b,c,d,e]  list == [a]
re = list.splice(1,2)   // re = [b,c]      list == [a,d,e]
```

### Adding items

#### Immutable

```bash
list.concat([X,Y])      // → [_,_,_,_,_,X,Y]
```

#### Mutative

```bash
list.push(X)            // list == [_,_,_,_,_,X]
list.unshift(X)         // list == [X,_,_,_,_,_]
list.splice(2, 0, X)    // list == [_,_,X,_,_,_]
```

### Inserting

```bash
// after -- [_,_,REF,NEW,_,_]
list.splice(list.indexOf(REF)+1, 0, NEW))
```

```bash
// before -- [_,_,NEW,REF,_,_]
list.splice(list.indexOf(REF), 0, NEW))
```

### Replace items

```bash
list.splice(2, 1, X)    // list == [a,b,X,d,e]
```

### Removing items

```bash
list.pop()              // → e    list == [a,b,c,d]
list.shift()            // → a    list == [b,c,d,e]
list.splice(2, 1)       // → [c]  list == [a,b,d,e]
```

### Iterables

```bash
.filter(n => ...) => array
```

```bash
.forEach(n => ...)
```

```bash
.find(n => ...)  // es6
.findIndex(...)  // es6
```

```bash
.every(n => ...) => Boolean // ie9+
.some(n => ..) => Boolean   // ie9+
```

```bash
.map(n => ...)   // ie9+
.reduce((total, n) => total) // ie9+
.reduceRight(...)
```


id: js-appcache
git_filename: ./js-appcache.md
format: md
field_title: applicationCache
field_category: JavaScript
data:
{"title": "applicationCache", "category": "JavaScript", "body": "## Reference\n{: .-one-column}\n\n### applicationCache checking\n\n```js\nif (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\nThis is a deprecated HTML feature. See: [Using the application cache](https://developer.mozilla.org/en-US/docs/HTML/Using_the_application_cache) _(developer.mozilla.org)_"}

field_body:
## Reference
{: .-one-column}

### applicationCache checking

```js
if (window.applicationCache) {
  // "Naturally" reload when an update is available
  var reload = false

  window.applicationCache.addEventListener('updateready', () => {
    if (window.applicationCache.status === window.applicationCache.UPDATEREADY) {
      window.applicationCache.swapCache()
      reload = true
    }
  }, false)

  setInterval(() => {
    try {
      // There's nothing to update for first-time load, browser freaks out :/
      window.applicationCache.update()
    } catch (e) { }
  }, 1000 * 60 * 60) // Every hour
}
```

This is a deprecated HTML feature. See: [Using the application cache](https://developer.mozilla.org/en-US/docs/HTML/Using_the_application_cache) _(developer.mozilla.org)_


id: jquery
git_filename: ./jquery.md
format: md
field_title: jQuery
field_category: JavaScript libraries
field_tags: WIP
data:
{"title": "jQuery", "category": "JavaScript libraries", "tags": ["WIP"], "weight": -1, "body": "### Traversing\n\n```js\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```js\n$.expr[':'].inline = function (el) {\n  return $(el).css('display') === 'inline'\n}\n```\n\nEnables `$(':inline')`\n\n### Extend CSS properties\n\n```js\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```js\n$.fn.step.someWhatever = function(fx) {\n  // ...\n}\n```"}

field_body:
### Traversing

```js
$('.box')
  .children()
  .closest('div')
  .filter(':selected')
  .find('div')
  .has('div')
  .first()
  .next('div')
  .nextUntil('div')
```

## Advanced features

### Extending selectors

```js
$.expr[':'].inline = function (el) {
  return $(el).css('display') === 'inline'
}
```

Enables `$(':inline')`

### Extend CSS properties

```js
$.cssHooks.someCSSProp = {
  get: function (elem, computed, extra) {
  },
  set: function (elem, value) {
  }
}

// Disable "px"
$.cssNumber["someCSSProp"] = true
```

### fn.animate() hooks

```js
$.fn.step.someWhatever = function(fx) {
  // ...
}
```


id: jquery-cdn
git_filename: ./jquery-cdn.md
format: md
field_title: jQuery CDN
field_category: JavaScript libraries
field_tags: Archived
data:
{"title": "jQuery CDN", "category": "JavaScript libraries", "tags": ["Archived"], "body": "### Google jQuery\n\n```html\n<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n```"}

field_body:
### Google jQuery

```html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
```


id: jinja
git_filename: ./jinja.md
format: md
field_title: Jinja
field_category: Python
data:
{"title": "Jinja", "category": "Python", "body": "{% raw %}\n### Basic usage\n\n```\n- variable x has content: {{ x }}\n- expression: {{ x + 1 }}\n- escaped for HTML: {{ x | e }}\n```\n\n### Control structures\n\n```\n{% for x in range(5) %}\n    {% if x % 2 == 0 %}\n        {{ x }} is even!\n    {% else %}\n        {{ x }} is odd!\n    {% endif %}\n{% endfor %}\n```\n\n### Whitespace trimming\n\n```\nthese are\n{{ \"three\" }}\nlines.\n\nthis is conc\n{{- \"at\" -}}\nenated.\n```\n\n### Special blocks\n\n```\n{% filter e %}{% endraw %}\n{ {%- if 0 -%}{%- endif -%} % raw %}\n{%- raw -%}\n    This is a raw block where {{nothing is evaluated}}\n    {% not even this %}\n    and <html is escaped> too with \"e\" filter\n{% endraw %}\n{ {%- if 0 -%}{%- endif -%} % endraw %}{% raw %}\n{% endfilter %}\n\n{% macro myfunc(x) %}\n    this is a reusable macro, with arguments: {{x}}\n{% endmacro %}\n\n{{ myfunc(42) }}\n\n{#\nthis is a comment\n#}\n```\n\n\n### Inheritance\n\n#### shared.html\n\n```\n<html>\n  <head>\n    <title>{%block title %}{% endblock %}</title>\n  </head>\n  <body>\n    <header><h1>{% block title %}{% endblock %}</h1></header>\n    <main>{% block content %}{% endblock %}</main>\n  </body>\n</html>\n```\n\n#### home.html\n\n```\n{% extends \"shared.html\" %}\n{% block title %}Welcome to my site{% endblock %}\n{% block content %}\nThis is the body\n{% endblock %}\n```\n\n## Library\n\n### Basic usage\n\n```python\nfrom jinja2 import Template\ntemplate = Template('Hello {{ name }}!')\ntemplate.render(name='John Doe') == u'Hello John Doe!'\n```\n\n{% endraw %}"}

field_body:
{% raw %}
### Basic usage

```
- variable x has content: {{ x }}
- expression: {{ x + 1 }}
- escaped for HTML: {{ x | e }}
```

### Control structures

```
{% for x in range(5) %}
    {% if x % 2 == 0 %}
        {{ x }} is even!
    {% else %}
        {{ x }} is odd!
    {% endif %}
{% endfor %}
```

### Whitespace trimming

```
these are
{{ "three" }}
lines.

this is conc
{{- "at" -}}
enated.
```

### Special blocks

```
{% filter e %}{% endraw %}
{ {%- if 0 -%}{%- endif -%} % raw %}
{%- raw -%}
    This is a raw block where {{nothing is evaluated}}
    {% not even this %}
    and <html is escaped> too with "e" filter
{% endraw %}
{ {%- if 0 -%}{%- endif -%} % endraw %}{% raw %}
{% endfilter %}

{% macro myfunc(x) %}
    this is a reusable macro, with arguments: {{x}}
{% endmacro %}

{{ myfunc(42) }}

{#
this is a comment
#}
```


### Inheritance

#### shared.html

```
<html>
  <head>
    <title>{%block title %}{% endblock %}</title>
  </head>
  <body>
    <header><h1>{% block title %}{% endblock %}</h1></header>
    <main>{% block content %}{% endblock %}</main>
  </body>
</html>
```

#### home.html

```
{% extends "shared.html" %}
{% block title %}Welcome to my site{% endblock %}
{% block content %}
This is the body
{% endblock %}
```

## Library

### Basic usage

```python
from jinja2 import Template
template = Template('Hello {{ name }}!')
template.render(name='John Doe') == u'Hello John Doe!'
```

{% endraw %}


id: jest
git_filename: ./jest.md
format: md
field_title: Jest
field_category: JavaScript libraries
field_tags: Featurable
field_updated: 2020-06-17
field_updated___timezone: UTC
data:
{"title": "Jest", "category": "JavaScript libraries", "updated": "2020-06-17", "weight": -3, "tags": ["Featurable"], "intro": "A quick overview to [Jest](https://facebook.github.io/jest/), a test framework for Node.js. This guide targets Jest v20.\n", "body": "Testing\n-------\n{: .-three-column}\n\n### Quick start\n{: .-prime}\n\n```bash\nnpm install --save-dev jest babel-jest\n```\n{: data-line=\"1\"}\n\n```js\n/* Add to package.json */\n\"scripts\": {\n  \"test\": \"jest\"\n}\n```\n\n```bash\n# Run your tests\nnpm test -- --watch\n```\n\nSee: [Getting started](https://facebook.github.io/jest/docs/en/getting-started.html)\n\n### Writing tests\n\n```js\ndescribe('My work', () => {\n  test('works', () => {\n    expect(2).toEqual(2)\n  })\n})\n```\n\nSee: [describe()](https://facebook.github.io/jest/docs/en/api.html#describename-fn), [test()](https://facebook.github.io/jest/docs/en/api.html#testname-fn), [expect()](https://facebook.github.io/jest/docs/en/expect.html#content)\n\n### BDD syntax\n\n```js\ndescribe('My work', () => {\n  it('works', () => {\n    \u00b7\u00b7\u00b7\n  })\n})\n```\n\n`it` is an alias for `test`.\nSee: [test()](https://facebook.github.io/jest/docs/en/api.html#testname-fn)\n\n### Setup\n\n```js\nbeforeEach(() => { ... })\nafterEach(() => { ... })\n```\n\n```js\nbeforeAll(() => { ... })\nafterAll(() => { ... })\n```\n\nSee: [afterAll() and more](https://facebook.github.io/jest/docs/en/api.html#afterallfn)\n\n### Focusing tests\n\n```js\ndescribe.only(\u00b7\u00b7\u00b7)\nit.only(\u00b7\u00b7\u00b7) // alias: fit()\n```\n\nSee: [test.only](https://facebook.github.io/jest/docs/en/api.html#testonlyname-fn)\n\n\n### Skipping tests\n\n```js\ndescribe.skip(\u00b7\u00b7\u00b7)\nit.skip(\u00b7\u00b7\u00b7) // alias: xit()\n```\n\nSee: [test.skip](https://facebook.github.io/jest/docs/en/api.html#testskipname-fn)\n\n\n### Optional flags\n\n| Flag                  | Description                              |\n| --------------------- | ---------------------------------------- |\n| `--coverage`          | See a summary of test coverage           |\n| `--detectOpenHandles` | See a summary of ports that didn't close |\n| `--runInBand`         | Run all tests one after the other        |\n\nExpect\n------\n{: .-three-column}\n\n### Basic expectations\n\n```js\nexpect(value)\n  .not\n  .toBe(value)\n  .toEqual(value)\n  .toBeTruthy()\n```\n\nNote that `toEqual` is a deep equality check.\nSee: [expect()](https://facebook.github.io/jest/docs/en/expect.html#expectvalue)\n\n### Snapshots\n\n```js\nexpect(value)\n  .toMatchSnapshot()\n  .toMatchInlineSnapshot()\n```\n\nNote that `toMatchInlineSnapshot()` requires Prettier to be set up for the project.\nSee: [Inline snapshots](https://jestjs.io/docs/en/snapshot-testing#inline-snapshots)\n\n### Errors\n\n```js\nexpect(value)\n  .toThrow(error)\n  .toThrowErrorMatchingSnapshot()\n```\n\n### Booleans\n\n```js\nexpect(value)\n  .toBeFalsy()\n  .toBeNull()\n  .toBeTruthy()\n  .toBeUndefined()\n  .toBeDefined()\n```\n\n### Numbers\n\n```js\nexpect(value)\n  .toBeCloseTo(number, numDigits)\n  .toBeGreaterThan(number)\n  .toBeGreaterThanOrEqual(number)\n  .toBeLessThan(number)\n  .toBeLessThanOrEqual(number)\n```\n\n### Objects\n\n```js\nexpect(value)\n  .toBeInstanceOf(Class)\n  .toMatchObject(object)\n  .toHaveProperty(keyPath, value)\n```\n\n### Objects\n\n```js\nexpect(value)\n  .toContain(item)\n  .toContainEqual(item)\n  .toHaveLength(number)\n```\n\n### Strings\n\n```js\nexpect(value)\n  .toMatch(regexpOrString)\n```\n\n### Others\n\n```js\nexpect.extend(matchers)\nexpect.any(constructor)\nexpect.addSnapshotSerializer(serializer)\n\nexpect.assertions(1)\n```\n\nMore features\n-------------\n\n### Asynchronous tests\n\n```js\ntest('works with promises', () => {\n  return new Promise((resolve, reject) => {\n    \u00b7\u00b7\u00b7\n  })\n})\n```\n{: data-line=\"2\"}\n\n```js\ntest('works with async/await', async () => {\n  const hello = await foo()\n  \u00b7\u00b7\u00b7\n})\n```\n{: data-line=\"2\"}\n\nReturn promises, or use async/await.\nSee: [Async tutorial](https://facebook.github.io/jest/docs/en/tutorial-async.html)\n\n### Snapshots\n\n```jsx\nit('works', () => {\n  const output = something()\n  expect(output).toMatchSnapshot()\n})\n```\n{: data-line=\"3\"}\n\nFirst run creates a snapshot. Subsequent runs match the saved snapshot.\nSee: [Snapshot testing](https://facebook.github.io/jest/docs/en/snapshot-testing.html)\n\n### React test renderer\n\n```jsx\nimport renderer from 'react-test-renderer'\n```\n{: .-setup}\n\n```jsx\nit('works', () => {\n  const tree = renderer.create(\n    <Link page=\"https://www.facebook.com\">Facebook</Link>\n  ).toJSON()\n\n  expect(tree).toMatchSnapshot()\n})\n```\n{: data-line=\"2,3,4\"}\n\nReact's test renderer can be used for Jest snapshots.\nSee: [Snapshot test](https://facebook.github.io/jest/docs/en/tutorial-react-native.html#snapshot-test)\n\n### Timers\n\n```js\njest.useFakeTimers()\n```\n\n```js\nit('works', () => {\n  jest.runOnlyPendingTimers()\n  jest.runTimersToTime(1000)\n  jest.runAllTimers()\n})\n```\n\nSee: [Timer Mocks](https://facebook.github.io/jest/docs/en/timer-mocks.html)\n\n## Mock functions\n\n### Mock functions\n\n```js\nconst fn = jest.fn()\n```\n\n```js\nconst fn = jest.fn(n => n * n)\n```\n\nSee: [Mock functions](https://facebook.github.io/jest/docs/en/mock-functions.html#using-a-mock-function)\n\n### Assertions\n\n```js\nexpect(fn)\n  .toHaveBeenCalled()\n  .toHaveBeenCalledTimes(number)\n  .toHaveBeenCalledWith(arg1, arg2, ...)\n  .toHaveBeenLastCalledWith(arg1, arg2, ...)\n```\n\n```js\nexpect(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```js\nconst Fn = jest.fn()\n\na = new Fn()\nb = new Fn()\n```\n\n```js\nFn.mock.instances\n// \u2192 [a, b]\n```\n{: data-line=\"1\"}\n\nSee: [.mock property](https://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)\n\n### Calls\n\n```js\nconst fn = jest.fn()\nfn(123)\nfn(456)\n```\n\n```js\nfn.mock.calls.length   // \u2192 2\nfn.mock.calls[0][0]    // \u2192 123\nfn.mock.calls[1][0]    // \u2192 456\n```\n{: data-line=\"1,2,3\"}\n\nSee: [.mock property](https://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)\n\n### Return values\n\n```js\nconst fn = jest.fn(() => 'hello')\n```\n\n#### or:\n\n```js\njest.fn().mockReturnValue('hello')\njest.fn().mockReturnValueOnce('hello')\n```\n\n### Mock implementations\n\n```js\nconst fn = jest.fn()\n  .mockImplementationOnce(() => 1)\n  .mockImplementationOnce(() => 2)\n```\n{: data-line=\"2,3\"}\n\n```js\nfn()    // \u2192 1\nfn()    // \u2192 2\n```\n\n## References\n{: .-one-column}\n\n- <https://facebook.github.io/jest/>\n{: .-also-see}"}

field_intro:
A quick overview to [Jest](https://facebook.github.io/jest/), a test framework for Node.js. This guide targets Jest v20.

field_body:
Testing
-------
{: .-three-column}

### Quick start
{: .-prime}

```bash
npm install --save-dev jest babel-jest
```
{: data-line="1"}

```js
/* Add to package.json */
"scripts": {
  "test": "jest"
}
```

```bash
# Run your tests
npm test -- --watch
```

See: [Getting started](https://facebook.github.io/jest/docs/en/getting-started.html)

### Writing tests

```js
describe('My work', () => {
  test('works', () => {
    expect(2).toEqual(2)
  })
})
```

See: [describe()](https://facebook.github.io/jest/docs/en/api.html#describename-fn), [test()](https://facebook.github.io/jest/docs/en/api.html#testname-fn), [expect()](https://facebook.github.io/jest/docs/en/expect.html#content)

### BDD syntax

```js
describe('My work', () => {
  it('works', () => {
    ···
  })
})
```

`it` is an alias for `test`.
See: [test()](https://facebook.github.io/jest/docs/en/api.html#testname-fn)

### Setup

```js
beforeEach(() => { ... })
afterEach(() => { ... })
```

```js
beforeAll(() => { ... })
afterAll(() => { ... })
```

See: [afterAll() and more](https://facebook.github.io/jest/docs/en/api.html#afterallfn)

### Focusing tests

```js
describe.only(···)
it.only(···) // alias: fit()
```

See: [test.only](https://facebook.github.io/jest/docs/en/api.html#testonlyname-fn)


### Skipping tests

```js
describe.skip(···)
it.skip(···) // alias: xit()
```

See: [test.skip](https://facebook.github.io/jest/docs/en/api.html#testskipname-fn)


### Optional flags

| Flag                  | Description                              |
| --------------------- | ---------------------------------------- |
| `--coverage`          | See a summary of test coverage           |
| `--detectOpenHandles` | See a summary of ports that didn't close |
| `--runInBand`         | Run all tests one after the other        |

Expect
------
{: .-three-column}

### Basic expectations

```js
expect(value)
  .not
  .toBe(value)
  .toEqual(value)
  .toBeTruthy()
```

Note that `toEqual` is a deep equality check.
See: [expect()](https://facebook.github.io/jest/docs/en/expect.html#expectvalue)

### Snapshots

```js
expect(value)
  .toMatchSnapshot()
  .toMatchInlineSnapshot()
```

Note that `toMatchInlineSnapshot()` requires Prettier to be set up for the project.
See: [Inline snapshots](https://jestjs.io/docs/en/snapshot-testing#inline-snapshots)

### Errors

```js
expect(value)
  .toThrow(error)
  .toThrowErrorMatchingSnapshot()
```

### Booleans

```js
expect(value)
  .toBeFalsy()
  .toBeNull()
  .toBeTruthy()
  .toBeUndefined()
  .toBeDefined()
```

### Numbers

```js
expect(value)
  .toBeCloseTo(number, numDigits)
  .toBeGreaterThan(number)
  .toBeGreaterThanOrEqual(number)
  .toBeLessThan(number)
  .toBeLessThanOrEqual(number)
```

### Objects

```js
expect(value)
  .toBeInstanceOf(Class)
  .toMatchObject(object)
  .toHaveProperty(keyPath, value)
```

### Objects

```js
expect(value)
  .toContain(item)
  .toContainEqual(item)
  .toHaveLength(number)
```

### Strings

```js
expect(value)
  .toMatch(regexpOrString)
```

### Others

```js
expect.extend(matchers)
expect.any(constructor)
expect.addSnapshotSerializer(serializer)

expect.assertions(1)
```

More features
-------------

### Asynchronous tests

```js
test('works with promises', () => {
  return new Promise((resolve, reject) => {
    ···
  })
})
```
{: data-line="2"}

```js
test('works with async/await', async () => {
  const hello = await foo()
  ···
})
```
{: data-line="2"}

Return promises, or use async/await.
See: [Async tutorial](https://facebook.github.io/jest/docs/en/tutorial-async.html)

### Snapshots

```jsx
it('works', () => {
  const output = something()
  expect(output).toMatchSnapshot()
})
```
{: data-line="3"}

First run creates a snapshot. Subsequent runs match the saved snapshot.
See: [Snapshot testing](https://facebook.github.io/jest/docs/en/snapshot-testing.html)

### React test renderer

```jsx
import renderer from 'react-test-renderer'
```
{: .-setup}

```jsx
it('works', () => {
  const tree = renderer.create(
    <Link page="https://www.facebook.com">Facebook</Link>
  ).toJSON()

  expect(tree).toMatchSnapshot()
})
```
{: data-line="2,3,4"}

React's test renderer can be used for Jest snapshots.
See: [Snapshot test](https://facebook.github.io/jest/docs/en/tutorial-react-native.html#snapshot-test)

### Timers

```js
jest.useFakeTimers()
```

```js
it('works', () => {
  jest.runOnlyPendingTimers()
  jest.runTimersToTime(1000)
  jest.runAllTimers()
})
```

See: [Timer Mocks](https://facebook.github.io/jest/docs/en/timer-mocks.html)

## Mock functions

### Mock functions

```js
const fn = jest.fn()
```

```js
const fn = jest.fn(n => n * n)
```

See: [Mock functions](https://facebook.github.io/jest/docs/en/mock-functions.html#using-a-mock-function)

### Assertions

```js
expect(fn)
  .toHaveBeenCalled()
  .toHaveBeenCalledTimes(number)
  .toHaveBeenCalledWith(arg1, arg2, ...)
  .toHaveBeenLastCalledWith(arg1, arg2, ...)
```

```js
expect(fn)
  .toHaveBeenCalledWith(expect.anything())
  .toHaveBeenCalledWith(expect.any(constructor))
  .toHaveBeenCalledWith(expect.arrayContaining([ values ]))
  .toHaveBeenCalledWith(expect.objectContaining({ props }))
  .toHaveBeenCalledWith(expect.stringContaining(string))
  .toHaveBeenCalledWith(expect.stringMatching(regexp))
```

### Instances

```js
const Fn = jest.fn()

a = new Fn()
b = new Fn()
```

```js
Fn.mock.instances
// → [a, b]
```
{: data-line="1"}

See: [.mock property](https://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)

### Calls

```js
const fn = jest.fn()
fn(123)
fn(456)
```

```js
fn.mock.calls.length   // → 2
fn.mock.calls[0][0]    // → 123
fn.mock.calls[1][0]    // → 456
```
{: data-line="1,2,3"}

See: [.mock property](https://facebook.github.io/jest/docs/en/mock-functions.html#mock-property)

### Return values

```js
const fn = jest.fn(() => 'hello')
```

#### or:

```js
jest.fn().mockReturnValue('hello')
jest.fn().mockReturnValueOnce('hello')
```

### Mock implementations

```js
const fn = jest.fn()
  .mockImplementationOnce(() => 1)
  .mockImplementationOnce(() => 2)
```
{: data-line="2,3"}

```js
fn()    // → 1
fn()    // → 2
```

## References
{: .-one-column}

- <https://facebook.github.io/jest/>
{: .-also-see}


id: jekyll
git_filename: ./jekyll.md
format: md
field_title: Jekyll
field_category: Jekyll
field_prism_languages: bash, yaml, ruby
field_updated: 2018-08-25
field_updated___timezone: UTC
data:
{"title": "Jekyll", "jekyll_escape": true, "prism_languages": ["bash", "yaml", "ruby"], "category": "Jekyll", "updated": "2018-08-25", "body": "{% raw %}\n\n### Installation\n\n```bash\n# Install the gems\ngem install jekyll bundler\n```\n\n```bash\n# Create a new site at `./myblog`\njekyll new myblog\ncd myblog\n```\n\n```bash\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```bash\nbundle exec jekyll serve\n```\n\nSee: [Jekyll quickstart](https://jekyllrb.com/docs/quickstart/)<br>\nSee: [github/pages-gem](https://github.com/github/pages-gem)\n\n### Directories\n\n```\n./\n\u251c\u2500\u2500 _config.yml\n\u2502\n\u251c\u2500\u2500 _data/\n\u2502   \u2514\u2500\u2500 ...\n\u2502\n\u251c\u2500\u2500 _drafts/\n\u2502   \u2514\u2500\u2500 ...\n\u2502\n\u251c\u2500\u2500 _posts/\n\u2502   \u2514\u2500\u2500 2014-01-01-hello.md\n\u2502\n\u251c\u2500\u2500 _layouts/\n\u2502   \u251c\u2500\u2500 default.html\n\u2502   \u2514\u2500\u2500 post.html\n\u2502\n\u251c\u2500\u2500 _includes/             - partials\n\u2502   \u251c\u2500\u2500 header.html\n\u2502   \u2514\u2500\u2500 footer.html\n\u2502\n\u2514\u2500\u2500 _site/\n    \u2514\u2500\u2500 ...\n```\n{: .-box-chars}\n\n## Front-matter\n{: .-three-column}\n\n### Basic frontmatter\n\n```\n---\nlayout: post\ntitle: Hello\n---\nHello! this is my post.\n```\n{: data-line=\"1,2,3,4\"}\n\nAttach metadata to a page by adding them on top of the page, delimited by `---`.\nSee: [Front-matter](https://jekyllrb.com/docs/frontmatter/)\n\n### Other frontmatter stuff\n\n```yaml\npermalink: '/hello'\npublished: false\ncategory: apple\ncategories: ['html', 'css']\ntags: ['html', 'css']\n```\n\n### Configuration\n\nIn `_config.yml`:\n{: .-setup}\n\n```yaml\nsource: .\ndestination: _site\nexclude:\n- Gemfile\n- Gemfile.lock\ninclude: ['.htaccess']\n```\n\nAll config keys are optional.\nSee: [Configuration](https://jekyllrb.com/docs/configuration/)\n\nMarkup\n------\n{: .-three-column}\n\n### Page variables\n\n```html\n<title>\n  {{ page.title }}\n</title>\n```\n{: data-line=\"2\"}\n\n\n### Filters\n\n```html\n<p>\n  {{ page.description | truncate_words: 20 }}\n</p>\n```\n{: data-line=\"2\"}\n\n### Loops\n\n```html\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{: data-line=\"1,6\"}\n\n### Dates\n\n```html\n{{ page.date | date: \"%b %d, %Y\" }}\n```\n\n### Conditionals\n\n```html\n{% if page.image.feature %}\n  ...\n{% elsif xyz %}\n  ...\n{% else %}\n  ...\n{% endif %}\n```\n{: data-line=\"1,3,5,7 }\n\n```html\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```html\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{: data-line=\"1,2,4,6,8\"}\n\n### Includes (partials)\n\n```\n{% include header.html %}\n```\n{: data-line=\"1\"}\n\n```html\n<!-- Including local vars -->\n{% include header.html page=page %}\n```\n{: data-line=\"2\"}\n\n### Comments\n\n```html\n{% comment %}\n  This is a comment!\n{% endcomment %}\n```\n{: data-line=\"1,3\"}\n\n## Variables\n\n### Top-level variables\n\n\n| `{{ site }}` | Data from `config.yml` |\n| `{{ page }}` | From frontmatter, and page-specific info |\n| `{{ content }}` | HTML content (use in layouts) |\n| `{{ paginator }}` | Paginator |\n\nSee: [Variables](https://jekyllrb.com/docs/variables/)\n\n### Site\n\n```html\n{{ site.time }}\n```\n{: .-setup}\n\n| `site.time` | Current time |\n| `site.pages` | List of pages |\n| `site.posts` | List of blog posts |\n| `site.related_posts` | List of posts related to current |\n| `site.categories.CATEGORY` | List |\n| `site.tags.TAG` | List |\n| `site.static_files` | List |\n\n### Page\n\n```html\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```html\n<!-- blog pagination: -->\n{{ page.next }}\n{{ page.previous }}\n```\n\nFilters\n-------\n{: .-three-column}\n\n### Dates\n\n```ruby\n{{ site.time | date: \"%Y %m %d\" }}\n```\n{: .-setup}\n\n| `date_to_xmlschema` | \u2192 `2008-11-07T13:07:54-08:00` |\n| `date_to_rfc822` | \u2192 `Mon, 07 Nov 2008 13:07:54 -0800` |\n| `date_to_string` | \u2192 `07 Nov 2008` |\n| `date_to_long_string` | \u2192 `07 November 2008` |\n| `date:` _'%Y %m %d'_ | \u2192 `2017 Nov  7` |\n\n### Preprocessors\n\n\n```ruby\n{{ page.description | markdownify }}\n```\n{: .-setup}\n\n| Filter | Description |\n| --- | --- |\n| `textilize` | Textile |\n| `markdownify` | Markdown |\n| `jsonify` | JSON |\n| `sassify` | Sass |\n| `scssify` | SCSS |\n| `smartify` | Smartypants |\n\n### Array filters\n\n```ruby\n{{ site.pages | where: \"year\", \"2014\" }}\n```\n{: .-setup}\n\n| Filter | Description |\n| --- | --- |\n| `where:` _\"year\", \"2014\"_ | |\n| `where_exp:` _\"item\", \"item.year >= 2014\"_ | |\n| --- | --- |\n| `group_by:` _\"genre\"_   | \u2192 `{name, items}` |\n| `group_by_exp:` _\"item\", \"item.genre\"_   | \u2192 `{name, items}` |\n| --- | --- |\n| `sort` | |\n| `sort:` _'author'_ | |\n| --- | --- |\n| `uniq` | |\n| --- | --- |\n| `first` | |\n| `last` | |\n| `join:` _','_ | |\n| `array_to_sentence_string` | \u2192 `\"X, Y and Z\"` |\n| --- | --- |\n| `map:` _'post'_ | Works like 'pluck' |\n| --- | --- |\n| `size` | |\n| `push:` _'xxx'_ | Adds an item |\n\n### String filters\n\n```ruby\n{{ page.title | default: \"xxx\" }}\n```\n{: .-setup}\n\n| Filter                             | Description |\n| ---                                | ---         |\n| `default:` _'xxx'_                 |             |\n| ---                                | ---         |\n| `upcase`                           |             |\n| `downcase`                         |             |\n| ---                                | ---         |\n| `remove:` _'p'_                    |             |\n| `replace:` _'super', 'mega'_       |             |\n| `remove_first:` _'p'_              |             |\n| `replace_first:` _'super', 'mega'_ |             |\n| ---                                | ---         |\n| `truncate:` _5_                    |             |\n| `truncatewords:` _20_              |             |\n| ---                                | ---         |\n| `prepend:` _'Mr. '_                |             |\n| `append:` _'Jr.'_                  |             |\n| ---                                | ---         |\n| `camelize`                         |             |\n| `capitalize`                       |             |\n| `strip_html`                       |             |\n| `strip_newlines`                   |             |\n| `newlines_to_br`                   |             |\n| ---                                | ---         |\n| `split:` _','_                     |             |\n| ---                                | ---         |\n| `escape`                           |             |\n| `escape_once`                      |             |\n| ---                                | ---         |\n| `slice:` _-3, 3_                   |             |\n\nSee: [String filters](https://docs.shopify.com/themes/liquid-documentation/filters)\n\n### String filters (Jekyll-only)\n\n```ruby\n{{ page.excerpt | number_of_words }}\n```\n{: .-setup}\n\n| Filter | Description |\n| --- | --- |\n| `number_of_words` | |\n| `slugify` | |\n| --- | --- |\n| `xml_escape` | \u2192 `CDATA` |\n| `cgi_escape` | \u2192 `foo%2Cbar` |\n| `uri_escape` | \u2192 `foo,%20bar` |\n\n### Numbers\n\n```\n{{ site.posts.size | minus: 2 }}\n```\n{: .-setup}\n\n| Filter | Description |\n| --- | --- |\n| `minus:` _2_ | |\n| `plus:` _2_ | |\n| `times:` _2_ | |\n| `divided_by:` _2_ | |\n| `modulo:` _2_ | |\n| --- | --- |\n| `ceil` | |\n| `floor` | |\n| `round` | |\n\n## Paginator\n\n### Paginator setup\n\nAdd this to `_config.yml`:\n{: .-setup}\n\n```yml\npaginate: 5\npaginate_path: \"blog/:num\"\n```\n\nSee: [Paginator](https://jekyllrb.com/docs/pagination/)\n\n### Numbers\n\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```\n{% for post in paginator.posts %} ... {% endfor %}\n```\n\n### Previous button\n\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```\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\nSee: [Blogging](https://jekyllrb.com/docs/posts/)\n\n### Image paths\n\n    ![My helpful screenshot]({{ site.url }}/assets/screenshot.jpg)\n\nSee: [Image paths](https://jekyllrb.com/docs/posts/#including-images-and-resources)\n\n### Drafts\n\n    vi _drafts/a-draft-post.md\n    jekyll build --drafts\n\nPosts in `_drafts` only show up in development, but not production.\nSee: [Drafts](https://jekyllrb.com/docs/drafts/)\n\n### Defining excerpts\n\n```\n---\ntitle: My blog post\nexcerpt: This post is about cats\n---\n\nHello, let's talk about cats. (\u00b7\u00b7\u00b7)\n```\n\nPut a key `excerpt` in the frontmatter.\nSee: [Excerpts](https://jekyllrb.com/docs/posts/#post-excerpts)\n\n### Displaying excerpts\n\n```html\n{{ post.excerpt }}\n```\n\n```html\n{{ post.excerpt | remove: '<p>' | remove: '</p>' }}\n{{ post.excerpt | strip_html }}\n```\n\n### Excerpt separator\n\n```html\n---\nexcerpt_separator: <!--more-->\n---\n\nExcerpt here\n<!--more-->\nMore post body here\n```\n\nAlternatively, you can put excerpts inline in your post by defining `excerpt_separator`.\n\n### Permalinks\n\n    # _config.yml\n    permalink: date   # /:categories/:year/:month/:day/:title.html\n    permalink: pretty # /:categories/:year/:month/:day/:title/\n    permalink: none   # /:categories/:title.html\n    permalink: \"/:title\"\n\nSee: [Permalinks](https://jekyllrb.com/docs/permalinks/)\n\n## More features\n\n### Data\n\n```\n_data/members.yml\n```\n{: .-setup}\n\n```\n{% for member in site.data.members %}\n  ...\n{% endfor %}\n```\n\nSee: [Data](https://jekyllrb.com/docs/datafiles/)\n\n### Collections\n\n```yml\n# _config.yml\ncollections:\n  - authors\n```\n{: .-setup}\n\n```yml\n# _/authors/a-n-roquelaire.md\n---\nname: A. N. Roquelaire\nreal_name: Anne Rice\n---\n```\n\n```\n{% for author in site.authors %}\n```\n\nSee: [Collections](https://jekyllrb.com/docs/collections/)\n\n### Code highlighter\n\n```html\n{% highlight ruby linenos %}\ndef show\n  ...\nend\n{% endhighlight %}\n```\n\nIntegration\n-----------\n\n### Bundler\n\nIn `_plugins/bundler.rb`:\n{: .-setup}\n\n```ruby\nrequire \"bunder/setup\"\nBundler.require :default\n```\n\n### Compass\n\n  * [Compass](https://gist.github.com/parkr/2874934)\n  * [Asset pipeline](https://github.com/matthodan/jekyll-asset-pipeline)\n\nAlso see\n--------\n{: .-one-column}\n\n* [Jekyll docs](https://jekyllrb.com/docs/home/) _jekyllrb.com_\n* [CloudCannon Jekyll cheatsheet](https://learn.cloudcannon.com/jekyll-cheat-sheet/) _cloudcannon.com_\n* [Jekyll: templates](https://jekyllrb.com/docs/templates/) _jekyllrb.com_\n* [Liquid: output](https://docs.shopify.com/themes/liquid-basics/output) _shopify.com_\n* [Liquid: logic](https://docs.shopify.com/themes/liquid-basics/logic) _shopify.com_\n* [Liquid: filters](https://docs.shopify.com/themes/liquid-documentation/filters) _shopify.com_\n* [Liquid for designers](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers) _github.com/Shopify_\n{: .-also-see}\n\n{% endraw %}"}

field_body:
{% raw %}

### Installation

```bash
# Install the gems
gem install jekyll bundler
```

```bash
# Create a new site at `./myblog`
jekyll new myblog
cd myblog
```

```bash
# Optional: if you're targeting github-pages,
# use this Gemfile instead.
cat > Gemfile <<-END
source 'https://rubygems.org'
gem 'github-pages', group: :jekyll_plugins
END
```

```bash
bundle exec jekyll serve
```

See: [Jekyll quickstart](https://jekyllrb.com/docs/quickstart/)<br>
See: [github/pages-gem](https://github.com/github/pages-gem)

### Directories

```
./
├── _config.yml
│
├── _data/
│   └── ...
│
├── _drafts/
│   └── ...
│
├── _posts/
│   └── 2014-01-01-hello.md
│
├── _layouts/
│   ├── default.html
│   └── post.html
│
├── _includes/             - partials
│   ├── header.html
│   └── footer.html
│
└── _site/
    └── ...
```
{: .-box-chars}

## Front-matter
{: .-three-column}

### Basic frontmatter

```
---
layout: post
title: Hello
---
Hello! this is my post.
```
{: data-line="1,2,3,4"}

Attach metadata to a page by adding them on top of the page, delimited by `---`.
See: [Front-matter](https://jekyllrb.com/docs/frontmatter/)

### Other frontmatter stuff

```yaml
permalink: '/hello'
published: false
category: apple
categories: ['html', 'css']
tags: ['html', 'css']
```

### Configuration

In `_config.yml`:
{: .-setup}

```yaml
source: .
destination: _site
exclude:
- Gemfile
- Gemfile.lock
include: ['.htaccess']
```

All config keys are optional.
See: [Configuration](https://jekyllrb.com/docs/configuration/)

Markup
------
{: .-three-column}

### Page variables

```html
<title>
  {{ page.title }}
</title>
```
{: data-line="2"}


### Filters

```html
<p>
  {{ page.description | truncate_words: 20 }}
</p>
```
{: data-line="2"}

### Loops

```html
{% for post in site.posts %}
  <a href="{{ post.url }}">
    <h2>{{ post.title }}</h2>
    <p>{{ post.date | date_to_string }}</p>
  </a>
{% endfor %}
```
{: data-line="1,6"}

### Dates

```html
{{ page.date | date: "%b %d, %Y" }}
```

### Conditionals

```html
{% if page.image.feature %}
  ...
{% elsif xyz %}
  ...
{% else %}
  ...
{% endif %}
```
{: data-line="1,3,5,7 }

```html
{% if page.category == 'React' %}
{% if page.category == 'React' or page.featured %}
{% if page.tags contains 'Featured' %}
```

### Case

```html
{% case shipping.title %}
  {% when 'international' %}
     Arriving in 2-3 weeks
  {% when 'Domestic' %}
     Arriving in 2-3 days
  {% else %}
     Thank you for your order!
{% endcase %}
```
{: data-line="1,2,4,6,8"}

### Includes (partials)

```
{% include header.html %}
```
{: data-line="1"}

```html
<!-- Including local vars -->
{% include header.html page=page %}
```
{: data-line="2"}

### Comments

```html
{% comment %}
  This is a comment!
{% endcomment %}
```
{: data-line="1,3"}

## Variables

### Top-level variables


| `{{ site }}` | Data from `config.yml` |
| `{{ page }}` | From frontmatter, and page-specific info |
| `{{ content }}` | HTML content (use in layouts) |
| `{{ paginator }}` | Paginator |

See: [Variables](https://jekyllrb.com/docs/variables/)

### Site

```html
{{ site.time }}
```
{: .-setup}

| `site.time` | Current time |
| `site.pages` | List of pages |
| `site.posts` | List of blog posts |
| `site.related_posts` | List of posts related to current |
| `site.categories.CATEGORY` | List |
| `site.tags.TAG` | List |
| `site.static_files` | List |

### Page

```html
{{ page.content }}  - un-rendered content
{{ page.title }}
{{ page.excerpt }}  - un-rendered excerpt
{{ page.url }}
{{ page.date }}
{{ page.id }}       - unique id for RSS feeds
{{ page.categories }}
{{ page.tags }}
{{ page.path }}
{{ page.dir }}
{{ page.excerpt | remove: '<p>' | remove: '</p>' }}
{{ page.excerpt | strip_html }}
```

```html
<!-- blog pagination: -->
{{ page.next }}
{{ page.previous }}
```

Filters
-------
{: .-three-column}

### Dates

```ruby
{{ site.time | date: "%Y %m %d" }}
```
{: .-setup}

| `date_to_xmlschema` | → `2008-11-07T13:07:54-08:00` |
| `date_to_rfc822` | → `Mon, 07 Nov 2008 13:07:54 -0800` |
| `date_to_string` | → `07 Nov 2008` |
| `date_to_long_string` | → `07 November 2008` |
| `date:` _'%Y %m %d'_ | → `2017 Nov  7` |

### Preprocessors


```ruby
{{ page.description | markdownify }}
```
{: .-setup}

| Filter | Description |
| --- | --- |
| `textilize` | Textile |
| `markdownify` | Markdown |
| `jsonify` | JSON |
| `sassify` | Sass |
| `scssify` | SCSS |
| `smartify` | Smartypants |

### Array filters

```ruby
{{ site.pages | where: "year", "2014" }}
```
{: .-setup}

| Filter | Description |
| --- | --- |
| `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 |

### String filters

```ruby
{{ page.title | default: "xxx" }}
```
{: .-setup}

| Filter                             | Description |
| ---                                | ---         |
| `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_                   |             |

See: [String filters](https://docs.shopify.com/themes/liquid-documentation/filters)

### String filters (Jekyll-only)

```ruby
{{ page.excerpt | number_of_words }}
```
{: .-setup}

| Filter | Description |
| --- | --- |
| `number_of_words` | |
| `slugify` | |
| --- | --- |
| `xml_escape` | → `CDATA` |
| `cgi_escape` | → `foo%2Cbar` |
| `uri_escape` | → `foo,%20bar` |

### Numbers

```
{{ site.posts.size | minus: 2 }}
```
{: .-setup}

| Filter | Description |
| --- | --- |
| `minus:` _2_ | |
| `plus:` _2_ | |
| `times:` _2_ | |
| `divided_by:` _2_ | |
| `modulo:` _2_ | |
| --- | --- |
| `ceil` | |
| `floor` | |
| `round` | |

## Paginator

### Paginator setup

Add this to `_config.yml`:
{: .-setup}

```yml
paginate: 5
paginate_path: "blog/:num"
```

See: [Paginator](https://jekyllrb.com/docs/pagination/)

### Numbers

```
{{ paginator.page }}         - page number
{{ paginator.total_posts }}
{{ paginator.total_pages }}
{{ paginator.per_page }}
```

### Iterating through posts

```
{% for post in paginator.posts %} ... {% endfor %}
```

### Previous button

```
{% if paginator.total_pages > 1 %}
  {% if paginator.previous_page %}
    <a href="{{ paginator.previous_page_path }}">Previous</a>
  {% else %}
  {% endif %}
{% endif %}
```

```
{{ paginator.next_page }}     - page number
{{ paginator.next_page_path }}
```

## Blogging

### Paths

    _posts/YEAR-MONTH-DAY-title.md

See: [Blogging](https://jekyllrb.com/docs/posts/)

### Image paths

    ![My helpful screenshot]({{ site.url }}/assets/screenshot.jpg)

See: [Image paths](https://jekyllrb.com/docs/posts/#including-images-and-resources)

### Drafts

    vi _drafts/a-draft-post.md
    jekyll build --drafts

Posts in `_drafts` only show up in development, but not production.
See: [Drafts](https://jekyllrb.com/docs/drafts/)

### Defining excerpts

```
---
title: My blog post
excerpt: This post is about cats
---

Hello, let's talk about cats. (···)
```

Put a key `excerpt` in the frontmatter.
See: [Excerpts](https://jekyllrb.com/docs/posts/#post-excerpts)

### Displaying excerpts

```html
{{ post.excerpt }}
```

```html
{{ post.excerpt | remove: '<p>' | remove: '</p>' }}
{{ post.excerpt | strip_html }}
```

### Excerpt separator

```html
---
excerpt_separator: <!--more-->
---

Excerpt here
<!--more-->
More post body here
```

Alternatively, you can put excerpts inline in your post by defining `excerpt_separator`.

### Permalinks

    # _config.yml
    permalink: date   # /:categories/:year/:month/:day/:title.html
    permalink: pretty # /:categories/:year/:month/:day/:title/
    permalink: none   # /:categories/:title.html
    permalink: "/:title"

See: [Permalinks](https://jekyllrb.com/docs/permalinks/)

## More features

### Data

```
_data/members.yml
```
{: .-setup}

```
{% for member in site.data.members %}
  ...
{% endfor %}
```

See: [Data](https://jekyllrb.com/docs/datafiles/)

### Collections

```yml
# _config.yml
collections:
  - authors
```
{: .-setup}

```yml
# _/authors/a-n-roquelaire.md
---
name: A. N. Roquelaire
real_name: Anne Rice
---
```

```
{% for author in site.authors %}
```

See: [Collections](https://jekyllrb.com/docs/collections/)

### Code highlighter

```html
{% highlight ruby linenos %}
def show
  ...
end
{% endhighlight %}
```

Integration
-----------

### Bundler

In `_plugins/bundler.rb`:
{: .-setup}

```ruby
require "bunder/setup"
Bundler.require :default
```

### Compass

  * [Compass](https://gist.github.com/parkr/2874934)
  * [Asset pipeline](https://github.com/matthodan/jekyll-asset-pipeline)

Also see
--------
{: .-one-column}

* [Jekyll docs](https://jekyllrb.com/docs/home/) _jekyllrb.com_
* [CloudCannon Jekyll cheatsheet](https://learn.cloudcannon.com/jekyll-cheat-sheet/) _cloudcannon.com_
* [Jekyll: templates](https://jekyllrb.com/docs/templates/) _jekyllrb.com_
* [Liquid: output](https://docs.shopify.com/themes/liquid-basics/output) _shopify.com_
* [Liquid: logic](https://docs.shopify.com/themes/liquid-basics/logic) _shopify.com_
* [Liquid: filters](https://docs.shopify.com/themes/liquid-documentation/filters) _shopify.com_
* [Liquid for designers](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers) _github.com/Shopify_
{: .-also-see}

{% endraw %}


id: jekyll-github
git_filename: ./jekyll-github.md
format: md
field_title: Jekyll for GitHub pages
field_category: Jekyll
field_tags: WIP
field_updated: 2017-11-17
field_updated___timezone: UTC
data:
{"title": "Jekyll for GitHub pages", "category": "Jekyll", "tags": ["WIP"], "updated": "2017-11-17", "body": "{% raw %}\n\nJekyll\n------\n{: .-one-column}\n\n* jekyll-avatar\n* jekyll-coffeescript\n* jekyll-default-layout\n* jekyll-feed\n* jekyll-gist\n* jekyll-github-metadata\n* jekyll-mentions\n* jekyll-optional-front-matter\n* jekyll-paginate\n* jekyll-readme-index\n* jekyll-redirect-from\n* jekyll-relative-links\n* jekyll-sass-converter\n* jekyll-seo-tag\n* jekyll-sitemap\n{: .-four-column}\n\nAs of github-pages v156. For an updated list, see: [Dependency versions](https://pages.github.com/versions/) _(pages.github.com)_\n\nGitHub Metadata\n---------------\n\n### Configuration\n\n```yaml\nplugins:\n  - jekyll-github-metadata\n\nrepository: username/project\n```\n\nPut this in your `_config.yml`.\nSee: [Repository metadata on GitHub pages](https://help.github.com/articles/repository-metadata-on-github-pages/)\n\n### Listing repos\n\n```html\n{% for repository in site.github.public_repositories %}\n  <a href='{{ repository.html_url }}'>\n    {{ repository.name }}\n  </a>\n{% endfor %}\n```\n\n### Link to repo\n\n```html\n<a href='{{ site.github.repository_url }}'>\n  {{ site.github.project_title }}\n</a>\n```\n\nGists\n-----\n\n### Configuration\n\n```yaml\nplugins:\n  - jekyll-gist\n```\n\nSee: [jekyll-gist](https://github.com/jekyll/jekyll-gist)\n\n### Usage\n\n```js\n{% gist parkr/c08ee0f2726fd0e3909d %}\n```\n\nThis places a Gist in your page.\n\nMentions\n--------\n\n### Configuration\n\n```yaml\nplugins:\n  - jekyll-mentions\n```\n\nSee: [jekyll-mentions](https://github.com/jekyll/jekyll-mentions)\n\n### Usage\n\n```js\nHey @rstacruz, what do you think of this?\n```\n\nJust mention anyone in any page. Their names will be turned into links.\n\n\nRedirects\n---------\n{: .-three-column}\n\n### Configuration\n\n```yaml\nplugins:\n    - jekyll-redirect-from\n```\n\nSee: [jekyll-redirect-from](https://rubygems.org/gems/jekyll-redirect-from)\n\n### Usage\n\n```yaml\n---\nredirect_from:\n  - /foo\n---\n```\n\nPlace on any page.\n\n### Redirecting\n\n```yaml\n---\nredirect_to:\n  - /foo\n---\n```\n\nPlace on any page.\nSee: [redirect to](https://github.com/jekyll/jekyll-redirect-from#redirect-to)\n\n{% endraw %}"}

field_body:
{% raw %}

Jekyll
------
{: .-one-column}

* jekyll-avatar
* jekyll-coffeescript
* jekyll-default-layout
* jekyll-feed
* jekyll-gist
* jekyll-github-metadata
* jekyll-mentions
* jekyll-optional-front-matter
* jekyll-paginate
* jekyll-readme-index
* jekyll-redirect-from
* jekyll-relative-links
* jekyll-sass-converter
* jekyll-seo-tag
* jekyll-sitemap
{: .-four-column}

As of github-pages v156. For an updated list, see: [Dependency versions](https://pages.github.com/versions/) _(pages.github.com)_

GitHub Metadata
---------------

### Configuration

```yaml
plugins:
  - jekyll-github-metadata

repository: username/project
```

Put this in your `_config.yml`.
See: [Repository metadata on GitHub pages](https://help.github.com/articles/repository-metadata-on-github-pages/)

### Listing repos

```html
{% for repository in site.github.public_repositories %}
  <a href='{{ repository.html_url }}'>
    {{ repository.name }}
  </a>
{% endfor %}
```

### Link to repo

```html
<a href='{{ site.github.repository_url }}'>
  {{ site.github.project_title }}
</a>
```

Gists
-----

### Configuration

```yaml
plugins:
  - jekyll-gist
```

See: [jekyll-gist](https://github.com/jekyll/jekyll-gist)

### Usage

```js
{% gist parkr/c08ee0f2726fd0e3909d %}
```

This places a Gist in your page.

Mentions
--------

### Configuration

```yaml
plugins:
  - jekyll-mentions
```

See: [jekyll-mentions](https://github.com/jekyll/jekyll-mentions)

### Usage

```js
Hey @rstacruz, what do you think of this?
```

Just mention anyone in any page. Their names will be turned into links.


Redirects
---------
{: .-three-column}

### Configuration

```yaml
plugins:
    - jekyll-redirect-from
```

See: [jekyll-redirect-from](https://rubygems.org/gems/jekyll-redirect-from)

### Usage

```yaml
---
redirect_from:
  - /foo
---
```

Place on any page.

### Redirecting

```yaml
---
redirect_to:
  - /foo
---
```

Place on any page.
See: [redirect to](https://github.com/jekyll/jekyll-redirect-from#redirect-to)

{% endraw %}


id: jasmine
git_filename: ./jasmine.md
format: md
field_title: Jasmine
field_category: JavaScript libraries
data:
{"title": "Jasmine", "category": "JavaScript libraries", "weight": -1, "body": "## Tests\n\n### Writing tests\n\n```js\ndescribe('A suite', () => {\n  it('works', () => {\n    expect(true).toBe(true)\n  })\n})\n```\n\nNote: This cheatsheet may be a little outdated. Also see the [Jest cheatsheet](./jest). Jest uses Jasmine, and therefore has similar API.\n\n### Expectations\n\n```js\nexpect(true).toBe(true)\nexpect(true).not.toBe(true)\n```\n\n```js\nexpect(a).toEqual(bar)\n```\n\n```js\nexpect(message).toMatch(/bar/)\nexpect(message).toMatch('bar')\n```\n\n```js\nexpect(a.foo).toBeDefined()\nexpect(a.foo).toBeUndefined()\nexpect(a.foo).toBeNull()\n```\n\n```js\nexpect(a.foo).toBeTruthy()\nexpect(a.foo).toBeFalsy()\n```\n\n```js\nexpect(message).toContain('hello')\n```\n\n```js\nexpect(pi).toBeGreaterThan(3)\nexpect(pi).toBeLessThan(4)\nexpect(pi).toBeCloseTo(3.1415, 0.1)\n```\n\n```js\nexpect(func).toThrow()\n```\n\n### Hooks\n\n```js\nbeforeEach(() => {\n  \u00b7\u00b7\u00b7\n})\n```\n\n```js\nafterEach(() => {\n  \u00b7\u00b7\u00b7\n})\n```\n\n### Pending\n\n```js\nxit('this is a pending test', () => {\n  \u00b7\u00b7\u00b7\n})\n```\n\n```js\nxdescribe('this is a pending block', () => {\n  \u00b7\u00b7\u00b7\n})\n```\n\n### Spies\n\n```js\nspyOn(foo, 'setBar')\nspyOn(foo, 'setBar').andReturn(123)\nspyOn(foo, 'getBar').andCallFake(function() { return 1001; })\nfoo.setBar(123)\n```\n\n```js\nexpect(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```js\nstub = jasmine.createSpy('stub')\nstub('hello')\n```\n\n```js\nexpect(stub.identity).toEqual('stub')\nexpect(stub).toHaveBeenCalled()\n```\n\n### Async\n\n```js\ntest('works with promises', () => {\n  return new Promise((resolve, reject) => {\n    \u00b7\u00b7\u00b7\n  })\n})\n```\n\nMake your test return a promise.\n\n### HTML runner\n\n```js\nvar jasmineEnv = jasmine.getEnv()\njasmineEnv.updateInterval = 250\n\nvar htmlReporter = new jasmine.HtmlReporter()\njasmineEnv.addReporter(htmlReporter)\n\n$(function() { jasmineEnv.execute() })\n```\n\nJasmine jQuery\n--------------\n\n### Expectations\n\n```js\nexpect($('#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```js\nexpect($('#toolbar')).toBeHidden()\nexpect($('#toolbar')).toBeVisible()\n```\n\n```js\nexpect($('#popup')).toHaveCss({ margin: \"10px\" })\nexpect($('option')).toBeSelected()\n```\n\n```js\nexpect($('.foo')).toExist()\n```\n\n```js\nexpect($('a')).toHaveAttr('rel')\nexpect($('a')).toHaveAttr('rel', 'nofollow')\n```\n\n```js\nexpect($('a')).toHaveClass('rel')\nexpect($('a')).toHaveId('home')\n```\n\n```js\nexpect($('a')).toHaveHtml('<span></span>')\nexpect($('a')).toContainHtml('<span></span>')\nexpect($('a')).toHaveText('hi')\n```\n\n```js\nexpect($form).toHandle('submit') // event\nexpect($form).toHandleWith('submit', onSumbit)\n```\n\nSee: [jasmine-jquery](https://github.com/velesin/jasmine-jquery)\n\n### Event spies\n\n```js\nspyOnEvent($('#some_element'), 'click')\n$('#some_element').click()\nexpect('click').toHaveBeenPreventedOn($('#some_element'))\nexpect('click').toHaveBeenTriggeredOn($('#some_element'))\n```\n\n## References\n{: .-one-column}\n\n* Also see the [Jest cheatsheet](./jest). Jest uses Jasmine, and therefore has similar API.\n* <https://jasmine.github.io>"}

field_body:
## Tests

### Writing tests

```js
describe('A suite', () => {
  it('works', () => {
    expect(true).toBe(true)
  })
})
```

Note: This cheatsheet may be a little outdated. Also see the [Jest cheatsheet](./jest). Jest uses Jasmine, and therefore has similar API.

### Expectations

```js
expect(true).toBe(true)
expect(true).not.toBe(true)
```

```js
expect(a).toEqual(bar)
```

```js
expect(message).toMatch(/bar/)
expect(message).toMatch('bar')
```

```js
expect(a.foo).toBeDefined()
expect(a.foo).toBeUndefined()
expect(a.foo).toBeNull()
```

```js
expect(a.foo).toBeTruthy()
expect(a.foo).toBeFalsy()
```

```js
expect(message).toContain('hello')
```

```js
expect(pi).toBeGreaterThan(3)
expect(pi).toBeLessThan(4)
expect(pi).toBeCloseTo(3.1415, 0.1)
```

```js
expect(func).toThrow()
```

### Hooks

```js
beforeEach(() => {
  ···
})
```

```js
afterEach(() => {
  ···
})
```

### Pending

```js
xit('this is a pending test', () => {
  ···
})
```

```js
xdescribe('this is a pending block', () => {
  ···
})
```

### Spies

```js
spyOn(foo, 'setBar')
spyOn(foo, 'setBar').andReturn(123)
spyOn(foo, 'getBar').andCallFake(function() { return 1001; })
foo.setBar(123)
```

```js
expect(foo.setBar).toHaveBeenCalled()
expect(foo.setBar).toHaveBeenCalledWith(123)
expect(foo.setBar.calls.length).toEqual(2)
expect(foo.setBar.calls[0].args[0]).toEqual(123)
```

### Creating spies

```js
stub = jasmine.createSpy('stub')
stub('hello')
```

```js
expect(stub.identity).toEqual('stub')
expect(stub).toHaveBeenCalled()
```

### Async

```js
test('works with promises', () => {
  return new Promise((resolve, reject) => {
    ···
  })
})
```

Make your test return a promise.

### HTML runner

```js
var jasmineEnv = jasmine.getEnv()
jasmineEnv.updateInterval = 250

var htmlReporter = new jasmine.HtmlReporter()
jasmineEnv.addReporter(htmlReporter)

$(function() { jasmineEnv.execute() })
```

Jasmine jQuery
--------------

### Expectations

```js
expect($('#id')).toBe('div')
expect($('input[type=checkbox]')).toBeChecked()
expect($('input[type=checkbox]')).toBeDisabled()
expect($('input[type=checkbox]')).toBeFocused()
expect($('#menu ul')).toBeEmpty()
```

```js
expect($('#toolbar')).toBeHidden()
expect($('#toolbar')).toBeVisible()
```

```js
expect($('#popup')).toHaveCss({ margin: "10px" })
expect($('option')).toBeSelected()
```

```js
expect($('.foo')).toExist()
```

```js
expect($('a')).toHaveAttr('rel')
expect($('a')).toHaveAttr('rel', 'nofollow')
```

```js
expect($('a')).toHaveClass('rel')
expect($('a')).toHaveId('home')
```

```js
expect($('a')).toHaveHtml('<span></span>')
expect($('a')).toContainHtml('<span></span>')
expect($('a')).toHaveText('hi')
```

```js
expect($form).toHandle('submit') // event
expect($form).toHandleWith('submit', onSumbit)
```

See: [jasmine-jquery](https://github.com/velesin/jasmine-jquery)

### Event spies

```js
spyOnEvent($('#some_element'), 'click')
$('#some_element').click()
expect('click').toHaveBeenPreventedOn($('#some_element'))
expect('click').toHaveBeenTriggeredOn($('#some_element'))
```

## References
{: .-one-column}

* Also see the [Jest cheatsheet](./jest). Jest uses Jasmine, and therefore has similar API.
* <https://jasmine.github.io>


id: ios-provision
git_filename: ./ios-provision.md
format: md
field_title: iOS Provisioning Profiles
data:
{"title": "iOS Provisioning Profiles", "body": "### Types of profiles\n\n * __Development__ - deploy to an iPhone via XCode\n * __Adhoc__ - deploy via testflightapp.com\n * __Appstore__ - only used for submitting to the app store\n\n### Requirements\n\n| What            | Dev | Adhoc | Appstore |\n|-----------------|-----|-------|----------|\n| CSR file        |     | \u221a     | \u221a        |\n| Device UDIDs    | \u221a   | \u221a     |          |\n| Developers list | \u221a   |       |          |\n\n### Obtaining a CSR file\n\nNeeded for Adhoc & Appstore builds.\n\n * Open *Keychain Access.app*\n * *Keychain Access* menu -> *Certificate Assistant* menu -> *Request a \n certificate...*\n   * User email address is *your email*\n   * Common name is *your name*\n   * CA Email address is *blank*\n   * Request is *Saved to disk*\n\n### Get the `.cer` files\n\nNeeded for Adhoc & Appstore builds.\n\n * in the iOS dev portal, go to *Certificates*, and download the certificate.  \n Install it on the dev machine.\n\n### Obtaining device UDIDs\n\nNeeded for Dev and Adhoc builds.\n\n * via iTunes: http://whatsmyudid.com\n * via XCode: cmd+shift+2 (Organizer), Devices\n\nFor developers\n--------------\n\nDon't ever ask Xcode to *Fix issue...* for you.\n\n### Using a provisioning profile\n\nNo need to use `.mobileprovision` files since XCode 5.\n\n * Open the `*.mobileprovision` file using Finder\n * XCode Project -> *Build settings* tab -> *Code signing* section -> \n *Provisioning Profile* section\n   * Set *Debug* to the *development* profile\n   * Set *Release* to the *ad-hoc* profile\n\n### Building an .ipa (Adhoc or Appstore)\n\n  * In the toolbar, select \"iOS Device\" as the target\n  * *Product* menu -> *Archive*\n  * In the Organizer (Cmd+Shift+2) -> *Archives* tab -> *Distribute...* button"}

field_body:
### Types of profiles

 * __Development__ - deploy to an iPhone via XCode
 * __Adhoc__ - deploy via testflightapp.com
 * __Appstore__ - only used for submitting to the app store

### Requirements

| What            | Dev | Adhoc | Appstore |
|-----------------|-----|-------|----------|
| CSR file        |     | √     | √        |
| Device UDIDs    | √   | √     |          |
| Developers list | √   |       |          |

### Obtaining a CSR file

Needed for Adhoc & Appstore builds.

 * Open *Keychain Access.app*
 * *Keychain Access* menu -> *Certificate Assistant* menu -> *Request a 
 certificate...*
   * User email address is *your email*
   * Common name is *your name*
   * CA Email address is *blank*
   * Request is *Saved to disk*

### Get the `.cer` files

Needed for Adhoc & Appstore builds.

 * in the iOS dev portal, go to *Certificates*, and download the certificate.  
 Install it on the dev machine.

### Obtaining device UDIDs

Needed for Dev and Adhoc builds.

 * via iTunes: http://whatsmyudid.com
 * via XCode: cmd+shift+2 (Organizer), Devices

For developers
--------------

Don't ever ask Xcode to *Fix issue...* for you.

### Using a provisioning profile

No need to use `.mobileprovision` files since XCode 5.

 * Open the `*.mobileprovision` file using Finder
 * XCode Project -> *Build settings* tab -> *Code signing* section -> 
 *Provisioning Profile* section
   * Set *Debug* to the *development* profile
   * Set *Release* to the *ad-hoc* profile

### Building an .ipa (Adhoc or Appstore)

  * In the toolbar, select "iOS Device" as the target
  * *Product* menu -> *Archive*
  * In the Organizer (Cmd+Shift+2) -> *Archives* tab -> *Distribute...* button


id: inkscape
git_filename: ./inkscape.md
format: md
field_title: Inkscape
field_category: Apps
field_tags: WIP
data:
{"title": "Inkscape", "category": "Apps", "tags": ["WIP"], "body": "### All\n\n| `-` _/_ `=` | Zoom in/out\n| `3` _/_ `4` | Zoom to selection / drawing\n| `5` _/_ `6` | Zoom to page / page width\n{: .-shortcuts}\n\n### Select tool (F1)\n\n| `[ ]` | Rotate\n{: .-shortcuts}\n\n### Edit path (F2)\n\n| `Ctrl` | constraint\n{: .-shortcuts}\n\n### Dragging an anchor handle\n\n| `Ctrl` | snap to 15 degrees\n| `Alt` | ?\n{: .-shortcuts}\n\n### Bezier (Shift F6)"}

field_body:
### All

| `-` _/_ `=` | Zoom in/out
| `3` _/_ `4` | Zoom to selection / drawing
| `5` _/_ `6` | Zoom to page / page width
{: .-shortcuts}

### Select tool (F1)

| `[ ]` | Rotate
{: .-shortcuts}

### Edit path (F2)

| `Ctrl` | constraint
{: .-shortcuts}

### Dragging an anchor handle

| `Ctrl` | snap to 15 degrees
| `Alt` | ?
{: .-shortcuts}

### Bezier (Shift F6)


id: index@2016
git_filename: ./index@2016.md
format: md
data:
{"full_title": "Devhints \u2014 for web development and more", "description": "TL;DR for developer documentation - a ridiculous collection of cheatsheets", "layout": "home", "type": "home", "og_type": "website", "body": ""}


id: index
git_filename: ./index.md
format: md
data:
{"full_title": "Devhints \u2014 TL;DR for developer documentation", "description": "A ridiculous collection of web development cheatsheets", "layout": "2017/home", "og_type": "website", "type": "home", "body": ""}


id: immutable.js
git_filename: ./immutable.js.md
format: md
field_title: Immutable.js
field_category: JavaScript libraries
data:
{"title": "Immutable.js", "category": "JavaScript libraries", "body": "### Maps\n\n```js\nvar map = Immutable.Map({ a: 1, b: 2, c: 3 })\n```\n\n```js\nmap\n  .set('b', 50)\n  .get('b') // 50\n```\n\n### Lists\n\n```js\nvar 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```js\nvar 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```"}

field_body:
### Maps

```js
var map = Immutable.Map({ a: 1, b: 2, c: 3 })
```

```js
map
  .set('b', 50)
  .get('b') // 50
```

### Lists

```js
var list = Immutable.List.of(1, 2)

list
  .push(3, 4, 5)
  .unshift(0)
  .concat(list2, list3)
  .get(0)
  .size
```

### Nested maps

```js
var nested = Immutable.fromJS({ user: { profile: { name: 'John' } } })

nested
  // Update
  .mergeDeep({ user: { profile: { age: 90 } } })
  .setIn([ 'user', 'profile', 'name' ], 'Jack')
  .updateIn([ 'user', 'profile', 'name' ], (s) => s.toUpperCase())

  // Get
  .getIn(['user', 'profile', 'name']) // 'JACK'
```


id: imagemagick
git_filename: ./imagemagick.md
format: md
field_title: Imagemagick
field_intro: A quick reference for common [Imagemagick](https://www.imagemagick.org) commands and switches.
data:
{"title": "Imagemagick", "intro": "A quick reference for common [Imagemagick](https://www.imagemagick.org) commands and switches.\n", "body": "### Common options\n\n| Option              | Description                     |\n| ------------------- | ------------------------------- |\n| `-resize 100x40`    | Resize to a dimension           |\n| `-crop 40x30+10+10` | (width)x(height)+(x)+y          |\n| `-crop 40x30-10-10` | (width)x(height)+(x)+y          |\n| `-flip`             | Vertical                        |\n| `-flop`             | Horizontal                      |\n| `-transpose`        | Flip vertical + rotate 90deg    |\n| `-transverse`       | Flip horizontal + rotate 270deg |\n| `-trim`             | Trim image edges                |\n| `-rotate 90`        | Rotate 90 degrees               |\n\n### Resize to fit\n\n```sh\nconvert input.jpg -resize 80x80^ -gravity center -extent 80x80 icon.png\n```\n\n### Convert all images to another format\n\n```sh\nmogrify -format jpg -quality 85 *.png\n```\n\n### Make a pdf\n\n```sh\nconvert *.jpg hello.pdf\n```\n\n### References\n\n- <http://www.noah.org/wiki/ImageMagick>\n- <https://www.imagemagick.org/>"}

field_body:
### Common options

| Option              | Description                     |
| ------------------- | ------------------------------- |
| `-resize 100x40`    | Resize to a dimension           |
| `-crop 40x30+10+10` | (width)x(height)+(x)+y          |
| `-crop 40x30-10-10` | (width)x(height)+(x)+y          |
| `-flip`             | Vertical                        |
| `-flop`             | Horizontal                      |
| `-transpose`        | Flip vertical + rotate 90deg    |
| `-transverse`       | Flip horizontal + rotate 270deg |
| `-trim`             | Trim image edges                |
| `-rotate 90`        | Rotate 90 degrees               |

### Resize to fit

```sh
convert input.jpg -resize 80x80^ -gravity center -extent 80x80 icon.png
```

### Convert all images to another format

```sh
mogrify -format jpg -quality 85 *.png
```

### Make a pdf

```sh
convert *.jpg hello.pdf
```

### References

- <http://www.noah.org/wiki/ImageMagick>
- <https://www.imagemagick.org/>


id: ie_bugs
git_filename: ./ie_bugs.md
format: md
field_title: Legacy IE bugs
field_category: HTML
field_intro: A bunch of bugs to take care of if you're going to target legacy IE browsers.
field_updated: 2018-03-06
field_updated___timezone: UTC
data:
{"title": "Legacy IE bugs", "category": "HTML", "updated": "2018-03-06", "intro": "A bunch of bugs to take care of if you're going to target legacy IE browsers.\n", "body": "### IE8: 'change' event\n\nThe 'change' event doesn't always fire. Not for checkboxes, radios, multi-select lists. Use the `click` handler instead.\n\n * [(1)](http://stackoverflow.com/questions/8005442/checkbox-change-event-works-when-click-the-label-in-ie8-ie7)\n\n### IE8: label with input\n\nClicking label with input inside doesn't focus the input.\n\n * [(1)](http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/LabelForWithImage.html)\n\n### IE8: Opacity propagation\n\nAn element's 'opacity' value isn't propagated to its positioned descendants.\n\n * [test case](http://jhop.me/tests/bugs/ie8/opacity_positioned.html)"}

field_body:
### IE8: 'change' event

The 'change' event doesn't always fire. Not for checkboxes, radios, multi-select lists. Use the `click` handler instead.

 * [(1)](http://stackoverflow.com/questions/8005442/checkbox-change-event-works-when-click-the-label-in-ie8-ie7)

### IE8: label with input

Clicking label with input inside doesn't focus the input.

 * [(1)](http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/LabelForWithImage.html)

### IE8: Opacity propagation

An element's 'opacity' value isn't propagated to its positioned descendants.

 * [test case](http://jhop.me/tests/bugs/ie8/opacity_positioned.html)


id: ie
git_filename: ./ie.md
format: md
field_title: Internet Explorer
field_category: HTML
field_updated: 2018-03-06
field_updated___timezone: UTC
data:
{"title": "Internet Explorer", "category": "HTML", "updated": "2018-03-06", "body": "## Support table\n{: .-one-column}\n\n### CSS Selectors\n\n| Feature                                                    | IE6 | IE7 | IE8 | IE9 | IE10 |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   |\n| `>` _(descendant)_                                         |     | 7 \u2713 | \u2713   | \u2713   | \u2713    |\n| `[attr]` _(attribute)_                                     |     | 7 \u2713 | \u2713   | \u2713   | \u2713    |\n| `.class1.class2` _(multiple classes)_                      |     | 7 \u2713 | \u2713   | \u2713   | \u2713    |\n| `~` _(sibling)_                                            |     | 7 \u2713 | \u2713   | \u2713   | \u2713    |\n| `+` _(adjacent)_                                           |     | 7 \u2713 | \u2713   | \u2713   | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   |\n| `:first-child` <sup>\\*</sup>                               |     |     | 8 \u2713 | \u2713   | \u2713    |\n| `:focus`                                                   |     |     | 8 \u2713 | \u2713   | \u2713    |\n| `:before` `:after` _(single colon only)_                   |     |     | 8 \u2713 | \u2713   | \u2713    |\n| `:lang`                                                    |     |     | 8 \u2713 | \u2713   | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   |\n| `:first-of-type`, `:last-of-type`                          |     |     |     | 9 \u2713 | \u2713    |\n| `:last-child`                                              |     |     |     | 9 \u2713 | \u2713    |\n| `:empty`                                                   |     |     |     | 9 \u2713 | \u2713    |\n| `:enabled` `:disabled` `:checked`                          |     |     |     | 9 \u2713 | \u2713    |\n| `:not()`                                                   |     |     |     | 9 \u2713 | \u2713    |\n| `:nth-child()` `:nth-last-child()`                         |     |     |     | 9 \u2713 | \u2713    |\n| `:nth-of-type()` `:nth-last-of-type()` `:only-of-type()`   |     |     |     | 9 \u2713 | \u2713    |\n| `:only-child()`                                            |     |     |     | 9 \u2713 | \u2713    |\n| `:target`                                                  |     |     |     | 9 \u2713 | \u2713    |\n| `::selection`                                              |     |     |     | 9 \u2713 | \u2713    |\n| `:root`                                                    |     |     |     | 9 \u2713 | \u2713    |\n{: .-headers.-no-wrap}\n\n`first-child:` doesn't work for elements inserted via JS.\n\n### CSS properties\n\n| Feature                                                    | IE6 | IE7 | IE8 | IE9 | IE10 | IE11 |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| `max-width`                                                |     | 7 \u2713 | \u2713   | \u2713   | \u2713    | \u2713    |\n| `position: fixed`                                          |     | 7 \u2713 | \u2713   | \u2713   | \u2713    | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| `outline`                                                  |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| `display: inline-block` <sup>\\*</sup>                      |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| `display: table`                                           |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| `border-collapse`, `border-spacing`, `table-layout`, ...   |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| `whitespace: pre-wrap`                                     |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| `whitespace: pre-line`                                     |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| `box-sizing`                                               |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| `background-clip`                                          |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| `background-origin`                                        |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| `background-size`                                          |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| `background: x, y, z` _(multiple backgrounds)_             |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| `opacity`                                                  |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| `border-radius`                                            |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| `box-shadow`                                               |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| `rgba()`                                                   |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| `transform`                                                |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| `animation`                                                |     |     |     |     | 10 \u2713 | \u2713    |\n| `transition`                                               |     |     |     |     | 10 \u2713 | \u2713    |\n| `linear-gradient()`                                        |     |     |     |     | 10 \u2713 | \u2713    |\n| `text-shadow` \u2014 [polyfill][text-shadow]                    |     |     |     |     | 10 \u2713 | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| `border-image`                                             |     |     |     |     |      | 11 \u2713 |\n{: .-headers.-no-wrap}\n\n`inline-block:` IE6/7 can only support inline-block for elements that are naturally inline, like span\n\n### Features\n\n| Feature                                                    | IE6 | IE7 | IE8 | IE9 | IE10 | IE11 |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| PNG alpha transparency                                     |     | 7 \u2713 | \u2713   | \u2713   | \u2713    | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| data URI [\u2299][datauri]                                      |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| JS: JSON parsing [\u2299][json]                                 |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| JS: Cross-origin resource sharing [\u2299][cors]                |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| JS: Local storage [\u2299][localstorage]                        |     |     | 8 \u2713 | \u2713   | \u2713    | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| CSS: `@media` queries \u2014 [polyfill][respond]                |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| HTML: new HTML5 elements - [polyfill][html5shiv]           |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| HTML: `<canvas>`                                           |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| HTML: `<svg>`                                              |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| HTML: `<img src='image.svg'>`                              |     |     |     | 9 \u2713 | \u2713    | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| CSS: flexbox [\u2299][flexbox] <sup>\\*</sup>                    |     |     |     |     | 10 \u2713 | \u2713    |\n| HTML: `<input placeholder='..'>` [\u2299][placeholder]          |     |     |     |     | 10 \u2713 | \u2713    |\n| HTML: `<input type='range'>`                               |     |     |     |     | 10 \u2713 | \u2713    |\n| HTML: `<input required>` [\u2299][validation]                   |     |     |     |     | 10 \u2713 | \u2713    |\n| JS: Web sockets                                            |     |     |     |     | 10 \u2713 | \u2713    |\n| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |\n| JS: Fullscreen mode                                        |     |     |     |     |      | 11 \u2713 |\n{: .-headers.-no-wrap}\n\n`flexbox:` IE10 only supports the 2012 syntax with -ms- prefix.\n\n## Polyfills\n\n### IE polyfills\n\nAlways install these in almost every project:\n\n - [json2] for JSON parsing (for IE7 below)\n - [selectivizr] for selectors (for IE8 below)\n - [html5shiv] for new HTML tags (for IE8 below)\n - [respond] for media queries (for IE8 below)\n - See [this article](http://ricostacruz.com/til/ie-polyfills.html) for info\n\n```html\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 - [modernizr] for feature detection\n\n### for CSS3 decorations\n\n - [css3pie]\n - [cssSandpaper]\n - [ecsstender]\n\nSee: [Cross-browser polyfills list][fills]\n\nMisc\n----\n\n### IE Conditional comment HTML\n\n```html\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```html\n<!--[if IE]>      I'm IE      <![endif]-->\n<!--[if !IE]> --> Not IE <!-- <![endif]-->\n```\n\n[text-shadow]: https://github.com/heygrady/textshadow\n[ie7.js]: http://ie7-js.googlecode.com/svn/test/index.html\n[selectivizr]: http://selectivizr.com/\n[css3pie]: http://css3pie.com/\n[cssSandpaper]: https://github.com/zoltan-dulac/cssSandpaper\n[html5shiv]: https://code.google.com/p/html5shiv/\n[fills]: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills\n[json2]: https://github.com/douglascrockford/JSON-js\n[modernizr]: https://modernizr.com\n[ecsstender]: http://ecsstender.org/\n[respond]: https://github.com/scottjehl/Respond\n[flexbox]: https://caniuse.com/#feat=flexbox\n[cors]: https://caniuse.com/#feat=cors\n[localstorage]: https://caniuse.com/#feat=localstorage\n[json]: https://caniuse.com/#feat=json\n[datauri]: https://caniuse.com/#feat=datauri\n[validation]: https://caniuse.com/#search=validation\n[placeholder]: https://caniuse.com/#feat=input-placeholder"}

field_body:
## Support table
{: .-one-column}

### CSS Selectors

| Feature                                                    | IE6 | IE7 | IE8 | IE9 | IE10 |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   |
| `>` _(descendant)_                                         |     | 7 ✓ | ✓   | ✓   | ✓    |
| `[attr]` _(attribute)_                                     |     | 7 ✓ | ✓   | ✓   | ✓    |
| `.class1.class2` _(multiple classes)_                      |     | 7 ✓ | ✓   | ✓   | ✓    |
| `~` _(sibling)_                                            |     | 7 ✓ | ✓   | ✓   | ✓    |
| `+` _(adjacent)_                                           |     | 7 ✓ | ✓   | ✓   | ✓    |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   |
| `:first-child` <sup>\*</sup>                               |     |     | 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 ✓ | ✓    |
{: .-headers.-no-wrap}

`first-child:` doesn't work for elements inserted via JS.

### CSS properties

| Feature                                                    | IE6 | IE7 | IE8 | IE9 | IE10 | IE11 |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |
| `max-width`                                                |     | 7 ✓ | ✓   | ✓   | ✓    | ✓    |
| `position: fixed`                                          |     | 7 ✓ | ✓   | ✓   | ✓    | ✓    |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |
| `outline`                                                  |     |     | 8 ✓ | ✓   | ✓    | ✓    |
| `display: inline-block` <sup>\*</sup>                      |     |     | 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-shadow` — [polyfill][text-shadow]                    |     |     |     |     | 10 ✓ | ✓    |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |
| `border-image`                                             |     |     |     |     |      | 11 ✓ |
{: .-headers.-no-wrap}

`inline-block:` IE6/7 can only support inline-block for elements that are naturally inline, like span

### Features

| Feature                                                    | IE6 | IE7 | IE8 | IE9 | IE10 | IE11 |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |
| PNG alpha transparency                                     |     | 7 ✓ | ✓   | ✓   | ✓    | ✓    |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |
| data URI [⊙][datauri]                                      |     |     | 8 ✓ | ✓   | ✓    | ✓    |
| JS: JSON parsing [⊙][json]                                 |     |     | 8 ✓ | ✓   | ✓    | ✓    |
| JS: Cross-origin resource sharing [⊙][cors]                |     |     | 8 ✓ | ✓   | ✓    | ✓    |
| JS: Local storage [⊙][localstorage]                        |     |     | 8 ✓ | ✓   | ✓    | ✓    |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |
| CSS: `@media` queries — [polyfill][respond]                |     |     |     | 9 ✓ | ✓    | ✓    |
| HTML: new HTML5 elements - [polyfill][html5shiv]           |     |     |     | 9 ✓ | ✓    | ✓    |
| HTML: `<canvas>`                                           |     |     |     | 9 ✓ | ✓    | ✓    |
| HTML: `<svg>`                                              |     |     |     | 9 ✓ | ✓    | ✓    |
| HTML: `<img src='image.svg'>`                              |     |     |     | 9 ✓ | ✓    | ✓    |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |
| CSS: flexbox [⊙][flexbox] <sup>\*</sup>                    |     |     |     |     | 10 ✓ | ✓    |
| HTML: `<input placeholder='..'>` [⊙][placeholder]          |     |     |     |     | 10 ✓ | ✓    |
| HTML: `<input type='range'>`                               |     |     |     |     | 10 ✓ | ✓    |
| HTML: `<input required>` [⊙][validation]                   |     |     |     |     | 10 ✓ | ✓    |
| JS: Web sockets                                            |     |     |     |     | 10 ✓ | ✓    |
| ---------------------------------------------------------- | -   | -   | -   | -   | --   | --   |
| JS: Fullscreen mode                                        |     |     |     |     |      | 11 ✓ |
{: .-headers.-no-wrap}

`flexbox:` IE10 only supports the 2012 syntax with -ms- prefix.

## Polyfills

### IE polyfills

Always install these in almost every project:

 - [json2] for JSON parsing (for IE7 below)
 - [selectivizr] for selectors (for IE8 below)
 - [html5shiv] for new HTML tags (for IE8 below)
 - [respond] for media queries (for IE8 below)
 - See [this article](http://ricostacruz.com/til/ie-polyfills.html) for info

```html
<!--[if lt IE 9]>
<script src='https://cdnjs.cloudflare.com/ajax/libs/nwmatcher/1.2.5/nwmatcher.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/json2/20140204/json2.min.js'>
<script src='https://cdn.rawgit.com/gisu/selectivizr/1.0.3/selectivizr.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.js'>
<![endif]--> 
```

### You may also need

 - [modernizr] for feature detection

### for CSS3 decorations

 - [css3pie]
 - [cssSandpaper]
 - [ecsstender]

See: [Cross-browser polyfills list][fills]

Misc
----

### IE Conditional comment HTML

```html
<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html class=""> <!--<![endif]-->
```

### IE conditionals

```html
<!--[if IE]>      I'm IE      <![endif]-->
<!--[if !IE]> --> Not IE <!-- <![endif]-->
```

[text-shadow]: https://github.com/heygrady/textshadow
[ie7.js]: http://ie7-js.googlecode.com/svn/test/index.html
[selectivizr]: http://selectivizr.com/
[css3pie]: http://css3pie.com/
[cssSandpaper]: https://github.com/zoltan-dulac/cssSandpaper
[html5shiv]: https://code.google.com/p/html5shiv/
[fills]: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills
[json2]: https://github.com/douglascrockford/JSON-js
[modernizr]: https://modernizr.com
[ecsstender]: http://ecsstender.org/
[respond]: https://github.com/scottjehl/Respond
[flexbox]: https://caniuse.com/#feat=flexbox
[cors]: https://caniuse.com/#feat=cors
[localstorage]: https://caniuse.com/#feat=localstorage
[json]: https://caniuse.com/#feat=json
[datauri]: https://caniuse.com/#feat=datauri
[validation]: https://caniuse.com/#search=validation
[placeholder]: https://caniuse.com/#feat=input-placeholder


