[ { "id": "101", "title": 101, "url": "/101", "category": "JavaScript libraries", "keywords": null, "content_html": "
const isObject = require('101/isObject')\nisObject({}) // → true\n
\n\nEvery function is exposed as a module.
\n\nSee: 101
\n\nisObject({})\nisString('str')\nisRegExp(/regexp/)\nisBoolean(true)\nisEmpty({})\nisfunction(x => x)\nisInteger(10)\nisNumber(10.1)\ninstanceOf(obj, 'string')\n
\n\nlet obj = {}\n
\n\nobj = put(obj, 'user.name', 'John')\n// → { user: { name: 'John' } }\n
\n\npluck(name, 'user.name')\n// → 'John'\n
\n\nobj = del(obj, 'user')\n// → { }\n
\n\npluck(state, 'user.profile.name')\n
\n\npick(state, ['user', 'ui'])\npick(state, /^_/)\n
\n\npluck
returns values, pick
returns subsets of objects.
put(state, 'user.profile.name', 'john')\n
\n\nSee:\nput
\n\ndel(state, 'user.profile')\nomit(state, ['user', 'data'])\n
\n\nomit
is like del
, but supports multiple keys to be deleted.
hasKeypaths(state, ['user'])\nhasKeypaths(state, { 'user.profile.name': 'john' })\n
\n\nSee:\nhasKeypaths
\n\nvalues(state)\n
\n\nand(x, y) | \n x && y | \n
or(x, y) | \n x || y | \n
xor(x, y) | \n !(!x && !y) && !(x && y) | \n
equals(x, y) | \n x === y | \n
exists(x) | \n !!x | \n
not(x) | \n !x | \n
Useful for function composition.
\n\n\n\ncompose(f, g) // x => f(g(x))\ncurry(f) // x => y => f(x, y)\nflip(f) // f(x, y) --> f(y, x)\n
\n\n\n\npassAll(f, g) // x => f(x) && g(x)\npassAny(f, g) // x => f(x) || g(x)\n
\n\n\n\nconverge(and, [pluck('a'), pluck('b')])(x)\n
\n\n// → and(pluck(x, 'a'), pluck(x, 'b'))\n
\n\nSee:\nconverge
\n\nfind(list, x => x.y === 2)\nfindIndex(list, x => ...)\nincludes(list, 'item')\nlast(list)\n
\n\nfind(list, hasProps('id'))\n
\n\ngroupBy(list, 'id')\nindexBy(list, 'id')\n
\n\nisFloat = passAll(isNumber, compose(isInteger, not))\n// n => isNumber(n) && not(isInteger(n))\n
\n\nfunction doStuff (object, options) { ... }\n\ndoStuffForce = curry(flip(doStuff))({ force: true })\n
\n\n101 is a JavaScript library for dealing with immutable data in a functional manner.
", "description_html": "", "tags": null, "updated": "2017-09-21" },{ "id": "absinthe", "title": "Absinthe", "url": "/absinthe", "category": "Hidden", "keywords": null, "content_html": "Schema
- The root. Defines what queries you can do, and what types they return.Resolver
- Functions that return data.Type
- A type definition describing the shape of the data you’ll return.defmodule Blog.Web.Router do\n use Phoenix.Router\n\n forward \"/\", Absinthe.Plug,\n schema: Blog.Schema\nend\n
\n\nAbsinthe is a Plug, and you pass it one Schema.
\n\nSee: Our first query
\n\ndefmodule Blog.Schema do\n use Absinthe.Schema\n import_types Blog.Schema.Types\n\n query do\n @desc \"Get a list of blog posts\"\n field :posts, list_of(:post) do\n resolve &Blog.PostResolver.all/2\n end\n end\nend\n
\n\nThis schema will account for { posts { ··· } }
. It returns a Type of :post
, and delegates to a Resolver.
defmodule Blog.PostResolver do\n def all(_args, _info) do\n {:ok, Blog.Repo.all(Blog.Post)}\n end\nend\n
\n\nThis is the function that the schema delegated the posts
query to.
defmodule Blog.Schema.Types do\n use Absinthe.Schema.Notation\n\n @desc \"A blog post\"\n object :post do\n field :id, :id\n field :title, :string\n field :body, :string\n end\nend\n
\n\nThis defines a type :post
, which is used by the resolver.
{ user(id: \"1\") { ··· } }\n
\n\nquery do\n field :user, type: :user do\n arg :id, non_null(:id)\n resolve &Blog.UserResolver.find/2\n end\nend\n
\n\ndef find(%{id: id} = args, _info) do\n ···\nend\n
\n\nSee: Query arguments
\n\n{\n mutation CreatePost {\n post(title: \"Hello\") { id }\n }\n}\n
\n\nmutation do\n @desc \"Create a post\"\n field :post, type: :post do\n arg :title, non_null(:string)\n resolve &Blog.PostResolver.create/2\n end\nend\n
\n\nSee: Mutations
\n\nAbsinthe allows you to write GraphQL servers in Elixir.
", "description_html": "", "tags": ["WIP"], "updated": "2017-10-10" },{ "id": "activeadmin", "title": "ActiveAdmin", "url": "/activeadmin", "category": "Ruby", "keywords": null, "content_html": "Allows you to filter listings by a certain scope.
\n\nscope :draft\nscope :for_approval\n
\n\nscope :public, if: ->{ current_admin_user.can?(...) }\nscope \"Unapproved\", :pending\nscope(\"Published\") { |books| books.where(:published: true) }\n
\n\nfilter :email\nfilter :username\n
\n\nYou can define custom actions for models.
\n\nbefore_filter only: [:show, :edit, :publish] do\n @post = Post.find(params[:id])\nend\n
\n\nmember_action :publish, method: :put do\n @post.publish!\n redirect_to admin_posts_path, notice: \"The post '#{@post}' has been published!\"\nend\n
\n\nindex do\n column do |post|\n link_to 'Publish', publish_admin_post_path(post), method: :put\n end\nend\n
\n\naction_item only: [:edit, :show] do\n @post = Post.find(params[:id])\n link_to 'Publish', publish_admin_post_path(post), method: :put\nend\n
\n\ncolumn :foo\n
\n\ncolumn :title, sortable: :name do |post|\n strong post.title\nend\n
\n\nstatus_tag \"Done\" # Gray\nstatus_tag \"Finished\", :ok # Green\nstatus_tag \"You\", :warn # Orange\nstatus_tag \"Failed\", :error # Red\n
\n\nActiveAdmin.register Post do\n actions :index, :edit\n # or: config.clear_action_items!\nend\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "adb",
"title": "adb (Android Debug Bridge)",
"url": "/adb",
"category": "CLI",
"keywords": null,
"content_html": "Command | \nDescription | \n
---|---|
adb devices | \n Lists connected devices | \n
adb devices -l | \n Lists connected devices and kind | \n
adb root | \n Restarts adbd with root permissions | \n
adb start-server | \n Starts the adb server | \n
adb kill-server | \n Kills the adb server | \n
adb remount | \n Remounts file system with read/write access | \n
adb reboot | \n Reboots the device | \n
adb reboot bootloader | \n Reboots the device into fastboot | \n
adb disable-verity | \n Reboots the device into fastboot | \n
wait-for-device
can be specified after adb
to ensure that the command will run once the device is connected.
-s
can be used to send the commands to a specific device when multiple are connected.
$ adb wait-for-device devices\n List of devices attached\n somedevice-1234 device\n someotherdevice-1234 device\n
\n\n$ adb -s somedevice-1234 root\n
\n\nCommand | \nDescription | \n
---|---|
adb logcat | \n Starts printing log messages to stdout | \n
adb logcat -g | \n Displays current log buffer sizes | \n
adb logcat -G <size> | \n Sets the buffer size (K or M) | \n
adb logcat -c | \n Clears the log buffers | \n
adb logcat *:V | \n Enables ALL log messages (verbose) | \n
adb logcat -f <filename> | \n Dumps to specified file | \n
$ adb logcat -G 16M\n$ adb logcat *:V > output.log\n
\n\nCommand | \nDescription | \n
---|---|
adb push <local> <remote> | \n Copies the local to the device at remote | \n
adb pull <remote> <local> | \n Copies the remote from the device to local | \n
$ echo \"This is a test\" > test.txt\n$ adb push test.txt /sdcard/test.txt\n$ adb pull /sdcard/test.txt pulledTest.txt\n
\n\nCommand | \nDescription | \n
---|---|
adb shell <command> | \n Runs the specified command on device (most unix commands work here) | \n
adb shell wm size | \n Displays the current screen resolution | \n
adb shell wm size WxH | \n Sets the resolution to WxH | \n
adb shell pm list packages | \n Lists all installed packages | \n
adb shell pm list packages -3 | \n Lists all installed 3rd-party packages | \n
adb shell monkey -p app.package.name | \n Starts the specified package | \n
ga('create', 'UA-XXXX-Y', 'auto')\nga('create', 'UA-XXXX-Y', { userId: 'USER_ID' })\n
\n\nga('send', 'pageview')\nga('send', 'pageview', { 'dimension15': 'My custom dimension' })\n
\n\nga('send', 'event', 'button', 'click', {color: 'red'});\n
\n\nga('send', 'event', 'button', 'click', 'nav buttons', 4);\n/* ^category ^action ^label ^value */\n
\n\nga('send', 'exception', {\n exDescription: 'DatabaseError',\n exFatal: false,\n appName: 'myapp',\n appVersion: '0.1.2'\n})\n
",
"intro_html": "Google Analytics’s analytics.js is deprecated.
", "description_html": "", "tags": null, "updated": "2017-10-29" },{ "id": "analytics", "title": "Analytics libraries", "url": "/analytics", "category": "Analytics", "keywords": null, "content_html": "mixpanel.identify('284');\nmixpanel.people.set({ $email: 'hi@gmail.com' });\nmixpanel.register({ age: 28, gender: 'male' }); /* set common properties */\n
\n\n\n\nga('create', 'UA-XXXX-Y', 'auto');\nga('create', 'UA-XXXX-Y', { userId: 'USER_ID' });\n
\n\nga('send', 'pageview');\nga('send', 'pageview', { 'dimension15': 'My custom dimension' });\n
\n\n",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "angularjs",
"title": "Angular.js",
"url": "/angularjs",
"category": "JavaScript libraries",
"keywords": null,
"content_html": " <html ng-app=\"nameApp\">\n
\n\n <ul ng-controller=\"MyListCtrl\">\n <li ng-repeat=\"phone in phones\">\n \n </li>\n </ul>\n
\n\n <select ng-model=\"orderProp\">\n <option value=\"name\">Alphabetical</option>\n <option value=\"age\">Newest</option>\n </select>\n
\n\n App = angular.module('myApp', []);\n\n App.controller('MyListCtrl', function ($scope) {\n $scope.phones = [ ... ];\n });\n
\n\n App.controller('Name', [\n '$scope',\n '$http',\n function ($scope, $http) {\n }\n ]);\n\n a.c 'name', [\n '$scope'\n '$http'\n ($scope, $http) ->\n ]\n
\n\n App.service('NameService', function($http){\n return {\n get: function(){\n return $http.get(url);\n }\n }\n });\n
\nIn controller you call with parameter and will use promises to return data from server.
\n\n App.controller('controllerName',\n function(NameService){\n NameService.get()\n .then(function(){})\n })\n
\n\n App.directive('name', function(){\n return {\n template: '<h1>Hello</h1>'\n }\n });\n
\n\nIn HTML will use <name></name>
to render your template <h1>Hello</h1>
App.controller('PhoneListCtrl', function ($scope, $http) {\n $http.get('/data.json').success(function (data) {\n $scope.phones = data;\n })\n });\n
\nReferences:
\n\nmkdir -p gif\nmplayer -ao null -vo gif89a:outdir=gif $INPUT\nmogrify -format gif *.png\ngifsicle --colors=256 --delay=4 --loopcount=0 --dither -O3 gif/*.gif > ${INPUT%.*}.gif\nrm -rf gif\n
\n\nYou’ll need mplayer
, imagemagick
and gifsicle
. This converts frames to .png, then turns them into an animated gif.
mplayer -ao null -ss 0:02:06 -endpos 0:05:00 -vo gif89a:outdir=gif videofile.mp4\n
\n\nSee -ss
and -endpos
.
\\033[#m\n
\n\n0 clear\n1 bold\n4 underline\n5 blink\n\n30-37 fg color\n40-47 bg color\n\n1K clear line (to beginning of line)\n2K clear line (entire line)\n2J clear screen\n0;0H move cursor to 0;0\n\n1A move up 1 line\n
\n\n0 black\n1 red\n2 green\n3 yellow\n4 blue\n5 magenta\n6 cyan\n7 white\n
\n\nhide_cursor() { printf \"\\e[?25l\"; }\nshow_cursor() { printf \"\\e[?25h\"; }\n
",
"intro_html": "Quick reference to ANSI color codes.
", "description_html": "", "tags": null, "updated": null },{ "id": "ansible-examples", "title": "Ansible examples", "url": "/ansible-examples", "category": "Ansible", "keywords": null, "content_html": "$ brew install ansible # OSX\n$ [sudo] apt install ansible # elsewhere\n
\n\nAnsible is available as a package in most OS’s.
\n\nSee: Installation
\n\n~$ mkdir setup\n~$ cd setup\n
\n\nMake a folder for your Ansible files.
\n\nSee: Getting started
\n\n[sites]\n127.0.0.1\n192.168.0.1\n192.168.0.2\n192.168.0.3\n
\n\nThis is a list of hosts you want to manage, grouped into groups. (Hint: try\nusing localhost ansible_connection=local
to deploy to your local machine.)
See: Intro to Inventory
\n\n- hosts: 127.0.0.1\n user: root\n tasks:\n - name: install nginx\n apt: pkg=nginx state=present\n\n - name: start nginx every bootup\n service: name=nginx state=started enabled=yes\n\n - name: do something in the shell\n shell: echo hello > /tmp/abc.txt\n\n - name: install bundler\n gem: name=bundler state=latest\n
\n\nSee: Intro to Playbooks
\n\n~/setup$ ls\nhosts\nplaybook.yml\n
\n\n~/setup$ ansible-playbook -i hosts playbook.yml\nPLAY [all] ********************************************************************\n\nGATHERING FACTS ***************************************************************\nok: [127.0.0.1]\n\nTASK: [install nginx] *********************************************************\nok: [127.0.0.1]\n\nTASK: start nginx every bootup] ***********************************************\nok: [127.0.0.1]\n...\n
\n\nA quick guide to getting started with your first Ansible playbook.
", "tags": null, "updated": null },{ "id": "ansible-modules", "title": "Ansible modules", "url": "/ansible-modules", "category": "Ansible", "keywords": null, "content_html": "---\n- hosts: production\n remote_user: root\n tasks:\n - ···\n
\n\nPlace your modules inside tasks
.
- apt: pkg=vim state=present\n
\n\n- apt:\n pkg: vim\n state: present\n
\n\n- apt: >\n pkg=vim\n state=present\n
\n\nDefine your tasks in any of these formats. One-line format is preferred for short declarations, while maps are preferred for longer.
\n\n- apt:\n pkg: nodejs\n state: present # absent | latest\n update_cache: yes\n force: no\n
\n\n- apt:\n deb: \"https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb\"\n
\n\n- apt_repository:\n repo: \"deb https://··· raring main\"\n state: present\n
\n\n- apt_key:\n id: AC40B2F7\n url: \"http://···\"\n state: present\n
\n\n- git:\n repo: git://github.com/\n dest: /srv/checkout\n version: master\n depth: 10\n bare: yes\n
\n\nSee: git module
\n\n- git_config:\n name: user.email\n scope: global # local | system\n value: hi@example.com\n
\n\nSee: git_config module
\n\n- user:\n state: present\n name: git\n system: yes\n shell: /bin/sh\n groups: admin\n comment: \"Git Version Control\"\n
\n\nSee: user module
\n\n- service:\n name: nginx\n state: started\n enabled: yes # optional\n
\n\nSee: service module
\n\n- shell: apt-get install nginx -y\n
\n\n- shell: echo hello\n args:\n creates: /path/file # skip if this exists\n removes: /path/file # skip if this is missing\n chdir: /path # cd here before running\n
\n\n- shell: |\n echo \"hello there\"\n echo \"multiple lines\"\n
\n\nSee: shell module
\n\n- script: /x/y/script.sh\n args:\n creates: /path/file # skip if this exists\n removes: /path/file # skip if this is missing\n chdir: /path # cd here before running\n
\n\nSee: script module
\n\n- file:\n path: /etc/dir\n state: directory # file | link | hard | touch | absent\n\n # Optional:\n owner: bin\n group: wheel\n mode: 0644\n recurse: yes # mkdir -p\n force: yes # ln -nfs\n
\n\nSee: file module
\n\n- copy:\n src: /app/config/nginx.conf\n dest: /etc/nginx/nginx.conf\n\n # Optional:\n owner: user\n group: user\n mode: 0644\n backup: yes\n
\n\nSee: copy module
\n\n- template:\n src: config/redis.j2\n dest: /etc/redis.conf\n\n # Optional:\n owner: user\n group: user\n mode: 0644\n backup: yes\n
\n\nSee: template module
\n\n- name: do something locally\n local_action: shell echo hello\n
\n\n- debug:\n msg: \"Hello {{ var }}\"\n
\n\nSee: debug module
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-10-03" },{ "id": "ansible-roles", "title": "Ansible roles", "url": "/ansible-roles", "category": "Ansible", "keywords": null, "content_html": "roles/\n common/\n tasks/\n handlers/\n files/ # 'copy' will refer to this\n templates/ # 'template' will refer to this\n meta/ # Role dependencies here\n vars/\n defaults/\n main.yml\n
\n\n$ sudo mkdir /etc/ansible\n$ sudo vim /etc/ansible/hosts\n\n[example]\n192.0.2.101\n192.0.2.102\n
\n\n$ ansible-playbook playbook.yml\n
\n\n- hosts: all\n user: root\n sudo: no\n vars:\n aaa: bbb\n tasks:\n - ...\n handlers:\n - ...\n
\n\ntasks:\n - include: db.yml\nhandlers:\n - include: db.yml user=timmy\n
\n\nhandlers:\n - name: start apache2\n action: service name=apache2 state=started\n\ntasks:\n - name: install apache\n action: apt pkg=apache2 state=latest\n notify:\n - start apache2\n
\n\n- host: lol\n vars_files:\n - vars.yml\n vars:\n project_root: /etc/xyz\n tasks:\n - name: Create the SSH directory.\n file: state=directory path=${project_root}/home/.ssh/\n only_if: \"$vm == 0\"\n
\n\n- host: xxx\n roles:\n - db\n - { role:ruby, sudo_user:$user }\n - web\n\n# Uses:\n# roles/db/tasks/*.yml\n# roles/db/handlers/*.yml\n
\n\n- name: my task\n command: ...\n register: result\n failed_when: \"'FAILED' in result.stderr\"\n\n ignore_errors: yes\n\n changed_when: \"result.rc != 2\"\n
\n\nvars:\n local_home: \"{{ lookup('env','HOME') }}\"\n
\n\nCACHE MANIFEST\n# version\n\nCACHE:\nhttp://www.google.com/jsapi\n/assets/app.js\n/assets/bg.png\n\nNETWORK:\n*\n
\n\nNote that Appcache is deprecated!
\n\nSee: Using the application cache (developer.mozilla.org)
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "applescript", "title": "AppleScript", "url": "/applescript", "category": "macOS", "keywords": null, "content_html": "osascript -e \"...\"\n
\n\ndisplay notification \"X\" with title \"Y\"\n
\n\n-- This is a single line comment\n
\n\n# This is another single line comment\n
\n\n(*\nThis is\na multi\nline comment\n*)\n
\n\n-- default voice\nsay \"Hi I am a Mac\"\n
\n\n-- specified voice\nsay \"Hi I am a Mac\" using \"Zarvox\"\n
\n\n-- beep once\nbeep\n
\n\n-- beep 10 times\nbeep 10\n
\n\n-- delay for 5 seconds\ndelay 5\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2018-12-06"
},{
"id": "applinks",
"title": "Applinks",
"url": "/applinks",
"category": "HTML",
"keywords": null,
"content_html": "<meta property=\"al:ios:url\" content=\"applinks://docs\" />\n<meta property=\"al:ios:app_store_id\" content=\"12345\" />\n<meta property=\"al:ios:app_name\" content=\"App Links\" />\n\n<meta property=\"al:android:url\" content=\"applinks://docs\" />\n<meta property=\"al:android:app_name\" content=\"App Links\" />\n<meta property=\"al:android:package\" content=\"org.applinks\" />\n\n<meta property=\"al:web:url\" content=\"http://applinks.org/documentation\" />\n
\n\nios
ipad
iphone
android
windows_phone
web
users = Arel::Table.new(:users)\nusers = User.arel_table # ActiveRecord model\n
\n\nusers[:name]\nusers[:id]\n
\n\nwhere
(restriction)users.where(users[:name].eq('amy'))\n# SELECT * FROM users WHERE users.name = 'amy'\n
\n\nselect
(projection)users.project(users[:id])\n# SELECT users.id FROM users\n
\n\njoin
In ActiveRecord (without Arel), if :photos
is the name of the association, use joins
users.joins(:photos)\n
\n\nIn Arel, if photos
is defined as the Arel table,
photos = Photo.arel_table\nusers.join(photos) \nusers.join(photos, Arel::Nodes::OuterJoin).on(users[:id].eq(photos[:user_id]))\n
\n\nusers.joins(:photos).merge(Photo.where(published: true))\n
\n\nIf the simpler version doesn’t help and you want to add more SQL statements to it:
\nusers.join(\n users.join(photos, Arel::Nodes::OuterJoin)\n .on(photos[:user_id].eq(users[:id]).and(photos[:published].eq(true)))\n)\n
\n\nmultiple joins
with the same table but different meanings and/or conditions
creators = User.arel_table.alias('creators')\nupdaters = User.arel_table.alias('updaters')\nphotos = Photo.arel_table\n\nphotos_with_credits = photos\n.join(photos.join(creators, Arel::Nodes::OuterJoin).on(photos[:created_by_id].eq(creators[:id])))\n.join(photos.join(updaters, Arel::Nodes::OuterJoin).on(photos[:assigned_id].eq(updaters[:id])))\n.project(photos[:name], photos[:created_at], creators[:name].as('creator'), updaters[:name].as('editor'))\n\nphotos_with_credits.to_sql\n# => \"SELECT `photos`.`name`, `photos`.`created_at`, `creators`.`name` AS creator, `updaters`.`name` AS editor FROM `photos` INNER JOIN (SELECT FROM `photos` LEFT OUTER JOIN `users` `creators` ON `photos`.`created_by_id` = `creators`.`id`) INNER JOIN (SELECT FROM `photos` LEFT OUTER JOIN `users` `updaters` ON `photos`.`updated_by_id` = `updaters`.`id`)\"\n\n# after the request is done, you can use the attributes you named\n# it's as if every Photo record you got has \"creator\" and \"editor\" fields, containing creator name and editor name\nphotos_with_credits.map{|x|\n \"#{photo.name} - copyright #{photo.created_at.year} #{photo.creator}, edited by #{photo.editor}\"\n}.join('; ')\n
\n\nlimit
/ offset
users.take(5) # => SELECT * FROM users LIMIT 5\nusers.skip(4) # => SELECT * FROM users OFFSET 4\n
\n\nusers.project(users[:age].sum) # .average .minimum .maximum\nusers.project(users[:id].count)\nusers.project(users[:id].count.as('user_count'))\n
\n\norder
users.order(users[:name])\nusers.order(users[:name], users[:age].desc)\nusers.reorder(users[:age])\n
\n\nUser.arel_table\nUser.where(id: 1).arel\n
\n\nMost of the clever stuff should be in scopes, e.g. the code above could become:
\nphotos_with_credits = Photo.with_creator.with_editor\n
\n\nYou can store requests in variables then add SQL segments:
\nall_time = photos_with_credits.count\nthis_month = photos_with_credits.where(photos[:created_at].gteq(Date.today.beginning_of_month))\nrecent_photos = photos_with_credits.where(photos[:created_at].gteq(Date.today.beginning_of_month)).limit(5)\n
\n\nShortcut | \nDescription | \n
---|---|
⌘\\ | \n Toggle tree | \n
⌘⇧\\ | \n Reveal current file | \n
Shortcut | \nDescription | \n
---|---|
⌘/ | \n Toggle comments | \n
Shortcut | \nDescription | \n
---|---|
⌘k ← | \n Split pane to the left | \n
⌘⌥= | \n Grow pane | \n
⌘⌥- | \n Shrink pane | \n
^⇧← | \n Move tab to left | \n
Shortcut | \nDescription | \n
---|---|
^m | \n Go to matching bracket | \n
^] | \n Remove brackets from selection | \n
^⌘m | \n Select inside brackets | \n
⌥⌘. | \n Close tag | \n
Shortcut | \nDescription | \n
---|---|
^⌥↓ | \n Jump to declaration under cursor | \n
^⇧r | \n Show tags | \n
Symbols view enables Ctags support for Atom.
\n\nSee: Symbols view
\n\n^⇧9 | \n Show Git pane | \n
^⇧8 | \n Show GitHub pane | \n
Shortcut | \nDescription | \n
---|---|
⌘d | \n Select word | \n
⌘l | \n Select line | \n
⌘↓ | \n Move line down | \n
⌘↑ | \n Move line up | \n
⌘⏎ | \n New line below | \n
⌘⇧⏎ | \n New line above | \n
⌘⇧k | \n Delete line | \n
⌘⇧d | \n Duplicate line | \n
Shortcut | \nDescription | \n
---|---|
⌘⇧p | \n Command palette | \n
⌘⇧a | \n Add project folder | \n
⌘n | \n New file | \n
⌘⇧n | \n New window | \n
⌘f | \n Find in file | \n
⌘⇧f | \n Find in project | \n
⌘t | \n Search files in project | \n
⌘
is the Control
key.Command
key.⌥
is the Alt
key.Option
key.Create action creators in flux standard action format.
\n\nincrement = createAction('INCREMENT', amount => amount)\nincrement = createAction('INCREMENT') // same\n
\n\nincrement(42) === { type: 'INCREMENT', payload: 42 }\n
\n\n// Errors are handled for you:\nerr = new Error()\nincrement(err) === { type: 'INCREMENT', payload: err, error: true }\n
\n\n\n\nA standard for flux action objects. An action may have an error
, payload
and meta
and nothing else.
{ type: 'ADD_TODO', payload: { text: 'Work it' } }\n{ type: 'ADD_TODO', payload: new Error(), error: true }\n
\n\n\n\nDispatch multiple actions in one action creator.
\n\nstore.dispatch([\n { type: 'INCREMENT', payload: 2 },\n { type: 'INCREMENT', payload: 3 }\n])\n
\n\n\n\nCombines reducers (like combineReducers()), but without namespacing magic.
\n\nre = reduceReducers(\n (state, action) => state + action.number,\n (state, action) => state + action.number\n)\n\nre(10, { number: 2 }) //=> 14\n
\n\n\n\nLogs actions to your console.
\n\n// Nothing to see here\n
\n\n\n\nPass promises to actions. Dispatches a flux-standard-action.
\n\nincrement = createAction('INCREMENT') // redux-actions\nincrement(Promise.resolve(42))\n
\n\n\n\nSorta like that, too. Works by letting you pass thunks (functions) to dispatch()
. Also has ‘idle checking’.
fetchData = (url) => (dispatch) => {\n dispatch({ type: 'FETCH_REQUEST' })\n fetch(url)\n .then((data) => dispatch({ type: 'FETCH_DONE', data })\n .catch((error) => dispatch({ type: 'FETCH_ERROR', error })\n})\n\nstore.dispatch(fetchData('/posts'))\n
\n\n// That's actually shorthand for:\nfetchData('/posts')(store.dispatch)\n
\n\n\n\nPass side effects declaratively to keep your actions pure.
\n\n{\n type: 'EFFECT_COMPOSE',\n payload: {\n type: 'FETCH'\n payload: {url: '/some/thing', method: 'GET'}\n },\n meta: {\n steps: [ [success, failure] ]\n }\n}\n
\n\n\n\nPass “thunks” to as actions. Extremely similar to redux-promises, but has support for getState.
\n\nfetchData = (url) => (dispatch, getState) => {\n dispatch({ type: 'FETCH_REQUEST' })\n fetch(url)\n .then((data) => dispatch({ type: 'FETCH_DONE', data })\n .catch((error) => dispatch({ type: 'FETCH_ERROR', error })\n})\n\nstore.dispatch(fetchData('/posts'))\n
\n\n// That's actually shorthand for:\nfetchData('/posts')(store.dispatch, store.getState)\n
\n\n// Optional: since fetchData returns a promise, it can be chained\n// for server-side rendering\nstore.dispatch(fetchPosts()).then(() => {\n ReactDOMServer.renderToString(<MyApp store={store} />)\n})\n
\n\n",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2017-11-19"
},{
"id": "awscli",
"title": "AWS CLI",
"url": "/awscli",
"category": "Devops",
"keywords": null,
"content_html": "aws ec2 describe-instances\naws ec2 start-instances --instance-ids i-12345678c\naws ec2 terminate-instances --instance-ids i-12345678c\n
\n\naws s3 ls s3://mybucket\naws s3 rm s3://mybucket/folder --recursive\naws s3 cp myfolder s3://mybucket/folder --recursive\naws s3 sync myfolder s3://mybucket/folder --exclude *.tmp\n
\n\naws ecs create-cluster\n --cluster-name=NAME\n --generate-cli-skeleton\n\naws ecs create-service\n
\n\nbrew install awscli\naws configure\n
\n\naws configure --profile project1\naws configure --profile project2\n
\n\neb config\n
\n\nSee: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html
\n\n.on('event', callback)\n.on('event', callback, context)\n
\n\n.on({\n 'event1': callback,\n 'event2': callback\n})\n
\n\n.on('all', callback)\n
\n\n.once('event', callback) // Only happens once\n
\n\nobject.off('change', onChange) // just the `onChange` callback\nobject.off('change') // all 'change' callbacks\nobject.off(null, onChange) // `onChange` callback for all events\nobject.off(null, null, context) // all callbacks for `context` all events\nobject.off() // all\n
\n\nobject.trigger('event')\n
\n\nview.listenTo(object, event, callback)\nview.stopListening()\n
\n\nadd
(model, collection, options)remove
(model, collection, options)reset
(collection, options)sort
(collection, options)change
(model, options)change:[attr]
(model, value, options)destroy
(model, collection, options)error
(model, xhr, options)request
(model, xhr, options)sync
(model, resp, options)route:[name]
(params)route
(router, route, params)// All attributes are optional\nvar View = Backbone.View.extend({\n model: doc,\n
\n\n tagName: 'div',\n className: 'document-item',\n id: \"document-\" + doc.id,\n attributes: { href: '#' },\n
\n\n el: 'body',\n
\n\n events: {\n 'click button.save': 'save',\n 'click .cancel': function() { ··· },\n 'click': 'onclick'\n },\n
\n\n constructor: function() { ··· },\n render: function() { ··· }\n})\n
\nview = new View()\nview = new View({ el: ··· })\n
\n\nview.$el.show()\nview.$('input')\n
\n\nview.remove()\n
\n\nview.delegateEvents()\nview.undelegateEvents()\n
\n\n// All attributes are optional\nvar Model = Backbone.Model.extend({\n defaults: {\n 'author': 'unknown'\n },\n idAttribute: '_id',\n parse: function() { ··· }\n})\n
\n\nvar obj = new Model({ title: 'Lolita', author: 'Nabokov' })\n
\n\nvar obj = new Model({ collection: ··· })\n
\n\nobj.id\nobj.cid // → 'c38' (client-side ID)\n
\n\nobj.clone()\n
\n\nobj.hasChanged('title')\nobj.changedAttributes() // false, or hash\nobj.previousAttributes() // false, or hash\nobj.previous('title')\n
\n\nobj.isNew()\n
\n\nobj.set({ title: 'A Study in Pink' })\nobj.set({ title: 'A Study in Pink' }, { validate: true, silent: true })\nobj.unset('title')\n
\n\nobj.get('title')\nobj.has('title')\nobj.escape('title') /* Like .get() but HTML-escaped */\n
\n\nobj.clear()\nobj.clear({ silent: true })\n
\n\nobj.save()\nobj.save({ attributes })\nobj.save(null, {\n silent: true, patch: true, wait: true,\n success: callback, error: callback\n})\n
\n\nobj.destroy()\nobj.destroy({\n wait: true,\n success: callback, error: callback\n})\n
\n\nobj.toJSON()\n
\n\nobj.fetch()\nobj.fetch({ success: callback, error: callback })\n
\n\nvar Model = Backbone.Model.extend({\n validate: function(attrs, options) {\n if (attrs.end < attrs.start) {\n return \"Can't end before it starts\"\n }\n }\n})\n
\n\nobj.validationError //=> \"Can't end before it starts\"\nobj.isValid()\nobj.on('invalid', function (model, error) { ··· })\n
\n\n// Triggered on:\nobj.save()\nobj.set({ ··· }, { validate: true })\n
\n\nvar Model = Backbone.Model.extend({\n // Single URL (string or function)\n url: '/account',\n url: function() { return '/account' },\n
\n\n // Both of these two work the same way\n url: function() { return '/books/' + this.id }),\n urlRoot: '/books'\n})\n
\n\nvar obj = new Model({ url: ··· })\nvar obj = new Model({ urlRoot: ··· })\n
\n\nHere are some badges for open source projects.
\n\nTravis\n[](https://travis-ci.org/rstacruz/REPO) \nCodeClimate (shields.io)\n[](https://codeclimate.com/github/rstacruz/REPO \n\"CodeClimate\")\n\nCoveralls (shields.io)\n[](https://coveralls.io/r/rstacruz/REPO)\n\nTravis (shields.io)\n[](https://travis-ci.org/rstacruz/REPO \"See test builds\")\n\nNPM (shields.io)\n[](https://npmjs.org/package/REPO \"View this project on npm\")\n\nRuby gem (shields.io)\n[](http://rubygems.org/gems/GEMNAME \"View this project in Rubygems\")\n
\n\nGitter chat\n[](https://gitter.im/REPO/GITTERROOM \"Gitter chat\")\n\nGitter chat (shields.io)\n[]( https://gitter.im/USER/REPO )\n\ndavid-dm\n[](https://david-dm.org/rstacruz/REPO)\n\n[](http://opensource.org/licenses/MIT)\n
\n\nSupport\n-------\n\n__Bugs and requests__: submit them through the project's issues tracker.<br>\n[]( https://github.com/USER/REPO/issues )\n\n__Questions__: ask them at StackOverflow with the tag *REPO*.<br>\n[]( http://stackoverflow.com/questions/tagged/REPO )\n\n__Chat__: join us at gitter.im.<br>\n[]( https://gitter.im/USER/REPO )\n
\n\nInstallation\n------------\n\nAdd [nprogress.js] and [nprogress.css] to your project.\n\n```html\n<script src='nprogress.js'></script>\n<link rel='stylesheet' href='nprogress.css'/>\n```\n\nNProgress is available via [bower] and [npm].\n\n $ bower install --save nprogress\n $ npm install --save nprogress\n\n[bower]: http://bower.io/search/?q=nprogress\n[npm]: https://www.npmjs.org/package/nprogress\n
\n\n**PROJECTNAME** © 2014+, Rico Sta. Cruz. Released under the [MIT] License.<br>\nAuthored and maintained by Rico Sta. Cruz with help from contributors ([list][contributors]).\n\n> [ricostacruz.com](http://ricostacruz.com) · \n> GitHub [@rstacruz](https://github.com/rstacruz) · \n> Twitter [@rstacruz](https://twitter.com/rstacruz)\n\n[MIT]: http://mit-license.org/\n[contributors]: http://github.com/rstacruz/nprogress/contributors\n
\n\nEverything: http://shields.io/
\nVersion badge (gems, npm): http://badge.fury.io/
\nDependencies (ruby): http://gemnasium.com/
\nCI: http://travis-ci.org/
\nCode quality (ruby): http://codeclimate.com/
\nTest coverage: https://coveralls.io/
\nThis is a quick reference to getting started with Bash scripting.
\n\n#!/usr/bin/env bash\n\nNAME=\"John\"\necho \"Hello $NAME!\"\n
\n\nNAME=\"John\"\necho $NAME\necho \"$NAME\"\necho \"${NAME}!\"\n
\n\nNAME=\"John\"\necho \"Hi $NAME\" #=> Hi John\necho 'Hi $NAME' #=> Hi $NAME\n
\n\necho \"I'm in $(pwd)\"\necho \"I'm in `pwd`\"\n# Same\n
\n\n\n\ngit commit && git push\ngit commit || echo \"Commit failed\"\n
\n\nget_name() {\n echo \"John\"\n}\n\necho \"You are $(get_name)\"\n
\n\nSee: Functions
\n\nif [[ -z \"$string\" ]]; then\n echo \"String is empty\"\nelif [[ -n \"$string\" ]]; then\n echo \"String is not empty\"\nfi\n
\n\nSee: Conditionals
\n\nset -euo pipefail\nIFS=$'\\n\\t'\n
\n\nSee: Unofficial bash strict mode
\n\necho {A,B}.js\n
\n\nExpression | \nDescription | \n
---|---|
{A,B} | \n Same as A B | \n
{A,B}.js | \n Same as A.js B.js | \n
{1..5} | \n Same as 1 2 3 4 5 | \n
See: Brace expansion
\n\nname=\"John\"\necho ${name}\necho ${name/J/j} #=> \"john\" (substitution)\necho ${name:0:2} #=> \"Jo\" (slicing)\necho ${name::2} #=> \"Jo\" (slicing)\necho ${name::-1} #=> \"Joh\" (slicing)\necho ${name:(-1)} #=> \"n\" (slicing from right)\necho ${name:(-2):1} #=> \"h\" (slicing from right)\necho ${food:-Cake} #=> $food or \"Cake\"\n
\n\nlength=2\necho ${name:0:length} #=> \"Jo\"\n
\n\nSee: Parameter expansion
\n\nSTR=\"/path/to/foo.cpp\"\necho ${STR%.cpp} # /path/to/foo\necho ${STR%.cpp}.o # /path/to/foo.o\necho ${STR%/*} # /path/to\n\necho ${STR##*.} # cpp (extension)\necho ${STR##*/} # foo.cpp (basepath)\n\necho ${STR#*/} # path/to/foo.cpp\necho ${STR##*/} # foo.cpp\n\necho ${STR/foo/bar} # /path/to/bar.cpp\n
\n\nSTR=\"Hello world\"\necho ${STR:6:5} # \"world\"\necho ${STR: -5:5} # \"world\"\n
\n\nSRC=\"/path/to/foo.cpp\"\nBASE=${SRC##*/} #=> \"foo.cpp\" (basepath)\nDIR=${SRC%$BASE} #=> \"/path/to/\" (dirpath)\n
\n\nCode | \nDescription | \n
---|---|
${FOO%suffix} | \n Remove suffix | \n
${FOO#prefix} | \n Remove prefix | \n
${FOO%%suffix} | \n Remove long suffix | \n
${FOO##prefix} | \n Remove long prefix | \n
${FOO/from/to} | \n Replace first match | \n
${FOO//from/to} | \n Replace all | \n
${FOO/%from/to} | \n Replace suffix | \n
${FOO/#from/to} | \n Replace prefix | \n
# Single line comment\n
\n\n: '\nThis is a\nmulti line\ncomment\n'\n
\n\nExpression | \nDescription | \n
---|---|
${FOO:0:3} | \n Substring (position, length) | \n
${FOO:(-3):3} | \n Substring from the right | \n
Expression | \nDescription | \n
---|---|
${#FOO} | \n Length of $FOO | \n
STR=\"HELLO WORLD!\"\necho ${STR,} #=> \"hELLO WORLD!\" (lowercase 1st letter)\necho ${STR,,} #=> \"hello world!\" (all lowercase)\n\nSTR=\"hello world!\"\necho ${STR^} #=> \"Hello world!\" (uppercase 1st letter)\necho ${STR^^} #=> \"HELLO WORLD!\" (all uppercase)\n
\n\nExpression | \nDescription | \n
---|---|
${FOO:-val} | \n $FOO , or val if unset (or null) | \n
${FOO:=val} | \n Set $FOO to val if unset (or null) | \n
${FOO:+val} | \n val if $FOO is set (and not null) | \n
${FOO:?message} | \n Show error message and exit if $FOO is unset (or null) | \n
Omitting the :
removes the (non)nullity checks, e.g. ${FOO-val}
expands to val
if unset otherwise $FOO
.
for i in /etc/rc.*; do\n echo $i\ndone\n
\n\nfor ((i = 0 ; i < 100 ; i++)); do\n echo $i\ndone\n
\n\nfor i in {1..5}; do\n echo \"Welcome $i\"\ndone\n
\n\nfor i in {5..50..5}; do\n echo \"Welcome $i\"\ndone\n
\n\ncat file.txt | while read line; do\n echo $line\ndone\n
\n\nwhile true; do\n ···\ndone\n
\n\nmyfunc() {\n echo \"hello $1\"\n}\n
\n\n# Same as above (alternate syntax)\nfunction myfunc() {\n echo \"hello $1\"\n}\n
\n\nmyfunc \"John\"\n
\n\nmyfunc() {\n local myresult='some value'\n echo $myresult\n}\n
\n\nresult=\"$(myfunc)\"\n
\n\nmyfunc() {\n return 1\n}\n
\n\nif myfunc; then\n echo \"success\"\nelse\n echo \"failure\"\nfi\n
\n\nExpression | \nDescription | \n
---|---|
$# | \n Number of arguments | \n
$* | \n All arguments | \n
$@ | \n All arguments, starting from first | \n
$1 | \n First argument | \n
$_ | \n Last argument of the previous command | \n
See Special parameters.
\n\nNote that [[
is actually a command/program that returns either 0
(true) or 1
(false). Any program that obeys the same logic (like all base utils, such as grep(1)
or ping(1)
) can be used as condition, see examples.
Condition | \nDescription | \n
---|---|
[[ -z STRING ]] | \n Empty string | \n
[[ -n STRING ]] | \n Not empty string | \n
[[ STRING == STRING ]] | \n Equal | \n
[[ STRING != STRING ]] | \n Not Equal | \n
[[ NUM -eq NUM ]] | \n Equal | \n
[[ NUM -ne NUM ]] | \n Not equal | \n
[[ NUM -lt NUM ]] | \n Less than | \n
[[ NUM -le NUM ]] | \n Less than or equal | \n
[[ NUM -gt NUM ]] | \n Greater than | \n
[[ NUM -ge NUM ]] | \n Greater than or equal | \n
[[ STRING =~ STRING ]] | \n Regexp | \n
(( NUM < NUM )) | \n Numeric conditions | \n
Condition | \nDescription | \n
---|---|
[[ -o noclobber ]] | \n If OPTIONNAME is enabled | \n
[[ ! EXPR ]] | \n Not | \n
[[ X && Y ]] | \n And | \n
[[ X || Y ]] | \n Or | \n
Condition | \nDescription | \n
---|---|
[[ -e FILE ]] | \n Exists | \n
[[ -r FILE ]] | \n Readable | \n
[[ -h FILE ]] | \n Symlink | \n
[[ -d FILE ]] | \n Directory | \n
[[ -w FILE ]] | \n Writable | \n
[[ -s FILE ]] | \n Size is > 0 bytes | \n
[[ -f FILE ]] | \n File | \n
[[ -x FILE ]] | \n Executable | \n
[[ FILE1 -nt FILE2 ]] | \n 1 is more recent than 2 | \n
[[ FILE1 -ot FILE2 ]] | \n 2 is more recent than 1 | \n
[[ FILE1 -ef FILE2 ]] | \n Same files | \n
# String\nif [[ -z \"$string\" ]]; then\n echo \"String is empty\"\nelif [[ -n \"$string\" ]]; then\n echo \"String is not empty\"\nelse\n echo \"This never happens\"\nfi\n
\n\n# Combinations\nif [[ X && Y ]]; then\n ...\nfi\n
\n\n# Equal\nif [[ \"$A\" == \"$B\" ]]\n
\n\n# Regex\nif [[ \"A\" =~ . ]]\n
\n\nif (( $a < $b )); then\n echo \"$a is smaller than $b\"\nfi\n
\n\nif [[ -e \"file.txt\" ]]; then\n echo \"file exists\"\nfi\n
\n\nFruits=('Apple' 'Banana' 'Orange')\n
\n\nFruits[0]=\"Apple\"\nFruits[1]=\"Banana\"\nFruits[2]=\"Orange\"\n
\n\necho ${Fruits[0]} # Element #0\necho ${Fruits[-1]} # Last element\necho ${Fruits[@]} # All elements, space-separated\necho ${#Fruits[@]} # Number of elements\necho ${#Fruits} # String length of the 1st element\necho ${#Fruits[3]} # String length of the Nth element\necho ${Fruits[@]:3:2} # Range (from position 3, length 2)\necho ${!Fruits[@]} # Keys of all elements, space-separated\n
\n\nFruits=(\"${Fruits[@]}\" \"Watermelon\") # Push\nFruits+=('Watermelon') # Also Push\nFruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match\nunset Fruits[2] # Remove one item\nFruits=(\"${Fruits[@]}\") # Duplicate\nFruits=(\"${Fruits[@]}\" \"${Veggies[@]}\") # Concatenate\nlines=(`cat \"logfile\"`) # Read from file\n
\n\nfor i in \"${arrayName[@]}\"; do\n echo $i\ndone\n
\n\ndeclare -A sounds\n
\n\nsounds[dog]=\"bark\"\nsounds[cow]=\"moo\"\nsounds[bird]=\"tweet\"\nsounds[wolf]=\"howl\"\n
\n\nDeclares sound
as a Dictionary object (aka associative array).
echo ${sounds[dog]} # Dog's sound\necho ${sounds[@]} # All values\necho ${!sounds[@]} # All keys\necho ${#sounds[@]} # Number of elements\nunset sounds[dog] # Delete dog\n
\n\nfor val in \"${sounds[@]}\"; do\n echo $val\ndone\n
\n\nfor key in \"${!sounds[@]}\"; do\n echo $key\ndone\n
\n\nset -o noclobber # Avoid overlay files (echo \"hi\" > foo)\nset -o errexit # Used to exit upon error, avoiding cascading errors\nset -o pipefail # Unveils hidden failures\nset -o nounset # Exposes unset variables\n
\n\nshopt -s nullglob # Non-matching globs are removed ('*.foo' => '')\nshopt -s failglob # Non-matching globs throw errors\nshopt -s nocaseglob # Case insensitive globs\nshopt -s dotglob # Wildcards match dotfiles (\"*.sh\" => \".foo.sh\")\nshopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')\n
\n\nSet GLOBIGNORE
as a colon-separated list of patterns to be removed from glob\nmatches.
Command | \nDescription | \n
---|---|
history | \n Show history | \n
shopt -s histverify | \n Don’t execute expanded result immediately | \n
Expression | \nDescription | \n
---|---|
!$ | \n Expand last parameter of most recent command | \n
!* | \n Expand all parameters of most recent command | \n
!-n | \n Expand n th most recent command | \n
!n | \n Expand n th command in history | \n
!<command> | \n Expand most recent invocation of command <command> | \n
Code | \nDescription | \n
---|---|
!! | \n Execute last command again | \n
!!:s/<FROM>/<TO>/ | \n Replace first occurrence of <FROM> to <TO> in most recent command | \n
!!:gs/<FROM>/<TO>/ | \n Replace all occurrences of <FROM> to <TO> in most recent command | \n
!$:t | \n Expand only basename from last parameter of most recent command | \n
!$:h | \n Expand only directory from last parameter of most recent command | \n
!!
and !$
can be replaced with any valid expansion.
Code | \nDescription | \n
---|---|
!!:n | \n Expand only n th token from most recent command (command is 0 ; first argument is 1 ) | \n
!^ | \n Expand first argument from most recent command | \n
!$ | \n Expand last token from most recent command | \n
!!:n-m | \n Expand range of tokens from most recent command | \n
!!:n-$ | \n Expand n th token to last from most recent command | \n
!!
can be replaced with any valid expansion i.e. !cat
, !-2
, !42
, etc.
$((a + 200)) # Add 200 to $a\n
\n\n$((RANDOM%=200)) # Random number 0..200\n
\n\n(cd somedir; echo \"I'm now in $PWD\")\npwd # still in first directory\n
\n\npython hello.py > output.txt # stdout to (file)\npython hello.py >> output.txt # stdout to (file), append\npython hello.py 2> error.log # stderr to (file)\npython hello.py 2>&1 # stderr to stdout\npython hello.py 2>/dev/null # stderr to (null)\npython hello.py &>/dev/null # stdout and stderr to (null)\n
\n\npython hello.py < foo.txt # feed foo.txt to stdin for python\n
\n\ncommand -V cd\n#=> \"cd is a function/alias/whatever\"\n
\n\ntrap 'echo Error at about $LINENO' ERR\n
\n\nor
\n\ntraperr() {\n echo \"ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}\"\n}\n\nset -o errtrace\ntrap traperr ERR\n
\n\ncase \"$1\" in\n start | up)\n vagrant up\n ;;\n\n *)\n echo \"Usage: $0 {start|stop|ssh}\"\n ;;\nesac\n
\n\nsource \"${0%/*}/../share/foo.sh\"\n
\n\nprintf \"Hello %s, I'm %s\" Sven Olga\n#=> \"Hello Sven, I'm Olga\n\nprintf \"1 + 1 = %d\" 2\n#=> \"1 + 1 = 2\"\n\nprintf \"This is how you print a float: %f\" 2\n#=> \"This is how you print a float: 2.000000\"\n
\n\nDIR=\"${0%/*}\"\n
\n\nwhile [[ \"$1\" =~ ^- && ! \"$1\" == \"--\" ]]; do case $1 in\n -V | --version )\n echo $version\n exit\n ;;\n -s | --string )\n shift; string=$1\n ;;\n -f | --flag )\n flag=1\n ;;\nesac; shift; done\nif [[ \"$1\" == '--' ]]; then shift; fi\n
\n\ncat <<END\nhello world\nEND\n
\n\necho -n \"Proceed? [y/n]: \"\nread ans\necho $ans\n
\n\nread -n 1 ans # Just one character\n
\n\nExpression | \nDescription | \n
---|---|
$? | \n Exit status of last task | \n
$! | \n PID of last background task | \n
$$ | \n PID of shell | \n
$0 | \n Filename of the shell script | \n
See Special parameters.
\n\npwd # /home/user/foo\ncd bar/\npwd # /home/user/foo/bar\ncd -\npwd # /home/user/foo\n
\n\nif ping -c 1 google.com; then\n echo \"It appears you have a working internet connection\"\nfi\n
\n\nif grep -q 'foo' ~/.bash_history; then\n echo \"You appear to have typed 'foo' in the past\"\nfi\n
\n\nscreen = blessed.screen({\n smartCSR: true // optimize for flickering\n autoPadding: true // ..\n})\n\nscreen.append(Element)\nscreen.destroy()\n\nscreen.width\nscreen.height\nscreen.title = 'My window title'\nscreen.key(['escape', 'q', 'C-c'], (ch, key) => { ... })\n
\n\nbox = blessed.box({\n style: { fg, bg, border.fg, scrollbar.bg, focus.bg, hover.bg },\n border: { type: 'line'|'bg', bg, fg, bold, underline }\n tags: true, // parse {bold}tags{/bold}\n\n top, left, width, height,\n width: '100%',\n height: '100%-1',\n top: 'center'\n})\n
\n\n{bold}\n{right} {center}\n{|} left-right separator\n{#c0ff33-fg}{/}\n
\n\nblessed.escape('...')\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "bluebird",
"title": "bluebird.js",
"url": "/bluebird",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "Also see the promise cheatsheet and Bluebird.js API (github.com).
\n\npromise\n .then(okFn, errFn)\n .spread(okFn, errFn) // *\n .catch(errFn)\n .catch(TypeError, errFn) // *\n .finally(fn)\n .map(function (e) { ··· }) // *\n .each(function (e) { ··· }) // *\n
\n\nThose marked with *
are non-standard Promise API that only work with Bluebird promises.
.then(function () {\n return [ 'abc', 'def' ]\n})\n.spread(function (abc, def) {\n ···\n})\n
\n\nUse Promise.spread
\n\nPromise.join(\n getPictures(),\n getMessages(),\n getTweets(),\n function (pics, msgs, tweets) {\n return ···\n }\n)\n
\n\nUse Promise.join
\n\ncount
to passsome([p], 1)
.any
insteadPromise.all([ promise1, promise2 ])\n .then(results => {\n results[0]\n results[1]\n })\n\n// succeeds if one succeeds first\nPromise.any(promises)\n .then(results => {\n })\n
\n\nPromise.map(urls, url => fetch(url))\n .then(···)\n
\n\nUse Promise.map to “promisify” a list of values.
\n\nPromise.props({\n photos: get('photos'),\n posts: get('posts')\n})\n.then(res => {\n res.photos\n res.posts\n})\n
\n\nUse Promise.props.
\n\nfunction getPhotos() {\n return Promise.try(() => {\n if (err) throw new Error(\"boo\")\n return result\n })\n}\n\ngetPhotos().then(···)\n
\n\nUse Promise.try.
\n\nvar readFile = Promise.promisify(fs.readFile)\nvar fs = Promise.promisifyAll(require('fs'))\n
\n\nSee Promisification.
\n\nUser.login = Promise.method((email, password) => {\n if (!valid)\n throw new Error(\"Email not valid\")\n\n return /* promise */\n})\n
\n\nSee Promise.method.
\n\nUser.login = Promise.coroutine(function* (email, password) {\n let user = yield User.find({email: email}).fetch()\n return user\n})\n
\n\nSee Promise.coroutine.
\n\nhttp://bluebirdjs.com/docs/api-reference.html
", "intro_html": "", "description_html": "", "tags": null, "updated": "2017-09-08" },{ "id": "bolt", "title": "Bolt Quickstart", "url": "/bolt", "category": "Bolt", "keywords": ["Puppet","tasks","modules"], "content_html": "# On MacOS\nbrew cask install puppetlabs/puppet/puppet-bolt\n# On Windows\nchoco install puppet-bolt\n
\n\nBolt is available as a package for most platforms. See installing bolt
\n\nmkdir -p ~/.puppetlabs/bolt/modules/mymodule/tasks\ncp myscript.sh ~/.puppetlabs/bolt/modules/mymodule/tasks/\n
\n\nTasks can be written in any language your targets can run. See writing tasks for more details.
\n\nbolt task run mymodule::myscript -n node1.example.com,node2.example.com --private-key ~/.ssh/id_rsa-private\n
\n\nSee bolt task run --help
for more information and command line options.
A quick guide to getting started writing Bolt tasks
", "tags": null, "updated": "2018-12-25" },{ "id": "bookshelf", "title": "Bookshelf.js", "url": "/bookshelf", "category": "JavaScript libraries", "keywords": null, "content_html": "Summary = bookshelf.Model.extend({\n tableName: 'summaries',\n hasTimestamps: true,\n hasTimestamps: ['created_at', 'updated_at'],\n})\n
\n\nSummary = bookshelf.Model.extend({\n book () {\n return this.belongsTo(Book)\n },\n author () {\n return this.hasOne(Author)\n }\n // belongsToMany\n // hasMany\n // hasMany().through()\n})\n
\n\nBook.create({ title: '..' }).save()\nnew Book({ title: '..' }).save()\n\nnew Book({ id: 1 }).fetch()\n\nBook.where({ id: 1 }).fetch()\nBook.where('favorite_color', 'red').fetch()\nBook.where('favorite_color', '<>', 'red').fetch()\nBook\n .query((q) => q.orderBy('updated_at')\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "bootstrap",
"title": "Bootstrap",
"url": "/bootstrap",
"category": "CSS",
"keywords": null,
"content_html": " 768 992 1200\n' ' ' ' ' ' ' ' '\n<---------^------------^------------------^--------->\n xs sm md lg\n (phone) (tablet) (laptop) (desktop)\n
\n\nMin:
\n\n@media (min-width: @screen-sm-min) // >= 768px (small tablet)\n@media (min-width: @screen-md-min) // >= 992px (medium laptop)\n@media (min-width: @screen-lg-min) // >= 1200px (large desktop)\n
\n\nMax:
\n\n@media (max-width: @screen-xs-max) { // < 768px (xsmall phone)\n@media (max-width: @screen-sm-max) { // < 992px (small tablet)\n@media (max-width: @screen-md-max) { // < 1200px (medium laptop)\n
\n\n.container\n.container-fluid\n
\n\n.col-xs-1\n.col-sm-1\n.col-md-1\n.col-lg-1\n.col-md-offset-1\n
\n\nMixins:
\n\n@include make-xs-column(12);\n@include make-sm-column(6);\n@include make-md-column(3);\n@include make-lg-column(3);\n
\n\n@include make-sm-column-offset(1);\n@include make-sm-column-push(1);\n@include make-sm-column-pull(1);\n
\n\n.pull-left\n.pull-right\n
\n\n.hidden-{xs,sm,md,lg}\n.visible-{xs,sm,md,lg}\n.visible-{xs,sm,md,lg,print}-{block,inline,inline-block}\n
\n\n.center-block /* margin: auto */\n.clearfix\n.text-{center,left,right,justify,nowrap}\n.text-{lowercase,uppercase,capitalize}\n
\n\n.show\n.hidden\n
\n\n<a data-toggle='modal' data-target='#new'>\n
\n\n#new.modal.fade(role='dialog')\n .modal-dialog // .modal-lg, .modal-sm\n .modal-content\n .modal-header\n %h4.modal-title hello\n %button.close{type: 'button', data: { dismiss: 'modal' }}\n %span{'aria-hidden' => true}!= \"×\"\n %span.sr-only Close\n .modal-body\n ...\n .modal-footer\n ...\n
\n\n%button.btn{data: { |\n toggle: 'modal', |\n target: '#chooseTheme', |\n remote: '/path/to/remote'}\n Change Theme\n
\n\n.modal.fade#chooseTheme\n .modal-dialog.modal-xl\n .modal-content\n .modal-header\n %h4.modal-title Choose a theme\n\n .modal-body\n .spinner-panel.-lg\n %i\n
\n\n<span\n data-toggle='tooltip'\n title='tooltip'\n data-placement='left|top|bottom|right'>\n
\n\n$(function () {\n $('[data-toogle~=\"tooltip\"]').tooltip()\n})\n
\n\n.input-group\n input.form-control(type='text')\n .input-group-addon years\n
",
"intro_html": "",
"description_html": ".container .row .col-md-6, @screen-sm-min, .form-control, grids, .modal-content, tooltips, and other Bootstrap CSS examples.
", "tags": null, "updated": null },{ "id": "deprecated/bower-api", "title": "Bower API", "url": "/deprecated/bower-api", "category": "JavaScript libraries", "keywords": null, "content_html": "require('bower').config\n
\n\n{ cwd: '/Users/rsc',\n directory: 'bower_components',\n registry:\n { search: [ 'https://bower.herokuapp.com' ],\n register: 'https://bower.herokuapp.com',\n publish: 'https://bower.herokuapp.com' },\n shorthandResolver: 'git://github.com//.git',\n tmp: '/var/folders/5y/190gjd_j2c5bfkn563dk2xdr0000gn/T/rsc/bower',\n timeout: 30000,\n ca: { search: [] },\n strictSsl: true,\n userAgent: 'node/v0.10.33 darwin x64',\n color: true,\n storage:\n { packages: '/Users/rsc/.cache/bower/packages',\n links: '/Users/rsc/.local/share/bower/links',\n completion: '/Users/rsc/.local/share/bower/completion',\n registry: '/Users/rsc/.cache/bower/registry',\n empty: '/Users/rsc/.local/share/bower/empty' },\n interactive: false,\n argv: { remain: [], cooked: [], original: [] } }\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "browser-sync",
"title": "Browsersync",
"url": "/browser-sync",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "npm i -g browser-sync\n
\n\nbrowser-sync start --server <path> --files='**/*.html, **/*.css'\n
\n\n --port=N\n --proxy=\"http://127.0.0.1:3000\"\n
\n\nbrowserify input.js\n -o output.js\n -t coffeeify\n -t [ coffeeify --extension coffee ]\n\n -u react (--exclude: omit a file)\n -x react (--external: reference in another bundle)\n -i react (--ignore: stub a file)\n -s Myapp (--standalone: generate a UMD bundle)\n --debug\n
\n\nbrowserify = require('browserify')\nbrowserify()\n .add('main.js')\n .bundle()\n .transform(coffeeify)\n .transform({extensions: '.coffee'}, coffeeify)\n .pipe(process.stdout)\n\nbrowserify({})\n
\n\nTransforms
\n\n 768 1024 1216 1408\n' ' ' ' ' ' ' ' ' ' ' '\n<---------^------------^------------------^-------------^------------->\n mobile tablet desktop widescreen fullhd\n
\n\n.container\n
\nWrap as many .column
’s’ as you like in a .columns
wrapper
<div class=\"columns\">\n <div class=\"column\"></div>\n <div class=\"column\"></div>\n <div class=\"column\"></div>\n <div class=\"column\"></div>\n <div class=\"column\"></div>\n</div>\n
\n\nThe following CSS classes affect the colour.
\n\n.is-primary\n.is-link\n.is-info\n.is-success\n.is-warning\n.is-danger\n
\n\nThe following classes modify the size.
\n.is-small\n.is-medium\n.is-large\n
\n\nThe following classes modify the state.
\n.is-outlined\n.is-loading\n
\n\nThe following classes modify the font-size
\n\nClass | \nFont-size | \n
---|---|
.is-size-1 | \n 3rem | \n
.is-size-2 | \n 2.5rem | \n
.is-size-3 | \n 2rem | \n
.is-size-4 | \n 1.5rem | \n
.is-size-5 | \n 1.25rem | \n
.is-size-6 | \n 1rem | \n
.is-size-7 | \n 0.75rem | \n
The following classes align the text
\n\nClass | \nAlignment | \n
---|---|
.has-text-centered | \n Makes the text centered | \n
.has-text-justified | \n Makes the text justified | \n
.has-text-left . | \n Makes the text align to the left | \n
.has-text-right | \n Makes the text align to the right | \n
The following classes transform the text
\n\nClass | \nTransformation | \n
---|---|
.is-capitalized | \n Transforms the first character of each word to uppercase | \n
.is-lowercase | \n Transforms all characters to lowercase | \n
.is-uppercase | \n Transforms all characters to uppercase | \n
<div class=\"content\">\n <!-- start WYSIWYG contents -->\n <h1>Heading</h1>\n <p>Paragraph</p>\n\n <ul>\n <li>Item 1</li>\n <li>Item 2</li>\n </ul>\n <!-- end WYSIWYG contents -->\n</div>\n
\n\nTo provide default stylings for commonly generated WYSIWYG contents, use the .content
class.
Basic guide on how to use Bulma, the lightweight css flexbox framework.
", "tags": null, "updated": "2018-11-19" },{ "id": "bundler", "title": "Bundler", "url": "/bundler", "category": "Ruby", "keywords": null, "content_html": "bundle # same as bundle install\nbundle install # installs gems\nbundle install -j3 # faster (3 jobs)\nbundle update # update all gems\nbundle update --source gemname # update specified gem\n\nbundle outdated # show outdated gems\ncd `bundle show rails` # inspect a gem's dir\n\nbundle gem # new gem skeleton\n
\n\ngem 'hello'\ngem 'hello', group: 'development'\n
\n\ngem 'hello', github: 'rstacruz/hello'\ngem 'hello', github: 'rstacruz/hello', 'branch: master'\n
\n\ngroup :development do\n gem 'hello'\nend\n
\n\n$ bundle install --without=test,development --deployment\n
\n\nIn your Gemfile, define a Git source and a branch:
\n\ngem 'hello', github: 'rstacruz/hello', branch: 'master'\n
\n\nAnd then:
\n\n$ bundle config --global local.xxx ~/projects/xxx\n
\n\n# Rakefile\nrequire 'bundler/gem_tasks'\n
\n\nTerminal:
\n\n$ rake release\n$ rake build\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "c_preprocessor",
"title": "C Preprocessor",
"url": "/c_preprocessor",
"category": "C-like",
"keywords": null,
"content_html": "$ cpp -P file > outfile\n
\n\n#include \"file\"\n
\n\n#define FOO\n#define FOO \"hello\"\n\n#undef FOO\n
\n\n#ifdef DEBUG\n console.log('hi');\n#elif defined VERBOSE\n ...\n#else\n ...\n#endif\n
\n\n#if VERSION == 2.0\n #error Unsupported\n #warning Not really supported\n#endif\n
\n\n#define DEG(x) ((x) * 57.29)\n
\n\n#define DST(name) name##_s name##_t\nDST(object); #=> \"object_s object_t;\"\n
\n\n#define LOG(msg) console.log(__FILE__, __LINE__, msg)\n#=> console.log(\"file.txt\", 3, \"hey\")\n
",
"intro_html": "Quick reference for the C macro preprocessor, which can be used independent of C/C++.
", "description_html": "", "tags": null, "updated": null },{ "id": "camp", "title": "Camp", "url": "/camp", "category": "JavaScript libraries", "keywords": null, "content_html": "const Camp = require('camp')\nconst camp = Camp.start({ port: 1234 })\n
\n\n<!doctype html>\n<body>Hello world!</body>\n
\n\nCamp serves files in web/
by default.
/search?q=rainbows
camp.path('/search', (req, res) => {\n const q = res.query.q\n res.json({ results: ··· })\n})\n
\n\nAlso available: camp.post
, camp.get
.
const tpl = Camp.template('./templates/post.html')\n\ncamp.path('/blog/:post.html', (req, res) => {\n res.template({\n text: 'Hello world'\n }, tpl)\n})\n
\n\nSee: Templates
\n\ncamp.notFound('/*.lol', (req, res) => {\n res.file('/404.html')\n})\n
\n\nSee: Fall through
\n\ncamp.handle((req, res, next) => {\n res.setHeader('X-Hello', 'world')\n next()\n})\n
\n\nSee: Handlers
\n\nconst tpl = Camp.template('/templates/post.html')\n\ncamp.path('/blog/:post.html', (req, res) => {\n res.template({\n text: 'Hello world'\n }, tpl)\n})\n
\n\ncamp.path('blog.html')\n
\n\nUses blog.html
as a template.
See: Templates
\n\ncamp.ws('/path', (socket) => { ··· })\n
\n\ncamp.wsChannels[path]\n
\n\ncamp.wsBroadcast('/path', (req, res) => {\n})\n
\n\nSorry I don’t completely understand this yet, but check it out in their docs.
\n\nSee: WebSocket
", "intro_html": "Camp is a Node.js web server framework. This guide targets Camp v17.x.
", "description_html": "", "tags": null, "updated": "2017-09-21" },{ "id": "canvas", "title": "Canvas", "url": "/canvas", "category": "JavaScript", "keywords": null, "content_html": "var canvas = document.getElementById('c')\nvar c = canvas.getContext('2d')\n
\n\n// x = 10, y = 20, width = 200, height = 100\nc.fillStyle = '#ff0000'\nc.strokeStyle = '#ff00ff'\n
\n\nc.lineWidth = 5\nc.lineCap = 'round'\n
\n\nc.fillRect(10, 20, 200, 100)\n
\n\nc.stroke()\nc.fill()\n
\n\nc.save()\n
\n\nc.restore()\n
\n\nSaves: strokeStyle
fillStyle
globalAlpha
lineWidth
lineCap
lineJoin
miterLimit
shadowOffsetX
shadowOffsetY
shadowBlur
shadowColor
\nglobalCompositeOperation
, Transformations (translate
rotate
scale
transform
setTransform
), Clipping path
onframe: function() {\n c.clearRect(0, 0, w, h)\n}\n
\n\nc.translate(0, 0)\nc.rotate(Math.PI*2/5)\nc.scale(1.0, 1.0)\n
\n\nTo rotate along origin:
\n\nc.translate(ox, oy)\nc.rotate(theta)\nc.translate(-ox, -oy)\n
\n\nTo scale along origin:
\n\nc.translate(-ox*x, -oy*y)\nc.scale(x, y)\nc.translate(ox/x, oy/y)\n
\n\nSee MDN: Transformations.
\n\nc.drawImage(image, dx, dy, [dw, dh]);\n/* `image` can be HTML Image/Canvas/Video */\n
\n\nSee MDN: Images.
\n\nc.strokeStyle = '#ff00ff';\nc.fillStyle = '#ff00ff';\n
\n\nc.shadowOffsetX = 0;\nc.shadowOffsetY = 0;\nc.shadowOffsetBlur = 3.0;\nc.shadowColor = 'rgba(0,0,0,0.2)';\n
\n\nSee MDN: Styles
\n\ngr = c.createLinearGradient(x0,y0,x1,y1)\ngr = c.createRadialGradient(x0,y0,r0,x1,y1,r1)\npat = c.createPattern(image, 'repeat-x')\n
\n\nc.fillStyle = gr\n
\n\nc.beginPath()\nc.moveTo(x,y)\nc.lineTo(x,y)\nc.quadraticCurveTo(cpx,cpy,x,y)\nc.bezierCurveTo(cp1x,cp1y,cp2x,cp2y)\nc.arcTo(...)\nc.arc(...)\nc.closePath()\n
\n\nvisit articles_path\n
\n\nclick_on 'Link Text'\nclick_button\nclick_link\n
\n\nattach_file 'Image', '/path/to/image.jpg'\nfill_in 'First Name', with: 'John'\n
\n\ncheck 'A checkbox'\nuncheck 'A checkbox'\n
\n\nchoose 'A radio button'\n
\n\nselect 'Option', from: 'Select box'\nunselect\n
\n\nwithin '.classname' do\n click '...'\nend\n
\n\nwithin_fieldset :id do\n ...\nend\n
\n\npage.has_css?('.button')\nexpect(page).to have_css('.button')\npage.should have_css('.button')\n
\n\nPositive | \nNegative | \n
---|---|
has_content? | \n has_no_content? | \n
has_css? (selector) | \n has_no_css? | \n
has_xpath? (path) | \n has_no_xpath? | \n
has_link? (selector) | \n has_no_link? | \n
has_button? (selector) | \n has_no_button? | \n
has_field? (selector) | \n has_no_field? | \n
has_checked_field? (selector) | \n has_unchecked_field? | \n
has_table? (selector) | \n has_no_table? | \n
has_select? (selector) | \n has_no_select? | \n
In Rspec, these also map to matchers like page.should have_content
.
expect(page).to have_button('Save')\n
\n\nexpect(page).to have_button('#submit')\n
\n\nexpect(page).to have_button('//[@id=\"submit\"]')\n
\n\nThe selector
arguments can be text, CSS selector, or XPath expression.
page.has_button?('Save')\n
\n\nexpect(page).to have_no_button('Save')\n
\n\nIn RSpec, you can use page.should
assertions.
expect(page).to have_no_button('Save') # OK\n
\nexpect(page).not_to have_button('Save') # Bad\n
\n\nUse should have_no_*
versions with RSpec matchers because\nshould_not have_*
doesn’t wait for a timeout from the driver.
expect(page).to \\\n
\n\n have_selector '.blank-state'\n have_selector 'h1#hola', text: 'Welcome'\n have_button 'Save'\n have_checked_field '#field'\n have_unchecked_field\n have_css '.class'\n have_field '#field'\n have_table '#table'\n have_xpath '//div'\n
\n\n have_link 'Logout', href: logout_path\n
\n\n have_select 'Language',\n selected: 'German'\n options: ['Engish', 'German']\n with_options: ['Engish', 'German'] # partial match\n
\n\n have_text 'Hello',\n type: :visible # or :all\n # alias: have_content\n
\n\nAll matchers have these options:
\n\n text: 'welcome'\n text: /Hello/\n visible: true\n count: 4\n between: 2..5\n minimum: 2\n maximum: 5\n wait: 10\n
\n\nfind(selector)\nfind_button(selector)\nfind_by_id(id)\nfind_field(selector)\nfind_link(selector)\nlocate\n
\n\nwithin '#delivery' do\n fill_in 'Street', with: 'Hello'\nend\n
\n\nwithin :xpath, '//article'\nwithin_fieldset\nwithin_table\nwithin_frame\nscope_to\n
\n\nfind('#x').fill_in('Street', with: 'Hello')\n# same as within\n
\n\nexecute_script('$(\"input\").trigger(\"change\")')\nevaluate_script('window.ga')\n
\n\nExecutes JavaScript.
\n\nsave_and_open_page\n
\n\nOpens the webpage in your browser.
\n\npage\n .all('h3')\n .body\n .html\n .source\n .current_host\n .current_path\n .current_url\n
\n\nusing_wait_time 10 do\n ...\nend\n
\n\ndrag\nfield_labeled\n
\n\npage.status_code == 200\npage.response_headers\n
\n\nSee: http://www.rubydoc.info/github/jnicklas/capybara/master/Capybara/Session
\n\nCapybara.register_driver :poltergeist do |app|\n Capybara::Poltergeist::Driver.new(app, :inspector => true)\nend\nCapybara.javascript_driver = :poltergeist\n
\n\nUse poltergeist to integrate PhantomJS.
\n\nconfig.before :each, :js do\n page.driver.browser.url_blacklist = [\n 'fonts.googleapis.com',\n 'use.typekit.net',\n 'f.vimeocdn.com',\n 'player.vimeo.com',\n 'www.googletagmanager.com'\n ].flat_map { |domain| [ \"http://#{domain}\", \"https://#{domain}\" ] }\nend\n
\n\nEnable inspector: true
and then:
page.driver.debug\n
\n\nTo pause execution for a while:
\n\npage.driver.pause\n
\n\naccept_alert { ... }\ndismiss_confirm { ... }\naccept_prompt(with: 'hi') { ... }\n
\n\nAlternatively:
\n\npage.driver.browser.switch_to.alert.accept\n
\n\npage.set_rack_session(foo: 'bar')\n
\n\nconst { assert } = require('chai')\n
\n\nassert(val)\nassert.fail(actual, expected)\nassert.ok(val) // is truthy\nassert.equal(actual, expected) // compare with ==\nassert.strictEqual(actual, expected) // compare with ===\nassert.deepEqual(actual, expected) // deep equal check\n
\n\nassert.isTrue(val)\nassert.isFalse(val)\n
\n\nassert.isNull(val)\nassert.isNotNull(val)\nassert.isUndefined(val)\nassert.isDefined(val)\nassert.isFunction(val)\nassert.isObject(val)\nassert.isArray(val)\nassert.isString(val)\nassert.isNumber(val)\nassert.isBoolean(val)\n
\n\nassert.typeOf(/tea/, 'regexp') // Object.prototype.toString()\nassert.instanceOf(chai, Tea)\nassert.include([ a,b,c ], a)\nassert.match(val, /regexp/)\nassert.property(obj, 'tea') // 'tea' in object\nassert.deepProperty(obj, 'tea.green')\nassert.propertyVal(person, 'name', 'John')\nassert.deepPropertyVal(post, 'author.name', 'John')\n
\n\nassert.lengthOf(object, 3)\nassert.throws(function() { ... })\nassert.throws(function() { ... }, /reference error/)\nassert.doesNotThrow\n
\n\nassert.operator(1, '<', 2)\nassert.closeTo(actual, expected)\n
\n\nSee: Assert API (chaijs.com)
\n\nconst { expect } = require('chai')\n
\n\nexpect(object)\n .to.equal(expected)\n .to.eql(expected) // deep equality\n .to.deep.equal(expected) // same as .eql\n .to.be.a('string')\n .to.include(val)\n
\n\n .be.ok(val)\n .be.true\n .be.false\n .to.exist\n
\n\n .to.be.null\n .to.be.undefined\n .to.be.empty\n .to.be.arguments\n .to.be.function\n .to.be.instanceOf\n
\n\n .to.be.gt(5) // aka: .above .greaterThan\n .to.be.gte(5) // aka: .at.least\n .to.be.lt(5) // aka: .below\n
\n\n .to.respondTo('bar')\n .to.satisfy((n) => n > 0)\n
\n\n .to.have.members([2, 3, 4])\n .to.have.keys(['foo'])\n .to.have.key('foo')\n .to.have.lengthOf(3)\n
\n\nexpect(() => { ··· })\n .to.throw(/not a function/)\n
\n\nSee: BDD (chaijs.com)
\n\n.to .be .been .is .that .and .have .with .at .of .same\n
\n\nThese don’t do anything and can be chained.
\n\nexpect(object).not.equal('x')\n
\n\nglobal.jQuery = ···\nchai.use(require('chai-jquery'))\n
\n\nexpect($body)\n .have.attr('foo')\n .have.prop('disabled')\n .have.css('background')\n .have.css('background-color', '#ffffff')\n .have.data('foo')\n
\n\n .have.class('active')\n .have.id('id')\n
\n\n .have.html('<em>hi</em>')\n .have.text('hello')\n .have.value('2013')\n
\n\nexpect($body)\n
\n\n .be.visible\n .be.hidden\n
\n\n .be.checked\n .be.selected\n
\n\n .be.enabled\n .be.disabled\n
\n\n .be.empty\n .to.exist\n .to.contain('text')\n .to.have('.selector')\n
",
"intro_html": "",
"description_html": "expect(x).to.be.equal(y) 〉 assert.equal(x, y) 〉 .to.be.true 〉 jQuery, assertions, TDD and BDD, and other Chai examples.
", "tags": null, "updated": "2018-06-25" },{ "id": "cheatsheet-styles", "title": "Cheatsheet styles", "url": "/cheatsheet-styles", "category": "Others", "keywords": null, "content_html": "-one-column | \n \n |
-two-column | \n (default) | \n
-three-column | \n \n |
-left-reference | \n 3 columns (short first column) | \n
-no-hide | \n Don’t hide H2 | \n
See: H2 sections
\n\n-prime | \n Highlight | \n
See: H3 sections
\n\n-bold-first | \n Bold first column | \n
-headers | \n Show headers | \n
-left-align | \n Don’t right align last column | \n
-mute-em | \n Lower opacity for italics | \n
-no-wrap | \n Don’t wrap text | \n
-shortcuts | \n Shortcut keys | \n
See: Tables
\n\n-box-chars | \n Less line height for box drawing chars | \n
-setup | \n Gray background | \n
-wrap | \n Enables line-wrapping | \n
See: Code
\n\n-setup | \n Gray background | \n
-crosslink | \n Has arrow on the link | \n
See: Paragraphs
\n\n-also-see | \n Lighter background | \n
-four-column | \n \n |
-six-column | \n \n |
See: Lists
\n\n## Section\n{: .-two-column}\n
\n\nDevhints uses Kramdown, and supports adding classes via Kramdown’s syntax.
\n\nEach section can have the following children:
\n\npre
ul
table
p
h4
This is a section with {: .-prime}
. Notice the fancy highlight! Great for “getting started” kind of snippets.
Every box is an H3 section. The box will encompass everything inside the body of the H3.
\n\nThis is a basic section with paragraphs in it.
\n\nhere.is(() => {\n some.code()\n})\n
\n\nhere.is.some.more()\n
\n\nCode blocks can be placed one after the other.
\n\nSee: Cheatsheets
\n\nhere.is(() => {\n some.code()\n})\n
\n\nhere.is.some.more()\n
\n\nCode blocks can have headings.
\n\napp.start(() => {\n const port = app.server.port\n console.log(`Started at ${port}`)\n})\n
\n\nAdd {: data-line=\"3\"}
to add line highlights.
app.start(() => {\n const port = app.server.port\n console.log(`Started at ${port}`)\n})\n
\n\nAdd {: data-line=\"2,3\"}
to add multiple line highlights.
import React from 'react'\n
\n\nclass Hello extends React.Component {\n render () {\n return <span>Hello</span>\n }\n}\n
\n\nAdd {: .-setup}
to a pre
or table
or ul
.
function createNode(nodeName: string, options: { key: string }) {\n return true\n}\n
\n\nLong lines will have scrollbars.
\n\n<script>(function(d,s){if(window.Promise&&[].includes&&Object.assign&&window.Map)return;var js,sc=d.getElementsByTagName(s)[0];js=d.createElement(s);js.src='https://cdn.polyfill.io/v2/polyfill.min.js';sc.parentNode.insertBefore(js, sc);}(document,'script'))</script>\n
\n\nAdd -wrap
to wrap long lines.
Here’s an extra paragraph after the list.
\n\ncreateElement()
componentDidMount()
componentWillUnmount()
shouldComponentUpdate()
componentWillReceiveProps()
Here’s an extra paragraph after the list.
\n\nAdd {: .-six-column}
to make large lists.
Add {: .-four-column}
to make large lists.
Add {: .-also-see}
.
This is a basic section with paragraphs in it. When paragraphs are the first elements in an H3 section’s body, they appear as white.
\n\n···\n
\n\nWhen paragraphs appear after pre
/table
/ul
, they appear with a gray background.
Here’s a prelude paragraph. Add {: .-setup}
to make paragraphs appear with a gray background.
···\n
\n\nAdd {: .-crosslink}
to make big loud external links:
···\n
\n\n\n\nExample | \nOutput | \n
---|---|
%m/%d/%Y | \n 06/05/2013 | \n
%A, %B %e, %Y | \n Sunday, June 5, 2013 | \n
%b %e %a | \n Jun 5 Sun | \n
Example | \nOutput | \n
---|---|
%H:%M | \n 23:05 | \n
%I:%M %p | \n 11:05 PM | \n
This is a basic table with h4’s.
\n\nV | \n Vector | \n
P | \n Pencil | \n
T | \n Text | \n
L | \n Line | \n
R | \n Rectangle | \n
O | \n Oval | \n
U | \n Rounded | \n
Add {: .-shortcuts}
to tables.
Prefix | \nExample | \nWhat | \n
---|---|---|
// | \n //hr[@class='edge'] | \n Anywhere | \n
./ | \n ./a | \n Relative | \n
/ | \n /html/body/div | \n Root | \n
Add {: .-headers}
to add headers.
···\n
\n\n···\n
\n\n···\n···\n···\n···\n···\n···\n···\n···\n
\n\n···\n
\n\n···\n
\n\n···\n
",
"intro_html": "This is a reference of styles that you can use on Devhints cheatsheets. How\nmeta!\nYou can refer to this when contributing your own cheatsheets to the GitHub repo.
", "description_html": "", "tags": ["WIP"], "updated": "2017-10-26" },{ "id": "chef", "title": "Chef", "url": "/chef", "category": "Devops", "keywords": null, "content_html": "In your server:
\n\n$ sudo apt-get install curl\n
\n\n$ curl -L https://omnitruck.chef.io/install.sh | sudo bash\nThank you for installing Chef!\n
\n\n$ chef-solo -v\n...\nChef: 14.5.33\n
\n\n wget http://github.com/chef-cookbooks/chef-repo/tarball/master -O - | tar xzf - --strip-components=1\n
\n\n$ knife supermarket download mysql\n
\n\n$ chef-solo -c solo.rb -j web.json\n
\n\nexecute \"tar --no-same-owner -zxf hi.tar.gz\" do\n cwd \"/usr/local/src\"\n creates \"/usr/local/src/node-v#{version}\"\nend\n
\n\nbash \"compile\" do\n cwd \"/usr/local/src/node-v#{version}\"\n code %[\n PATH=/usr/local/bin:$PATH\n ./configure\n make\n ]\n creates \"/usr/local/src/node-v#{version}/node\"\nend\n
\n\nremote_file \"/usr/local/src/hi.tar.gz\" do\n source \"http://...\"\n checksum \"ab83be...\"\n mode 0644\n action :create_if_missing\nend\n
\n\nruby_block \"name\" do\n block { File.read ... }\n not_if { File.exists?(...) }\nend\n
\n\nexecute \"name\" do\n cwd \"...\"\n environment({ \"PATH\" => \"...\" })\n command \"make install\"\n creates \"...\"\nend\n
\n\n creates \"/usr/local/src/node-v#{version}/node\"\n not_if { File.exists?('...') }\n
\n\nimage = ChunkyPNG::Image.from_file('file.png')\n
\n\nimage = ChunkyPNG::Image.from_blob(File.read('file.png'))\nimage = ChunkyPNG::Image.from_io(io) \n
\n\nLoads from file.png
.
image.save('filename.png')\n
\n\nFile.open('newfile.png', 'wb') { |io| image.write(io) }\nbinary_string = image.to_blob\n
\n\nWrites an image to newfile.png
.
image[0, 0] = ChunkyPNG::Color.rgba(255, 0,0, 128)\nimage.line(1, 1, 10, 1, ChunkyPNG::Color.from_hex('#aa007f'))\n
\n\ncrop(x, y, w, h)\n
\n\nnew_image = image.flip_horizontally.rotate_right\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "cidr",
"title": "CIDR",
"url": "/cidr",
"category": "Misc",
"keywords": null,
"content_html": "Range | \nFirst IP | \nLast IP | \n
---|---|---|
10.0.0.0/24 | \n10.0.0.0 | \n10.0.0.255 | \n
10.0.0.0/16 | \n10.0.0.0 | \n10.0.255.255 | \n
10.0.0.0/8 | \n10.0.0.0 | \n10.255.255.255 | \n
0.0.0.0/0 | \n(all) | \n(all) | \n
See: https://circleci.com/docs/configuration
\n\n## Customize the test machine\nmachine:\n\n timezone:\n America/Los_Angeles # Set the timezone\n\n # Version of ruby to use\n ruby:\n version:\n 1.8.7-p358-falcon-perf\n\n # Override /etc/hosts\n hosts:\n circlehost: 127.0.0.1\n dev.mycompany.com: 127.0.0.1\n\n # Add some environment variables\n environment:\n CIRCLE_ENV: test\n DATABASE_URL: postgres://ubuntu:@127.0.0.1:5432/circle_test\n\n## Customize checkout\ncheckout:\n post:\n - git submodule sync\n - git submodule update --init # use submodules\n\n## Customize dependencies\ndependencies:\n pre:\n - npm install coffeescript # install from a different package manager\n - gem uninstall bundler # use a custom version of bundler\n - gem install bundler --pre\n\n override:\n - bundle install: # note ':' here\n timeout: 180 # fail if command has no output for 3 minutes\n\n # we automatically cache and restore many dependencies between\n # builds. If you need to, you can add custom paths to cache:\n cache_directories:\n - \"custom_1\" # relative to the build directory\n - \"~/custom_2\" # relative to the user's home directory\n\n## Customize database setup\ndatabase:\n override:\n # replace CircleCI's generated database.yml\n - cp config/database.yml.ci config/database.yml\n - bundle exec rake db:create db:schema:load\n\n## Customize test commands\ntest:\n override:\n - phpunit test/unit-tests # use PHPunit for testing\n post:\n - bundle exec rake jasmine:ci: # add an extra test type\n environment:\n RAILS_ENV: test\n RACK_ENV: test\n\n## Customize deployment commands\ndeployment:\n staging:\n branch: master\n heroku:\n appname: foo-bar-123\n\n## Custom notifications\nnotify:\n webhooks:\n # A list of hashes representing hooks. Only the url field is supported.\n - url: https://someurl.com/hooks/circle\n
\n\nSee: https://circleci.com/docs/config-sample
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "co", "title": "co", "url": "/co", "category": "JavaScript libraries", "keywords": null, "content_html": "co(function * () {\n yield Promise.resolve(true)\n}).then(...)\n
\n\nA generator can yield
a thunk or promise. Using co()
will immediately invoke the block inside it.
var fn = co.wrap(function * (val) {\n return yield Promise.resolve(val)\n})\n\nfn().then(...)\n
\n\nUse co.wrap()
. Most of the time, you’ll be using co.wrap.
var get = unyield(function * () {\n})\n\nget(function (err, res) { ... })\n
\n\nUse unyield. (You can thunkify this later)
\n\nvar readFile = thunkify(fs.readFile)\n\nco(function * () {\n var data = yield readFile('index.txt', 'utf-8')\n})\n
\n\nUse thunkify. You can yield this. You can also use thenify too.
\n\nvar readFile = require('mz/fs').readFile\n\nvar getLines = co.wrap(function * (filename) {\n var data = yield readFile(filename, 'utf-8')\n return data.split('\\n')\n})\n\ngetLines('file.txt').then((lines) => { ... })\n
\n\nUse mz for async Node.js API. You can also either thunkify or thenify them instead.
", "intro_html": "co allows you to use generators to manage async flow.
", "description_html": "", "tags": null, "updated": "2017-10-27" },{ "id": "command_line", "title": "Command line stuff", "url": "/command_line", "category": "Others", "keywords": null, "content_html": "ls [options] [paths]\n
\n\nSwitch | \nDescription | \n
---|---|
-1 | \n One entry per line | \n
-l | \n Long view | \n
-o | \n Long view (without groups) | \n
-C | \n Multicolumn (sorted horizontally) | \n
-x | \n Multicolumn (sorted vertically) | \n
-F | \n Add / after directories | \n
-G | \n Color | \n
-R | \n Recurse | \n
-a | \n Include hidden (dotfiles) | \n
-A | \n Include hidden (but not . and ..) | \n
Switch | \nDescription | \n
---|---|
-r | \n reverse order | \n
-S | \n sort by size | \n
-t | \n sort by time modified | \n
-u | \n sort by time accessed | \n
-U | \n sort by time created | \n
-c | \n sort by time status was changed | \n
-h | \n Human-readable size (3k) | \n
tail [-F | -f | -r] [-bN | -cN | -nN] [file ...]\n
\n\n-f | \n follow | \n
-F | \n follow by filename (accounts for log rotation) | \n
-r | \n Reverse order | \n
-bN | \n N*512 bytes | \n
-cN | \n N bytes | \n
-nN | \n N lines | \n
+N | \n Start from line N | \n
sudo [options] <command>\n
\n\n-l | \n List allowed commands | \n
-A | \n Use $SUDO_ASKPASS | \n
-b | \n Run in background | \n
-E | \n Preserve environment | \n
-H | \n use target’s $HOME | \n
-n | \n Don’t prompt for password | \n
-P | \n Preserve group vector | \n
-S | \n Read password from stdin | \n
-C fd | \n Close all open file descriptors | \n
-p prompt | \n Custom prompt (-p “%p password:”) | \n
Switch | \nDescription | \n
---|---|
-i [cmd] | \n Interactive shell without variables | \n
-s [cmd] | \n Interactive shell | \n
-u user | \n run as this user | \n
-g group | \n run as this group | \n
-v | \n revalidate timestamp for 5 mins | \n
-k | \n invalidate timestamp | \n
-K | \n just like -k | \n
... | wc [options]\n
\n\n-c | \n Bytes | \n
-l | \n Lines | \n
-m | \n Characters (incl multi-byte) | \n
-w | \n Words | \n
perl -p -i -e 's/hello/HELLO/g' **/*\n
\n\ngrep [options] [pattern] [file ...]\n
\n\nSwitch | \nDescription | \n
---|---|
-A num | \n Print num lines of training context | \n
-G | \n –basic-regexp (default) | \n
-E | \n –extended-regexp | \n
-P | \n –perl-regexp | \n
-f file | \n –file (Get patterns for file) | \n
-F | \n –fixed-strings | \n
-h | \n –no-filename | \n
-H | \n –with-filename | \n
-l | \n –files-with-matches (just print filenames) | \n
-L | \n –files-without-match | \n
-r, -R | \n –recursive | \n
-v | \n –invert-match | \n
-i | \n –ignore-case | \n
egrep => grep -E\nfgrep => grep -F\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "commander.js",
"title": "Commander.js",
"url": "/commander.js",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "var cli = require('commander');\n
\n\ncli\n .version(require('../package').version)\n .usage('[options] <command>')\n .option('-w, --words <n>', 'generate <n> words')\n .option('-i, --interval <n>', 'interval [1000]', 1000)\n .option('-s, --symbols', 'include symbols')\n .parse(process.argv);\n
\n\n.on('--help', function() {\n console.log('');\n})\n
\n\ncli.outputHelp();\ncli.args == [\"hello\"];\n
\n\nprocess.exit(0);\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "composer",
"title": "composer",
"url": "/composer",
"category": "CLI",
"keywords": null,
"content_html": "All composer commands, depending on your install, may need to use php composer.phar
in the install folder for composer, instead of plain composer
.
Command | \nDescription | \n
---|---|
composer install | \n Downloads and installs all the libraries and dependencies outlined in the composer.lock file. If the file does not exist it will look for composer.json and do the same, creating a composer.lock file. | \n
composer install --dry-run | \n Simulates the install without installing anything | \n
This command doesn’t change any file. If composer.lock
is not present, it will create it.
composer.lock
should always be committed to the repository. It has all the information needed to bring the \nlocal dependencies to the last committed state. If that file is modified on the repository, you will need to run \ncomposer install
again after fetching the changes to update your local dependencies to those on that file.
Command | \nDescription | \n
---|---|
composer update | \n Updates all packages | \n
composer update --with-dependencies | \n Updates all packages and its dependencies | \n
composer update vendor/package | \n Updates a certain package from vendor | \n
composer update vendor/* | \n Updates all packages from vendor | \n
composer update --lock | \n Updates composer.lock hash without updating any packages | \n
This command changes only the composer.lock
file.
Command | \nDescription | \n
---|---|
composer dumpautoload -o | \n Generates optimized autoload files | \n
Command | \nDescription | \n
---|---|
composer require vendor/package . | \n Adds package from vendor to composer.json’s require section and installs it | \n
composer require vendor/package --dev | \n Adds package from vendor to composer.json’s require-dev section and installs it. | \n
This command changes both the composer.json
and composer.lock
files.
Command | \nDescription | \n
---|---|
composer require vendor/pkg \"1.3.2\" | \n Installs 1.3.2 | \n
composer require vendor/pkg \">=1.3.2\" | \n Above or equal 1.3.2 | \n
composer require vendor/pkg \"<1.3.2\" | \n Below 1.3.2 | \n
composer require vendor/pkg \"1.3.*\" | \n Latest of >=1.3.0 <1.4.0 | \n
composer require vendor/pkg \"~1.3.2\" | \n Latest of >=1.3.2 <1.4.0 | \n
composer require vendor/pkg \"~1.3\" | \n Latest of >=1.3.0 <2.0.0 | \n
composer require vendor/pkg \"^1.3.2\" | \n Latest of >=1.3.2 <2.0.0 | \n
composer require vendor/pkg \"^1.3\" | \n Latest of >=1.3.0 <2.0.0 | \n
composer require vendor/pkg \"^0.3.2\" | \n Latest of >=0.3.0 <0.4.0 (for pre-1.0) | \n
composer require vendor/pkg \"dev-BRANCH_NAME\" | \n From the branch BRANCH_NAME | \n
Command | \nDescription | \n
---|---|
composer remove vendor/package | \n Removes vendor/package from composer.json and uninstalls it | \n
This command changes both the composer.json
and composer.lock
files.
Basic guide on how to use Composer, the PHP Package manager.
", "tags": null, "updated": "2020-02-23" },{ "id": "cordova", "title": "Apache Cordova", "url": "/cordova", "category": "Others", "keywords": null, "content_html": "cordova plugin ls\ncordova plugin search facebook\ncordova plugin add com.phonegap.plugins.facebookconnect\n
\n\ncordova platform add ios\ncordova platform ls\ncordova platform update ios\ncordova platform check\n
\n\nSome commonly-used plugins:
\n\nAlso:
\n\nA quick reference to common Apache Cordova commands.
", "description_html": "", "tags": null, "updated": null },{ "id": "cron", "title": "Cron", "url": "/cron", "category": "CLI", "keywords": null, "content_html": "Min Hour Day Mon Weekday\n
\n\n* * * * * command to be executed\n
\n\n┬ ┬ ┬ ┬ ┬\n│ │ │ │ └─ Weekday (0=Sun .. 6=Sat)\n│ │ │ └────── Month (1..12)\n│ │ └─────────── Day (1..31)\n│ └──────────────── Hour (0..23)\n└───────────────────── Minute (0..59)\n
\n\nExample | \nDescription | \n
---|---|
0 * * * * | \n every hour | \n
*/15 * * * * | \n every 15 mins | \n
0 */2 * * * | \n every 2 hours | \n
0 0 * * 0 | \n every Sunday midnight | \n
@reboot | \n every reboot | \n
# Adding tasks easily\necho \"@reboot echo hi\" | crontab\n
\n\n# Open in editor\ncrontab -e\n
\n\n# List tasks\ncrontab -l [-u user]\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2018-05-03"
},{
"id": "csharp7",
"title": "C# 7",
"url": "/csharp7",
"category": "C-like",
"keywords": null,
"content_html": "public void PrintCoordinates(Point p)\n{\n p.GetCoordinates(out int x, out int y);\n WriteLine($\"({x}, {y})\");\n}\n
\n\nout
is used to declare a variable at the point where it is passed as an argument.
public void PrintStars(object o)\n{\n if (o is null) return; // constant pattern \"null\"\n if (!(o is int i)) return; // type pattern \"int i\"\n WriteLine(new string('*', i));\n}\n
\n\nswitch(shape)\n{\n case Circle c:\n WriteLine($\"circle with radius {c.Radius}\");\n break;\n case Rectangle s when (s.Length == s.Height):\n WriteLine($\"{s.Length} x {s.Height} square\");\n break;\n case Rectangle r:\n WriteLine($\"{r.Length} x {r.Height} rectangle\");\n break;\n default:\n WriteLine(\"<unknown shape>\");\n break;\n case null:\n throw new ArgumentNullException(nameof(shape));\n}\n
\n\n(string, string, string) LookupName(long id) // tuple return type\n{\n ... // retrieve first, middle and last from data storage\n return (first, middle, last); // tuple literal\n}\n
\n\nvar names = LookupName(id);\nWriteLine($\"found {names.Item1} {names.Item3}.\");\n
\n\n(string first, string middle, string last) LookupName(long id) // tuple elements have names\n
\n\nvar names = LookupName(id);\nWriteLine($\"found {names.first} {names.last}.\");\n
\n\n return (first: first, middle: middle, last: last); // named tuple elements in a literal\n
\n\n(var first, var middle, var last) = LookupName(id1);\nWriteLine($\"found {first} {last}.\");\n
\nor
\nvar (first, middle, last) = LookupName(id1); // var outside\n
\nor
\n(first, middle, last) = LookupName(id2); // assign onto existing variables\n
\n\npublic int Fibonacci(int x)\n{\n if (x < 0) throw new ArgumentException(\"Less negativity please!\", nameof(x));\n return Fib(x).current;\n\n (int current, int previous) Fib(int i)\n {\n if (i == 0) return (1, 0);\n var (p, pp) = Fib(i - 1);\n return (p + pp, p);\n }\n}\n
\n\nvar d = 123_456;\nvar x = 0xAB_CD_EF;\n
\n\nvar b = 0b1010_1011_1100_1101_1110_1111;\n
\n\npublic ref int Find(int number, int[] numbers)\n{\n for (int i = 0; i < numbers.Length; i++)\n {\n if (numbers[i] == number) \n {\n return ref numbers[i]; // return the storage location, not the value\n }\n }\n throw new IndexOutOfRangeException($\"{nameof(number)} not found\");\n}\n\nint[] array = { 1, 15, -39, 0, 7, 14, -12 };\nref int place = ref Find(7, array); // aliases 7's place in the array\nplace = 9; // replaces 7 with 9 in the array\nWriteLine(array[4]); // prints 9\n
\n\nC# 7.0 adds accessors, constructors and finalizers to the list of things that can have expression bodies:
\n\nclass Person\n{\n private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>();\n private int id = GetId();\n\n public Person(string name) => names.TryAdd(id, name); // constructors\n ~Person() => names.TryRemove(id, out *); // destructors\n public string Name\n {\n get => names[id]; // getters\n set => names[id] = value; // setters\n }\n}\n
\n\nclass Person\n{\n public string Name { get; }\n public Person(string name) => Name = name ?? throw new ArgumentNullException(name);\n public string GetFirstName()\n {\n var parts = Name.Split(\" \");\n return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException(\"No name!\");\n }\n public string GetLastName() => throw new NotImplementedException();\n}\n
",
"intro_html": "",
"description_html": "A quick overview of C# 7
", "tags": null, "updated": "2018-12-06" },{ "id": "css-antialias", "title": "CSS antialiasing", "url": "/css-antialias", "category": "CSS", "keywords": null, "content_html": "* {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n
\n\nHere’s a 4-line snippet on how to get beautiful, antialiased text with CSS.
", "description_html": "", "tags": null, "updated": "2017-10-13" },{ "id": "css-flexbox", "title": "CSS flexbox", "url": "/css-flexbox", "category": "CSS", "keywords": null, "content_html": ".container {\n display: flex;\n}\n
\n\n.container > div {\n flex: 1 1 auto;\n}\n
\n\n.container {\n
\n\n display: flex;\n display: inline-flex;\n
\n\n flex-direction: row; /* ltr - default */\n flex-direction: row-reverse; /* rtl */\n flex-direction: column; /* top-bottom */\n flex-direction: column-reverse; /* bottom-top */\n
\n\n flex-wrap: nowrap; /* one-line */\n flex-wrap: wrap; /* multi-line */\n
\n\n align-items: flex-start; /* vertical-align to top */\n align-items: flex-end; /* vertical-align to bottom */\n align-items: center; /* vertical-align to center */\n align-items: stretch; /* same height on all (default) */\n
\n\n justify-content: flex-start; /* [xxx ] */\n justify-content: center; /* [ xxx ] */\n justify-content: flex-end; /* [ xxx] */\n justify-content: space-between; /* [x x x] */\n justify-content: space-around; /* [ x x x ] */\n justify-content: space-evenly; /* [ x x x ] */\n
\n\n}\n
\n\n.container > div {\n
\n\n /* This: */\n flex: 1 0 auto;\n\n /* Is equivalent to this: */\n flex-grow: 1;\n flex-shrink: 0;\n flex-basis: auto;\n
\n\n order: 1;\n
\n\n align-self: flex-start; /* left */\n margin-left: auto; /* right */\n
\n\n}\n
\n\n.container {\n display: flex;\n}\n\n.container > div {\n width: 100px;\n height: 100px;\n margin: auto;\n}\n
\n\n.container {\n display: flex;\n align-items: center; /* vertical */\n justify-content: center; /* horizontal */\n}\n
\n\n.container > .top {\n order: 1;\n}\n\n.container > .bottom {\n order: 2;\n}\n
\n\n.container {\n display: flex;\n flex-direction: column;\n}\n\n.container > .top {\n flex: 0 0 100px;\n}\n\n.container > .content {\n flex: 1 0 auto;\n}\n
\n\nA fixed-height top bar and a dynamic-height content area.
\n\n.container {\n display: flex;\n}\n\n/* the 'px' values here are just suggested percentages */\n.container > .checkbox { flex: 1 0 20px; }\n.container > .subject { flex: 1 0 400px; }\n.container > .date { flex: 1 0 120px; }\n
\n\nThis creates columns that have different widths, but size accordingly according\nto the circumstances.
\n\n.container {\n align-items: center;\n}\n
\n\nVertically-center all items.
\n\n.menu > .left { align-self: flex-start; }\n.menu > .right { align-self: flex-end; }\n
\n\n.grid-container {\n
\n\n /* Display properties */\n display: grid;\n display: inline-grid;\n display: subgrid;\n
\n\n /* Columns and rows */\n grid-template-columns: 1rem 2rem 1rem; /* Measurement units */\n grid-template-columns: 25% 50% 25%; /* Percentage units */\n grid-template-columns: 1rem auto 1rem 2fr; /* Fill remaining widths with auto or fr units */\n grid-template-columns: repeat(12, 1fr); /* Repeat columns without needing to write them */\n \n grid-template-rows: 1rem 10% auto repeat(5, 10px); /* Mix any group, same rules work for rows */\n
\n\n /* Automatic columns and rows */\n\n grid-auto-columns: 10px; /* No matter how many columns of content end up in the grid, each column will be this same width */\n grid-auto-rows: 1rem; /* No matter how many rows of content end up in the grid, each row will be this same height */\n
\n\n /* Areas */\n grid-template-areas:\n \"header header\"\n \"main aside\"\n \"footer footer\"; /* Grid-style */\n\n grid-template-areas: \"header header\" \"main aside\" \"footer footer\"; /* Inline-style */\n
\n\n /* Template shorthand */\n grid-template:\n \"header header\" auto\n \"main aside\" 100vh\n \"footer footer\" 10rem\n / 80% 20%;\n\n /* The above is the same as below long-hand */\n grid-template-columns: 80% 20%;\n grid-template-rows: auto 100vh 10rem;\n grid-template-areas:\n \"header header\"\n \"main aside\"\n \"footer footer\";\n
\n\n /* Gaps */\n grid-row-gap: 1rem;\n grid-column-gap: 0.5rem; /* Define values separately */\n\n grid-gap: 1rem 0.5rem; /* Short-hand for row / column */\n grid-gap: 1rem; /* Gap in both dimensions */\n
\n\n /* Item justification (horizontal or column alignment) */\n justify-items: start; /* Align items to the left */\n justify-items: center; /* Align items centered within its column */\n justify-items: end; /* Align items to the right */\n justify-items: stretch; /* (default) Fills available area (horizontally) */\n
\n\n /* Item alignment (vertical or row alignment) */\n align-items: start; /* Align items to the top */\n align-items: center; /* Align items centered within its row */\n align-items: end; /* Align items to the bottom */\n align-items: stretch; /* (default) Fills available area (vertically) */\n
\n\n /* Place item shorthand */\n place-items: start stretch;\n\n /* The above is the same as below long-hand */\n align-items: start;\n justify-items: stretch;\n
\n\n /* Content justification (horizontal or column alignment) */\n justify-content: start; /* Align content to the left */\n justify-content: center; /* Align content centered horizontally within the grid */\n justify-content: end; /* Align content to the right */\n justify-content: stretch; /* (default) Fills available area (horizontally) */\n\n justify-content: space-around; /* Chooses a space for both sides of the columns like a left and right margin */\n justify-content: space-between; /* Chooses a space to go between columns, no margins on outside of content */\n justify-content: space-evenly; /* Chooses a space that goes between all columns and edges consistently */\n
\n\n /* Content alignment (horizontal or column alignment) */\n align-content: start; /* Align content to the top */\n align-content: center; /* Align content centered vertically within the grid */\n align-content: end; /* Align content to the bottom */\n align-content: stretch; /* (default) Fills available area (vertically) */\n\n align-content: space-around; /* Chooses a space for the top and bottom of the rows like a top and bottom margin */\n align-content: space-between; /* Chooses a space to go between rows, no margins on outside of content */\n align-content: space-evenly; /* Chooses a space that goes between all rows and edges consistently */\n
\n\n /* Place item shorthand */\n place-content: center start;\n\n /* The above is the same as below long-hand */\n align-content: center;\n justify-content: start;\n
\n\n /* Automatic grid positioning */\n\n grid-auto-flow: row; /* Left-to-right rows, then top-to-bottom*/\n grid-auto-flow: column; /* Top-to-bottom columns, then left-to-right */\n grid-auto-flow: dense; /* Responds with best-guess on left-to-right, top-to-bottom order with advanced layouts */\n
\n\n /* There is one final shorthand for all container properties in one */\n\n /* Explicit grid columns, rows, and areas */\n grid:\n \"header header\" auto\n \"main aside\" 100vh\n \"footer footer\" 10rem\n / 80% 20%; /* You can include a template as the only value, which is equivalent to below */\n grid-template:\n \"header header\" auto\n \"main aside\" 100vh\n \"footer footer\" 10rem\n / 80% 20%; /* Which is again equivalent to below */\n grid-template-columns: 80% 20%;\n grid-template-rows: auto 100vh 10rem;\n grid-template-areas:\n \"header header\"\n \"main aside\"\n \"footer footer\";\n\n /* Automatic grid flows */\n grid: 1rem / auto-flow dense 1fr; /* You can include rows, a flow, and automatic columns, which is equivalent to below */\n grid-template-rows: 1rem;\n grid-auto-flow: dense;\n grid-auto-columns: 1fr;\n\n grid: auto-flow dense 1rem / repeat(10, 10%); /* Conversely, you can do the same thing with automatic rows, and defined columns */\n grid-auto-flow: dense;\n grid-auto-rows: 1rem;\n grid-template-columns: repeat(10, 10%);\n
\n\n}\n
\n\n.grid-child {\n
\n\n /* Column position */\n grid-column-start: 1;\n grid-column-end: 2;\n\n grid-column: 1 / 2; /* Short hand */\n grid-column: 1 / span 2; /* Span 2 columns without explicitly defining an endpoint */\n grid-column: 1; /* Start in and occupy a single column */\n
\n\n /* Row position */\n grid-row-start: 2;\n grid-row-end: 4;\n\n grid-row: 2 / 4; /* Short hand */\n grid-row: 2 / span 3;/* Span 3 rows without explicitly defining an endpoint */\n grid-row: 1; /* Start in and occupy a single row */\n
\n\n /* Area positioning */\n grid-area: header; /* You can use a named grid area from the container */\n\n grid-area: 2 / 1 / 4 / 2; /* Or you can use positioning. This is equivalent to... */\n grid-row-start: 2;\n grid-column-start: 1;\n grid-row-end: 4;\n grid-column-end: 2;\n
\n\n /* Self justification (horizontal or column alignment) */\n justify-self: start; /* Align item to the left */\n justify-self: center; /* Align item centered within its column */\n justify-self: end; /* Align item to the right */\n justify-self: stretch; /* (default) Fills available area (horizontally) */\n
\n\n /* Self alignment (vertical or row alignment) */\n align-self: start; /* Align item to the top */\n align-self: center; /* Align item centered within its row */\n align-self: end; /* Align item to the bottom */\n align-self: stretch; /* (default) Fills available area (vertically) */\n
\n\n /* Placement shorthand */\n place-self: start stretch;\n\n /* The above is the same as below long-hand */\n align-self: start;\n justify-self: stretch;\n
\n\n}\n
\n\nfont-family: -apple-system, BlinkMacSystemFont,\n \"Segoe UI\", \"Roboto\", \"Oxygen\",\n \"Ubuntu\", \"Cantarell\", \"Fira Sans\",\n \"Droid Sans\", \"Helvetica Neue\", sans-serif;\n
\n\nThis uses whatever system font is available. See: System shock - Designing Medium (medium.com)
\n\nFont | \nOS | \n
---|---|
-apple-system | \n OS X (10.11+), iOS (9+) | \n
BlinkMacSystemFont | \n OS X, Chrome | \n
Segoe UI | \n Windows | \n
Roboto | \n Android 4.0+ | \n
Oxygen | \n Linux, KDE | \n
Ubuntu | \n Linux, Ubuntu | \n
Cantarell | \n Linux, GNOME | \n
Fira Sans | \n Firefox OS | \n
Droid Sans | \n Android (until 3.2) | \n
Helvetica Neue | \n OS X (10.9) | \n
h1, h2, h3 {\n text-rendering: optimizeLegibility;\n}\n
\n\n-webkit-overflow-scrolling: touch;\noverflow-y: auto;\n
\n\nbackground: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#333));\n-webkit-background-clip: text;\n-webkit-text-fill-color: transparent;\n
\n\n-webkit-text-stroke: 3px black;\n
\n\n\n\ndocument.ontouchstart = (e) ->\n $pane = $(e.target).closest('.scrollable>div')\n if $pane.length is 0 or $pane[0].scrollHeight <= $pane.innerHeight()\n e.preventDefault()\n
\n\n%ios-scrollable {\n &, >div {\n -webkit-overflow-scrolling: touch;\n overflow: auto;\n }\n\n >div {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n }\n}\n
\n\nRelevant in iOS6, but maybe not anymore.
\n\n* {\n -webkit-tap-highlight-color: rgba(0,0,0,0);\n -webkit-user-select: none; /* disable text select */\n -webkit-touch-callout: none; /* disable callout, image save panel (popup) */\n -webkit-tap-highlight-color: transparent; /* \"turn off\" link highlight */\n}\n\na:focus {\n outline: 0; // Firefox (remove border on link click)\n}\n
\n\nSee: http://www.bitsandpix.com/entry/ios-webkit-uiwebview-remove-tapclick-highlightborder-with-css/
\n\nSee: http://www.yuiblog.com/blog/2010/10/01/quick-tip-customizing-the-mobile-safari-tap-highlight-color/
\n\nNot recommended, but here they are if you ever need them. Note that vendor\nprefixes may go away eventually.
\n\n@-moz-document url-prefix() {\n .box { color: blue; }\n}\n
\n\n@media all and (-webkit-min-device-pixel-ratio: 1) {\n}\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "css",
"title": "CSS",
"url": "/css",
"category": "CSS",
"keywords": ["margin, padding, border","div, .class, #id, [attr]","font, background","display: block, inline, flex","Selectors","Properties"],
"content_html": ".class {\n font-weight: bold;\n}\n
\n\nSelector | \nDescription | \n
---|---|
* | \n All elements | \n
div | \n Element | \n
.class | \n Class | \n
#id | \n ID | \n
[disabled] | \n Attribute | \n
[role=\"dialog\"] | \n Attribute | \n
Selector | \nDescription | \n
---|---|
.parent .child | \n Descendant | \n
.parent > .child | \n Direct descendant | \n
.child + .sibling | \n Adjacent sibling | \n
.child ~ .sibling | \n Far sibling | \n
.class1.class2 | \n Have both classes | \n
Selector | \nDescription | \n
---|---|
[role=\"dialog\"] | \n = Exact | \n
[class~=\"box\"] | \n ~= Has word | \n
[class|=\"box\"] | \n |= Exact or prefix (eg, value- ) | \n
[href$=\".doc\"] | \n $= Ends in | \n
[href^=\"/index\"] | \n ^= Begins with | \n
[class*=\"-is-\"] | \n *= Contains | \n
Selector | \nDescription | \n
---|---|
:target | \n eg, h2#foo:target | \n
:disabled | \n \n |
:focus | \n \n |
:active | \n \n |
:nth-child(3) | \n 3rd child | \n
:nth-child(3n+2) | \n 2nd child in groups of 3 | \n
:nth-child(-n+4) | \n \n |
:nth-last-child(2) | \n \n |
:nth-of-type(2) | \n \n |
:checked | \n Checked inputs | \n
:disabled | \n Disabled elements | \n
:default | \n Default element in a group | \n
:empty | \n Elements without children | \n
Selector | \n
---|
:first-of-type | \n
:last-of-type | \n
:nth-of-type(2) | \n
:only-of-type | \n
:first-child | \n
:last-child | \n
:nth-child(2) | \n
:only-child | \n
Property | \nDescription | \n
---|---|
font-family: | \n <font>, <fontN> | \n
font-size: | \n <size> | \n
letter-spacing: | \n <size> | \n
line-height: | \n <number> | \n
font-weight: | \n bold normal | \n
font-style: | \n italic normal | \n
text-decoration: | \n underline none | \n
text-align: | \n left right center justify | \n
text-transform: | \n capitalize uppercase lowercase | \n
\n | style | \nweight | \nsize (required) | \n\n | line-height | \nfamily | \n
---|---|---|---|---|---|---|
font: | \n italic | \n 400 | \n 14px | \n / | \n 1.5 | \n sans-serif | \n
\n | style | \nweight | \nsize (required) | \n\n | line-height | \nfamily (required) | \n
font-family: Arial;\nfont-size: 12pt;\nline-height: 1.5;\nletter-spacing: 0.02em;\ncolor: #aa3322;\n
\n\ntext-transform: capitalize; /* Hello */\ntext-transform: uppercase; /* HELLO */\ntext-transform: lowercase; /* hello */\n
\n\nProperty | \nDescription | \n
---|---|
background: | \n (Shorthand) | \n
background-color: | \n <color> | \n
background-image: | \n url(...) | \n
background-position: | \n left/center/right top/center/bottom | \n
background-size: | \n cover X Y | \n
background-clip: | \n border-box padding-box content-box | \n
background-repeat: | \n no-repeat repeat-x repeat-y | \n
background-attachment: | \n scroll fixed local | \n
\n | color | \nimage | \npositionX | \npositionY | \n\n | size | \nrepeat | \nattachment | \n
---|---|---|---|---|---|---|---|---|
background: | \n #ff0 | \n url(bg.jpg) | \n left | \n top | \n / | \n 100px auto | \n no-repeat | \n fixed; | \n
background: | \n #abc | \n url(bg.png) | \n center | \n center | \n / | \n cover | \n repeat-x | \n local; | \n
\n | color | \nimage | \npositionX | \npositionY | \n\n | size | \nrepeat | \nattachment | \n
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),\n url('background.jpg') center center / cover, #333;\n
\n\nProperty | \nValue | \n
---|---|
animation: | \n (shorthand) | \n
animation-name: | \n <name> | \n
animation-duration: | \n <time>ms | \n
animation-timing-function: | \n ease linear ease-in ease-out ease-in-out | \n
animation-delay: | \n <time>ms | \n
animation-iteration-count: | \n infinite <number> | \n
animation-direction: | \n normal reverse alternate alternate-reverse | \n
animation-fill-mode: | \n none forwards backwards both initial inherit | \n
animation-play-state: | \n normal reverse alternate alternate-reverse | \n
\n | name | \nduration | \ntiming-function | \ndelay | \ncount | \ndirection | \nfill-mode | \nplay-state | \n
---|---|---|---|---|---|---|---|---|
animation: | \n bounce | \n 300ms | \n linear | \n 100ms | \n infinite | \n alternate-reverse | \n both | \n reverse | \n
\n | name | \nduration | \ntiming-function | \ndelay | \ncount | \ndirection | \nfill-mode | \nplay-state | \n
animation: bounce 300ms linear 0s infinite normal;\nanimation: bounce 300ms linear infinite;\nanimation: bounce 300ms linear infinite alternate-reverse;\nanimation: bounce 300ms linear 2s infinite alternate-reverse forwards normal;\n
\n\n.one('webkitAnimationEnd oanimationend msAnimationEnd animationend')\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "cssnext",
"title": "cssnext",
"url": "/cssnext",
"category": "CSS",
"keywords": null,
"content_html": ":root {\n --text-color: #30333a;\n}\n
\n\nbody {\n background: var(--text-color);\n background: color(var(--text-color) shade(30%));\n}\n
\n\na {\n /* Adjustments */\n color: color(red alpha(-10%));\n color: color(red tint(-10%)); /* lighten */\n color: color(red shade(-10%)); /* darken */\n\n /* Absolute */\n color: color(red alpha(50%));\n color: color(red hue(225));\n color: color(red saturation(100%));\n color: color(red lightness(50%));\n\n color: gray(33); /* rgb(33, 33, 33) */\n color: gray(33%); /* rgb(84, 84, 84) */\n color: gray(33%, 50%); /* rgba(84, 84, 84, 0.5) */\n color: #0000ff80; /* rgba(0, 0, 255, 0.5) */\n\n color: hwb(90, 0%, 0%, 0.5); /* like hsl() but easier for humans */\n color: hsl(90deg 90% 70%); /* hsl(180, 90%, 70%) -- supports deg */\n color: hsl(90deg 90% 70% / 30%); /* hsla(180, 90%, 70%, 0.3) */\n color: rgb(30 60 90 / 30%); /* rgba(30, 60, 90, 0.3) */\n}\n
\n\nAlso see colorme.io.
\n\n:root {\n --centered: {\n display: flex;\n align-items: center;\n justify-content: center;\n };\n}\n\n.centered {\n @apply --centered;\n}\n
\n\n.class-name {\n & .nesting { ··· } /* direct nesting starts with & */\n @nest span & { ··· } /* complex nesting */\n @media (min-width: 30em) { ··· }\n}\n
\n\n@custom-selector :--button input[type='submit'], input[type='button'];\n@custom-selector :--enter :hover, :focus;\n
\n\n:--button { ··· }\n:--button:--enter { ··· }\n
\n\n:any-link { ··· } /* :link, :visited */\np:matches(.a, .b) { ··· } /* p.a, p.b */\np:not(.a, .b) { ··· } /* p:not(.a), p:not(.b) */\na::before { ··· } /* a:before -- for IE compatibility */\n[frame=hsides i] { ··· } /* [frame=hsides] -- but case insensitive */\n
\n\n@custom-media --viewport-medium (width <= 50rem);\n
\n\n@media (--viewport-medium) { ··· }\n
\n\n@media (width >= 500px) { ··· } /* (min-width: 500px) */\n
\n\n/* font-feature-settings fallback */\nh2 { font-variant-caps: small-caps; }\ntable { font-variant-numeric: lining-nums; }\n
\n\ndiv { filter: blur(4px); } /* svg filter fallback */\ndiv { overflow-wrap: break-word; } /* word-wrap fallback */\n
\n\ndiv {\n display: flex;\n}\n
\n\n/*\n * display: -webkit-box;\n * display: -ms-flexbox;\n * display: flex;\n */\n
\n\ndiv {\n all: initial;\n}\n
\n\nSets animation, background, margin, padding, and so on.
\n\n-o <file> # --output: write to file\n-u user:pass # --user: Authentication\n
\n\n-v # --verbose\n-vv # Even more verbose\n-s # --silent\n
\n\n-i # --include: Include the HTTP-header in the output\n-I # --head: headers only\n
\n\n-X POST # --request\n-L # follow link if page redirects \n
\n\n-d 'data' # --data: HTTP post data, URL encoded (eg, status=\"Hello\")\n-d @file # --data via file\n-G # --get: send -d data via get\n
\n\n-A <str> # --user-agent\n-b name=val # --cookie\n-b FILE # --cookie\n-H \"X-Foo: y\" # --header\n--compressed # use deflate/gzip\n
\n\n --cacert <file>\n --capath <dir>\n
\n\n-E, --cert <cert> # --cert: Client cert file\n --cert-type # der/pem/eng\n-k, --insecure # for self-signed certs\n
\n\n# Post data:\ncurl -d password=x http://x.com/y\n
\n\n# Auth/data:\ncurl -u user:pass -d status=\"Hello\" http://twitter.com/statuses/update.xml\n
\n\n# multipart file upload\ncurl -v -include --form key1=value1 --form upload=@localfilename URL\n
\n\n# Use Curl to Check if a remote resource is available\n# details: https://matthewsetter.com/check-if-file-is-available-with-curl/\ncurl -o /dev/null --silent -Iw \"%{http_code}\" https://example.com/my.remote.tarball.gz\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2020-03-09"
},{
"id": "datetime",
"title": "Date & time formats",
"url": "/datetime",
"category": "Others",
"keywords": null,
"content_html": "date
, and moreExample | \nOutput | \n
---|---|
%m/%d/%Y | \n 06/05/2013 | \n
%A, %B %e, %Y | \n Sunday, June 5, 2013 | \n
%b %e %a | \n Jun 5 Sun | \n
Example | \nOutput | \n
---|---|
%H:%M | \n 23:05 | \n
%I:%M %p | \n 11:05 PM | \n
Used by Ruby, UNIX date
, and many more.
Symbol | \nExample | \nArea | \n
---|---|---|
%a | \n Sun | \n Weekday | \n
%A | \n Sunday | \n \n |
%w | \n 0 ..6 (Sunday is 0) | \n \n |
%y | \n 13 | \n Year | \n
%Y | \n 2013 | \n \n |
%b | \n Jan | \n Month | \n
%B | \n January | \n \n |
%m | \n 01 ..12 | \n \n |
%d | \n 01 ..31 | \n Day | \n
%e | \n 1 ..31 | \n \n |
Symbol | \nExample | \nArea | \n
---|---|---|
%l | \n 1 | \n Hour | \n
%H | \n 00 ..23 | \n 24h Hour | \n
%I | \n 01 ..12 | \n 12h Hour | \n
%M | \n 00 ..59 | \n Minute | \n
%S | \n 00 ..60 | \n Second | \n
%p | \n AM | \n AM or PM | \n
%Z | \n +08 | \n Time zone | \n
%j | \n 001 ..366 | \n Day of the year | \n
%% | \n % | \n Literal % character | \n
Example | \nOutput | \n
---|---|
YYYY-MM-DD | \n 2014-01-01 | \n
dddd, MMMM Do YYYY | \n Friday, May 16th 2014 | \n
Example | \nOutput | \n
---|---|
hh:mm a | \n 12:30 pm | \n
Used by Moment.js and date-fns/format. Similar to Java SimpleDateFormat.
\n\nSymbol | \nExample | \nArea | \n
---|---|---|
d | \n 0 ..6 | \n Weekday | \n
dd | \n Su | \n \n |
ddd | \n Sun | \n \n |
dddd | \n Sunday | \n \n |
YY | \n 13 | \n Year | \n
YYYY | \n 2013 | \n \n |
M | \n 1 ..12 (Jan is 1) | \n Month | \n
Mo | \n 1st ..12th | \n \n |
MM | \n 01 ..12 (Jan is 1) | \n \n |
MMM | \n Jan | \n \n |
MMMM | \n January | \n \n |
Q | \n 1 ..4 | \n Quarter | \n
Qo | \n 1st ..4th | \n \n |
D | \n 1 ..31 | \n Day | \n
Do | \n 1st ..31st | \n \n |
DD | \n 01 ..31 | \n \n |
DDD | \n 1 ..365 | \n Day of year | \n
DDDo | \n 1st ..365th | \n \n |
DDDD | \n 001 ..365 | \n \n |
w | \n 1 ..53 | \n Week of year | \n
wo | \n 1st ..53rd | \n \n |
ww | \n 01 ..53 | \n \n |
Symbol | \nExample | \nArea | \n
---|---|---|
H | \n 0 ..23 | \n 24h hour | \n
HH | \n 00 ..23 | \n \n |
h | \n 1 ..12 | \n 12h hour | \n
hh | \n 01 ..12 | \n \n |
m | \n 0 ..59 | \n Minutes | \n
mm | \n 00 ..59 | \n \n |
s | \n 0 ..59 | \n Seconds | \n
ss | \n 00 ..59 | \n \n |
a | \n am | \n AM/PM | \n
A | \n AM | \n \n |
Z | \n +07:00 | \n Timezone offset | \n
ZZ | \n +0730 | \n \n |
S | \n 0 ..9 | \n Deciseconds | \n
SS | \n 00 ..99 | \n Centiseconds | \n
SSS | \n 000 ..999 | \n Milliseconds | \n
X | \n \n | Unix timestamp | \n
x | \n \n | Millisecond Unix timestamp | \n
Example | \nOutput | \n
---|---|
LT | \n 8:30 PM | \n
LTS | \n 8:30:25 PM | \n
LL | \n August 2 1985 | \n
ll | \n Aug 2 1985 | \n
LLL | \n August 2 1985 08:30 PM | \n
lll | \n Aug 2 1985 08:30 PM | \n
LLLL | \n Thursday, August 2 1985 08:30 PM | \n
llll | \n Thu, Aug 2 1985 08:30 PM | \n
deis create app-name\ngit push deis master\ndeis open\n
\n\n$ deis create app-name\n$ deis pull redis:latest\n Creating build... done, v2\n# default process type is `cmd`\n
\n\ndeis config:list\ndeis config:set FOO=bar BAZ=foo\ndeis config:unset FOO\ndeis config:pull # writes to .env\ndeis config:push # reads from .env\n
\n\ndeis logs\ndeis run rake db:migrate\ndeis ps\n
\n\ndeis domains:list\ndeis domains:add www.myapp.com\ndeis domains:remove www.myapp.com\n
\n\ndeis limits:set web=1G\ndeis limits:set web=1024 --cpu\n# (`web` is a process type)\n
\n\ndeis perms:create otheruser\n
\n\ndeis certs:add server.crt server.key\n
\n\nSee: SSL
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "deku", "title": "Deku v2", "url": "/deku", "category": "JavaScript libraries", "keywords": null, "content_html": "/** @jsx element */\nimport { element } from 'deku'\n\nfunction render ({ props, children, context, path }) {\n // props = properties object\n // children = children array\n // path = path to current component (like 0.1.5.2)\n // context = common properties in all components\n return (\n <div class='App' hidden={props.hidden} color={context.theme.color}>\n {children}\n </div>\n }\n}\n\nfunction onCreate ({ props, dispatch, path }) { ... }\nfunction onUpdate ({ props, dispatch, path }) { ... }\nfunction onRemove ({ props, dispatch, path }) { ... }\n// actually { children, props, path, context }\n\nexport default { render, onCreate, onRemove }\n
\n\nimport { createStore } from 'redux'\nimport { dom, element } from 'deku'\n\n// Create a Redux store to handle all UI actions and side-effects\nlet store = createStore(reducer)\n\n// Create a renderer that can turn vnodes into real DOM elements\nlet render = createRenderer(document.body, store.dispatch)\n\n// Update the page and add redux state to the context\nrender(<MyButton>Hello World!</MyButton>, store.getState())\n
",
"intro_html": "Quick reference for Deku, a minimal virtual DOM library.
", "description_html": "", "tags": null, "updated": null },{ "id": "deku@1", "title": "Deku v1", "url": "/deku@1", "category": "JavaScript libraries", "keywords": null, "content_html": "/** @jsx element */\nimport element from 'virtual-element' // replacement for React.createElement\nimport { render, tree } from 'deku'\n\nvar app = <div class='my-app'>Hello World!</div>\n\nrender(tree(app), document.body)\n
\n\nButton = {\n render() {\n return <button>Submit</button>\n }\n}\n\nApp = {\n render() {\n return (\n <div>\n <Button />\n </div>\n )\n }\n}\n\nrender(tree(<App />), document.body)\nrender(tree(element(App)), document.body)\n
\n\nApp = {\n render ({ props, state }) {\n return <div>{ /*...use state.store here*/ }</div>\n }\n\n initialState (props) {\n return { store: store.getState() }\n },\n\n afterMount (comp, el, setState) {\n store.subscribe(() => setState({ store: store.getState() }))\n }\n}\n\nrender(tree(<App />), document.body)\n
\n\n<a onClick={onClick}>{props.text}</a>\n
\n\nUse magic-virtual-element to enable nice classnames.
\n\nimport element from 'magic-virtual-element'\n<div style={style} class={[ 'button', '-active' ]}>\n
\n\nname = 'MyComponent'\n\n// Defaults\ninitialState (props) {...} // return initial state\ndefaultProps = { hi: 'hello' }\n\n// Render\nrender ({props, state}, setState) {...}\n\n// Lifecycle\nbeforeUpdate ({props, state, id}, nextProps, nextState) {}\nafterRender ({props, state, id}, el) {}\nafterUpdate ({props, state, id}, prevProps, prevState, setState) {}\nafterMount ({props, state, id}, el, setState) {}\nbeforeUnmount ({props, state, id}, el) {}\n
\n\nSee: https://www.npmjs.com/package/deku
", "intro_html": "Quick reference for Deku, a minimal virtual DOM library. Deprecated: This is for Deku v1. See deku for a more updated cheatsheet.
", "description_html": "", "tags": null, "updated": null },{ "id": "devise", "title": "Devise", "url": "/devise", "category": "Others", "keywords": null, "content_html": "Devise is a flexible authentication \ngem.
\n\nRails 3: Add the following to your Gemfile
\n\ngem \"devise\"\ngem \"hpricot\"\ngem \"ruby_parser\"\n
\n\nInstall devise in your project
\n\n$ rails generate devise:install\n
\n\nGenerate devise for your model
\n\n$ rails generate devise MODEL\n$ rake db:migrate\n
\n\n(Optional) Generate devise views
\n\n$ rails generate devise:views\n
\n\nuser_signed_in?\ncurrent_user\nuser_session\ndestroy_user_session_path (Logout)\nnew_user_session_path (Login)\nedit_user_registration_path (Edit registration)\nnew_user_registration_path (Register new user)\n
\n\nbefore_filter :authenticate_user!\n
\n\nclass User < ActiveRecord::Base\n devise :database_authenticatable,\n :registerable,\n :confirmable,\n :recoverable,\n :rememberable,\n :trackable,\n :validatable\nend\n
\n\ncreate_table :users do |t|\n t.database_authenticatable\n t.confirmable\n t.recoverable\n t.rememberable\n t.trackable\n t.timestamps\nend\n
\n\nunauthenticated do\n root :to => 'home#index'\nend\n\nauthenticated do\n root :to => 'dashboard#index'\nend\n
\n\nas :user do\n get 'sign_in', :to => 'devise/sessions#new'\nend\n
\n\ndevise_for :users\n\n # Session routes for Authenticatable (default)\n new_user_session GET /users/sign_in {:controller=>\"devise/sessions\", :action=>\"new\"}\n user_session POST /users/sign_in {:controller=>\"devise/sessions\", :action=>\"create\"}\n destroy_user_session GET /users/sign_out {:controller=>\"devise/sessions\", :action=>\"destroy\"}\n \n # Password routes for Recoverable, if User model has :recoverable configured\n new_user_password GET /users/password/new(.:format) {:controller=>\"devise/passwords\", :action=>\"new\"}\n edit_user_password GET /users/password/edit(.:format) {:controller=>\"devise/passwords\", :action=>\"edit\"}\n user_password PUT /users/password(.:format) {:controller=>\"devise/passwords\", :action=>\"update\"}\n POST /users/password(.:format) {:controller=>\"devise/passwords\", :action=>\"create\"}\n \n # Confirmation routes for Confirmable, if User model has :confirmable configured\n new_user_confirmation GET /users/confirmation/new(.:format) {:controller=>\"devise/confirmations\", :action=>\"new\"}\n user_confirmation GET /users/confirmation(.:format) {:controller=>\"devise/confirmations\", :action=>\"show\"}\n POST /users/confirmation(.:format) {:controller=>\"devise/confirmations\", :action=>\"create\"}\n
\n\ndevise_for :users,\n :path => \"usuarios\",\n :path_names => {\n :sign_in => 'login',\n :sign_out => 'logout',\n :password => 'secret',\n :confirmation => 'verification',\n :unlock => 'unblock',\n :registration => 'register',\n :sign_up => 'cmon_let_me_in' }\n
\n\ninclude Devise::TestHelpers\nhttps://github.com/plataformatec/devise/blob/1094ba65aac1d37713f2cba71f9edad76b5ca274/lib/devise/test_helpers.rb\n\nsign_in @user\nsign_out @user\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "divshot",
"title": "Divshot",
"url": "/divshot",
"category": "Others",
"keywords": null,
"content_html": "$ npm install -g divshot-cli\n$ divshot login\n
\n\n{\n \"name\": \"yourapp\",\n \"root\": \"./app\"\n}\n
\n\n$ divshot push\n
\n\nSee configuration reference and routing guide.
\n\n{\n \"name\": \"yourapp\",\n \"root\": \"./app\",\n \"clean_urls\": true,\n \"clean_urls\": [\"/app/**\", \"/!components/**\"],,\n \"error_page\": \"error.html\",\n \"exclude\": [ \"Gruntfile.js\" ],\n \"cache_control\": {},\n \"routes\": {\n \"/*.html\": \"index.html\",\n \"/app/**/*.html\": \"app.html\",\n \"**\": \"index.html\"\n },\n \"redirects\": {\n \"/old/:segment/path\": \"/new/path/:segment\",\n \"/some/old/path\": {\n \"status\": 302,\n \"url\": \"/some/new/path\"\n }\n },\n \"headers\": {\n \"/cors-stuff/**\": {\n \"Access-Control-Allow-Origin\": \"*\"\n },\n \"/scripts/**\": {\n \"content-type\": \"text/javascript\"\n }\n }\n}\n
\n\ndivshot s # server\n\ndivshot push [staging|production|development]\ndivshot pull [staging|production|development]\ndivshot purge # cleans cache\ndivshot files\n\ndivshot promote development production\n\ndivshot open [<env>]\n
\n\nEdits divshot.json
\ndivshot config:add name your-app-name\ndivshot config:remove name\n
\n\ndivshot env:add <env> KEY=value\ndivshot env:remove <env> KEY\ndivshot env:pull <env>\n
\n\ndivshot create <appname>\ndivshot rename <newname>\ndivshot status\ndivshot destroy\n
\n\ndivshot apps\ndivshot account
\n\n### Password protect\n\n```sh\ndivshot protect <env> <username:password>\n
\n\nSee custom domains guide.
\n\ndivshot domains:add foo.bar.com\n
\n\nIn your DNS create a CNAME
: (no apex domains are supported)
www. CNAME yourname.divshot.io\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "do",
"title": "Do gem",
"url": "/do",
"category": "Ruby libraries",
"keywords": null,
"content_html": "server = DO::Server.new('srv1', 'srv1.domain.local', 'root', :key => \n %w[srv1.pem]\n
\n\nserver.run 'uname'\n# root@srv1 ~ # uname\n# Linux\n\nserver.run 'uname', '-a'\n# root@srv1 ~ # uname -a\n# Linux srv1.lipsiasoft.net 2.6.18-194.32.1.el5 x86_64 x86_64 x86_64 GNU/Linux\n\nserver.run 'mysqladmin -u root -p password \"oldone\"', 'newpassword'\n# root@srv1 ~ # mysqladmin -u root -p password 'oldone'\n# Enter password: oldone\n# mysqladmin: connect to server at 'localhost' failed\n# error: 'Access denied for user 'root'@'localhost' (using password: YES)'\n
\n\nserver.exist?('~/.ssh')\n# root@srv1 ~ # test -e ~/.ssh && echo True\n# => true\n\nserver.read('/etc/redhat-release')\n# root@srv1 ~ # cat /etc/redhat-release\n# => \"CentOS release 5.5 (Final)\"\n
\n\nserver.upload '/tmp/file', '/tmp/foo'\n# root@srv1 ~ # upload from '/tmp/file' to '/tmp/foo'\n\nserver.download '/tmp/foo', '/tmp/file2'\n# root@srv1 ~ # download from '/tmp/foo' to '/tmp/file2'\n
\n\nserver.replace :all, 'new content', '/tmp/file'\n# root@srv1 ~ # replace all in '/tmp/foo'\n\nserver.read('/tmp/foo')\n# root@srv1 ~ # cat /tmp/foo\n# => \"new content\"\n
\n\nserver.replace /content$/, 'changed content', '/tmp/foo'\n# root@srv1 ~ # replace /content$/ in '/tmp/foo'\n\nserver.read('/tmp/foo')\n# root@srv1 ~ # cat /tmp/foo\n# => \"new changed content\"\n
\n\nserver.append('appended', '/tmp/foo')\n# root@srv1 ~ # append to 'bottom' in '/tmp/foo'\n\nserver.read('/tmp/foo')\n# root@srv1 ~ # cat /tmp/foo\n# => \"new changed contentappended\"\n
\n\nserver.append('---', '/tmp/foo', :top)\n# root@srv1 ~ # append to 'top' in '/tmp/foo'\n\nserver.read('/tmp/foo')\n# root@srv1 ~ # cat /tmp/foo\n# => \"---new changed contentappended\"\n
\n\nserver.ask \"Please choose\"\n# root@srv1 ~ # Please choose: foo\n# => \"foo\"\n\nserver.yes? \"Do you want to proceed\"\n# root@srv1 ~ # Do you want to proceed? (y/n): y\n# => 0\n\nserver.wait\n# Press ENTER to continue...\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "docker-compose",
"title": "docker-compose",
"url": "/docker-compose",
"category": "Devops",
"keywords": null,
"content_html": "# docker-compose.yml\nversion: '2'\n\nservices:\n web:\n build: .\n # build from Dockerfile\n context: ./Path\n dockerfile: Dockerfile\n ports:\n - \"5000:5000\"\n volumes:\n - .:/code\n redis:\n image: redis\n
\n\ndocker-compose start\ndocker-compose stop\n
\n\ndocker-compose pause\ndocker-compose unpause\n
\n\ndocker-compose ps\ndocker-compose up\ndocker-compose down\n
\n\nweb:\n # build from Dockerfile\n build: .\n args: # Add build arguments\n APP_HOME: app\n
\n\n # build from custom Dockerfile\n build:\n context: ./dir\n dockerfile: Dockerfile.dev\n
\n\n # build from image\n image: ubuntu\n image: ubuntu:14.04\n image: tutum/influxdb\n image: example-registry:4000/postgresql\n image: a4bc65fd\n
\n\n ports:\n - \"3000\"\n - \"8000:80\" # host:container\n
\n\n # expose ports to linked services (not to host)\n expose: [\"3000\"]\n
\n\n # command to execute\n command: bundle exec thin -p 3000\n command: [bundle, exec, thin, -p, 3000]\n
\n\n # override the entrypoint\n entrypoint: /app/start.sh\n entrypoint: [php, -d, vendor/bin/phpunit]\n
\n\n # environment vars\n environment:\n RACK_ENV: development\n environment:\n - RACK_ENV=development\n
\n\n # environment vars from file\n env_file: .env\n env_file: [.env, .development.env]\n
\n\n # makes the `db` service available as the hostname `database`\n # (implies depends_on)\n links:\n - db:database\n - redis\n
\n\n # make sure `db` is alive before starting\n depends_on:\n - db\n
\n\n # make this service extend another\n extends:\n file: common.yml # optional\n service: webapp\n
\n\n volumes:\n - /var/lib/mysql\n - ./_data:/var/lib/mysql\n
\n\nservices:\n web:\n labels:\n com.example.description: \"Accounting web app\"\n
\n\nservices:\n web:\n dns: 8.8.8.8\n dns:\n - 8.8.8.8\n - 8.8.4.4\n
\n\nservices:\n web:\n devices:\n - \"/dev/ttyUSB0:/dev/ttyUSB0\"\n
\n\nservices:\n web:\n external_links:\n - redis_1\n - project_db_1:mysql\n
\n\nservices:\n web:\n extra_hosts:\n - \"somehost:192.168.1.100\"\n
\n\n# creates a custom network called `frontend`\nnetworks:\n frontend:\n
\n\n# join a pre-existing network\nnetworks:\n default:\n external:\n name: frontend\n
\n\n# Mount host paths or named volumes, specified as sub-options to a service\n db:\n image: postgres:latest\n volumes:\n - \"/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock\"\n - \"dbdata:/var/lib/postgresql/data\"\n\nvolumes:\n dbdata:\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2020-01-01"
},{
"id": "docker",
"title": "Docker CLI",
"url": "/docker",
"category": "Devops",
"keywords": null,
"content_html": "docker build
docker build [options] .\n -t \"app/container_name\" # name\n --build-arg APP_HOME=$APP_HOME # Set build-time variables\n
\n\nCreate an image
from a Dockerfile.
docker run
docker run [options] IMAGE\n # see `docker create` for options\n
\n\n$ docker run -it debian:buster /bin/bash\n
\nRun a command in an image
.
docker create
docker create [options] IMAGE\n -a, --attach # attach stdout/err\n -i, --interactive # attach stdin (interactive)\n -t, --tty # pseudo-tty\n --name NAME # name your image\n -p, --publish 5000:5000 # port map\n --expose 5432 # expose a port to linked containers\n -P, --publish-all # publish all ports\n --link container:alias # linking\n -v, --volume `pwd`:/app # mount (absolute paths needed)\n -e, --env NAME=hello # env vars\n
\n\n$ docker create --name app_redis_1 \\\n --expose 6379 \\\n redis:3.0.2\n
\n\nCreate a container
from an image
.
docker exec
docker exec [options] CONTAINER COMMAND\n -d, --detach # run in background\n -i, --interactive # stdin\n -t, --tty # interactive\n
\n\n$ docker exec app_web_1 tail logs/development.log\n$ docker exec -t -i app_web_1 rails c\n
\n\nRun commands in a container
.
docker start
docker start [options] CONTAINER\n -a, --attach # attach stdout/err\n -i, --interactive # attach stdin\n\ndocker stop [options] CONTAINER\n
\n\nStart/stop a container
.
docker ps
$ docker ps\n$ docker ps -a\n$ docker kill $ID\n
\n\nManage container
s using ps/kill.
docker logs
$ docker logs $ID\n$ docker logs $ID 2>&1 | less\n$ docker logs -f $ID # Follow log output\n
\n\nSee what’s being logged in an container
.
docker images
$ docker images\n REPOSITORY TAG ID\n ubuntu 12.10 b750fe78269d\n me/myapp latest 7b2431a8d968\n
\n\n$ docker images -a # also show intermediate\n
\n\nManages image
s.
docker rmi
docker rmi b750fe78269d\n
\n\nDeletes image
s.
docker system prune\n
\n\nCleans up dangling images, containers, volumes, and networks (ie, not associated with a container)
\n\ndocker system prune -a\n
\n\nAdditionally remove any stopped containers and all unused images (not just dangling images)
\n\n# Stop all running containers\ndocker stop $(docker ps -a -q)\n\n# Delete stopped containers\ndocker container prune\n
\n\ndocker image prune [-a]\n
\n\nDelete all the images
\n\ndocker volume prune\n
\n\nDelete all the volumes
\n\nFROM ruby:2.2.2\n
\n\nENV APP_HOME /myapp\nRUN mkdir $APP_HOME\n
\n\nARG APP_HOME=\"\"\nRUN mkdir $APP_HOME\n
\n\nRUN bundle install\n
\n\nWORKDIR /myapp\n
\n\nVOLUME [\"/data\"]\n# Specification for mount point\n
\n\nADD file.xyz /file.xyz\nCOPY --chown=user:group host_file.xyz /path/container_file.xyz\n
\n\nONBUILD RUN bundle install\n# when used with another file\n
\n\nEXPOSE 5900\nCMD [\"bundle\", \"exec\", \"rails\", \"server\"]\n
\n\nENTRYPOINT [\"executable\", \"param1\", \"param2\"]\nENTRYPOINT command param1 param2\n
\n\nConfigures a container that will run as an executable.
\n\nENTRYPOINT exec top -b\n
\n\nThis will use shell processing to substitute shell variables, and will ignore any CMD
or docker run
command line arguments.
LABEL version=\"1.0\"\n
\n\nLABEL \"com.example.vendor\"=\"ACME Incorporated\"\nLABEL com.example.label-with-value=\"foo\"\n
\n\nLABEL description=\"This text illustrates \\\nthat label-values can span multiple lines.\"\n
\n\nvar range = document.createRange()\n
\n\nSee: https://devdocs.io/dom/document/createrange
\n\nrange\n .setStart(startNode, startOffset)\n .setEnd(endNode, endOffset)\n\n .setStartBefore(node)\n .setStartAfter(node)\n .setEndBefore(node)\n .setEndAfter(node)\n\n .selectNode(node)\n .selectNodeContents(node)\n
\n\nSee: https://devdocs.io/dom/range
\n\nrange.collapse() // to end (a single point)\nrange.collapse(true) // to start (a single point)\nrange.collapsed // true | false\n
\n\nrange.cloneContents() // copy => DocumentFragment\nrange.extractContents() // cut => DocumentFragment\nrange.deleteContents() // delete\n
\n\nrange.insertNode(node)\n
\n\nrange.toString()\n
\n\nrange.collapsed // => true/false\nrange.startContainer // => Node\nrange.startOffset\nrange.endContainer // => Node\nrange.endOffset\nrange.commonAncestorContainer // closest of start and end containers\n
",
"intro_html": "Quick reference to the HTML DOM createRange API.
", "description_html": "", "tags": null, "updated": null },{ "id": "dom-selection", "title": "DOM Selection", "url": "/dom-selection", "category": "JavaScript", "keywords": null, "content_html": "var sel = document.getSelection()\n
\n\nSee: https://devdocs.io/dom/selection
\n\nsel.removeAllRanges() // deselects\nsel.addRange(range) // sets a selection\nsel.removeRange(range) // remove a range\n
\n\nsel.rangeCount\nsel.getRangeAt(0) // get the 0th range\n
\n\nsel.collapse(parent, offset)\nsel.collapseToEnd()\nsel.collapseToStart()\nsel.isCollapsed\n
\n\nsel.containsNode(node)\n
\n\nsel.deleteFromDocument()\n
\n\ndocument.addEventListener('selectionchange', () => {})\n
",
"intro_html": "Quick introduction to the HTML DOM selection API.
", "description_html": "", "tags": null, "updated": null },{ "id": "editorconfig", "title": "editorconfig", "url": "/editorconfig", "category": "Apps", "keywords": null, "content_html": "# editorconfig.org\nroot = true\n\n[*]\nindent_style = space\nindent_size = 2\ntab_width = 2\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n
\n\nThis example should be fine for most projects indented by 2 spaces. See: animate.css editorconfig
\n\nindent_style = {space|tab}\nindent_size = {4|tab}\ntab_width = 2\nend_of_line = {cr|lf|crlf}\ncharset = {utf-8|utf-16be|utf-16le|latin1}\ntrim_trailing_whitespace = false\ninsert_final_newline = true\nmax_line_length = 80\n
\n\n# top-most EditorConfig file\nroot = true\n\n# Unix-style newlines with a newline ending every file\n[*]\nend_of_line = lf\ninsert_final_newline = true\n\n# 4 space indentation\n[*.py]\nindent_style = space\nindent_size = 4\n\n# Tab indentation (no size specified)\n[*.js]\nindent_style = tab\n\n# Indentation override for all JS under lib directory\n[lib/**.js]\nindent_style = space\nindent_size = 2\n\n# Matches the exact files either package.json or .travis.yml\n[{package.json,.travis.yml}]\nindent_style = space\nindent_size = 2\n
\n\nMost of these magic is defined in Kernel.SpecialForms.
\n\n__DIR__ # current dir\n__MODULE__ # current module\n__CALLER__ # caller of the function\n
\n\n__ENV__
Map.keys(__ENV__)\n[:__struct__, :aliases, :context, :context_modules, :export_vars, :file,\n :function, :functions, :lexical_tracker, :line, :macro_aliases, :macros,\n :module, :requires, :vars]\n
\n\n__CALLER__.module |> Module.definitions_in |> IO.inspect\n
\n\napply(Enum, :reverse, [[1, 2, 3]])\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "elixir",
"title": "Elixir",
"url": "/elixir",
"category": "Elixir",
"keywords": null,
"content_html": "# hello.exs\ndefmodule Greeter do\n def greet(name) do\n message = \"Hello, \" <> name <> \"!\"\n IO.puts message\n end\nend\n\nGreeter.greet(\"world\")\n
\n\nelixir hello.exs\n# Hello, world!\n
\n\nage = 23\n
\n\nuser = %{\n name: \"John\",\n city: \"Melbourne\"\n}\n
\n\nIO.puts \"Hello, \" <> user.name\n
\n\nusers = [ \"Tom\", \"Dick\", \"Harry\" ]\n
\n\nEnum.map(users, fn user ->\n IO.puts \"Hello \" <> user\nend)\n
\n\nsource\n|> transform(:hello)\n|> print()\n
\n\n# Same as:\nprint(transform(source, :hello))\n
\n\nThese two are equivalent.
\n\nuser = %{name: \"Tom\", age: 23}\n%{name: username} = user\n
\n\nThis sets username
to \"Tom\"
.
def greet(%{name: username}) do\n IO.puts \"Hello, \" <> username\nend\n\nuser = %{name: \"Tom\", age: 23}\n
\n\nPattern matching works in function parameters too.
\n\nif false do\n \"This will never be seen\"\nelse\n \"This will\"\nend\n
\ncase {1, 2, 3} do\n {4, 5, 6} ->\n \"This clause won't match\"\n {1, x, 3} ->\n \"This will match and bind x to 2\"\n _ ->\n \"This will match any value\"\nend\n
\n\ncond do\n 1 + 1 == 3 ->\n \"I will never be seen\"\n 2 * 5 == 12 ->\n \"Me neither\"\n true ->\n \"But I will (this is essentially an else)\"\nend\n
\n\ntry do\n throw(:hello)\ncatch\n message -> \"Got #{message}.\"\nafter\n IO.puts(\"I'm the after clause.\")\nend\n
\n\nSample | \nType | \n
---|---|
nil | \n Nil/null | \n
true / false | \n Boolean | \n
?a | \n Integer (ASCII) | \n
23 | \n Integer | \n
3.14 | \n Float | \n
'hello' | \n Charlist | \n
<<2, 3>> | \n Binary | \n
\"hello\" | \n Binary string | \n
:hello | \n Atom | \n
[a, b] | \n List | \n
{a, b} | \n Tuple | \n
%{a: \"hello\"} | \n Map | \n
%MyStruct{a: \"hello\"} | \n Struct | \n
fn -> ... end | \n Function | \n
is_atom/1\nis_bitstring/1\nis_boolean/1\nis_function/1\nis_function/2\nis_integer/1\nis_float/1\n
\n\nis_binary/1\nis_list/1\nis_map/1\nis_tuple/1\n
\n\nis_nil/1\nis_number/1\nis_pid/1\nis_port/1\nis_reference/1\n
\n\nleft != right # equal\nleft !== right # match\nleft ++ right # concat lists\nleft <> right # concat string/binary\nleft =~ right # regexp\n
\n\nrequire Redux # compiles a module\nimport Redux # compiles, and you can use without the `Redux.` prefix\n\nuse Redux # compiles, and runs Redux.__using__/1\nuse Redux, async: true\n\nimport Redux, only: [duplicate: 2]\nimport Redux, only: :functions\nimport Redux, only: :macros\n\nimport Foo.{Bar, Baz}\n
\n\nalias Foo.Bar, as: Bar\nalias Foo.Bar # same as above\n\nalias Foo.{Bar, Baz}\n
\n\nimport String\n
\n\nstr = \"hello\"\nstr |> length() # → 5\nstr |> codepoints() # → [\"h\", \"e\", \"l\", \"l\", \"o\"]\nstr |> slice(2..-1) # → \"llo\"\nstr |> split(\" \") # → [\"hello\"]\nstr |> capitalize() # → \"Hello\"\nstr |> match(regex)\n
\n\ninspect(object, opts \\\\ [])\n
\nvalue |> IO.inspect()\n
\nvalue |> IO.inspect(label: \"value\")\n
\n\nabs(n)\nround(n)\nrem(a, b) # remainder (modulo)\ndiv(a, b) # integer division\n
\n\nimport Float\n
\n\nn = 10.3\n
\n\nn |> ceil() # → 11.0\nn |> ceil(2) # → 11.30\nn |> to_string() # → \"1.030000+e01\"\nn |> to_string([decimals: 2, compact: true])\n
\n\nFloat.parse(\"34\") # → { 34.0, \"\" }\n
\n\nimport Integer\n
\n\nn = 12\n
\n\nn |> digits() # → [1, 2]\nn |> to_charlist() # → '12'\nn |> to_string() # → \"12\"\nn |> is_even()\nn |> is_odd()\n
\n\n# Different base:\nn |> digits(2) # → [1, 1, 0, 0]\nn |> to_charlist(2) # → '1100'\nn |> to_string(2) # → \"1100\"\n
\n\nparse(\"12\") # → {12, \"\"}\nundigits([1, 2]) # → 12\n
\n\nFloat.parse(\"34.1\") # → {34.1, \"\"}\nInteger.parse(\"34\") # → {34, \"\"}\n
\n\nFloat.to_string(34.1) # → \"3.4100e+01\"\nFloat.to_string(34.1, [decimals: 2, compact: true]) # → \"34.1\"\n
\n\nm = %{name: \"hi\"} # atom keys (:name)\nm = %{\"name\" => \"hi\"} # string keys (\"name\")\n
\n\nimport Map\n
\n\nm = %{m | name: \"yo\"} # key must exist\n
\n\nm |> put(:id, 2) # → %{id: 2, name: \"hi\"}\nm |> put_new(:id, 2) # only if `id` doesn't exist (`||=`)\n
\n\nm |> put(:b, \"Banana\")\nm |> merge(%{b: \"Banana\"})\nm |> update(:a, &(&1 + 1))\nm |> update(:a, fun a -> a + 1 end)\n
\n\nm |> get_and_update(:a, &(&1 || \"default\"))\n# → {old, new}\n
\n\nm |> delete(:name) # → %{}\nm |> pop(:name) # → {\"John\", %{}}\n
\n\nm |> get(:id) # → 1\nm |> keys() # → [:id, :name]\nm |> values() # → [1, \"hi\"]\n
\n\nm |> to_list() # → [id: 1, name: \"hi\"]\n # → [{:id, 1}, {:name, \"hi\"}]\n
\n\nput_in(map, [:b, :c], \"Banana\")\nput_in(map[:b][:c], \"Banana\") # via macros\n
\n\nget_and_update_in(users, [\"john\", :age], &{&1, &1 + 1})\n
\n\nMap.new([{:b, 1}, {:a, 2}])\nMap.new([a: 1, b: 2])\nMap.new([:a, :b], fn x -> {x, x} end) # → %{a: :a, b: :b}\n
\n\nimport List\n
\n\nl = [ 1, 2, 3, 4 ]\n
\n\nl = l ++ [5] # push (append)\nl = [ 0 | list ] # unshift (prepend)\n
\n\nl |> first()\nl |> last()\n
\n\nl |> flatten()\nl |> flatten(tail)\n
\n\nAlso see Enum.
\n\nimport Enum\n
\n\nlist = [:a, :b, :c]\n
\n\nlist |> at(0) # → :a\nlist |> count() # → 3\nlist |> empty?() # → false\nlist |> any?() # → true\n
\n\nlist |> concat([:d]) # → [:a, :b, :c, :d]\n
\n\nAlso, consider streams instead.
\n\nlist |> reduce(fn)\nlist |> reduce(acc, fn)\nlist |> map(fn)\nlist |> reject(fn)\nlist |> any?(fn)\nlist |> empty?(fn)\n
\n\n[1, 2, 3, 4]\n|> Enum.reduce(0, fn(x, acc) -> x + acc end)\n
\n\nimport Tuple\n
\n\nt = { :a, :b }\n
\n\nt |> elem(1) # like tuple[1]\nt |> put_elem(index, value)\nt |> tuple_size()\n
\n\nlist = [{ :name, \"John\" }, { :age, 15 }]\nlist[:name]\n
\n\n# For string-keyed keyword lists\nlist = [{\"size\", 2}, {\"type\", \"shoe\"}]\nList.keyfind(list, \"size\", 0) # → {\"size\", 2}\n
\n\nsquare = fn n -> n*n end\nsquare.(20)\n
\n\nsquare = &(&1 * &1)\nsquare.(20)\n\nsquare = &Math.square/1\n
\n\nfun.(args)\napply(fun, args)\napply(module, fun, args)\n
\n\ndef join(a, b \\\\ nil)\ndef join(a, b) when is_nil(b) do: a\ndef join(a, b) do: a <> b\n
\n\ndefmodule User do\n defstruct name: \"\", age: nil\nend\n\n%User{name: \"John\", age: 20}\n\n%User{}.struct # → User\n
\n\nSee: Structs
\n\ndefprotocol Blank do\n @doc \"Returns true if data is considered blank/empty\"\n def blank?(data)\nend\n
\n\ndefimpl Blank, for: List do\n def blank?([]), do: true\n def blank?(_), do: false\nend\n\nBlank.blank?([]) # → true\n
\n\ndefimpl Blank, for: Any do ... end\n\ndefmodule User do\n @derive Blank # Falls back to Any\n defstruct name: \"\"\nend\n
\n\nEnumerable
and Enum.map()
Inspect
and inspect()
for n <- [1, 2, 3, 4], do: n * n\nfor n <- 1..4, do: n * n\n
\n\nfor {key, val} <- %{a: 10, b: 20}, do: val\n# → [10, 20]\n
\n\nfor {key, val} <- %{a: 10, b: 20}, into: %{}, do: {key, val*val}\n
\n\nfor n <- 1..10, rem(n, 2) == 0, do: n\n# → [2, 4, 6, 8, 10]\n
\n\nfor dir <- dirs,\n file <- File.ls!(dir), # nested comprehension\n path = Path.join(dir, file), # invoked\n File.regular?(path) do # condition\n IO.puts(file)\nend\n
\n\n__MODULE__\n__MODULE__.__info__\n\n@after_compile __MODULE__\ndef __before_compile__(env)\ndef __after_compile__(env, _bytecode)\ndef __using__(opts) # invoked on `use`\n\n@on_definition {__MODULE__, :on_def}\ndef on_def(_env, kind, name, args, guards, body)\n\n@on_load :load_check\ndef load_check\n
\n\nexp = ~r/hello/\nexp = ~r/hello/i\n\"hello world\" =~ exp\n
\n\n~r/regexp/\n~w(list of strings)\n~s|strings with #{interpolation} and \\x20 escape codes|\n~S|no interpolation and no escapes|\n~c(charlist)\n
\n\nAllowed chars: /
|
\"
'
(
[
{
<
\"\"\"
.\nSee: Sigils
@spec round(number) :: integer\n\n@type number_with_remark :: {number, String.t}\n@spec add(number, number) :: number_with_remark\n
\n\nUseful for dialyzer.\nSee: Typespecs
\n\ndefmodule Parser do\n @callback parse(String.t) :: any\n @callback extensions() :: [String.t]\nend\n
\n\ndefmodule JSONParser do\n @behaviour Parser\n\n def parse(str), do: # ... parse JSON\n def extensions, do: [\"json\"]\nend\n
\n\nSee: Module
\n\n^n ^p # up/down\n ^f ^b # left/right
\n\n^v Mv # up/down page
\n\n^a ^e # begin/end of line\n Ma Me # begin/end of sentence
\n\n^x ^f # find file\n ^x ^s # save file
\n\nMx
\n\nMx package-install RET evil RET
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ember", "title": "Ember.js", "url": "/ember", "category": "JavaScript libraries", "keywords": null, "content_html": "App.Router.map(function() {\n this.resource('trips', function() {\n this.route('item', { path: '/:trip_id' });\n });\n\n this.route('upcoming');\n this.route('about', { path: '/about' });\n this.route('schedules');\n this.route('history');\n this.route('post');\n});\n
\n\nApp.IndexRoute = Ember.Route.extend({\n setupController: function(controller) {\n controller.set('title', 'my app');\n // <h1>{{title}}</h1>\n },\n\n setupController: function(controller, model) {\n controller.set(\"model\", model);\n this.controllerFor('topPost').set('model', model);\n },\n\n model: function(params) {\n return this.store.find('posts');\n return this.store.find('post', params.post_id);\n },\n \n serialize: function(model) {\n // this will make the URL `/posts/foo-post`\n return { post_slug: model.get('slug') };\n }\n});\n
\n\nApp.InfoView = Ember.View.extend({\n templateName: 'input', /* optional */\n\n fooName: \"Hello\" /* {{ view.fooName }} */\n\n click: function(e) {\n \"I was clicked\";\n }\n\n});\n
\n\n<img {{bindAttr src=\"avatarURL\"}}>\n<button {{action follow}}>\n
\n\nValue binding:
\n\n{{view Ember.TextField class=\"input block\" valuebinding=\"emailAddresses\"}}\n
\n\nActions:
\n\n<button {{action invite emailAddresses}}>Invite></button>\n\n<a href=\"#\" {{action set \"isEditingContacts\" true target=\"view\"}} \n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "emmet",
"title": "Emmet",
"url": "/emmet",
"category": "Markup",
"keywords": null,
"content_html": "nav>ul>li\n
\nExpands to
\n<nav>\n <ul>\n <li></li>\n </ul>\n</nav>\n
\n\nsection>p+p+p\n
\nExpands to
\n<section>\n <p></p>\n <p></p>\n <p></p>\n</section>\n
\n\nsection>header>h1^footer\n
\nExpands to
\n<section>\n <header>\n <h1></h1>\n </header>\n <footer></footer>\n</section>\n
\n\nsection>(header>nav>ul>li)+footer>p\n
\nExpands to
\n<section>\n <header>\n <nav>\n <ul>\n <li></li>\n </ul>\n </nav>\n </header>\n <footer>\n <p></p>\n </footer>\n</section>\n
\n\nul>li*3\n
\nExpands to
\n<ul>\n <li></li>\n <li></li>\n <li></li>\n</ul>\n
\n\nul.menu>li.menu__item+li#id_item+li.menu__item#id_2\n
\nExpands to
\n<ul>\n <li class=\"menu__item\"></li>\n <li id=\"id_item\"></li>\n <li class=\"menu__item\" id=\"id_2\"></li>\n</ul>\n
\n\nul>li.item$*3\nul>li.item$$*3\nul>li.item$@-*3\nul>li.item$@3*5\n
\nExpands to
\n<ul>\n <li class=\"item1\"></li>\n <li class=\"item2\"></li>\n <li class=\"item3\"></li>\n</ul>\n<ul>\n <li class=\"item01\"></li>\n <li class=\"item02\"></li>\n <li class=\"item03\"></li>\n</ul>\n<ul>\n <li class=\"item3\"></li>\n <li class=\"item2\"></li>\n <li class=\"item1\"></li>\n</ul>\n<ul>\n <li class=\"item3\"></li>\n <li class=\"item4\"></li>\n <li class=\"item5\"></li>\n</ul>\n
\n\ninput[type=\"text\"]\ndiv[data-attr=\"test\"]\n
\nExpands to
\n<input type=\"text\" />\n<div data-attr=\"test\"></div>\n
\n\np{Lorem ipsum}\n
\nExpands to
\n<p>Lorem ipsum</p>\n
\n\n.default-block\nem>.default-inline\nul>.default-list\ntable>.default-table-row>.default-table-column\n
\nExpands to
\n<div class=\"default-block\"></div>\n<em><span class=\"default-inline\"></span></em>\n<ul>\n <li class=\"default-list\"></li>\n</ul>\n<table>\n <tr class=\"default-table-row\">\n <td class=\"default-table-column\"></td>\n </tr>\n</table>\n
",
"intro_html": "Emmet is a markup language for expanding CSS rules into HTML
", "description_html": "", "tags": null, "updated": "2020-07-03" },{ "id": "enzyme", "title": "Enzyme", "url": "/enzyme", "category": "React", "keywords": ["shallow()","mount()","wrap.setProps()","wrap.find().simulate('click')","wrap.contains()"], "content_html": "Enzyme lets you write unit tests for React components. This guide covers Enzyme 3.x.
\n\nimport {shallow, mount} from 'enzyme'\n
\n\nwrap = shallow(<MyComponent />)\n
\n\nwrap = mount(<MyComponent />)\n
\n\nShallow wrapping doesn’t descend down to sub-components.\nA full mount also mounts sub-components.
\n\nSee: Shallow rendering,\nFull rendering
\n\nconsole.log(wrap.debug())\n
\n\nShows HTML for debugging purposes.
\n\nSee: debug()
\n\nimport { shallow } from 'enzyme'\nimport MyComponent from '../MyComponent'\n
\n\nit('works', () => {\n const wrap = shallow(\n <MyComponent name='Groot' />\n )\n\n expect(wrap.text()).toEqual('I am Groot')\n})\n
\n\nwrap.setProps({ name: 'Moe' })\nwrap.setState({ show: true })\n
\n\nexpect(wrap.prop('name')).toEqual('Moe')\nexpect(wrap.state('show')).toEqual(true)\n
\n\nexpect('name' in wrap.props()).toEqual('Moe')\nexpect('show' in wrap.state()).toEqual(true)\n
\n\nexpect(\n wrap.containsMatchingElement(\n <span>I am groot</span>\n )\n).toBeTruthy()\n
\n\ncontainsMatchingElement()
is probably the most useful assertion in Jest.
expect(wrap).toMatchSnapshot()\n
\n\nBe sure you’ve set up enzyme-to-json for snapshots (see Installing below).
\n\nexpect(\n wrap.find('button').text()\n).toEqual('Submit')\n
\n\nUse .find()
to traverse down to nodes. It will return wrapper objects, too.
wrap.find('input').simulate('click')\n
\n\nwrap.find('input').simulate('change', {\n target: { value: 'hello' }\n})\n
\n\nnpm install --save-dev enzyme \\\n enzyme-adapter-react-16 \\\n react-test-renderer\n
\n\nimport Enzyme from 'enzyme'\nimport Adapter from 'enzyme-adapter-react-16'\n\nEnzyme.configure({ adapter: new Adapter() })\n
\n\n\"jest\": {\n \"setupFiles\": [\n \"test/setup.js\"\n ]\n}\n
\n\nThis configures Enzyme for React v16, and Jest to automatically configure Enzyme for you. There are other adapters in Enzyme’s installation instructions.
\n\nSee: Installation
\n\nnpm install --save-dev enzyme-to-json\n
\n\n\"jest\": {\n \"snapshotSerializers\": [\n \"enzyme-to-json/serializer\"\n ]\n}\n
\n\nit('works', () => {\n wrap = mount(<MyComponent />)\n expect(wrap).toMatchSnapshot()\n})\n
\n\nOptional, but recommended: This allows you to use Enzyme wrappers with Jest snapshots.
\n\nSee: enzyme-to-json
\n\nwrap.find('button') // → ReactWrapper\nwrap.filter('button') // → ReactWrapper\nwrap.not('span') // → ReactWrapper (inverse of filter())\nwrap.children() // → ReactWrapper\nwrap.parent() // → ReactWrapper\nwrap.closest('div') // → ReactWrapper\nwrap.childAt(0) // → ReactWrapper\nwrap.at(0) // → ReactWrapper\nwrap.first() // → ReactWrapper\nwrap.last() // → ReactWrapper\n
\n\nwrap.get(0) // → ReactElement\nwrap.getElement() // → ReactElement\nwrap.getElements() // → Array<ReactElement>\nwrap.getDOMNode() // → DOMComponent\n
\n\nSee: Full rendering API
\n\nwrap.simulate('click')\n
\n\nwrap.setState({ ··· })\nwrap.setProps({ ··· })\nwrap.setContext({ ··· })\n
\n\nwrap.state() // get full state\nwrap.props() // get full props\nwrap.context() // get full context\n
\n\nwrap.state('key') // → any\nwrap.prop('key') // → any\nwrap.context('key') // → any\n
\n\nwrap.instance() // → ReactComponent\n
\n\nwrap.mount()\nwrap.unmount()\nwrap.update() // calls forceUpdate()\n
\n\nwrap.debug() // → string\nwrap.html() // → string\nwrap.text() // → string\nwrap.type() // → string | function\nwrap.name() // → string\nwrap.is('.classname') // → boolean\nwrap.hasClass('class') // → boolean\nwrap.exists() // → boolean\nwrap.contains(<div />) // → boolean\nwrap.contains([ <div /> ]) // → boolean\nwrap.some('.child') // → boolean\n\nwrap.someWhere(n => n.hasClass('foo'))\n\nwrap.containsMatchingElement(<div />) // → boolean\nwrap.containsAllMatchingElements([ <div /> ]) // → boolean\nwrap.containsAnyMatchingElements([ <div /> ]) // → boolean\n
\n\n(Deprecated) Enzyme lets you write unit tests for React components. This guide covers a previous version (v2.x).
\n\nimport {shallow, mount} from 'enzyme'\n
\n\nwrap = shallow(<MyComponent />)\n
\n\nwrap = mount(<MyComponent />)\n
\n\nShallow wrapping doesn’t descend down to sub-components.\nA full mount also mounts sub-components.\nSee: Shallow rendering,\nFull rendering
\n\nimport toJson from 'enzyme-to-json'\n
\n\nit('works', () => {\n wrap = mount(<MyComponent />)\n expect(toJson(wrap)).toMatchSnapshot()\n})\n
\n\nConverts an Enzyme wrapper to a format compatible with Jest snapshots. See: enzyme-to-json
\n\nconsole.log(wrap.debug())\n
\n\nShows HTML for debugging purposes. See: debug()
\n\nwrap.find('button') // => ReactWrapper\nwrap.filter('button') // => ReactWrapper\nwrap.not('span') // => ReactWrapper (inverse of filter())\nwrap.children() // => ReactWrapper\nwrap.parent() // => ReactWrapper\nwrap.closest('div') // => ReactWrapper\nwrap.childAt(0) // => ReactWrapper\nwrap.at(0) // => ReactWrapper\nwrap.first() // => ReactWrapper\nwrap.last() // => ReactWrapper\n
\n\nwrap.get(0) // => ReactElement\nwrap.getNode() // => ReactElement\nwrap.getNodes() // => Array<ReactElement>\nwrap.getDOMNode() // => DOMComponent\n
\n\nSee: Full rendering API
\n\nwrap.simulate('click')\n
\n\nwrap.setState({ ... })\nwrap.setProps({ ... })\nwrap.setContext({ ... })\n\nwrap.state() // => Any (get state)\nwrap.props() // => object (get props)\nwrap.context() // => Any (get context)\n\nwrap.instance() // => ReactComponent\n
\n\nwrap.mount()\nwrap.unmount()\nwrap.update() // calls forceUpdate()\n
\n\nwrap.debug() // => string\nwrap.html() // => string\nwrap.text() // => string\nwrap.type() // => string | function\nwrap.name() // => string\nwrap.is('.classname') // => boolean\nwrap.hasClass('class') // => boolean\nwrap.exists() // => boolean\nwrap.contains(<div />) // => boolean\nwrap.contains([ <div /> ]) // => boolean\n\nwrap.containsMatchingElement(<div />) // => boolean\nwrap.containsAllMatchingElements([ <div /> ]) // => boolean\nwrap.containsAnyMatchingElements([ <div /> ]) // => boolean\n
\n\nfunction fn () {\n let x = 0\n if (true) {\n let x = 1 // only inside this `if`\n }\n}\n
\n\nconst a = 1\n
\n\nlet
is the new var
. Constants work just like let
, but can’t be reassigned.\nSee: Let and const
const message = `Hello ${name}`\n
\n\nconst str = `\nhello\nworld\n`\n
\n\nTemplates and multiline strings.\nSee: Template strings
\n\nlet bin = 0b1010010\nlet oct = 0o755\n
\n\nSee: Binary and octal literals
\n\n\"hello\".repeat(3)\n\"hello\".includes(\"ll\")\n\"hello\".startsWith(\"he\")\n\"hello\".padStart(8) // \" hello\"\n\"hello\".padEnd(8) // \"hello \" \n\"hello\".padEnd(8, '!') // hello!!!\n\"\\u1E9B\\u0323\".normalize(\"NFC\")\n
\n\nSee: New methods
\n\nclass Circle extends Shape {\n
\n\n constructor (radius) {\n this.radius = radius\n }\n
\n\n getArea () {\n return Math.PI * 2 * this.radius\n }\n
\n\n expand (n) {\n return super.expand(n) * Math.PI\n }\n
\n\n static createFromDiameter(diameter) {\n return new Circle(diameter / 2)\n }\n}\n
\n\nSyntactic sugar for prototypes.\nSee: Classes
\n\nconst byte = 2 ** 8\n// Same as: Math.pow(2, 8)\n
\n\nnew Promise((resolve, reject) => {\n if (ok) { resolve(result) }\n else { reject(error) }\n})\n
\n\nFor asynchronous programming.\nSee: Promises
\n\npromise\n .then((result) => { ··· })\n .catch((error) => { ··· })\n
\n\npromise\n .then((result) => { ··· })\n .catch((error) => { ··· })\n .finally(() => { // logic independent of success/error })\n
\n\nThe handler is called when the promise is fulfilled or rejected.
\n\nPromise.all(···)\nPromise.race(···)\nPromise.reject(···)\nPromise.resolve(···)\n
\n\nasync function run () {\n const user = await getUser()\n const tweets = await getTweets(user)\n return [user, tweets]\n}\n
\n\nasync
functions are another way of using functions.
See: async function
\n\nconst [first, last] = ['Nikola', 'Tesla']\n
\n\nlet {title, author} = {\n title: 'The Silkworm',\n author: 'R. Galbraith'\n}\n
\n\nSupports for matching arrays and objects.\nSee: Destructuring
\n\nconst scores = [22, 33]\nconst [math = 50, sci = 50, arts = 50] = scores\n
\n\n// Result:\n// math === 22, sci === 33, arts === 50\n
\n\nDefault values can be assigned while destructuring arrays or objects.
\n\nfunction greet({ name, greeting }) {\n console.log(`${greeting}, ${name}!`)\n}\n
\n\ngreet({ name: 'Larry', greeting: 'Ahoy' })\n
\n\nDestructuring of objects and arrays can also be done in function arguments.
\n\nfunction greet({ name = 'Rauno' } = {}) {\n console.log(`Hi ${name}!`);\n}\n
\n\ngreet() // Hi Rauno!\ngreet({ name: 'Larry' }) // Hi Larry!\n
\n\nfunction printCoordinates({ left: x, top: y }) {\n console.log(`x: ${x}, y: ${y}`)\n}\n
\n\nprintCoordinates({ left: 25, top: 90 })\n
\n\nThis example assigns x
to the value of the left
key.
for (let {title, artist} of songs) {\n ···\n}\n
\n\nThe assignment expressions work in loops, too.
\n\nconst { id, ...detail } = song;\n
\n\nExtract some keys individually and remaining keys in the object using rest (…) operator
\n\nconst options = {\n ...defaults,\n visible: true\n}\n
\n\nconst options = Object.assign(\n {}, defaults,\n { visible: true })\n
\n\nThe Object spread operator lets you build new objects from other objects.
\n\nSee: Object spread
\n\nconst users = [\n ...admins,\n ...editors,\n 'rstacruz'\n]\n
\n\nconst users = admins\n .concat(editors)\n .concat([ 'rstacruz' ])\n
\n\nThe spread operator lets you build new arrays in the same way.
\n\nSee: Spread operator
\n\nfunction greet (name = 'Jerry') {\n return `Hello ${name}`\n}\n
\n\nfunction fn(x, ...y) {\n // y is an Array\n return x * y.length\n}\n
\n\nfn(...[1, 2, 3])\n// same as fn(1, 2, 3)\n
\n\nDefault, rest, spread.\nSee: Function arguments
\n\nsetTimeout(() => {\n ···\n})\n
\n\nreadFile('text.txt', (err, data) => {\n ...\n})\n
\n\nnumbers.map(n => n * 2)\n// No curly braces = implicit return\n// Same as: numbers.map(function (n) { return n * 2 })\nnumbers.map(n => ({\n result: n * 2\n}))\n// Implicitly returning objects requires parentheses around the object\n
\n\nLike functions but with this
preserved.\nSee: Fat arrows
module.exports = { hello, bye }\n// Same as: module.exports = { hello: hello, bye: bye }\n
\n\nSee: Object literal enhancements
\n\nconst App = {\n start () {\n console.log('running')\n }\n}\n// Same as: App = { start: function () {···} }\n
\n\nSee: Object literal enhancements
\n\nconst App = {\n get closed () {\n return this.status === 'closed'\n },\n set closed (value) {\n this.status = value ? 'closed' : 'open'\n }\n}\n
\n\nSee: Object literal enhancements
\n\nlet event = 'click'\nlet handlers = {\n [`on${event}`]: true\n}\n// Same as: handlers = { 'onclick': true }\n
\n\nSee: Object literal enhancements
\n\nconst fatherJS = { age: 57, name: \"Brendan Eich\" }\n\nObject.values(fatherJS)\n// [57, \"Brendan Eich\"]\nObject.entries(fatherJS)\n// [[\"age\", 57], [\"name\", \"Brendan Eich\"]]\n
\n\nimport 'helpers'\n// aka: require('···')\n
\n\nimport Express from 'express'\n// aka: const Express = require('···').default || require('···')\n
\n\nimport { indent } from 'helpers'\n// aka: const indent = require('···').indent\n
\n\nimport * as Helpers from 'helpers'\n// aka: const Helpers = require('···')\n
\n\nimport { indentSpaces as indent } from 'helpers'\n// aka: const indent = require('···').indentSpaces\n
\n\nimport
is the new require()
.\nSee: Module imports
export default function () { ··· }\n// aka: module.exports.default = ···\n
\n\nexport function mymethod () { ··· }\n// aka: module.exports.mymethod = ···\n
\n\nexport const pi = 3.14159\n// aka: module.exports.pi = ···\n
\n\nexport
is the new module.exports
.\nSee: Module exports
function* idMaker () {\n let id = 0\n while (true) { yield id++ }\n}\n
\n\nlet gen = idMaker()\ngen.next().value // → 0\ngen.next().value // → 1\ngen.next().value // → 2\n
\n\nIt’s complicated.\nSee: Generators
\n\nfor (let i of iterable) {\n ···\n}\n
\n\nFor iterating through generators and arrays.\nSee: For..of iteration
", "intro_html": "A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.
", "description_html": "", "tags": ["Featured"], "updated": "2019-11-14" },{ "id": "ets", "title": "Erlang ETS", "url": "/ets", "category": "Elixir", "keywords": null, "content_html": "iex> table = :ets.new(:my_table, [])\n 8211\n
\n\niex> :ets.insert(table, {:fruit, \"Apple\"})\niex> :ets.lookup(table, :fruit)\n [{:fruit, \"Apple\"}]\n
\n\niex> :ets.delete(table)\niex> :ets.delete_all_objects(table)\n
\n\niex> table = :ets.new(:my_table, [:set, :protected])\n
\n\n:set | \n no duplicate keys (or: :ordered_set , :bag , :duplicate_bag ) | \n
:protected | \n only this process can use it (or: :public , :private ) | \n
:ets.first(table)\n:ets.last(table)\n:ets.next(table, key)\n:ets.prev(table, key)\n
\n\nnpm install --save-dev expect\n
\n\n// using ES6 modules\nimport expect, { createSpy, spyOn, isSpy } from 'expect'\n
\n\n// using CommonJS modules\nvar expect = require('expect')\nvar createSpy = expect.createSpy\nvar spyOn = expect.spyOn\nvar isSpy = expect.isSpy\n
\n\nExpect is a library for assertions in tests.\nSee: mjackson/expect
\n\nexpect(x).toBe(y)\n .toBe(val)\n .toEqual(val)\n .toThrow(err)\n .toExist() // aka: toBeTruthy()\n .toNotExist() // aka: toBeFalsy()\n .toBeA(constructor)\n .toBeA('string')\n .toMatch(/expr/)\n .toBeLessThan(n)\n .toBeGreaterThan(n)\n .toBeLessThanOrEqualTo(n)\n .toBeGreaterThanOrEqualTo(n)\n .toInclude(val) // aka: toContain(val)\n .toExclude(val)\n .toIncludeKey(key)\n .toExcludeKey(key)\n
\n\nAlso: toNotBe
, toNotEqual
, etc for negatives.
expect(3.14)\n .toExist()\n .toBeLessThan(4)\n .toBeGreaterThan(3)\n
\n\nAssertions can be chained.
\n\nconst video = {\n play: function () { ··· }\n}\n
\n\nspy = expect.spyOn(video, 'play')\n
\n\nspy = expect.spyOn(···)\n .andCallThrough() // pass through\n .andCall(fn)\n .andThrow(exception)\n .andReturn(value)\n
\n\nexpect(spy.calls.length).toEqual(1)\nexpect(spy.calls[0].context).toBe(video)\nexpect(spy.calls[0].arguments).toEqual([ 'some', 'args' ])\nexpect(spy.getLastCall().arguments).toEqual(...)\n
\n\nexpect(spy).toHaveBeenCalled()\nexpect(spy).toHaveBeenCalledWith('some', 'args')\n
\n\napp.set('x', 'yyy')\napp.get('x') //=> 'yyy'\n\napp.enable('trust proxy')\napp.disable('trust proxy')\n\napp.enabled('trust proxy') //=> true\n
\n\napp.get('env')\n
\n\napp.configure('production', function() {\n app.set...\n})\n
\n\napp.use(express.static(__dirname + '/public'))\napp.use(express.logger())\n
\n\napp.locals({\n title: \"MyApp\",\n})\n
\n\n// GET /user/tj\nreq.path //=> \"/user/tj\"\nreq.url //=> \"/user/tj\"\nreq.xhr //=> true|false\nreq.method //=> \"GET\"\nreq.params\nreq.params.name //=> \"tj\"\nreq.params[0]\n
\n\n// GET /search?q=tobi+ferret\nreq.query.q // => \"tobi ferret\"\n
\n\nreq.cookies\n
\n\nreq.accepted\n// [ { value: 'application/json', quality: 1, type: 'application', subtype: 'json' },\n// { value: 'text/html', quality: 0.5, type: 'text',subtype: 'html' } ]\n
\n\nreq.is('html')\nreq.is('text/html')\n
\n\nreq.headers\nreq.headers['host']\nreq.headers['user-agent']\nreq.headers['accept-encoding']\nreq.headers['accept-language']\n
\n\nres.redirect('/')\nres.redirect(301, '/')\n
\n\nres.set('Content-Type', 'text/html')\n
\n\nres.send('hi')\nres.send(200, 'hi')\n
\n\nres.json({ a: 2 })\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "exunit",
"title": "ExUnit",
"url": "/exunit",
"category": "Elixir",
"keywords": null,
"content_html": "defmodule MyTest do\n use ExUnit.Case\n use ExUnit.Case, async: true # for async\n\n test \"the truth\" do\n assert 1 + 1 == 2\n end\nend\n
\n\nimport ExUnit.CaptureIO\n\ntest \"capture io\" do\n result = capture_io(fn ->\n IO.puts \"sup\"\n end)\n\n assert result == \"sup\\n\"\nend\n
\n\nconfig :ex_unit, capture_logs: true\n
\n\ndefmodule AssertionTest do\n # run concurrently with other test cases\n use ExUnit.Case, async: true\nend\n
\n\nassert x == y\nrefute x == y\n\nassert_raise ArithmeticError, fn ->\n 1 + \"test\"\nend\n\nassert_raise ArithmeticError, \"message\", fn -> ...\nassert_raise ArithmeticError, ~r/message/, fn -> ...\n\nflunk \"This should've been an error\"\n
\n\nSee: Assertions
\n\nsetup do\n {:ok, name: \"John\"}\nend\n
\n\ntest \"it works\", %{name: name} do\n assert name == \"John\"\nend\n
\n\ndefp my_hook(_context) do\n # Invoked in every block in \"a block\"\n {:ok, name: \"John\", age: 54}\nend\n\ndescribe \"a block\" do\n setup [:my_hook]\n \n test \"John's age\", context do\n assert context[:name] == \"John\"\n assert context[:age] == 54\n end\nend\n
\n\nFactory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl. For older versions, use FactoryGirl
instead of FactoryBot
.
FactoryBot.define do\n factory :user do\n first_name { 'John' }\n last_name { 'Doe' }\n birthdate { 21.years.ago }\n admin { false }\n\n sequence(:username) { |n| \"user#{n}\" }\n end\nend\n
\n\nSee: Defining factories
\n\nfactory :user, class: 'User' do\n ···\nend\n
\n\nfactory :user, aliases: [:author] do\n ···\nend\n
\n\nFactoryBot.build(:user)\n
\n\nbuild(:user) # → model (not saved)\ncreate(:user) # → model (saved)\nattributes_for(:user) # → hash\nbuild_stubbed(:user) # stubbed out attributes\n
\n\nbuild(:user, name: 'John')\n
\n\ncreate_list(:user, 3)\nbuild_list(:user, 3)\n
\n\nfactory :post do\n association :author, factory: :user\n association :author, factory: [:user, :admin]\nend\n
\n\nfactory :post do\n author # assumes there's a factory :author\nend\n
\n\nfactory :post do\n after :create do |post|\n create :theme, post: post # has_one\n create_list :comment, 3, post: post # has_many\n end\nend\n
\n\nfactory :user do\n trait :admin do\n admin { true }\n end\nend\n
\n\ncreate :user, :admin\n
\n\nTraits allow you to group attributes together.\nSee: Traits
\n\nfactory :user do\n first_name { 'John' }\n\n factory :sample_user do\n first_name { FFaker::Name.first_name }\n end\nend\n
\n\ncreate :sample_user\n
\n\nSee: Inheritance
\n\nfactory :user do\n ···\nend\n
\n\nfactory :sample_user, parent: :user do\n first_name { FFaker::Name.first_name }\nend\n
\n\ncreate :sample_user\n
\n\nWorks the same as nested factories.
\n\nfactory :user do\n transient do\n upcased { true }\n end\n\n after :create do |user, options|\n user.name.upcase! if options.upcased\n end\nend\n
\n\ncreate(user, upcased: true)\n
\n\nTransient attributes will not get passed to the model, but will be available in after-create hooks.\nSee: Transient attributes
\n\nPlace your factories in these locations.
\n\nFastify lets you create HTTP servers in Node.js with good performance. This guide targets fastify v0.28.x.
\n\nconst fastify = require('fastify')()\n\nfastify.get('/', (req, reply) => {\n reply.send({ hello: 'world' })\n})\n\nfastify.listen(3000, err => {\n if (err) throw err\n const port = fastify.server.address().port\n console.log(`server listening on ${port}`)\n})\n
\n\nfastify.register(require('./route'))\n
\n\nfunction (fastify, opts, next) {\n fastify.get('/', (req, reply) => {\n reply.send({ hello: 'world' })\n })\n\n next()\n})\n
\n\nCompose your app functionality into plugins. Plugins are simply functions.
\n\nSee: Plugins
\n\nfastify.route({\n method: 'GET',\n url: '/',\n schema: { ··· },\n handler: (req, reply) => { ··· }\n beforeHandler: (req, reply, done) => { ··· }\n})\n
\n\nfastify.get(path, [options], handler)\nfastify.head(···)\nfastify.post(···)\nfastify.put(···)\nfastify.delete(···)\nfastify.options(···)\nfastify.patch(···)\n
\n\nfastify.get('/', options, async (req, reply) => {\n return data\n // or\n reply.send(data)\n})\n
\n\nWhen using async functions, you can either return
data or use reply.send
.
request.query\nrequest.body\nrequest.params\nrequest.headers\nrequest.req // Node.js core\nrequest.log.info('hello')\n
\n\nSee: Request
\n\nreply.code(404)\nreply.header('Content-Type', 'text/html')\nreply.type('text/html')\n
\n\nreply.redirect('/foo')\nreply.redirect(302, '/foo')\n
\n\nreply.send(payload)\nreply.sent // → true|false\n
\n\nSee: Reply
\n\nconst schema = {\n querystring: {\n name: { type: 'string' },\n excitement: { type: 'integer' }\n },\n response: {\n 200: {\n type: 'object',\n properties: {\n hello: { type: 'string' }\n }\n }\n }\n}\n
\n\nfastify.get('/', { schema }, (req, reply) => {\n ···\n})\n
\n\nfastify.route({\n method: 'GET',\n url: '/',\n schema,\n handler: (req, reply) => { ··· }\n})\n
\n\nBy defining a JSON schema, you get validation and improved performance.
\n\nSee: Validation and serialization
\n\nfastify.register(\n require('./route'),\n err => { if (err) throw err }\n)\n
\n\nmodule.exports = (fastify, options, next) => {\n fastify.get('/', ···)\n next()\n}\n
\n\nSee: Register
\n\nfastify.register([\n require('./another-route'),\n require('./yet-another-route')\n], opts, (err) => {\n if (err) throw err\n})\n
\n\nYou can pass arrays to register()
.
fastify.register(\n require('./route'),\n { prefix: '/v1' }\n)\n
\n\nThis prefixes all routes in that module.
\n\nconst helmet = require('fastify-helmet')\n\nfastify.register(helmet)\n
\n\nSee: fastify-helmet
\n\nconst fp = require('fastify-plugin')\n\nmodule.exports = fp((fastify, opts, next) => {\n // your plugin code\n fastify.decorate('utility', () => {})\n\n next()\n}, '0.x')\n
\n\nAllows you to limit Fastify versions via semver, and allows you not make a new Fastify scope.
\n\nSee: fastify-plugin
\n\nfastify.use(require('cors')())\nfastify.use(require('dns-prefetch-control')())\nfastify.use(require('frameguard')())\nfastify.use(require('hide-powered-by')())\nfastify.use(require('hsts')())\nfastify.use(require('ienoopen')())\nfastify.use(require('x-xss-protection')())\n
\n\nCompatible with Express and Restify middlewares. (Don’t use these middleware, these are covered by fastify-helmet.)
\n\nSee: Middlewares
\n\nconst fastify = require('fastify')()\n\nfastify.register(require('point-of-view'), {\n engine: {\n ejs: require('ejs')\n }\n})\n
\n\nfastify.get('/', (req, reply) => {\n reply.view('/templates/index.ejs', { text: 'text' })\n})\n
\n\nSupport ejs
, pug
, handlebars
and marko
.
See: point-of-view
\n\nfastify.register(require('point-of-view'), {\n engine: {\n ejs: require('ejs')\n },\n templates: '/templates',\n options: {}\n})\n
\n\ntemplates
lets you update the templates folder. options
are options passed onto the template engines.
# gem install ffaker\nrequire 'ffaker'\n
\n\nFaker::Address.city #=> \"Autumnside\"\n #=> \"South Brielleberg\"\n #=> \"West Alvera\"\n
\n\nFaker::Address.street_name #=> \"Greyson Rapid\"\n #=> \"Hoppe Grove\"\n #=> \"Reichert Lights\"\n
\n\nFaker::Address.street_address #=> \"98786 Neal Motorway\"\n #=> \"6619 Yvonne Dale\"\n #=> \"6143 Bailey Plaza\"\n
\n\nFaker::Address.secondary_address #=> \"Suite 560\"\n #=> \"Apt. 332\"\n #=> \"Apt. 411\"\n
\n\nFaker::Company.name #=> \"Pouros-Ondricka\"\n #=> \"Ward Group\"\n #=> \"Walter-Romaguera\"\n
\n\nFaker::Company.suffix #=> \"and Sons\"\n #=> \"LLC\"\n #=> \"and Sons\"\n
\n\nFaker::Company.catch_phrase #=> \"Versatile mobile help-desk\"\n #=> \"Extended fresh-thinking utilisation\"\n #=> \"Reactive coherent flexibility\"\n
\n\nFaker::Company.bs #=> \"extend one-to-one convergence\"\n #=> \"architect 24/7 interfaces\"\n #=> \"revolutionize viral vortals\"\n
\n\nFaker::Company.position #=> \"General Corporate President\"\n #=> \"Executive Department Consultant\"\n #=> \"Associate Director\"\n
\n\nFaker::Education.school #=> \"Larkwood Institution\"\n #=> \"Whiteshire School\"\n #=> \"California International College\"\n
\n\nFaker::Education.degree #=> \"Bachelor of Science in Political Administration\"\n #=> \"Doctor of Medicine in Marketing Economics\"\n #=> \"Bachelor of Music in Marketing Development\"\n
\n\nFaker::Education.degree_short #=> \"MD in Industrial Arts\"\n #=> \"DPhil in Social Management\"\n #=> \"AB in Political Science\"\n
\n\nFaker::Education.major #=> \"Financial Philosophy\"\n #=> \"Social Arts\"\n #=> \"Business Accountancy\"\n
\n\nFaker::Education.school_name #=> \"Larkfield\"\n #=> \"Northshire\"\n #=> \"Lakepoint\"\n
\n\nFaker::Geolocation.lat #=> 40.89505\n #=> 41.77117\n #=> 41.022921\n
\n\nFaker::Geolocation.lng #=> -115.120716573\n #=> -118.427610513239\n #=> -72.204989\n
\n\nFaker::Internet.email #=> \"dayna@auer.name\"\n #=> \"joy@nienowbradtke.info\"\n #=> \"bernhard@wyman.ca\"\n
\n\nFaker::Internet.user_name #=> \"emory\"\n #=> \"janelle_schamberger\"\n #=> \"brigitte.dooley\"\n
\n\nFaker::Internet.domain_name #=> \"langworth.biz\"\n #=> \"corkery.info\"\n #=> \"schroeder.uk\"\n
\n\nFaker::Internet.disposable_email #=> \"barrett_schroeder@spamherelots.com\"\n #=> \"nicholaus@suremail.info\"\n #=> \"gladys@safetymail.info\"\n
\n\nFaker::Internet.free_email #=> \"lemuel@yahoo.com\"\n #=> \"nickolas.gulgowski@gmail.com\"\n #=> \"isaac_ankunding@gmail.com\"\n
\n\nFaker::Internet.domain_word #=> \"purdykutch\"\n #=> \"sauer\"\n #=> \"trantowmaggio\"\n
\n\nFaker::Internet.domain_suffix #=> \"us\"\n #=> \"info\"\n #=> \"biz\"\n
\n\nFaker::Job.title #=> \"Future Data Assistant\"\n #=> \"Product Division Technician\"\n #=> \"Product Research Developer\"\n
\n\nFaker::Lorem.word #=> \"sint\"\n #=> \"sit\"\n #=> \"omnis\"\n
\n\nFaker::Lorem.sentence #=> \"Expedita et aspernatur eum sit ipsam culpa.\"\n #=> \"Rem sunt voluptatem laborum dolores.\"\n #=> \"Ad explicabo atque culpa.\"\n
\n\nFaker::Lorem.paragraph #=> \"Quidem deserunt qui atque labore sunt quis laborum. Et iste\n # laudantium nobis adipisci delectus. Quod vero repudiandae m\n # agni repellat totam. Id ullam a aperiam et laboriosam. Volup\n # tas aut perspiciatis o...\"\n #=> \"Dolor et quae quisquam placeat. Accusantium quidem totam no\n # n et deleniti accusamus hic. Iure quidem inventore molestiae\n # harum magni dolor. Deleniti ex a voluptas nihil temporibus.\n # \"\n #=> \"Fugiat sapiente vero voluptatum natus assumenda quam beatae\n # in. Nemo velit incidunt dolor perspiciatis. Ipsum minima oc\n # caecati est laudantium ducimus libero. Et fugit et adipisci\n # molestias. Cupiditate ...\"\n
\n\nFaker::Lorem.words(4) #=> [\"repellat\", \"quos\", \"amet\", \"voluptatem\"]\n #=> [\"porro\", \"molestias\", \"ut\", \"qui\"]\n #=> [\"blanditiis\", \"soluta\", \"enim\", \"fugit\"]\n
\n\nFaker::Lorem.sentence(5) #=> \"Laborum sint voluptate voluptatem rem doloremque et incidun\n # t itaque.\"\n #=> \"Autem atque eum laborum alias perspiciatis debitis suscipit\n # deserunt sint.\"\n #=> \"Quaerat nam consectetur eum dolor deleniti tempore doloremq\n # ue et aspernatur.\"\n
\n\nFaker::Lorem.sentences(3) #=> [\"Culpa debitis architecto est.\", \"Quo et voluptatem distinc\n # tio repellendus qui cupiditate.\", \"Quo repellendus ut eius.\"\n # ]\n #=> [\"Quos nihil dolorem quidem maxime.\", \"Expedita ab veniam do\n # lorum at et placeat iure.\", \"In perspiciatis cupiditate amet\n # non saepe consequatur molestias minus.\"]\n #=> [\"Quasi velit et voluptas est.\", \"Dolores ut dolor aut repel\n # lat fuga minima sed quia.\", \"Eum id minus atque ex modi.\"]\n
\n\nFaker::Lorem.paragraphs(3) #=> [\"Iusto mollitia sequi nam perspiciatis fuga aut. Modi moles\n # tiae consectetur architecto et dolorem aut perferendis. Cumq\n # ue rerum aliquam sapiente. Dolorum quo reiciendis nemo vero.\n # Quo earum explicabo pariatur.\", \"Possimus omnis accusamus f\n # uga. Harum sint facere sed dolor itaque quia. Ullam optio at\n # que vel nihil facilis quidem accusantium sint.\", \"Itaque per\n # ferendis saepe pariatur maxime expedita laborum qui. Ea nemo\n # dolor aut. In sed sit minus itaque sit.\"]\n #=> [\"Ducimus non quo qui doloremque aperiam aspernatur. Consequ\n # atur id qui sit occaecati. Incidunt tempora quia et. Esse vo\n # luptatem debitis similique ab totam sit. Illo neque vel face\n # re maxime voluptatum non voluptatem.\", \"Aut eveniet consequa\n # tur laudantium veniam qui dolores. Provident pariatur perspi\n # ciatis id. Eum iste id quasi. Esse nihil quis rerum laudanti\n # um aliquam molestiae eum tempora.\", \"Quia porro sint numquam\n # qui. Ut sint reiciendis quis pariatur veniam nesciunt optio\n # . Officia unde fugit distinctio dolorem voluptatem incidunt.\n # Ex omnis sit et non aut.\"]\n #=> [\"Dicta consequatur sapiente saepe fugiat ut. Necessitatibus\n # enim explicabo qui fugiat occaecati expedita quis. Quo iust\n # o magnam facere nihil earum.\", \"In deleniti explicabo veniam\n # dolorem temporibus enim. Delectus exercitationem ipsum dolo\n # r modi. Aut quia voluptas velit sint aperiam sed eveniet.\",\n # \"Quo doloribus explicabo ut magnam quasi. Voluptatem debitis\n # quaerat aperiam. Accusantium quis voluptatem dolorem.\"]\n
\n\nFaker::HipsterIpsum.paragraph #=> \"Wayfarers mustache thundercats pitchfork messenger bag high\n # life. Beard messenger bag wayfarers squid vinyl letterpress\n # party iphone jean shorts. Lomo irony before they sold out e\n # thical wayfarers scene...\"\n #=> \"Tofu stumptown cliche sartorial vhs letterpress keffiyeh wi\n # lliamsburg. Whatever jean shorts williamsburg lomo salvia fo\n # od truck 8-bit. Cosby sweater portland artisan wayfarers vhs\n # photo booth.\"\n #=> \"Skateboard fanny pack wes anderson sartorial cred gluten-fr\n # ee vinyl marfa locavore. Messenger bag master cleanse mlkshk\n # vegan thundercats beard wes anderson brunch. Helvetica mess\n # enger bag lo-fi four l...\"\n
\n\nFaker::HTMLIpsum.body #=> \"<h1>Exercitationem et</h1><table><thead><tr><th>Eligendi</t\n # h><th>Vel</th><th>Sed</th><th>At</th></tr></thead><tbody><tr\n # ><...\"\n #=> \"<h1>Excepturi sequi</h1><table><thead><tr><th>Quam</th><th>\n # Eius</th><th>Quibusdam</th><th>Totam</th></tr></thead><tbody\n # ><tr>...\"\n #=> \"<h1>Iusto voluptatem</h1><p>Laborum velit ducimus eius. Mol\n # estiae id vel ipsam a accusantium et ut. Sunt et fugiat qui\n # sint ab quia. Eum ut molestiae cumque molestiae error volupt\n # ates. Ipsum molestiae ...\"\n
\n\nFaker::HTMLIpsum.table #=> \"<table><thead><tr><th>Voluptatem</th><th>Porro</th><th>Tene\n # tur</th><th>Facilis</th></tr></thead><tbody><tr><td>Numquam<\n # /t...\"\n #=> \"<table><thead><tr><th>Impedit</th><th>Voluptatem</th><th>Qu\n # i</th><th>Est</th></tr></thead><tbody><tr><td>Nihil</td>...\"\n #=> \"<table><thead><tr><th>Iste</th><th>Et</th><th>Sequi</th><th\n # >Et</th></tr></thead><tbody><tr><td>Blanditiis</td>...\"\n
\n\nFaker::HTMLIpsum.fancy_string #=> \"<a href=\\\"#distinctio\\\" title=\\\"Tenetur explicabo\\\">Velit e\n # st</a> <code>aperiam reiciendis</code> Consectetur aut hic e\n # um quisquam. Dolore aut rerum dolor accusantium ab repellend\n # us magni. Deserunt optio o...\"\n #=> \"Et vel similique ullam accusantium laboriosam. Sit ut ea to\n # tam. Iusto praesentium ut molestiae. Voluptatem laudantium a\n # ut qui adipisci. Est saepe repellendus qui blanditiis volupt\n # ates sed odit ullam. <...\"\n #=> \"Neque et omnis ipsam ad culpa maiores inventore. Laborum cu\n # m est fugit libero repellendus vero. Modi pariatur sunt tene\n # tur soluta inventore ratione. Iste consequuntur quia omnis n\n # umquam excepturi quod ...\"\n
\n\nFaker::Name.name #=> \"Trevion Herman V\"\n #=> \"Aracely Balistreri\"\n #=> \"Daphnee Terry Sr.\"\n
\n\nFaker::Name.first_name #=> \"Aliza\"\n #=> \"Joseph\"\n #=> \"Orland\"\n
\n\nFaker::Name.last_name #=> \"Hand\"\n #=> \"Macejkovic\"\n #=> \"Heller\"\n
\n\nFaker::Name.prefix #=> \"Dr.\"\n #=> \"Ms.\"\n #=> \"Mr.\"\n
\n\nFaker::Name.suffix #=> \"I\"\n #=> \"III\"\n #=> \"DDS\"\n
\n\nFaker::PhoneNumber.phone_number #=> \"335-364-4549 x430\"\n #=> \"040-278-4021 x753\"\n #=> \"420.645.4382\"\n
\n\nFaker::PhoneNumber.short_phone_number #=> \"473-412-3192\"\n #=> \"353-084-1297\"\n #=> \"080-546-2356\"\n
\n\nFaker::Product.brand #=> \"Trouffeforge\"\n #=> \"VIG\"\n #=> \"NDZ\"\n
\n\nFaker::Product.product_name #=> \"Air HD Viewer\"\n #=> \"HD Kit\"\n #=> \"Air HD Bridge\"\n
\n\nFaker::Product.product #=> \"Amnix Air HD Tuner\"\n #=> \"Panapod Audible Filter\"\n #=> \"Phuffe Disc Receiver\"\n
\n\nFaker::Product.model #=> \"I-422\"\n #=> \"J89\"\n #=> \"L6\"\n
\n\nFaker::NameCN.name #=> \"姵书虞\"\n #=> \"修男嵇\"\n #=> \"瑜人军\"\n
\n\nFaker::NameCN.last_first #=> \"向坚舜\"\n #=> \"疏骏哲\"\n #=> \"秘合雪\"\n
\n\nFaker::NameCN.first_name #=> \"佑淑\"\n #=> \"燕谦\"\n #=> \"重生\"\n
\n\nFaker::NameCN.last_name #=> \"释\"\n #=> \"巩\"\n #=> \"麻\"\n
\n\nFaker::NameDE.name #=> \"Noelle Schuster\"\n #=> \"Bendix Schmid\"\n #=> \"Azra Neumann\"\n
\n\nFaker::NameDE.first_name #=> \"Victoria\"\n #=> \"Lotta\"\n #=> \"Mads\"\n
\n\nFaker::NameDE.last_name #=> \"Martin\"\n #=> \"Klein\"\n #=> \"Walter\"\n
\n\nFaker::NameDE.prefix #=> \"Frau\"\n #=> \"Prof.\"\n #=> \"Prof.\"\n
\n\nFaker::NameJA.name #=> \"飛鳥田部\"\n #=> \"未杉浦\"\n #=> \"功本間\"\n
\n\nFaker::NameJA.last_first #=> \"青木杏子\"\n #=> \"棚原大貴\"\n #=> \"知名翔\"\n
\n\nFaker::NameJA.first_name #=> \"巴\"\n #=> \"浩子\"\n #=> \"沙耶\"\n
\n\nFaker::NameJA.last_name #=> \"小栗\"\n #=> \"高江洲\"\n #=> \"友寄\"\n
\n\nFaker::NameRU.name #=> \"Стелла Карнилина\"\n #=> \"Евгения Мазовская\"\n #=> \"Кузьма Ваиренко\"\n
\n\nFaker::NameRU.last_name #=> \"Манишева\"\n #=> \"Тюлева\"\n #=> \"Понченко\"\n
\n\nFaker::NameRU.first_name #=> \"Артур\"\n #=> \"Руслана\"\n #=> \"Зинаида\"\n
\n\nFaker::NameRU.patronymic #=> \"Мечеславович\"\n #=> \"Ионович\"\n #=> \"Исаевич\"\n
\n\nFaker::NameRU.name(:male) #=> \"Слежиков Роман Всеволодович\"\n #=> \"Осип Мугрузин\"\n #=> \"Джиджаев Гавриил Леванович\"\n
\n\nFaker::NameRU.name(:female) #=> \"Зиядтдинова Полина Людвиговна\"\n #=> \"Андреева Тереза Арсеновна\"\n #=> \"Дарина Минхазова\"\n
\n\nFaker::NameSN.name_sn #=> \"mame Djaly Mbodj\"\n #=> \"Hatab Samy\"\n #=> \"Niouma Dramé\"\n
\n\nFaker::NameSN.name_male #=> \"serigne Yakou Diagne\"\n #=> \"serigne Sécouba Diagne\"\n #=> \"Sihalébé Badji\"\n
\n\nFaker::NameSN.name_female #=> \"Thiomba Niang\"\n #=> \"adjaratou Kiné Panduppy\"\n #=> \"Nini Gakou\"\n
\n\nFaker::NameSN.first_name_male #=> \"Khoudia\"\n #=> \"Sanokho\"\n #=> \"Diomaye\"\n
\n\nFaker::NameSN.first_name_female #=> \"Assa\"\n #=> \"Sahaba\"\n #=> \"Manthita\"\n
\n\nFaker::NameSN.prefix_male #=> \"eladji\"\n #=> \"eladji\"\n #=> \"serigne\"\n
\n\nFaker::NameSN.prefix_female #=> \"adjaratou\"\n #=> \"adja\"\n #=> \"adja\"\n
\n\nFaker::PhoneNumberAU.phone_number #=> \"0495 539 191\"\n #=> \"(05) 6838 2406\"\n #=> \"0496 013 652\"\n
\n\nFaker::PhoneNumberSN.phone_number #=> \"77-356-93-09\"\n #=> \"33-891-67-75\"\n #=> \"33-886-02-02\"\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2017-09-12"
},{
"id": "ffmpeg",
"title": "ffmpeg",
"url": "/ffmpeg",
"category": "CLI",
"keywords": null,
"content_html": "-codecs # list codecs\n-c:v # video codec (-vcodec) - 'copy' to copy stream\n-c:a # audio codec (-acodec)\n
\n\n-fs SIZE # limit file size (bytes)\n
\n\n-b:v 1M # video bitrate (1M = 1Mbit/s)\n-b:a 1M # audio bitrate\n
\n\n-aspect RATIO # aspect ratio (4:3, 16:9, or 1.25)\n-r RATE # frame rate per sec\n-s WIDTHxHEIGHT # frame size\n-vn # no video\n
\n\n-aq QUALITY # audio quality (codec-specific)\n-ar 44100 # audio sample rate (hz)\n-ac 1 # audio channels (1=mono, 2=stereo)\n-an # no audio\n-vol N # volume (256=normal)\n
\n\nffmpeg -i foo.mp3 -ac 1 -ab 128000 -f mp4 -acodec libfaac -y target.m4r\n
\n\n# no audio\nffmpeg -i input.mov -vcodec h264 -an -strict -2 output.mp4\nffmpeg -i input.mov -vcodec libvpx -an output.webm\n
\n\nffmpeg -i input.mov -vcodec h264 -acodec aac -strict -2 output.mp4\nffmpeg -i input.mov -vcodec libvpx -acodec libvorbis output.webm\n
\n\n<video width=\"320\" height=\"240\" controls>\n <source src=\"movie.mp4\" type='video/mp4'></source>\n <source src=\"movie.webm\" type='video/ogg'></source>\n</video>\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "figlet",
"title": "Figlet",
"url": "/figlet",
"category": "Others",
"keywords": null,
"content_html": "echo \"Hamburger\" | figlet -f cybermedium\n
\n\n_ _ ____ _ _ ___ _ _ ____ ____ ____ ____ \n|__| |__| |\\/| |__] | | |__/ | __ |___ |__/ \n| | | | | | |__] |__| | \\ |__] |___ | \\ \n
\n\nRun figlet
with -f <font>
to use a font.
echo \"Hello\" | \\\n figlet -f smmono12 -d /usr/local/share/figlet\n
\n\nFiglet comes with support for Toilet fonts, which are in {share}/figlet
. This is not the default font dir, so you’ll have to use -d <path>
to access it.
Hamburger\n
\n\n,-_/,. . \n' |_|/ ,-. ,-,-. |-. . . ,-. ,-. ,-. ,-. \n /| | ,-| | | | | | | | | | | |-' | \n `' `' `-^ ' ' ' ^-' `-^ ' `-| `-' ' \n ,| \n `' \n
\n\n_ _ ____ _ _ ___ _ _ ____ ____ ____ ____ \n|__| |__| |\\/| |__] | | |__/ | __ |___ |__/ \n| | | | | | |__] |__| | \\ |__] |___ | \\ \n
\n\n _ _ _______ _______ ______ _ _ ______ ______ _______ ______\n |_____| |_____| | | | |_____] | | |_____/ | ____ |______ |_____/\n | | | | | | | |_____] |_____| | \\_ |_____| |______ | \\_\n
\n\n| | | \n|---|,---.,-.-.|---.. .,---.,---.,---.,---.\n| |,---|| | || || || | ||---'| \n` '`---^` ' '`---'`---'` `---|`---'` \n `---' \n
\n\n ⣇⣸ ⢀⣀ ⣀⣀ ⣇⡀ ⡀⢀ ⡀⣀ ⢀⡀ ⢀⡀ ⡀⣀\n ⠇⠸ ⠣⠼ ⠇⠇⠇ ⠧⠜ ⠣⠼ ⠏ ⣑⡺ ⠣⠭ ⠏ \n
\n\n _____ _ \n| | |___ _____| |_ _ _ ___ ___ ___ ___ \n| | .'| | . | | | _| . | -_| _|\n|__|__|__,|_|_|_|___|___|_| |_ |___|_| \n |___| \n
\n\n __ __ _ \n | | ___ , _ , _ \\ ___ , . .___ ___. ___ .___ \n |___| / ` |' `|' `. |/ \\ | | / \\ .' ` .' ` / \\\n | | | | | | | | ` | | | ' | | |----' | '\n / / `.__/| / ' / `___,' `._/| / `---| `.___, / \n \\___/ \n
\n\n ** ** ** \n/** /** /** ***** \n/** /** ****** ********** /** ** ** ****** **///** ***** ******\n/********** //////** //**//**//**/****** /** /**//**//*/** /** **///**//**//*\n/**//////** ******* /** /** /**/**///**/** /** /** / //******/******* /** / \n/** /** **////** /** /** /**/** /**/** /** /** /////**/**//// /** \n/** /**//******** *** /** /**/****** //******/*** ***** //******/*** \n// // //////// /// // // ///// ////// /// ///// ////// /// \n
\n\n# # # \n# # ## ### ### # # ### ### ### ### \n### # # ### # # # # # # # ## # \n# # ### # # ### ### # ## ### # \n# # ### \n
\n\n // / / \n //___ / / ___ _ __ / __ __ ___ ___ __ \n / ___ / // ) ) // ) ) ) ) // ) ) // / / // ) ) // ) ) //___) ) // ) ) \n // / / // / / // / / / / // / / // / / // ((___/ / // // \n// / / ((___( ( // / / / / ((___/ / ((___( ( // //__ ((____ // \n
\n\n o o o \n <|> <|> <|> \n < > < > / > \n | | o__ __o/ \\o__ __o__ __o \\o__ __o o o \\o__ __o o__ __o/ o__ __o \\o__ __o \n o__/_ _\\__o /v | | | |> | v\\ <|> <|> | |> /v | /v |> | |> \n | | /> / \\ / \\ / \\ / \\ / \\ <\\ < > < > / \\ < > /> / \\ /> // / \\ < > \n <o> <o> \\ \\o/ \\o/ \\o/ \\o/ \\o/ / | | \\o/ \\ \\o/ \\o o/ \\o/ \n | | o | | | | | o o o | o | v\\ /v __o | \n / \\ / \\ <\\__ / \\ / \\ / \\ / \\ / \\ __/> <\\__ __/> / \\ <\\__ < > <\\/> __/> / \\ \n | \n o__ o \n <\\__ __/> \n
\n\n ::: ::: ::: ::: ::: ::::::::: ::: :::::::::::: :::::::: ::::::::::::::::::: \n :+: :+: :+: :+: :+:+: :+:+: :+: :+::+: :+::+: :+::+: :+::+: :+: :+: \n +:+ +:+ +:+ +:+ +:+ +:+:+ +:++:+ +:++:+ +:++:+ +:++:+ +:+ +:+ +:+ \n +#++:++#+++#++:++#++:+#+ +:+ +#++#++:++#+ +#+ +:++#++:++#: :#: +#++:++# +#++:++#: \n +#+ +#++#+ +#++#+ +#++#+ +#++#+ +#++#+ +#++#+ +#+#+#+ +#+ +#+ \n #+# #+##+# #+##+# #+##+# #+##+# #+##+# #+##+# #+##+# #+# #+# \n### ###### ###### ############ ######## ### ### ######## ############# ### \n
\n\n::: ::: ::: :::: :::: ::::::::: ::: :::::::::::: :::::::: ::::::::::::::::::: \n:+: :+: :+: :+: +:+:+: :+:+:+:+: :+::+: :+::+: :+::+: :+::+: :+: :+: \n+:+ +:+ +:+ +:+ +:+ +:+:+ +:++:+ +:++:+ +:++:+ +:++:+ +:+ +:+ +:+ \n+#++:++#+++#++:++#++:+#+ +:+ +#++#++:++#+ +#+ +:++#++:++#: :#: +#++:++# +#++:++#: \n+#+ +#++#+ +#++#+ +#++#+ +#++#+ +#++#+ +#++#+ +#+#+#+ +#+ +#+ \n#+# #+##+# #+##+# #+##+# #+##+# #+##+# #+##+# #+##+# #+# #+# \n### ###### ###### ############ ######## ### ### ######## ############# ### \n
\n\nH H b \nH H b \nHHHH aa mmmm bbb u u rrr ggg eee rrr \nH H a a m m m b b u u r g g e e r \nH H aaa m m m bbb uuu r ggg ee r \n g \n ggg \n
\n\n _ ____ _ ____ _ ____ _____ _____ ____ \n/ \\ /|/ _ \\/ \\__/|/ _ \\/ \\ /\\/ __\\/ __// __// __\\\n| |_||| / \\|| |\\/||| | //| | ||| \\/|| | _| \\ | \\/|\n| | ||| |-||| | ||| |_\\\\| \\_/|| /| |_//| /_ | /\n\\_/ \\|\\_/ \\|\\_/ \\|\\____/\\____/\\_/\\_\\\\____\\\\____\\\\_/\\_\\\n
\n\n# # \n# # ## # # ##### # # ##### #### ###### ##### \n# # # # ## ## # # # # # # # # # # # \n####### # # # ## # ##### # # # # # ##### # # \n# # ###### # # # # # # ##### # ### # ##### \n# # # # # # # # # # # # # # # # # \n# # # # # # ##### #### # # #### ###### # # \n
\n\n'##::::'##::::'###::::'##::::'##:'########::'##::::'##:'########:::'######:::'########:'########::\n ##:::: ##:::'## ##::: ###::'###: ##.... ##: ##:::: ##: ##.... ##:'##... ##:: ##.....:: ##.... ##:\n ##:::: ##::'##:. ##:: ####'####: ##:::: ##: ##:::: ##: ##:::: ##: ##:::..::: ##::::::: ##:::: ##:\n #########:'##:::. ##: ## ### ##: ########:: ##:::: ##: ########:: ##::'####: ######::: ########::\n ##.... ##: #########: ##. #: ##: ##.... ##: ##:::: ##: ##.. ##::: ##::: ##:: ##...:::: ##.. ##:::\n ##:::: ##: ##.... ##: ##:.:: ##: ##:::: ##: ##:::: ##: ##::. ##:: ##::: ##:: ##::::::: ##::. ##::\n ##:::: ##: ##:::: ##: ##:::: ##: ########::. #######:: ##:::. ##:. ######::: ########: ##:::. ##:\n..:::::..::..:::::..::..:::::..::........::::.......:::..:::::..:::......::::........::..:::::..::\n
\n\n## ## ### ## ## ######## ## ## ######## ###### ######## ######## \n## ## ## ## ### ### ## ## ## ## ## ## ## ## ## ## ## \n## ## ## ## #### #### ## ## ## ## ## ## ## ## ## ## \n######### ## ## ## ### ## ######## ## ## ######## ## #### ###### ######## \n## ## ######### ## ## ## ## ## ## ## ## ## ## ## ## ## \n## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n## ## ## ## ## ## ######## ####### ## ## ###### ######## ## ## \n
\n\n.##.....##....###....##.....##.########..##.....##.########...######...########.########.\n.##.....##...##.##...###...###.##.....##.##.....##.##.....##.##....##..##.......##.....##\n.##.....##..##...##..####.####.##.....##.##.....##.##.....##.##........##.......##.....##\n.#########.##.....##.##.###.##.########..##.....##.########..##...####.######...########.\n.##.....##.#########.##.....##.##.....##.##.....##.##...##...##....##..##.......##...##..\n.##.....##.##.....##.##.....##.##.....##.##.....##.##....##..##....##..##.......##....##.\n.##.....##.##.....##.##.....##.########...#######..##.....##..######...########.##.....##\n
\n\n><< ><< ><< \n><< ><< ><< \n><< ><< ><< ><<< ><< ><< ><< ><< ><<>< ><<< ><< ><< >< ><<<\n><<<<<< ><< ><< ><< ><< >< ><<><< ><< ><< ><< ><< ><< ><< >< ><< ><< \n><< ><<><< ><< ><< >< ><<><< ><<><< ><< ><< ><< ><<><<<<< ><< ><< \n><< ><<><< ><< ><< >< ><<><< ><<><< ><< ><< ><< ><<>< ><< \n><< ><< ><< ><<<><<< >< ><<><< ><< ><<><<><<< ><< ><<<< ><<< \n ><< \n
\n\ndb db .d8b. .88b d88. d8888b. db db d8888b. d888b d88888b d8888b. \n88 88 d8' `8b 88'YbdP`88 88 `8D 88 88 88 `8D 88' Y8b 88' 88 `8D \n88ooo88 88ooo88 88 88 88 88oooY' 88 88 88oobY' 88 88ooooo 88oobY' \n88~~~88 88~~~88 88 88 88 88~~~b. 88 88 88`8b 88 ooo 88~~~~~ 88`8b \n88 88 88 88 88 88 88 88 8D 88b d88 88 `88. 88. ~8~ 88. 88 `88. \nYP YP YP YP YP YP YP Y8888P' ~Y8888P' 88 YD Y888P Y88888P 88 YD \n
\n\n __ __ _ \n | | ___ , _ , _ \\ ___ , . .___ ___. ___ .___ \n |___| / ` |' `|' `. |/ \\ | | / \\ .' ` .' ` / \\\n | | | | | | | | ` | | | ' | | |----' | '\n / / `.__/| / ' / `___,' `._/| / `---| `.___, / \n \\___/ \n
\n\n _ _ _ \n| | | | | | \n| |__| | __ _ _ __ ___ | |__ _ _ _ __ __ _ ___ _ __ \n| __ |/ _` | '_ ` _ \\| '_ \\| | | | '__/ _` |/ _ \\ '__|\n| | | | (_| | | | | | | |_) | |_| | | | (_| | __/ | \n|_| |_|\\__,_|_| |_| |_|_.__/ \\__,_|_| \\__, |\\___|_| \n __/ | \n |___/ \n
\n\n_____________________________________________________________\n _ _ \n / / / \n---/___ /-----__---_--_---/__----------)__----__----__---)__-\n / / / ) / / ) / ) / / / ) / ) /___) / )\n_/____/____(___(_/_/__/_(___/_(___(__/_____(___/_(___ _/_____\n / \n (_ / \n
\n\n01001000 01100001 01101101 01100010 01110101 01110010 01100111 01100101 01110010 \n
\n\n_| _| _| \n_| _| _|_|_| _|_|_| _|_| _|_|_| _| _| _| _|_| _|_|_| _|_| _| _|_| \n_|_|_|_| _| _| _| _| _| _| _| _| _| _|_| _| _| _|_|_|_| _|_| \n_| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| \n_| _| _|_|_| _| _| _| _|_|_| _|_|_| _| _|_|_| _|_|_| _| \n _| \n _|_| \n
\n\n . . \n8 8888 8 .8. ,8. ,8. 8 888888888o 8 8888 88 8 888888888o. ,o888888o. 8 8888888888 8 888888888o. \n8 8888 8 .888. ,888. ,888. 8 8888 `88. 8 8888 88 8 8888 `88. 8888 `88. 8 8888 8 8888 `88. \n8 8888 8 :88888. .`8888. .`8888. 8 8888 `88 8 8888 88 8 8888 `88 ,8 8888 `8. 8 8888 8 8888 `88 \n8 8888 8 . `88888. ,8.`8888. ,8.`8888. 8 8888 ,88 8 8888 88 8 8888 ,88 88 8888 8 8888 8 8888 ,88 \n8 8888 8 .8. `88888. ,8'8.`8888,8^8.`8888. 8 8888. ,88' 8 8888 88 8 8888. ,88' 88 8888 8 888888888888 8 8888. ,88' \n8 8888 8 .8`8. `88888. ,8' `8.`8888' `8.`8888. 8 8888888888 8 8888 88 8 888888888P' 88 8888 8 8888 8 888888888P' \n8 8888888888888 .8' `8. `88888. ,8' `8.`88' `8.`8888. 8 8888 `88. 8 8888 88 8 8888`8b 88 8888 8888888 8 8888 8 8888`8b \n8 8888 8 .8' `8. `88888. ,8' `8.`' `8.`8888. 8 8888 88 ` 8888 ,8P 8 8888 `8b. `8 8888 .8' 8 8888 8 8888 `8b. \n8 8888 8 .888888888. `88888. ,8' `8 `8.`8888. 8 8888 ,88' 8888 ,d8P 8 8888 `8b. 8888 ,88' 8 8888 8 8888 `8b. \n8 8888 8 .8' `8. `88888. ,8' ` `8.`8888. 8 888888888P `Y88888P' 8 8888 `88. `8888888P' 8 888888888888 8 8888 `88. \n
\n\n _ _ _ _ _ _ _ _ _ \n / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ \n( H | a | m | b | u | r | g | e | r )\n \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \n
\n\n _ _ __ __ __ ____ __ __ ____ ___ ____ ____ \n( )_( ) /__\\ ( \\/ )( _ \\( )( )( _ \\ / __)( ___)( _ \\\n ) _ ( /(__)\\ ) ( ) _ < )(__)( ) /( (_-. )__) ) /\n(_) (_)(__)(__)(_/\\/\\_)(____/(______)(_)\\_) \\___/(____)(_)\\_)\n
\n\n ##### ## / \n ###### / #### / #/ \n /# / / ####/ ## \n/ / / # # ## \n / / # ## \n ## ## # /### ### /### /### ## /### ## #### ### /### /### /## ### /### \n ## ## # / ### / ##/ ###/ /## / ##/ ### / ## ### / ###/ #### / / ### / / ### ###/ #### / \n ## ######## / ###/ ## ###/ ###/ ## ###/ ## ###/ ## ###/ / ###/ / ### ## ###/ \n ## ## # ## ## ## ## ## ## ## ## ## ## ## ## ## ### ## \n ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ######## ## \n # ## ## ## ## ## ## ## ## ## ## ## ## ## ## ####### ## \n / ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n /##/ ## ## /# ## ## ## ## /# ## /# ## ## ## #### / ## \n / ##### ## ####/ ## ### ### ### ####/ ######/ ## ### ######## ######/ ### \n/ ## ### ## ### ### ### ### ##### ## ### ### ### ##### ### \n# ### \n ## #### ### \n /###### /# \n / ###/ \n
\n\n ***** ** * \n ****** * **** * ** \n ** * * ***** ** \n* * * * * ** \n * * * ** ** **** *** **** *** **** \n ** ** * **** *** **** **** ** **** ** *** * **** **** * **** *** **** **** * \n ** ** * * *** * *** **** *** * *** *** * ** **** ** **** * *** * * *** ** **** \n ** ******** * **** ** **** **** ** **** ** ** ** * **** * *** ** \n ** ** * ** ** ** ** ** ** ** ** ** ** ** ** ** *** ** \n ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ******** ** \n * ** ** ** ** ** ** ** ** ** ** ** ** ** ** ******* ** \n * ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** \n **** ** ** ** ** ** ** ** ** ******* ** *** ** ** **** * *** \n * ***** ** ***** ** *** *** *** ***** ***** ** *** ******** ******* *** \n* ** *** ** *** *** *** *** *** *** ***** \n* *** \n ** **** *** \n ******* ** \n * **** \n
\n\n_// _// _// \n_// _// _// \n_// _// _// _/// _// _// _// _// _//_/ _/// _// _// _/ _///\n_////// _// _// _// _// _/ _//_// _// _// _// _// _// _// _/ _// _// \n_// _//_// _// _// _/ _//_// _//_// _// _// _// _//_///// _// _// \n_// _//_// _// _// _/ _//_// _//_// _// _// _// _//_/ _// \n_// _// _// _///_/// _/ _//_// _// _//_//_/// _// _//// _/// \n _// \n
\n\n _______ __ \n| | |.---.-.--------.| |--.--.--.----.-----.-----.----.\n| || _ | || _ | | | _| _ | -__| _|\n|___|___||___._|__|__|__||_____|_____|__| |___ |_____|__| \n |_____| \n
\n\nO)) O)) O)) \nO)) O)) O)) \nO)) O)) O)) O))) O)) O)) O)) O)) O))O) O))) O)) O)) O) O)))\nO)))))) O)) O)) O)) O)) O) O))O)) O)) O)) O)) O)) O)) O)) O) O)) O)) \nO)) O))O)) O)) O)) O) O))O)) O))O)) O)) O)) O)) O))O))))) O)) O)) \nO)) O))O)) O)) O)) O) O))O)) O))O)) O)) O)) O)) O))O) O)) \nO)) O)) O)) O)))O))) O) O))O)) O)) O))O))O))) O)) O)))) O))) \n O)) \n
\n\n888 888 888 \n888 888 888 \n888 888 888 \n8888888888 8888b. 88888b.d88b. 88888b. 888 888888d888 .d88b. .d88b. 888d888 \n888 888 \"88b888 \"888 \"88b888 \"88b888 888888P\" d88P\"88bd8P Y8b888P\" \n888 888.d888888888 888 888888 888888 888888 888 88888888888888 \n888 888888 888888 888 888888 d88PY88b 888888 Y88b 888Y8b. 888 \n888 888\"Y888888888 888 88888888P\" \"Y88888888 \"Y88888 \"Y8888 888 \n 888 \n Y8b d88P \n \"Y88P\" \n
\n\n8 8 \n8 8 eeeee eeeeeee eeeee e e eeeee eeeee eeee eeeee \n8eee8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 \n88 8 8eee8 8e 8 8 8eee8e 8e 8 8eee8e 8e 8eee 8eee8e \n88 8 88 8 88 8 8 88 8 88 8 88 8 88 \"8 88 88 8 \n88 8 88 8 88 8 8 88eee8 88ee8 88 8 88ee8 88ee 88 8 \n
\n\n. . . \n|__| _.._ _ |_ . .._. _ _ ._.\n| |(_][ | )[_)(_|[ (_](/,[ \n ._| \n
\n\n.%%..%%...%%%%...%%...%%..%%%%%...%%..%%..%%%%%....%%%%...%%%%%%..%%%%%..\n.%%..%%..%%..%%..%%%.%%%..%%..%%..%%..%%..%%..%%..%%......%%......%%..%%.\n.%%%%%%..%%%%%%..%%.%.%%..%%%%%...%%..%%..%%%%%...%%.%%%..%%%%....%%%%%..\n.%%..%%..%%..%%..%%...%%..%%..%%..%%..%%..%%..%%..%%..%%..%%......%%..%%.\n.%%..%%..%%..%%..%%...%%..%%%%%....%%%%...%%..%%...%%%%...%%%%%%..%%..%%.\n.........................................................................\n
\n\n :: .: :::. . : :::::::. ... ::::::::::.. .,-:::::/ .,:::::: :::::::.. \n ,;; ;;, ;;`;; ;;,. ;;; ;;;'';;' ;; ;;;;;;;``;;;; ,;;-'````' ;;;;'''' ;;;;``;;;; \n,[[[,,,[[[ ,[[ '[[, [[[[, ,[[[[, [[[__[[\\.[[' [[[ [[[,/[[[' [[[ [[[[[[/[[cccc [[[,/[[[' \n\"$$$\"\"\"$$$c$$$cc$$$c $$$$$$$$\"$$$ $$\"\"\"\"Y$$$$ $$$ $$$$$$c \"$$c. \"$$ $$\"\"\"\" $$$$$$c \n 888 \"88o888 888,888 Y88\" 888o_88o,,od8P88 .d888 888b \"88bo,`Y8bo,,,o88o888oo,__ 888b \"88bo,\n MMM YMMYMM \"\"` MMM M' \"MMM\"\"YUMMMP\" \"YmmMMMM\"\" MMMM \"W\" `'YMUP\"YMM\"\"\"\"YUMMMMMMM \"W\" \n
\n\n :: .: :::. . : :::::::. ... ::::::::::.. .,-:::::/ .,:::::: :::::::.. \n ,;; ;;, ;;`;; ;;,. ;;; ;;;'';;' ;; ;;;;;;;``;;;; ,;;-'````' ;;;;'''' ;;;;``;;;; \n,[[[,,,[[[ ,[[ '[[, [[[[, ,[[[[, [[[__[[\\.[[' [[[ [[[,/[[[' [[[ [[[[[[/[[cccc [[[,/[[[' \n\"$$$\"\"\"$$$c$$$cc$$$c $$$$$$$$\"$$$ $$\"\"\"\"Y$$$$ $$$ $$$$$$c \"$$c. \"$$ $$\"\"\"\" $$$$$$c \n 888 \"88o888 888,888 Y88\" 888o_88o,,od8P88 .d888 888b \"88bo,`Y8bo,,,o88o888oo,__ 888b \"88bo,\n MMM YMMYMM \"\"` MMM M' \"MMM\"\"YUMMMP\" \"YmmMMMM\"\" MMMM \"W\" `'YMUP\"YMM\"\"\"\"YUMMMMMMM \"W\" \n
\n\n __ __ ____ ___ ___ ____ __ __ ____ ____ ___ ____ \n| T T / T| T T| \\ | T T| \\ / T / _]| \\ \n| l |Y o || _ _ || o )| | || D )Y __j / [_ | D )\n| _ || || \\_/ || T| | || / | T |Y _]| / \n| | || _ || | || O || : || \\ | l_ || [_ | \\ \n| | || | || | || |l || . Y| || T| . Y\nl__j__jl__j__jl___j___jl_____j \\__,_jl__j\\_jl___,_jl_____jl__j\\_j\n
\n\n ___ ___ __ \n| Y .---.-.--------| |--.--.--.----.-----.-----.----.\n|. 1 | _ | | _ | | | _| _ | -__| _|\n|. _ |___._|__|__|__|_____|_____|__| |___ |_____|__| \n|: | | |_____| \n|::.|:. | \n`--- ---' \n
\n\n _ , \n' ) / / \n /--/ __. ______ /__. . __ _, _ __ \n/ (_(_/|_/ / / <_/_)(_/_/ (_(_)_</_/ (_\n /| \n |/ \n
\n\n _ _ _______ _______ ______ _ _ ______ ______ _______ ______\n |_____| |_____| | | | |_____] | | |_____/ | ____ |______ |_____/\n | | | | | | | |_____] |_____| | \\_ |_____| |______ | \\_\n
\n\n_ _ ____ _ _ ___ _ _ ____ ____ ____ ____ \n|__| |__| |\\/| |__] | | |__/ | __ |___ |__/ \n| | | | | | |__] |__| | \\ |__] |___ | \\ \n
\n\n _ _ ____ _ _ ___ _ _ ____ ____ ____ ____\n |--| |--| |\\/| |==] |__| |--< |__, |=== |--<\n
\n\n72 97 109 98 117 114 103 101 114 \n
\n\n/\\\\ /\\\\ /\\\\ \n/\\\\ /\\\\ /\\\\ \n/\\\\ /\\\\ /\\\\ /\\\\\\ /\\\\ /\\\\ /\\\\ /\\\\ /\\\\/\\ /\\\\\\ /\\\\ /\\\\ /\\ /\\\\\\\n/\\\\\\\\\\\\ /\\\\ /\\\\ /\\\\ /\\\\ /\\ /\\\\/\\\\ /\\\\ /\\\\ /\\\\ /\\\\ /\\\\ /\\\\ /\\ /\\\\ /\\\\ \n/\\\\ /\\\\/\\\\ /\\\\ /\\\\ /\\ /\\\\/\\\\ /\\\\/\\\\ /\\\\ /\\\\ /\\\\ /\\\\/\\\\\\\\\\ /\\\\ /\\\\ \n/\\\\ /\\\\/\\\\ /\\\\ /\\\\ /\\ /\\\\/\\\\ /\\\\/\\\\ /\\\\ /\\\\ /\\\\ /\\\\/\\ /\\\\ \n/\\\\ /\\\\ /\\\\ /\\\\\\/\\\\\\ /\\ /\\\\/\\\\ /\\\\ /\\\\/\\\\/\\\\\\ /\\\\ /\\\\\\\\ /\\\\\\ \n /\\\\ \n
\n\n+-+-+-+-+-+-+-+-+-+\n|H|a|m|b|u|r|g|e|r|\n+-+-+-+-+-+-+-+-+-+\n
\n\n bbbbbbbb \nHHHHHHHHH HHHHHHHHH b::::::b \nH:::::::H H:::::::H b::::::b \nH:::::::H H:::::::H b::::::b \nHH::::::H H::::::HH b:::::b \n H:::::H H:::::H aaaaaaaaaaaaa mmmmmmm mmmmmmm b:::::bbbbbbbbb uuuuuu uuuuuu rrrrr rrrrrrrrr ggggggggg ggggg eeeeeeeeeeee rrrrr rrrrrrrrr \n H:::::H H:::::H a::::::::::::a mm:::::::m m:::::::mm b::::::::::::::bb u::::u u::::u r::::rrr:::::::::r g:::::::::ggg::::g ee::::::::::::ee r::::rrr:::::::::r \n H::::::HHHHH::::::H aaaaaaaaa:::::a m::::::::::mm::::::::::mb::::::::::::::::b u::::u u::::u r:::::::::::::::::r g:::::::::::::::::g e::::::eeeee:::::eer:::::::::::::::::r \n H:::::::::::::::::H a::::a m::::::::::::::::::::::mb:::::bbbbb:::::::bu::::u u::::u rr::::::rrrrr::::::rg::::::ggggg::::::gge::::::e e:::::err::::::rrrrr::::::r\n H:::::::::::::::::H aaaaaaa:::::a m:::::mmm::::::mmm:::::mb:::::b b::::::bu::::u u::::u r:::::r r:::::rg:::::g g:::::g e:::::::eeeee::::::e r:::::r r:::::r\n H::::::HHHHH::::::H aa::::::::::::a m::::m m::::m m::::mb:::::b b:::::bu::::u u::::u r:::::r rrrrrrrg:::::g g:::::g e:::::::::::::::::e r:::::r rrrrrrr\n H:::::H H:::::H a::::aaaa::::::a m::::m m::::m m::::mb:::::b b:::::bu::::u u::::u r:::::r g:::::g g:::::g e::::::eeeeeeeeeee r:::::r \n H:::::H H:::::H a::::a a:::::a m::::m m::::m m::::mb:::::b b:::::bu:::::uuuu:::::u r:::::r g::::::g g:::::g e:::::::e r:::::r \nHH::::::H H::::::HHa::::a a:::::a m::::m m::::m m::::mb:::::bbbbbb::::::bu:::::::::::::::uur:::::r g:::::::ggggg:::::g e::::::::e r:::::r \nH:::::::H H:::::::Ha:::::aaaa::::::a m::::m m::::m m::::mb::::::::::::::::b u:::::::::::::::ur:::::r g::::::::::::::::g e::::::::eeeeeeee r:::::r \nH:::::::H H:::::::H a::::::::::aa:::am::::m m::::m m::::mb:::::::::::::::b uu::::::::uu:::ur:::::r gg::::::::::::::g ee:::::::::::::e r:::::r \nHHHHHHHHH HHHHHHHHH aaaaaaaaaa aaaammmmmm mmmmmm mmmmmmbbbbbbbbbbbbbbbb uuuuuuuu uuuurrrrrrr gggggggg::::::g eeeeeeeeeeeeee rrrrrrr \n g:::::g \n gggggg g:::::g \n g:::::gg gg:::::g \n g::::::ggg:::::::g \n gg:::::::::::::g \n ggg::::::ggg \n gggggg \n
\n\n _ _ _ \n| | | | | | \n| |_| | __ _ _ __ ___ | |__ _ _ _ __ __ _ ___ _ __ \n| _ |/ _` | '_ ` _ \\| '_ \\| | | | '__/ _` |/ _ \\ '__|\n| | | | (_| | | | | | | |_) | |_| | | | (_| | __/ | \n\\_| |_/\\__,_|_| |_| |_|_.__/ \\__,_|_| \\__, |\\___|_| \n __/ | \n |___/ \n
\n\n _ _ _ \n(_) (_) (_) \n(_) (_) _ _ _ _ _ _ _ (_) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n(_) _ _ _ (_) (_)(_)(_) _ (_)(_)_(_)(_) (_)(_)(_)(_)_ (_) (_)(_)_ _ (_)(_)_(_)(_)(_)(_) (_)(_)(_)(_)_(_)_ _ (_)(_) \n(_)(_)(_)(_)(_) _ _ _ (_) (_) (_) (_)(_) (_)(_) (_) (_)(_) (_) (_)(_) _ _ _ (_) (_)(_) \n(_) (_) _(_)(_)(_)(_) (_) (_) (_)(_) (_)(_) (_) (_) (_) (_)(_)(_)(_)(_)(_) (_) \n(_) (_)(_)_ _ _ (_)_ (_) (_) (_)(_) _ _ _(_)(_)_ _ _(_)_ (_) (_)_ _ _ (_)(_)_ _ _ _ (_) \n(_) (_) (_)(_)(_) (_)(_) (_) (_)(_)(_)(_)(_) (_)(_)(_) (_)(_) (_)(_)(_)(_) (_)(_)(_)(_) (_) \n _ _ _ (_) \n (_)(_)(_) \n
\n\n__ __ ___ ___ _______ __ ______ ___ ________ \n|| ||// \\\\||\\\\//|||| ))|| |||| \\\\ // \\\\|| || \\\\\n||==||||=|||| \\/ ||||=) || ||||_//(( ___||== ||_//\n|| |||| |||| ||||_))\\\\_//|| \\\\ \\\\_||||___|| \\\\\n
\n\n _ _ _ \n| | | ___ ._ _ _ | |_ _ _ _ _ ___ ___ _ _ \n| |<_> || ' ' || . \\| | || '_>/ . |/ ._>| '_>\n|_|_|<___||_|_|_||___/`___||_| \\_. |\\___.|_| \n <___' \n
\n\nH m ur r\n X X XX \n X . XX \n . . XX \n . . .X \n . . .X \n . . .. \nHamburger\n
\n\n ######### ######### ######### ####################################\n [`'`'] ##\\`.'/## ':v:` ##/\\:/\\## |:+:| ##':v:`## \\`.'/ ##[`'`']###'\\v/`####[`'`']###[`'`']#\n |::| ##(o:o)## (o:0) #/(o:o)\\# (o:o) ##(o:0)## (o:o) ###|::|####(o 0)#####| |#####| |##\n |::| ###\\:/:\\# (:) ###(:)### (:) ###(:)### \\:/:\\ ###|::|#####(_)######|__|#####|__|##\n ####\"#### ######### ######### \" ####################################\n
\n\n _ _ \n| U |_ _ _ || _ _ _ _ \n| /o\\ |/ \\ \\|o\\U|/_|/oYoY_|\n|_n_\\_,]L_n_n||_|_/L| \\_|(L| \n _) \n
\n\n[]-|amburger\n
\n\n _ _ _ \n( )( ) ( ) \n| L| | ___ __ __ | |_ _ _ __ __ ___ __ \n( __ )( o )( _`'_ )( o \\( U )( _)/o )( o_)( _)\n/_\\/_\\/_^_\\/_\\`'/_\\/___//___\\/_\\ \\__\\ \\( /_\\ \n _|/ \n
\n\n _ __ \n /// / _ _ /7 _ _ __ _ \n / ` /,'o| / \\'\\ /o\\ /7/7//7,'o|,'o///7\n/_n_/ |_,7/_nn_//_,'/__/// |_,'|_(// \n _// \n
\n\n | ___ ( ( ( o !!! |\"| !!! \n *** |.===. /_\\ `* '. ___ .' ` /_\\ ' ` _ _ ' __MMM__ _|_|_ ` _ _ ' \n (o o) {}o o{} (o o) ' (> <) ' - (o o) - - (OXO) - (o o) (o o) - (OXO) - \nooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-\n
\n\n _ _ _ \n )L`) ___ _ _ )) _ __ ___ __ __ \n(( ( ((_( ((`1( ((_)((_( (| ((_( (('(| \n _)) \n
\n\n _______ _______ ______ _______ _______ _______ _______ \n|\\ /|( ___ )( )( ___ \\ |\\ /|( ____ )( ____ \\( ____ \\( ____ )\n| ) ( || ( ) || () () || ( ) )| ) ( || ( )|| ( \\/| ( \\/| ( )|\n| (___) || (___) || || || || (__/ / | | | || (____)|| | | (__ | (____)|\n| ___ || ___ || |(_)| || __ ( | | | || __)| | ____ | __) | __)\n| ( ) || ( ) || | | || ( \\ \\ | | | || (\\ ( | | \\_ )| ( | (\\ ( \n| ) ( || ) ( || ) ( || )___) )| (___) || ) \\ \\__| (___) || (____/\\| ) \\ \\__\n|/ \\||/ \\||/ \\||/ \\___/ (_______)|/ \\__/(_______)(_______/|/ \\__/\n
\n\n'|| ||` '|| \n || || || \n ||''|| '''|. '||),,(|, ||''|, '|| ||` '||''| .|''|, .|''|, '||''| \n || || .|''|| || || || || || || || || || || ||..|| || \n.|| ||. `|..||. .|| ||. .||..|' `|..'|. .||. `|..|| `|... .||. \n || \n `..|' \n
\n\n| | | \n|--|/~~||/~\\ /~\\ |~~\\| ||/~\\/~~|/~/|/~\\\n| |\\__|| | ||__/ \\_/|| \\__|\\/_| \n \\__| \n
\n\n .. \n .xHL . uW8\" \n .-`8888hxxx~ .. . : `t888 x. . .u . .u . \n .H8X `%888*\" u .888: x888 x888. 8888 . .@88k z88u .d88B :@8c uL .u .d88B :@8c \n 888X ..x.. us888u. ~`8888~'888X`?888f` 9888.z88N ~\"8888 ^8888 =\"8888f8888r .ue888Nc.. ud8888. =\"8888f8888r \n '8888k .x8888888x .@88 \"8888\" X888 888X '888> 9888 888E 8888 888R 4888>'88\" d88E`\"888E` :888'8888. 4888>'88\" \n ?8888X \"88888X 9888 9888 X888 888X '888> 9888 888E 8888 888R 4888> ' 888E 888E d888 '88%\" 4888> ' \n ?8888X '88888> 9888 9888 X888 888X '888> 9888 888E 8888 888R 4888> 888E 888E 8888.+\" 4888> \n H8H %8888 `8888> 9888 9888 X888 888X '888> 9888 888E 8888 ,888B . .d888L .+ 888E 888E 8888L .d888L .+ \n'888> 888\" 8888 9888 9888 \"*88%\"\"*88\" '888!` .8888 888\" \"8888Y 8888\" ^\"8888*\" 888& .888E '8888c. .+ ^\"8888*\" \n \"8` .8\" .. 88* \"888*\"\"888\" `~ \" `\"` `%888*%\" `Y\" 'YP \"Y\" *888\" 888& \"88888% \"Y\" \n ` x8888h. d*\" ^Y\" ^Y' \"` `\" \"888E \"YP' \n !\"\"*888%~ .dWi `88E \n ! `\" . 4888~ J8% \n '-....:~ ^\"===*\"` \n
\n\n.-..-. .-. \n: :; : : : \n: : .--. ,-.,-.,-.: `-. .-..-..--. .--. .--. .--. \n: :: :' .; ; : ,. ,. :' .; :: :; :: ..'' .; :' '_.': ..'\n:_;:_;`.__,_;:_;:_;:_;`.__.'`.__.':_; `._. ;`.__.':_; \n .-. : \n `._.' \n
\n\n ___ _____ _____ _ ___ ___ _ _____ ___ __ ___\n\\ | | / / \\ | | \\ \\ | | | | | \\ ) ____) \\ ___) | \\ \n | \\_/ | / \\ | |\\/| | | ) | | | | | ) / / __ | (__ | ) \n | _ | / () \\ | | | | | < | | | | | / ( ( ( \\ | __) | / \n | / \\ | | __ | | | | | | ) | \\_/ | | |\\ \\ \\ \\__) ) | (___ | |\\ \\ \n/ |___| \\_| (__) |_| |__| |_/ /___\\ /__| |_\\ \\___) (__/ )_| |_\\ \\_\n
\n\n_-_- ,, \n /, _ || _ \n || __ < \\, \\\\/\\\\/\\\\ ||/|, \\\\ \\\\ ,._-_ / \\\\ _-_ ,._-_ \n ~||- - /-|| || || || || || || || || || || || \\\\ || \n ||===|| (( || || || || || |' || || || || || ||/ || \n ( \\_, | \\/\\\\ \\\\ \\\\ \\\\ \\\\/ \\\\/\\\\ \\\\, \\\\_-| \\\\,/ \\\\, \n ` / \\ \n '----` \n
\n\n _ _ __ _ _ ____ _ _ ____ ___ ____ ____ \n/ )( \\ / _\\ ( \\/ )( _ \\/ )( \\( _ \\ / __)( __)( _ \\\n) __ (/ \\/ \\/ \\ ) _ () \\/ ( ) /( (_ \\ ) _) ) /\n\\_)(_/\\_/\\_/\\_)(_/(____/\\____/(__\\_) \\___/(____)(__\\_)\n
\n\neee..eee..eeeeee..eee......eee.eeeeeee..eee..eee.eeeeeee...eeeeee..eeeeee.eeeeeee..\n@@@::@@@:@@@@@@@@:@@@@::::@@@@:@@@@@@@@:@@@::@@@:@@@@@@@@:@@@@@@@@:@@@@@@:@@@@@@@@:\n%%%--%%%-%%%--%%%-%%%%%--%%%%%-%%%--%%%-%%%--%%%-%%%--%%%-%%%------%%%----%%%--%%%-\n&&&&&&&&+&&&&&&&&+&&&&&&&&&&&&+&&&&&&&++&&&++&&&+&&&&&&&++&&&++++++&&&&&++&&&&&&&++\n||||||||*||||||||*|||*||||*|||*||||||||*|||**|||*||||||***|||*||||*|||||**||||||***\n!!!==!!!=!!!==!!!=!!!==!!==!!!=!!!==!!!=!!!==!!!=!!!=!!!==!!!==!!!=!!!====!!!=!!!==\n:::##:::#:::##:::#:::######:::#::::::::#::::::::#:::##:::#::::::::#::::::#:::##:::#\n...@@...@...@@...@...@@@@@@...@.......@@@......@@...@@...@@......@@......@...@@...@\n
\n\n ___ ___ ___. \n / | \\_____ _____\\_ |__ __ _________ ____ ___________ \n/ ~ \\__ \\ / \\| __ \\| | \\_ __ \\/ ___\\_/ __ \\_ __ \\\n\\ Y // __ \\| Y Y \\ \\_\\ \\ | /| | \\/ /_/ > ___/| | \\/\n \\___|_ /(____ /__|_| /___ /____/ |__| \\___ / \\___ >__| \n \\/ \\/ \\/ \\/ /_____/ \\/ \n
\n\n48 61 6D 62 75 72 67 65 72 \n
\n\n _ \n ' ) ) /' \n /' /' /' \n ,/' /' ____ ,__________ /'__ ____ ____ ____ ____ \n /`---,/' /' ) /' ) ) /' ) /' / )' )--/' ) /' ) )' )--\n /' /' /' /' /' /' /' /' /' /' /' /' /' /' /(___,/' /' \n(,/' (_,(___,/(__/' /' /(__(___,/(__(___,/(__/' (___,/(__(________/' \n /' \n / /' \n (___,/' \n
\n\n ____ ___) \n (, / / /) \n /---/ _ ___ (/_ __ _ _ __ \n ) / (__(_(_// (_/_) (_(_/ (_(_/__(/_/ (_\n(_/ .-/ \n (_/ \n
\n\n ___ ___ ___ ___ ___ ___ ___ ___ ___ \n /\\__\\ /\\ \\ /\\__\\ /\\ \\ /\\__\\ /\\ \\ /\\ \\ /\\ \\ /\\ \\ \n /:/ / /::\\ \\ /::| | /::\\ \\ /:/ / /::\\ \\ /::\\ \\ /::\\ \\ /::\\ \\ \n /:/__/ /:/\\:\\ \\ /:|:| | /:/\\:\\ \\ /:/ / /:/\\:\\ \\ /:/\\:\\ \\ /:/\\:\\ \\ /:/\\:\\ \\ \n /::\\ \\ ___ /::\\~\\:\\ \\ /:/|:|__|__ /::\\~\\:\\__\\ /:/ / ___ /::\\~\\:\\ \\ /:/ \\:\\ \\ /::\\~\\:\\ \\ /::\\~\\:\\ \\ \n /:/\\:\\ /\\__\\ /:/\\:\\ \\:\\__\\ /:/ |::::\\__\\ /:/\\:\\ \\:|__| /:/__/ /\\__\\ /:/\\:\\ \\:\\__\\ /:/__/_\\:\\__\\ /:/\\:\\ \\:\\__\\ /:/\\:\\ \\:\\__\\\n \\/__\\:\\/:/ / \\/__\\:\\/:/ / \\/__/~~/:/ / \\:\\~\\:\\/:/ / \\:\\ \\ /:/ / \\/_|::\\/:/ / \\:\\ /\\ \\/__/ \\:\\~\\:\\ \\/__/ \\/_|::\\/:/ /\n \\::/ / \\::/ / /:/ / \\:\\ \\::/ / \\:\\ /:/ / |:|::/ / \\:\\ \\:\\__\\ \\:\\ \\:\\__\\ |:|::/ / \n /:/ / /:/ / /:/ / \\:\\/:/ / \\:\\/:/ / |:|\\/__/ \\:\\/:/ / \\:\\ \\/__/ |:|\\/__/ \n /:/ / /:/ / /:/ / \\::/__/ \\::/ / |:| | \\::/ / \\:\\__\\ |:| | \n \\/__/ \\/__/ \\/__/ ~~ \\/__/ \\|__| \\/__/ \\/__/ \\|__| \n
\n\n ___ ___ ___ ___ ___ ___ ___ ___ \n /\\ \\ /\\ \\ /\\ \\ _____ /\\ \\ /\\ \\ /\\__\\ /\\__\\ /\\ \\ \n \\:\\ \\ /::\\ \\ |::\\ \\ /::\\ \\ \\:\\ \\ /::\\ \\ /:/ _/_ /:/ _/_ /::\\ \\ \n \\:\\ \\ /:/\\:\\ \\ |:|:\\ \\ /:/\\:\\ \\ \\:\\ \\ /:/\\:\\__\\ /:/ /\\ \\ /:/ /\\__\\ /:/\\:\\__\\ \n ___ /::\\ \\ /:/ /::\\ \\ __|:|\\:\\ \\ /:/ /::\\__\\ ___ \\:\\ \\ /:/ /:/ / /:/ /::\\ \\ /:/ /:/ _/_ /:/ /:/ / \n /\\ /:/\\:\\__\\ /:/_/:/\\:\\__\\ /::::|_\\:\\__\\ /:/_/:/\\:|__| /\\ \\ \\:\\__\\ /:/_/:/__/___ /:/__\\/\\:\\__\\ /:/_/:/ /\\__\\ /:/_/:/__/___\n \\:\\/:/ \\/__/ \\:\\/:/ \\/__/ \\:\\~~\\ \\/__/ \\:\\/:/ /:/ / \\:\\ \\ /:/ / \\:\\/:::::/ / \\:\\ \\ /:/ / \\:\\/:/ /:/ / \\:\\/:::::/ /\n \\::/__/ \\::/__/ \\:\\ \\ \\::/_/:/ / \\:\\ /:/ / \\::/~~/~~~~ \\:\\ /:/ / \\::/_/:/ / \\::/~~/~~~~ \n \\:\\ \\ \\:\\ \\ \\:\\ \\ \\:\\/:/ / \\:\\/:/ / \\:\\~~\\ \\:\\/:/ / \\:\\/:/ / \\:\\~~\\ \n \\:\\__\\ \\:\\__\\ \\:\\__\\ \\::/ / \\::/ / \\:\\__\\ \\::/ / \\::/ / \\:\\__\\ \n \\/__/ \\/__/ \\/__/ \\/__/ \\/__/ \\/__/ \\/__/ \\/__/ \\/__/ \n
\n\n ___ ___ ___ ___ ___ ___ ___ ___ \n /__/\\ / /\\ /__/\\ _____ /__/\\ / /\\ / /\\ / /\\ / /\\ \n \\ \\:\\ / /::\\ | |::\\ / /::\\ \\ \\:\\ / /::\\ / /:/_ / /:/_ / /::\\ \n \\__\\:\\ / /:/\\:\\ | |:|:\\ / /:/\\:\\ \\ \\:\\ / /:/\\:\\ / /:/ /\\ / /:/ /\\ / /:/\\:\\ \n ___ / /::\\ / /:/~/::\\ __|__|:|\\:\\ / /:/~/::\\ ___ \\ \\:\\ / /:/~/:/ / /:/_/::\\ / /:/ /:/_ / /:/~/:/ \n /__/\\ /:/\\:\\ /__/:/ /:/\\:\\ /__/::::| \\:\\ /__/:/ /:/\\:| /__/\\ \\__\\:\\ /__/:/ /:/___ /__/:/__\\/\\:\\ /__/:/ /:/ /\\ /__/:/ /:/___\n \\ \\:\\/:/__\\/ \\ \\:\\/:/__\\/ \\ \\:\\~~\\__\\/ \\ \\:\\/:/~/:/ \\ \\:\\ / /:/ \\ \\:\\/:::::/ \\ \\:\\ /~~/:/ \\ \\:\\/:/ /:/ \\ \\:\\/:::::/\n \\ \\::/ \\ \\::/ \\ \\:\\ \\ \\::/ /:/ \\ \\:\\ /:/ \\ \\::/~~~~ \\ \\:\\ /:/ \\ \\::/ /:/ \\ \\::/~~~~ \n \\ \\:\\ \\ \\:\\ \\ \\:\\ \\ \\:\\/:/ \\ \\:\\/:/ \\ \\:\\ \\ \\:\\/:/ \\ \\:\\/:/ \\ \\:\\ \n \\ \\:\\ \\ \\:\\ \\ \\:\\ \\ \\::/ \\ \\::/ \\ \\:\\ \\ \\::/ \\ \\::/ \\ \\:\\ \n \\__\\/ \\__\\/ \\__\\/ \\__\\/ \\__\\/ \\__\\/ \\__\\/ \\__\\/ \\__\\/ \n
\n\n ___ ___ ___ ___ ___ ___ ___ ___ ___ \n / /\\ / /\\ / /\\ / /\\ / /\\ / /\\ / /\\ / /\\ / /\\ \n / /:/ / /::\\ / /::| / /::\\ / /:/ / /::\\ / /::\\ / /::\\ / /::\\ \n / /:/ / /:/\\:\\ / /:|:| / /:/\\:\\ / /:/ / /:/\\:\\ / /:/\\:\\ / /:/\\:\\ / /:/\\:\\ \n / /::\\ ___ / /::\\ \\:\\ / /:/|:|__ / /::\\ \\:\\ / /:/ / /::\\ \\:\\ / /:/ \\:\\ / /::\\ \\:\\ / /::\\ \\:\\ \n /__/:/\\:\\ /\\ /__/:/\\:\\_\\:\\ /__/:/_|::::\\ /__/:/\\:\\_\\:| /__/:/ /\\ /__/:/\\:\\_\\:\\ /__/:/_\\_ \\:\\ /__/:/\\:\\ \\:\\ /__/:/\\:\\_\\:\\\n \\__\\/ \\:\\/:/ \\__\\/ \\:\\/:/ \\__\\/ /~~/:/ \\ \\:\\ \\:\\/:/ \\ \\:\\ /:/ \\__\\/~|::\\/:/ \\ \\:\\__/\\_\\/ \\ \\:\\ \\:\\_\\/ \\__\\/~|::\\/:/\n \\__\\::/ \\__\\::/ / /:/ \\ \\:\\_\\::/ \\ \\:\\ /:/ | |:|::/ \\ \\:\\ \\:\\ \\ \\:\\ \\:\\ | |:|::/ \n / /:/ / /:/ / /:/ \\ \\:\\/:/ \\ \\:\\/:/ | |:|\\/ \\ \\:\\/:/ \\ \\:\\_\\/ | |:|\\/ \n /__/:/ /__/:/ /__/:/ \\__\\::/ \\ \\::/ |__|:|~ \\ \\::/ \\ \\:\\ |__|:|~ \n \\__\\/ \\__\\/ \\__\\/ ~~ \\__\\/ \\__\\| \\__\\/ \\__\\/ \\__\\| \n
\n\n )__/_ _ / _ _ _ _ \n/ /(///)()(// (/(-/ \n _/ \n
\n\n _ _ _ \n _ __ ___ __ _ _ __ _ _| |__ _ __ ___ __ _| | | |\n | '__/ _ \\/ _` | '__| | | | '_ \\| '_ ` _ \\ / _` | |_| |\n | | | __/ (_| | | | |_| | |_) | | | | | | (_| | _ |\n |_| \\___|\\__, |_| \\__,_|_.__/|_| |_| |_|\\__,_|_| |_|\n |___/ \n
\n\n o o 8 \n 8 8 8 \no8oooo8 .oPYo. ooYoYo. 8oPYo. o o oPYo. .oPYo. .oPYo. oPYo. \n 8 8 .oooo8 8' 8 8 8 8 8 8 8 `' 8 8 8oooo8 8 `' \n 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8. 8 \n 8 8 `YooP8 8 8 8 `YooP' `YooP' 8 `YooP8 `Yooo' 8 \n:..:::..:.....:..:..:..:.....::.....:..:::::....8 :.....:..::::\n:::::::::::::::::::::::::::::::::::::::::::::ooP'.:::::::::::::\n:::::::::::::::::::::::::::::::::::::::::::::...:::::::::::::::\n
\n\n ______ ________ _ ______ ___ ___ __ __._ _ _ _ _ \n |____ |____ \\ \\ | |____ |_ ||_ | \\ \\ / /| | | | | | | | |\n | | _ | |\\ \\| | | | | | | | \\ V / | | | | | | |_| |\n | || | |_|_\\ ` | | | | |__| |___\\ \\ | |/ /_/ /| _ |\n |_|| | |______| |_| |_|____|______| |_______/ |_| |_|\n |_| \n
\n\n # # ######### ######## ########## # \n ######## # ### # # # ######### # ########## ######### \n # # #### # # # # # # # # # \n# ## # ######## # ######## # # # # # # \n ## # # ## ## # # # # # # # # \n ## # # ## ## ######### ######### # ######### \n ## ####### ######## ## ## # # \n
\n\n'||' '||' '|| \n || || .... .. .. .. || ... ... ... ... .. ... . .... ... .. \n ||''''|| '' .|| || || || ||' || || || ||' '' || || .|...|| ||' '' \n || || .|' || || || || || | || || || |'' || || \n.||. .||. '|..'|' .|| || ||. '|...' '|..'|. .||. '||||. '|...' .||. \n .|....' \n
\n\n|-|4mbvrg3r\n
\n\n __ __ __ \n/\\ \\/\\ \\ /\\ \\ \n\\ \\ \\_\\ \\ __ ___ ___\\ \\ \\____ __ __ _ __ __ __ _ __ \n \\ \\ _ \\ /'__`\\ /' __` __`\\ \\ '__`\\/\\ \\/\\ \\/\\`'__\\/'_ `\\ /'__`\\/\\`'__\\\n \\ \\ \\ \\ \\/\\ \\L\\.\\_/\\ \\/\\ \\/\\ \\ \\ \\L\\ \\ \\ \\_\\ \\ \\ \\//\\ \\L\\ \\/\\ __/\\ \\ \\/ \n \\ \\_\\ \\_\\ \\__/.\\_\\ \\_\\ \\_\\ \\_\\ \\_,__/\\ \\____/\\ \\_\\\\ \\____ \\ \\____\\\\ \\_\\ \n \\/_/\\/_/\\/__/\\/_/\\/_/\\/_/\\/_/\\/___/ \\/___/ \\/_/ \\/___L\\ \\/____/ \\/_/ \n /\\____/ \n \\_/__/ \n
\n\n _ \n| | | | | \n|-+-| - |- - |- |- -| - |- \n| | | | | | | | | | | | | |/ | \n -- - -- - -- \n
\n\n _/ _/ _/ \n _/ _/ _/_/_/ _/_/_/ _/_/ _/_/_/ _/ _/ _/ _/_/ _/_/_/ _/_/ _/ _/_/ \n _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/_/_/_/ _/_/ \n _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ \n_/ _/ _/_/_/ _/ _/ _/ _/_/_/ _/_/_/ _/ _/_/_/ _/_/_/ _/ \n _/ \n _/_/ \n
\n\nHH HH bb \nHH HH aa aa mm mm mmmm bb uu uu rr rr gggggg eee rr rr \nHHHHHHH aa aaa mmm mm mm bbbbbb uu uu rrr r gg gg ee e rrr r \nHH HH aa aaa mmm mm mm bb bb uu uu rr ggggggg eeeee rr \nHH HH aaa aa mmm mm mm bbbbbb uuuu u rr gg eeeee rr \n ggggg \n
\n\n.-. .-..---..-.-.-..--..-..-..---. .---..---..---. \n| |=| || | || | | ||-< | || || |-< | |'_| |- | |-< \n`-' `-'`-^-'`-'-'-'`--'`----'`-'`-'`-'-/`---'`-'`-'\n
\n\n::| ::| :| \n::::::|.::\\ :\\/| ::'| :\\:| :::| /::| :~~/ :::| \n::| ::|`::| :::| :::| `::| :| \\::| :::, :| \n ,.:/ \n
\n\n/ \\ | \n|=| /=| /=\\=\\ |=\\ | | /= /=| /=\\ /= \n\\ / \\=| | | | |=/ \\=/ | \\=| \\= | \n \\=| \n
\n\n.:: .:: .:: \n.:: .:: .:: \n.:: .:: .:: .::: .:: .:: .:: .:: .::.: .::: .:: .:: .: .:::\n.:::::: .:: .:: .:: .:: .: .::.:: .:: .:: .:: .:: .:: .:: .: .:: .:: \n.:: .::.:: .:: .:: .: .::.:: .::.:: .:: .:: .:: .::.::::: .:: .:: \n.:: .::.:: .:: .:: .: .::.:: .::.:: .:: .:: .:: .::.: .:: \n.:: .:: .:: .:::.::: .: .::.:: .:: .::.::.::: .:: .:::: .::: \n .:: \n
\n\n| | | \n|--|/~~||/~\\ /~\\ |~~\\| ||/~\\/~~|/~/|/~\\\n| |\\__|| | ||__/ \\_/|| \\__|\\/_| \n \\__| \n
\n\n | | _ _ _\n |\\ //| ||\\ |/ |/| | /| |/ | \n | \n
\n\n|_| _.._ _ |_ .__ _ ._ \n| |(_|| | ||_)|_||(_|(/_| \n _| \n
\n\n _ _ _ \n __ _ ___ _ __ __ _ _ _ __| | ___ __ _ _ __ | | | |\n |__` / _ \\| '_ \\__` | | | |/ _` |/ _ ' _` | '_ \\| |_| |\n | \\__ | |_) | | | |_| | (_| | | | | | | |_) | _ |\n |_|___/| .__/ |_|_.__/ \\__,_|_| |_| |_|_.__/|_| |_|\n \\___| \n
\n\nHamburger\n
\n\n.... .- -- -... ..- .-. --. . .-. \n
\n\n# # # # # #### # # #### ##### ##### #### \n # # # # ## ## # # # # # # # # # # \n # ##### # # # #### # #### # #### #### \n # # # # # # # # # # # # # \n# # # # # # ##### # # # ##### # \n
\n\n \"\"|\"\"|\\ |\"\"|| |\\/|/ |\n || ' \\/ ||_|_\\|_/ \n | -' \n
\n\nM\"\"MMMMM\"\"MM dP \nM MMMMM MM 88 \nM `M .d8888b. 88d8b.d8b. 88d888b. dP dP 88d888b. .d8888b. .d8888b. 88d888b. \nM MMMMM MM 88' `88 88'`88'`88 88' `88 88 88 88' `88 88' `88 88ooood8 88' `88 \nM MMMMM MM 88. .88 88 88 88 88. .88 88. .88 88 88. .88 88. ... 88 \nM MMMMM MM `88888P8 dP dP dP 88Y8888' `88888P' dP `8888P88 `88888P' dP \nMMMMMMMMMMMM .88 \n d8888P \n
\n\ndP dP dP \n88 88 88 \n88aaaaa88a .d8888b. 88d8b.d8b. 88d888b. dP dP 88d888b. .d8888b. .d8888b. 88d888b. \n88 88 88' `88 88'`88'`88 88' `88 88 88 88' `88 88' `88 88ooood8 88' `88 \n88 88 88. .88 88 88 88 88. .88 88. .88 88 88. .88 88. ... 88 \ndP dP `88888P8 dP dP dP 88Y8888' `88888P' dP `8888P88 `88888P' dP \nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo~~~~.88~oooooooooooooooooo\n d8888P \n
\n\ndP dP dP \n88 88 88 \n88aaaaa88a .d8888b. 88d8b.d8b. 88d888b. dP dP 88d888b. .d8888b. .d8888b. 88d888b. \n88 88 88' `88 88'`88'`88 88' `88 88 88 88' `88 88' `88 88ooood8 88' `88 \n88 88 88. .88 88 88 88 88. .88 88. .88 88 88. .88 88. ... 88 \ndP dP `88888P8 dP dP dP 88Y8888' `88888P' dP `8888P88 `88888P' dP \n .88 \n d8888P \n
\n\n{__ {__ {__ \n{__ {__ {__ \n{__ {__ {__ {___ {__ {__ {__ {__ {__{_ {___ {__ {__ {_ {___\n{______ {__ {__ {__ {__ {_ {__{__ {__ {__ {__ {__ {__ {__ {_ {__ {__ \n{__ {__{__ {__ {__ {_ {__{__ {__{__ {__ {__ {__ {__{_____ {__ {__ \n{__ {__{__ {__ {__ {_ {__{__ {__{__ {__ {__ {__ {__{_ {__ \n{__ {__ {__ {___{___ {_ {__{__ {__ {__{__{___ {__ {____ {___ \n {__ \n
\n\n _ _ ___ \n| | | | / _ \\ \n| |_| | __ ___ _| |_) )_ _ ___ _ _ ___ ___ \n| _ |/ \\/ / | | | _ <| | | |/ _ ( \\ / ) __)/ _ \\ \n| | | ( () <| |_| | |_) ) |_| | |_) ) v /> _)| |_) )\n|_| |_|\\__/\\_\\ ._,_| __/ \\___/| __/ | | \\___) __/ \n | | | | | | | | | | \n |_| |_| |_| |_| |_| \n
\n\n ,ggg, gg \ndP\"\"Y8b 88 ,dPYb, \nYb, `88 88 IP'`Yb \n `\" 88 88 I8 8I \n 88aaaaaaa88 I8 8' \n 88\"\"\"\"\"\"\"88 ,gggg,gg ,ggg,,ggg,,ggg, I8 dP gg gg ,gggggg, ,gggg,gg ,ggg, ,gggggg, \n 88 88 dP\" \"Y8I ,8\" \"8P\" \"8P\" \"8, I8dP 88ggI8 8I dP\"\"\"\"8I dP\" \"Y8I i8\" \"8i dP\"\"\"\"8I \n 88 88 i8' ,8I I8 8I 8I 8I I8P 8I I8, ,8I ,8' 8I i8' ,8I I8, ,8I ,8' 8I \n 88 Y8,,d8, ,d8b,,dP 8I 8I Yb,,d8b, ,8I ,d8b, ,d8b,,dP Y8,,d8, ,d8I `YbadP' ,dP Y8,\n 88 `Y8P\"Y8888P\"`Y88P' 8I 8I `Y88P'\"Y88P\"' 8P'\"Y88P\"`Y88P `Y8P\"Y8888P\"888888P\"Y8888P `Y8\n ,d8I' \n ,dP'8I \n ,8\" 8I \n I8 8I \n `8, ,8I \n `Y8P\" \n
\n\nooooo ooooo oooo \n 888 888 ooooooo oo ooo oooo 888ooooo oooo oooo oo oooooo oooooooo8 ooooooooo8 oo oooooo \n 888ooo888 ooooo888 888 888 888 888 888 888 888 888 888 888 88o 888oooooo8 888 888 \n 888 888 888 888 888 888 888 888 888 888 888 888 888oo888o 888 888 \no888o o888o 88ooo88 8o o888o888o888o o888ooo88 888o88 8o o888o 888 888 88oooo888 o888o \n 888ooo888 \n
\n\n110 141 155 142 165 162 147 145 162 \n
\n\n _ \n /\\ /\\__ _ _ __ ___ | |__ _ _ _ __ __ _ ___ _ __ \n / /_/ / _` | '_ ` _ \\| '_ \\| | | | '__/ _` |/ _ \\ '__|\n/ __ / (_| | | | | | | |_) | |_| | | | (_| | __/ | \n\\/ /_/ \\__,_|_| |_| |_|_.__/ \\__,_|_| \\__, |\\___|_| \n |___/ \n
\n\noo____oo___________________oo______________________________________________\noo____oo__ooooo__oo_oo_oo__oooooo__oo____o_oo_ooo___oooo____ooooo__oo_ooo__\noo____oo_oo___oo_ooo_oo__o_oo___oo_oo____o_ooo___o_oo__oo__oo____o_ooo___o_\noooooooo_oo___oo_oo__oo__o_oo___oo_oo____o_oo______oo___o__ooooooo_oo______\noo____oo_oo___oo_oo__oo__o_oo___oo_ooo___o_oo_______oooooo_oo______oo______\noo____oo__oooo_o_oo______o_oooooo__oo_ooo__oo______o____oo__ooooo__oo______\n____________________________________________________ooooo__________________\n
\n\n _ _ _ \n(_) (_) (_) _ ____ _ \n(_)___(_) ____ __ __ (_)_ _ _ (_)__ ____ (____)(_)__ \n(_______) (____) (__)_(__) (___)_ (_) (_)(____)(____)(_)_(_)(____)\n(_) (_)( )_( )(_) (_) (_)(_)_(_)(_)_(_)(_) ( )_(_)(__)__ (_) \n(_) (_) (__)_)(_) (_) (_)(____) (___) (_) (____) (____)(_) \n (_)_(_) \n (___) \n
\n\n/^^ /^^ /^^ \n/^^ /^^ /^^ \n/^^ /^^ /^^ /^^^ /^^ /^^ /^^ /^^ /^^/^ /^^^ /^^ /^^ /^ /^^^\n/^^^^^^ /^^ /^^ /^^ /^^ /^ /^^/^^ /^^ /^^ /^^ /^^ /^^ /^^ /^ /^^ /^^ \n/^^ /^^/^^ /^^ /^^ /^ /^^/^^ /^^/^^ /^^ /^^ /^^ /^^/^^^^^ /^^ /^^ \n/^^ /^^/^^ /^^ /^^ /^ /^^/^^ /^^/^^ /^^ /^^ /^^ /^^/^ /^^ \n/^^ /^^ /^^ /^^^/^^^ /^ /^^/^^ /^^ /^^/^^/^^^ /^^ /^^^^ /^^^ \n /^^ \n
\n\no O o \nO o O \no O O \nOoOooOOo o \no O .oOoO' `oOOoOO. OoOo. O o `OoOo. .oOoO .oOo. `OoOo. \nO o O o O o o O o o O o o O OooO' o \no o o O o O O o O O o O O o O O \no O `OoO'o O o o `OoO' `OoO'o o `OoOo `OoO' o \n O \n OoO' \n
\n\n /_/_ _ _ /_ __ _ _\n/ //_|/ / //_//_///_//_'/ \n _/ \n
\n\n@@@ @@@ @@@@@@ @@@@@@@@@@ @@@@@@@ @@@ @@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@ \n@@@ @@@ @@@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@@ @@@ @@@@@@@@ @@@@@@@@@ @@@@@@@@ @@@@@@@@ \n@@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ !@@ @@! @@! @@@ \n!@! @!@ !@! @!@ !@! !@! !@! !@ @!@ !@! @!@ !@! @!@ !@! !@! !@! @!@ \n@!@!@!@! @!@!@!@! @!! !!@ @!@ @!@!@!@ @!@ !@! @!@!!@! !@! @!@!@ @!!!:! @!@!!@! \n!!!@!!!! !!!@!!!! !@! ! !@! !!!@!!!! !@! !!! !!@!@! !!! !!@!! !!!!!: !!@!@! \n!!: !!! !!: !!! !!: !!: !!: !!! !!: !!! !!: :!! :!! !!: !!: !!: :!! \n:!: !:! :!: !:! :!: :!: :!: !:! :!: !:! :!: !:! :!: !:: :!: :!: !:! \n:: ::: :: ::: ::: :: :: :::: ::::: :: :: ::: ::: :::: :: :::: :: ::: \n : : : : : : : : :: : :: : : : : : : :: :: : : :: :: : : : \n
\n\n _ _ _ \n( ) ( ) ( ) \n| |_| | _ _ ___ ___ | |_ _ _ _ __ __ __ _ __ \n| _ | /'_` )/' _ ` _ `\\| '_`\\ ( ) ( )( '__)/'_ `\\ /'__`\\( '__)\n| | | |( (_| || ( ) ( ) || |_) )| (_) || | ( (_) |( ___/| | \n(_) (_)`\\__,_)(_) (_) (_)(_,__/'`\\___/'(_) `\\__ |`\\____)(_) \n ( )_) | \n \\___/' \n
\n\n ^ ^ ^ ^ ^ ^ ^ ^ ^ \n /H\\ /a\\ /m\\ /b\\ /u\\ /r\\ /g\\ /e\\ /r\\ \n<___><___><___><___><___><___><___><___><___>\n
\n\n _____ _ \n| | |___ _____| |_ _ _ ___ ___ ___ ___ \n| | .'| | . | | | _| . | -_| _|\n|__|__|__,|_|_|_|___|___|_| |_ |___|_| \n |___| \n
\n\n___________________________________________________________________________________________________\n/~~\\__/~~\\__/~~~~~~\\__/~~\\__/~~\\_/~~~~~~~\\__/~~\\__/~~\\_/~~~~~~~\\___/~~~~~~\\__/~~~~~~~~\\_/~~~~~~~\\__\n/~~\\__/~~\\_/~~\\__/~~\\_/~~~\\/~~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\_______/~~\\__/~~\\_\n/~~~~~~~~\\_/~~~~~~~~\\_/~~~~~~~~\\_/~~~~~~~\\__/~~\\__/~~\\_/~~~~~~~\\__/~~\\_______/~~~~~~\\___/~~~~~~~\\__\n/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~\\_______/~~\\__/~~\\_\n/~~\\__/~~\\_/~~\\__/~~\\_/~~\\__/~~\\_/~~~~~~~\\___/~~~~~~\\__/~~\\__/~~\\__/~~~~~~~\\_/~~~~~~~~\\_/~~\\__/~~\\_\n________________________________________________________________________/~~\\_______________________\n
\n\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n/// \\\\/// \\\\/////// \\\\/// \\\\/// \\//////// \\\\/// \\\\/// \\//////// \\\\\\/////// \\\\///////// \\//////// \\\\\n/// \\\\/// \\/// \\\\/// \\//// //// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\\\\\\\\\\\/// \\\\/// \\\n///////// \\///////// \\/// / /// \\//////// \\\\/// \\\\/// \\//////// \\\\/// \\\\\\\\\\\\\\/////// \\\\\\//////// \\\\\n/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\/// \\\\\\\\\\\\\\/// \\\\/// \\\n/// \\\\/// \\/// \\\\/// \\/// \\\\/// \\//////// \\\\\\/////// \\\\/// \\\\/// \\\\//////// \\///////// \\/// \\\\/// \\\n\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n
\n\n=========================================================================\n= ==== =================== ===========================================\n= ==== =================== ===========================================\n= ==== =================== ===========================================\n= ==== === === = = === ===== = == = ==== ==== === = ==\n= == = == == === = == = == = == = == = =\n= ==== ===== == = = == = == = == ======== == == ======\n= ==== === == = = == = == = == ========== == ===== ======\n= ==== == = == = = == = == = == ======= = == = == ======\n= ==== === == = = == ==== == ======== ==== === ======\n=========================================================================\n
\n\nooooo ooooo .o8 \n`888' `888' \"888 \n 888 888 .oooo. ooo. .oo. .oo. 888oooo. oooo oooo oooo d8b .oooooooo .ooooo. oooo d8b \n 888ooooo888 `P )88b `888P\"Y88bP\"Y88b d88' `88b `888 `888 `888\"\"8P 888' `88b d88' `88b `888\"\"8P \n 888 888 .oP\"888 888 888 888 888 888 888 888 888 888 888 888ooo888 888 \n 888 888 d8( 888 888 888 888 888 888 888 888 888 `88bod8P' 888 .o 888 \no888o o888o `Y888\"\"8o o888o o888o o888o `Y8bod8P' `V88V\"V8P' d888b `8oooooo. `Y8bod8P' d888b \n d\" YD \n \"Y88888P' \n
\n\nUnzohetre\n
\n\n _ _ _ \n(_) (_) | | \n _______ _____ ____ | |__ _ _ ____ ____ _____ ____ \n| ___ (____ | \\| _ \\| | | |/ ___) _ | ___ |/ ___)\n| | | / ___ | | | | |_) ) |_| | | ( (_| | ____| | \n|_| |_\\_____|_|_|_|____/|____/|_| \\___ |_____)_| \n (_____| \n
\n\n dMP dMP .aMMMb dMMMMMMMMb dMMMMb dMP dMP dMMMMb .aMMMMP dMMMMMP dMMMMb \n dMP dMP dMP\"dMP dMP\"dMP\"dMPdMP\"dMP dMP dMP dMP.dMP dMP\" dMP dMP.dMP \n dMMMMMP dMMMMMP dMP dMP dMPdMMMMK\" dMP dMP dMMMMK\" dMP MMP\"dMMMP dMMMMK\" \n dMP dMP dMP dMP dMP dMP dMPdMP.aMF dMP.aMP dMP\"AMF dMP.dMP dMP dMP\"AMF \ndMP dMP dMP dMP dMP dMP dMPdMMMMP\" VMMMP\" dMP dMP VMMMP\" dMMMMMP dMP dMP \n
\n\n888 888 888 \n888 888 ,\"Y88b 888 888 8e 888 88e 8888 8888 888,8, e88 888 ,e e, 888,8, \n8888888 \"8\" 888 888 888 88b 888 888b 8888 8888 888 \" d888 888 d88 88b 888 \" \n888 888 ,ee 888 888 888 888 888 888P Y888 888P 888 Y888 888 888 , 888 \n888 888 \"88 888 888 888 888 888 88\" \"88 88\" 888 \"88 888 \"YeeP\" 888 \n , 88P \n \"8\",P\" \n
\n\n| | \n|\\ | \n| \\ | \n| \\ | \n| \\| \n| | \n
\n\n| | \n|\\ | \n| \\ | \n| \\ | |\\ |\\/| |\\ |\\ |\\ \\ / |\\/| |\\ \n| \\| |\\ |/\\| |< | | |/ X | | |/ \n| | | | | |/ | | |\\ / \\ | | |\\ \n
\n\n @@@ @@@ @@@@@@ @@@@@@@@@@ @@@@@@@ @@@ @@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@ \n @@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ !@@ @@! @@! @@@\n @!@!@!@! @!@!@!@! @!! !!@ @!@ @!@!@!@ @!@ !@! @!@!!@! !@! @!@!@ @!!!:! @!@!!@! \n !!: !!! !!: !!! !!: !!: !!: !!! !!: !!! !!: :!! :!! !!: !!: !!: :!! \n : : : : : : : : :: : :: :.:: : : : : :: :: : : :: ::: : : :\n
\n\n , _ \n/| | | | \n |___| __, _ _ _ | | ,_ __, _ ,_ \n | |\\/ | / |/ |/ | |/ \\_| | / | / | |/ / | \n | |/\\_/|_/ | | |_/\\_/ \\_/|_/ |_/\\_/|/|__/ |_/\n /| \n \\| \n
\n\n _ _ __ __ __ ___ _ _ ___ __ ___ ___ \n( )( ) ( ) ( \\/ )( ,)( )( )( ,) / _)( _)( ,) \n )__( /__\\ ) ( ) ,\\ )()( ) \\( (/\\ ) _) ) \\ \n(_)(_)(_)(_)(_/\\/\\_)(___/ \\__/ (_)\\_)\\__/(___)(_)\\_)\n
\n\n | | | \n | | _` | __ `__ \\ __ \\ | | __| _` | _ \\ __| \n ___ | ( | | | | | | | | | ( | __/ | \n_| _|\\__,_|_| _| _|_.__/ \\__,_|_| \\__, |\\___|_| \n |___/ \n
\n\n|_| ,_ | _ \n| |(|||||)L||`(|(/_|`\n _| \n
\n\n __ __ __ \n / / / /___ _____ ___ / /_ __ ___________ ____ _____\n / /_/ / __ `/ __ `__ \\/ __ \\/ / / / ___/ __ `/ _ \\/ ___/\n / __ / /_/ / / / / / / /_/ / /_/ / / / /_/ / __/ / \n/_/ /_/\\__,_/_/ /_/ /_/_.___/\\__,_/_/ \\__, /\\___/_/ \n /____/ \n
\n\n## || ## \n## ||##| ##H H| ## ## H|## H|#HH| #H| ## H| \n##HH|| H| ### HH|##H| ## H|##H|## H|##HH|##H| \n## ||##H| ## H H|## H|## H|## #HH|## ## \n## ||##HH|## H|##H| #HH|## H| #HH|## \n ##H| \n
\n\n _ , \n' ) / / \n /--/ __. ______ /__. . __ _, _ __ \n/ (_(_/|_/ / / <_/_)(_/_/ (_(_)_</_/ (_\n /| \n |/ \n
\n\n _ _ _ \n| || |__ _ _ __ | |__ _ _ _ _ __ _ ___ _ _ \n| __ / _` | ' \\| '_ \\ || | '_/ _` / -_) '_|\n|_||_\\__,_|_|_|_|_.__/\\_,_|_| \\__, \\___|_| \n |___/ \n
\n\n ___ ___ ___ ___ ___ ___ ___ ___ ___ \n /\\__\\ /\\ \\ /\\__\\ /\\ \\ /\\__\\ /\\ \\ /\\ \\ /\\ \\ /\\ \\ \n /:/__/_ /::\\ \\ /::L_L_ /::\\ \\ /:/ _/_ /::\\ \\ /::\\ \\ /::\\ \\ /::\\ \\ \n /::\\/\\__\\ /::\\:\\__\\ /:/L:\\__\\ /::\\:\\__\\ /:/_/\\__\\ /::\\:\\__\\ /:/\\:\\__\\ /::\\:\\__\\ /::\\:\\__\\\n \\/\\::/ / \\/\\::/ / \\/_/:/ / \\:\\::/ / \\:\\/:/ / \\;:::/ / \\:\\:\\/__/ \\:\\:\\/ / \\;:::/ /\n /:/ / /:/ / /:/ / \\::/ / \\::/ / |:\\/__/ \\::/ / \\:\\/ / |:\\/__/ \n \\/__/ \\/__/ \\/__/ \\/__/ \\/__/ \\|__| \\/__/ \\/__/ \\|__| \n
\n\n ____ ____ ____ ____ ____ ____ ____ ____ ____ \n||H |||a |||m |||b |||u |||r |||g |||e |||r ||\n||__|||__|||__|||__|||__|||__|||__|||__|||__||\n|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|\n
\n\n , \n/| | _, |) ,_ _, _ ,_ \n |--| / | /|/|/| |/\\_| | / | / | |/ / | \n | |)\\/|_/ | | |_/\\/ \\/|_/ |/\\/|/|_/ |/\n (| \n
\n\n | | | \n __ | _` | ` \\ _ \\ | | _|_` | -_) _| \n_| _|\\__,_|_|_|_|_.__/\\_,_|_|\\__, |\\___|_| \n ____/ \n
\n\n __ __ __ \n / // /__ ___ _ / / __ _________ ____ ____\n / _ / _ `/ ' \\/ _ \\/ // / __/ _ `/ -_) __/\n/_//_/\\_,_/_/_/_/_.__/\\_,_/_/ \\_, /\\__/_/ \n /___/ \n
\n\n\\ .', _ _ _ _ ? _____ ,' \n/\\ | |_)_) |_)_) | \\/ (_(_| | \\/ \n | (, | (, \n
\n\n______ __ ______ \n___ / / /_____ _______ ______ /_____ _______________ _____________\n__ /_/ /_ __ `/_ __ `__ \\_ __ \\ / / /_ ___/_ __ `/ _ \\_ ___/\n_ __ / / /_/ /_ / / / / / /_/ / /_/ /_ / _ /_/ // __/ / \n/_/ /_/ \\__,_/ /_/ /_/ /_//_.___/\\__,_/ /_/ _\\__, / \\___//_/ \n /____/ \n
\n\n__________________________________________________________________\n7 7 77 _ 77 77 _ 77 7 77 _ 77 77 77 _ 7\n| ! || _ || _ _ || __|| | || _|| __!| ___!| _|\n| || 7 || 7 7 || _ || | || _ \\ | ! 7| __|_| _ \\ \n| 7 || | || | | || 7 || ! || 7 || || 7| 7 |\n!__!__!!__!__!!__!__!__!!_____!!_____!!__!__!!_____!!_____!!__!__!\n
\n\n,-_/,. . \n' |_|/ ,-. ,-,-. |-. . . ,-. ,-. ,-. ,-. \n /| | ,-| | | | | | | | | | | |-' | \n `' `' `-^ ' ' ' ^-' `-^ ' `-| `-' ' \n ,| \n `' \n
\n\n _ _ _ \n| | | | __ _ _ __ ___ | |__ _ _ _ __ __ _ ___ _ __ \n| |_| |/ _` | '_ ` _ \\| '_ \\| | | | '__/ _` |/ _ \\ '__|\n| _ | (_| | | | | | | |_) | |_| | | | (_| | __/ | \n|_| |_|\\__,_|_| |_| |_|_.__/ \\__,_|_| \\__, |\\___|_| \n |___/ \n
\n\n __ __ ___ .___ ___. .______ __ __ .______ _______ _______ .______ \n| | | | / \\ | \\/ | | _ \\ | | | | | _ \\ / _____|| ____|| _ \\ \n| |__| | / ^ \\ | \\ / | | |_) | | | | | | |_) | | | __ | |__ | |_) | \n| __ | / /_\\ \\ | |\\/| | | _ < | | | | | / | | |_ | | __| | / \n| | | | / _____ \\ | | | | | |_) | | `--' | | |\\ \\----.| |__| | | |____ | |\\ \\----.\n|__| |__| /__/ \\__\\ |__| |__| |______/ \\______/ | _| `._____| \\______| |_______|| _| `._____|\n
\n\n`.. `.. `.. \n`.. `.. `.. \n`.. `.. `.. `... `.. `.. `.. `.. `..`. `... `.. `.. `. `...\n`...... `.. `.. `.. `.. `. `..`.. `.. `.. `.. `.. `.. `.. `. `.. `.. \n`.. `..`.. `.. `.. `. `..`.. `..`.. `.. `.. `.. `..`..... `.. `.. \n`.. `..`.. `.. `.. `. `..`.. `..`.. `.. `.. `.. `..`. `.. \n`.. `.. `.. `...`... `. `..`.. `.. `..`..`... `.. `.... `... \n `.. \n
\n\n _ _ _ \n| | | | | | \n| |__ | | ____ ____ | | _ _ _ ____ ____ ____ ____ \n| __)| |/ _ | \\| || \\| | | |/ ___) _ |/ _ )/ ___)\n| | | ( ( | | | | | |_) ) |_| | | ( ( | ( (/ /| | \n|_| |_|\\_||_|_|_|_|____/ \\____|_| \\_|| |\\____)_| \n (_____| \n
\n\n|__| _ _ |_ _ _ _ _ \n| |(_|||||_)|_|| (_)(-| \n _/ \n
\n\nH) hh b) \nH) hh b) \nH)hhhhhh a)AAAA m)MM MMM b)BBBB u) UU r)RRR g)GGG e)EEEEE r)RRR \nH) hh a)AAA m) MM MM b) BB u) UU r) RR g) GG e)EEEE r) RR \nH) hh a) A m) MM MM b) BB u) UU r) g) GG e) r) \nH) hh a)AAAA m) MM b)BBBB u)UUU r) g)GGGG e)EEEE r) \n GG \n g)GGGG \n
\n\n`Yb. db dP\"Yb. .dP' \n `Yb db db `b 'Yb dP' \n Yb \"Ybaaaaaaaaad8' \n Yb 'Yb `Yb d88b d88b `Yb d88b d88b 'Yb `Yb dP' .dP' dP' 88 'Yb `Yb dP' \n dPYb 88 88P 88 8b 88P 8Y 8b 88 Yb dP 88 88 88 88 Yb dP \n ,dP Yb 88 88 8P 88 88 8P 88 88 YbdP Y8 Y8 .88 88 YbdP \n.dP' `Yb. .8P 88 .dP .dP 88 .dP' .dP' .8P .8P `Y88P`Y88P'88 .8P .8P \n .888888888888b. 888888888888b. dP' b 88 dP' b \n 88 Y. ,P 88 Y. ,P \n .8P `\"\"' Y8. `\"\"' \n
\n\nHamburger\n
\n\n8 8 8 \n8www8 .d88 8d8b.d8b. 88b. 8 8 8d8b .d88 .d88b 8d8b \n8 8 8 8 8P Y8P Y8 8 8 8b d8 8P 8 8 8.dP' 8P \n8 8 `Y88 8 8 8 88P' `Y8P8 8 `Y88 `Y88P 8 \n wwdP \n
\n\n| | | \n|---|,---.,-.-.|---.. .,---.,---.,---.,---.\n| |,---|| | || || || | ||---'| \n` '`---^` ' '`---'`---'` `---|`---'` \n `---' \n
\n\n|_| _ _ _ |_ _ _ _ _\n| |(_|| | ||_)|_|| (_|(/_| \n _| \n
\n\n_/\\/\\____/\\/\\______________________________/\\/\\___________________________________________________________________\n_/\\/\\____/\\/\\__/\\/\\/\\______/\\/\\/\\__/\\/\\____/\\/\\________/\\/\\__/\\/\\__/\\/\\__/\\/\\____/\\/\\/\\/\\____/\\/\\/\\____/\\/\\__/\\/\\_\n_/\\/\\/\\/\\/\\/\\______/\\/\\____/\\/\\/\\/\\/\\/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\/\\__/\\/\\/\\/\\/\\__/\\/\\/\\/\\___\n_/\\/\\____/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__________/\\/\\/\\/\\__/\\/\\________/\\/\\_______\n_/\\/\\____/\\/\\__/\\/\\/\\/\\/\\__/\\/\\______/\\/\\__/\\/\\/\\/\\______/\\/\\/\\/\\__/\\/\\______________/\\/\\____/\\/\\/\\/\\__/\\/\\_______\n_______________________________________________________________________________/\\/\\/\\/\\___________________________\n
\n\n _/\\/\\____/\\/\\______________________________/\\/\\___________________________________________________________________\n _/\\/\\____/\\/\\__/\\/\\/\\______/\\/\\/\\__/\\/\\____/\\/\\________/\\/\\__/\\/\\__/\\/\\__/\\/\\____/\\/\\/\\/\\____/\\/\\/\\____/\\/\\__/\\/\\_ \n _/\\/\\/\\/\\/\\/\\______/\\/\\____/\\/\\/\\/\\/\\/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\/\\__/\\/\\/\\/\\/\\__/\\/\\/\\/\\___ \n _/\\/\\____/\\/\\__/\\/\\/\\/\\____/\\/\\__/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__/\\/\\__________/\\/\\/\\/\\__/\\/\\________/\\/\\_______ \n _/\\/\\____/\\/\\__/\\/\\/\\/\\/\\__/\\/\\______/\\/\\__/\\/\\/\\/\\______/\\/\\/\\/\\__/\\/\\______________/\\/\\____/\\/\\/\\/\\__/\\/\\_______ \n_______________________________________________________________________________/\\/\\/\\/\\___________________________ \n
\n\no o o \n| | | \nO--O oo o-O-o O-o o o o-o o--o o-o o-o \n| | | | | | | | | | | | | | |-' | \no o o-o-o o o o-o o--o o o--O o-o o \n | \n o--o \n
\n\n _,_ _, _, _ __, _,_ __, _, __, __,\n |_| /_\\ |\\/| |_) | | |_) / _ |_ |_)\n | | | | | | |_) | | | \\ \\ / | | \\\n ~ ~ ~ ~ ~ ~ ~ `~' ~ ~ ~ ~~~ ~ ~\n
\n\n dBP dBP dBBBBBb dBBBBBBb dBBBBb dBP dBP dBBBBBb dBBBBb dBBBP dBBBBBb\n BB dBP dBP dBP dBP\n dBBBBBP dBP BB dBPdBPdBP dBBBK' dBP dBP dBBBBK dBBBB dBBP dBBBBK \n dBP dBP dBP BB dBPdBPdBP dB' db dBP_dBP dBP BB dB' BB dBP dBP BB \n dBP dBP dBBBBBBB dBPdBPdBP dBBBBP' dBBBBBP dBP dB' dBBBBBB dBBBBP dBP dB' \n
\n\n __ __ -|- __ __ ___ ___ __ \n/ ' | \\ | ` \\ , |~, / ' |_-_ | / ' \n\\_ | \\ | _ |@| | | ,_ `\\/\\ |_, | ,_ \n/ _ | / | _ | | | | / | ' | | | | ' | ' | \n\\__, |__/ _| \\_|_/ \\/ \\__/ \\/ _|_ \\__/ \n
\n\n|_| _ ._ _ |_ ._(~| _._\n| |(_|| | ||_)|_|| _|}_| \n
\n\n88 88 88 \n88 88 88 \n88 88 88 \n88aaaaaaaa88 ,adPPYYba, 88,dPYba,,adPYba, 88,dPPYba, 88 88 8b,dPPYba, ,adPPYb,d8 ,adPPYba, 8b,dPPYba, \n88\"\"\"\"\"\"\"\"88 \"\" `Y8 88P' \"88\" \"8a 88P' \"8a 88 88 88P' \"Y8 a8\" `Y88 a8P_____88 88P' \"Y8 \n88 88 ,adPPPPP88 88 88 88 88 d8 88 88 88 8b 88 8PP\"\"\"\"\"\"\" 88 \n88 88 88, ,88 88 88 88 88b, ,a8\" \"8a, ,a88 88 \"8a, ,d88 \"8b, ,aa 88 \n88 88 `\"8bbdP\"Y8 88 88 88 8Y\"Ybbd8\"' `\"YbbdP'Y8 88 `\"YbbdP\"Y8 `\"Ybbd8\"' 88 \n aa, ,88 \n \"Y8bbdP\" \n
\n\n ::: === :::==== :::======= :::==== ::: === :::==== :::===== :::===== :::==== \n ::: === ::: === ::: === === ::: === ::: === ::: === ::: ::: ::: ===\n ======== ======== === === === ======= === === ======= === ===== ====== ======= \n === === === === === === === === === === === === === === === === === \n === === === === === === ======= ====== === === ======= ======== === ===\n
\n\n / | / \n(___| ___ _ _ (___ ___ ___ ___ ___ \n| )| )| | )| )| )| )| )|___)| )\n| / |__/|| / |__/ |__/ | |__/ |__ | \n __/ \n
\n\n d8b d8b \n ?88 ?88 \n 88b 88b \n 888888b d888b8b 88bd8b,d88b 888888b ?88 d8P 88bd88b d888b8b d8888b 88bd88b\n 88P `?8bd8P' ?88 88P'`?8P'?8b 88P `?8bd88 88 88P' `d8P' ?88 d8b_,dP 88P' `\n d88 88P88b ,88b d88 d88 88P d88, d88?8( d88 d88 88b ,88b 88b d88 \nd88' 88b`?88P'`88bd88' d88' 88bd88'`?88P'`?88P'?8bd88' `?88P'`88b`?888P'd88' \n )88 \n ,88P \n `?8888P \n
\n\n mm mm mm \n ## ## ## \n ## ## m#####m ####m##m ##m###m ## ## ##m#### m###m## m####m ##m#### \n ######## \" mmm## ## ## ## ##\" \"## ## ## ##\" ##\" \"## ##mmmm## ##\" \n ## ## m##\"\"\"## ## ## ## ## ## ## ## ## ## ## ##\"\"\"\"\"\" ## \n ## ## ##mmm### ## ## ## ###mm##\" ##mmm### ## \"##mm### \"##mmmm# ## \n \"\" \"\" \"\"\"\" \"\" \"\" \"\" \"\" \"\" \"\"\" \"\"\"\" \"\" \"\" m\"\"\" ## \"\"\"\"\" \"\" \n \"####\"\" \n
\n\n m m # \n # # mmm mmmmm #mmm m m m mm mmmm mmm m mm \n #mmmm# \" # # # # #\" \"# # # #\" \" #\" \"# #\" # #\" \"\n # # m\"\"\"# # # # # # # # # # # #\"\"\"\" # \n # # \"mm\"# # # # ##m#\" \"mm\"# # \"#m\"# \"#mm\" # \n m # \n \"\" \n
\n\n ## ## ## \n ## ## ## \n ## ## ## \n ## ## :#### ## #:##: ##.###: ## ## ##.#### :###:## .####: ##.#### \n ## ## ###### ######## #######: ## ## ####### .####### .######: ####### \n ######## #: :## ##.##.## ### ### ## ## ###. ### ### ##: :## ###. \n ######## :##### ## ## ## ##. .## ## ## ## ##. .## ######## ## \n ## ## .####### ## ## ## ## ## ## ## ## ## ## ######## ## \n ## ## ## . ## ## ## ## ##. .## ## ## ## ##. .## ## ## \n ## ## ##: ### ## ## ## ### ### ##: ### ## ### ### ###. :# ## \n ## ## ######## ## ## ## #######: ####### ## .####### .####### ## \n ## ## ###.## ## ## ## ##.###: ###.## ## :###:## .#####: ## \n #. :## \n ###### \n :####: \n
\n\n # \n # # # \n # # # \n # # .###. ## # # ## # # #:##: ## # ### #:##:\n # # #: :# #:#:# # # # # ## # # # :# ## #\n ###### # # # # # # # # # # # # # # \n # # :#### # # # # # # # # # # ##### # \n # # #: # # # # # # # # # # # # # \n # # #. # # # # # # #: # # # # # # \n # # :##:# # # # # ## :##:# # ##:# ###: # \n # \n :# \n :##. \n
\n\n ██ ██ ██ \n ██ ██ ██ \n ██ ██ ██ \n ██ ██ ▒████▓ ██▓█▒██▒ ██░███▒ ██ ██ ██░████ ▒███▒██ ░████▒ ██░████ \n ██ ██ ██████▓ ████████ ███████▒ ██ ██ ███████ ░███████ ░██████▒ ███████ \n ████████ █▒ ▒██ ██░██░██ ███ ███ ██ ██ ███░ ███ ███ ██▒ ▒██ ███░ \n ████████ ▒█████ ██ ██ ██ ██░ ░██ ██ ██ ██ ██░ ░██ ████████ ██ \n ██ ██ ░███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████████ ██ \n ██ ██ ██▓░ ██ ██ ██ ██ ██░ ░██ ██ ██ ██ ██░ ░██ ██ ██ \n ██ ██ ██▒ ███ ██ ██ ██ ███ ███ ██▒ ███ ██ ███ ███ ███░ ▒█ ██ \n ██ ██ ████████ ██ ██ ██ ███████▒ ▓███████ ██ ░███████ ░███████ ██ \n ██ ██ ▓███░██ ██ ██ ██ ██░███▒ ▓███░██ ██ ▒███▒██ ░█████▒ ██ \n █░ ▒██ \n ██████▓ \n ▒████▒ \n
\n\n █ \n █ █ █ \n █ █ █ \n █ █ ░███░ ██▓█▓ █▓██ █ █ █▒██▒ ██▓█ ███ █▒██▒\n █ █ █▒ ▒█ █▒█▒█ █▓ ▓█ █ █ ██ █ █▓ ▓█ ▓▓ ▒█ ██ █\n ██████ █ █ █ █ █ █ █ █ █ █ █ █ █ █ \n █ █ ▒████ █ █ █ █ █ █ █ █ █ █ █████ █ \n █ █ █▒ █ █ █ █ █ █ █ █ █ █ █ █ █ \n █ █ █░ ▓█ █ █ █ █▓ ▓█ █▒ ▓█ █ █▓ ▓█ ▓▓ █ █ \n █ █ ▒██▒█ █ █ █ █▓██ ▒██▒█ █ ██▒█ ███▒ █ \n █ \n ▓ ▒█ \n ▒██░ \n
\n\nⒽⓐⓜⓑⓤⓡⓖⓔⓡ\n
\n\n┃ ┃┏━┃┏┏ ┏━ ┃ ┃┏━┃┏━┛┏━┛┏━┃\n┏━┃┏━┃┃┃┃┏━┃┃ ┃┏┏┛┃ ┃┏━┛┏┏┛\n┛ ┛┛ ┛┛┛┛━━ ━━┛┛ ┛━━┛━━┛┛ ┛\n
\n\n║ ║╔═║╔╔ ╔═ ║ ║╔═║╔═╝╔═╝╔═║\n╔═║╔═║║║║╔═║║ ║╔╔╝║ ║╔═╝╔╔╝\n╝ ╝╝ ╝╝╝╝══ ══╝╝ ╝══╝══╝╝ ╝\n
\n\n╻ ╻┏━┓┏┳┓┏┓ ╻ ╻┏━┓┏━╸┏━╸┏━┓\n┣━┫┣━┫┃┃┃┣┻┓┃ ┃┣┳┛┃╺┓┣╸ ┣┳┛\n╹ ╹╹ ╹╹ ╹┗━┛┗━┛╹┗╸┗━┛┗━╸╹┗╸\n
\n\nH H A M M BBBB U U RRRR GGG EEEEE RRRR \nH H A A MM MM B B U U R R G E R R \nHHHHH AAAAA M M M BBBB U U RRRR G GG EEEE RRRR \nH H A A M M B B U U R R G G E R R \nH H A A M M BBBB UUU R R GGG EEEEE R R \n
\n\n ▄▄ ▄▄ ▄▄ \n ██ ██ ██ \n ██ ██ ▄█████▄ ████▄██▄ ██▄███▄ ██ ██ ██▄████ ▄███▄██ ▄████▄ ██▄████ \n ████████ ▀ ▄▄▄██ ██ ██ ██ ██▀ ▀██ ██ ██ ██▀ ██▀ ▀██ ██▄▄▄▄██ ██▀ \n ██ ██ ▄██▀▀▀██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██▀▀▀▀▀▀ ██ \n ██ ██ ██▄▄▄███ ██ ██ ██ ███▄▄██▀ ██▄▄▄███ ██ ▀██▄▄███ ▀██▄▄▄▄█ ██ \n ▀▀ ▀▀ ▀▀▀▀ ▀▀ ▀▀ ▀▀ ▀▀ ▀▀ ▀▀▀ ▀▀▀▀ ▀▀ ▀▀ ▄▀▀▀ ██ ▀▀▀▀▀ ▀▀ \n ▀████▀▀ \n
\n\n ▄ ▄ █ \n █ █ ▄▄▄ ▄▄▄▄▄ █▄▄▄ ▄ ▄ ▄ ▄▄ ▄▄▄▄ ▄▄▄ ▄ ▄▄ \n █▄▄▄▄█ ▀ █ █ █ █ █▀ ▀█ █ █ █▀ ▀ █▀ ▀█ █▀ █ █▀ ▀\n █ █ ▄▀▀▀█ █ █ █ █ █ █ █ █ █ █ █▀▀▀▀ █ \n █ █ ▀▄▄▀█ █ █ █ ██▄█▀ ▀▄▄▀█ █ ▀█▄▀█ ▀█▄▄▀ █ \n ▄ █ \n ▀▀ \n
\n\n░█░█░█▀█░█▄█░█▀▄░█░█░█▀▄░█▀▀░█▀▀░█▀▄\n░█▀█░█▀█░█░█░█▀▄░█░█░█▀▄░█░█░█▀▀░█▀▄\n░▀░▀░▀░▀░▀░▀░▀▀░░▀▀▀░▀░▀░▀▀▀░▀▀▀░▀░▀\n
\n\n., ., ., \n][ ][ ][ \n][ ][ dWW,]WbW,]bWb ][ ][ WdW[ dWd[ dWb WdW[\n]WWW[ `md[][W][]P T[][ ][ W` ]P T[]bmd[ W` \n][ ][.W\"T[][W][][ ][][ ][ W ][ ][]P\"\"` W \n][ ][]bmW[][W][]WmW`]bmW[ W 'WmW['Wmm[ W \n'` '` \"\"'`'`\"'`'`\"` \"\"'` \" /\"][ '\"\" \" \n TWP` \n
\n\n. , ] \n] [ m, .mm ]m, . . ,m mm m, ,m \n]mm[' ] ]]] ]`T ] ] P `]`T ]`] P `\n] [.\"T ]]] ] ] ] ] [ ] ] ]\"\" [ \n] ['mT ]]] ]bP 'mT [ 'bT 'b/ [ \n ,] \n '` \n
\n\n▌ ▌ ▌ \n▙▄▌▝▀▖▛▚▀▖▛▀▖▌ ▌▙▀▖▞▀▌▞▀▖▙▀▖\n▌ ▌▞▀▌▌▐ ▌▌ ▌▌ ▌▌ ▚▄▌▛▀ ▌ \n▘ ▘▝▀▘▘▝ ▘▀▀ ▝▀▘▘ ▗▄▘▝▀▘▘ \n
\n\n ⣇⣸ ⢀⣀ ⣀⣀ ⣇⡀ ⡀⢀ ⡀⣀ ⢀⡀ ⢀⡀ ⡀⣀\n ⠇⠸ ⠣⠼ ⠇⠇⠇ ⠧⠜ ⠣⠼ ⠏ ⣑⡺ ⠣⠭ ⠏ \n
\n\n▗▖ ▗▖ ▗▖ \n▐▌ ▐▌ ▐▌ \n▐▌ ▐▌ ▟██▖▐█▙█▖▐▙█▙ ▐▌ ▐▌ █▟█▌ ▟█▟▌ ▟█▙ █▟█▌\n▐███▌ ▘▄▟▌▐▌█▐▌▐▛ ▜▌▐▌ ▐▌ █▘ ▐▛ ▜▌▐▙▄▟▌ █▘ \n▐▌ ▐▌▗█▀▜▌▐▌█▐▌▐▌ ▐▌▐▌ ▐▌ █ ▐▌ ▐▌▐▛▀▀▘ █ \n▐▌ ▐▌▐▙▄█▌▐▌█▐▌▐█▄█▘▐▙▄█▌ █ ▝█▄█▌▝█▄▄▌ █ \n▝▘ ▝▘ ▀▀▝▘▝▘▀▝▘▝▘▀▘ ▀▀▝▘ ▀ ▞▀▐▌ ▝▀▀ ▀ \n ▜█▛▘ \n
\n\n▗ ▖ ▐ \n▐ ▌ ▄▖ ▗▄▄ ▐▄▖ ▗ ▗ ▖▄ ▄▄ ▄▖ ▖▄ \n▐▄▄▌▝ ▐ ▐▐▐ ▐▘▜ ▐ ▐ ▛ ▘▐▘▜ ▐▘▐ ▛ ▘\n▐ ▌▗▀▜ ▐▐▐ ▐ ▐ ▐ ▐ ▌ ▐ ▐ ▐▀▀ ▌ \n▐ ▌▝▄▜ ▐▐▐ ▐▙▛ ▝▄▜ ▌ ▝▙▜ ▝▙▞ ▌ \n ▖▐ \n ▝▘ \n
\n\nHamburger\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2018-06-14"
},{
"id": "find",
"title": "Find",
"url": "/find",
"category": "CLI",
"keywords": null,
"content_html": "find <path> <conditions> <actions>\n
\n\n-name \"*.c\"\n
\n\n-user jonathan\n-nouser\n
\n\n-type f # File\n-type d # Directory\n-type l # Symlink\n
\n\n-depth 2 # At least 3 levels deep\n-regex PATTERN\n
\n\n-size 8 # Exactly 8 512-bit blocks \n-size -128c # Smaller than 128 bytes\n-size 1440k # Exactly 1440KiB\n-size +10M # Larger than 10MiB\n-size +2G # Larger than 2GiB\n
\n\n-newer file.txt\n-newerm file.txt # modified newer than file.txt\n-newerX file.txt # [c]hange, [m]odified, [B]create\n-newerXt \"1 hour ago\" # [t]imestamp\n
\n\n-atime 0 # Last accessed between now and 24 hours ago\n-atime +0 # Accessed more than 24 hours ago\n-atime 1 # Accessed between 24 and 48 hours ago\n-atime +1 # Accessed more than 48 hours ago\n-atime -1 # Accessed less than 24 hours ago (same a 0)\n-ctime -6h30m # File status changed within the last 6 hours and 30 minutes\n-mtime +1w # Last modified more than 1 week ago\n
\n\nThese conditions only work in MacOS and BSD-like systems (no GNU/Linux support).
\n\n\\! -name \"*.c\"\n\\( x -or y \\)\n
\n\n-exec rm {} \\;\n-print\n-delete\n
\n\nfind . -name '*.jpg'\nfind . -name '*.jpg' -exec rm {} \\;\n
\n\nfind . -newerBt \"24 hours ago\"\n
\n\nfind . -type f -mtime +29 # find files modified more than 30 days ago\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2019-11-17"
},{
"id": "firebase",
"title": "Firebase",
"url": "/firebase",
"category": "Others",
"keywords": null,
"content_html": "FB = new Firebase('https://xxx.firebase.io')\nFB.auth(TOKEN, (err, result) => { ···})\n
\n\nFB.authAnonymously(···)\nFB.authWithPassword(···)\nFB.authWithOAuthPopup(···)\nFB.authWithOAuthToken(···)\n
\n\nUsers = FB.child('users')\n
\n\n// Create\nuser = Users.push(first: \"Frank\", last: \"Sinatra\")\n
\n\n// Retrieve\nuser = Users.child('alan') // gets `users/alan`\n
\n\n// Update\nuser.set(first: \"Miles\", last: \"Davis\")\nuser.update(first: \"Miles\")\nuser.setWithPriority({ ··· }, priority)\n
\n\n// Destroy\nuser.remove()\n
\n\n// Getting\nuser.name() // primary id\n\nuser.once('value', (snap) => {\n snap.name() // primary id\n snap.val() // value\n}, (err) => {\n ···\n})\n
\n\n// traversal\nuser.parent()\n
\n\nUsers = FB.child('users')\nUsers\n .startAt(1000)\n .limit(50)\n .equalTo(priority, [name])\n .on 'child_added', (snap) -> ···\n
\nPosts = FB.child('posts')\npost = Posts.push({ title: \"How to do things\", author: \"alan\" })\n
\n\nline-height
in <input type='button'>
Console.count()
box-shadow
window.devicePixelRatio
ontouchstart
<input type='number'>
<input type='color'>
FillPaint
and StrokePaint
<iframe sandbox=...>
(docs)<audio played>
(and <video>
)<source media=...>
column-fill
(docs)Map
and Set
background-position
extended syntax:invalid
rotate(0.5turn)
)text-align-last
(docs)element.outerHTML
(docs)text-size-adjust
(docs)<bdi>
elementfont-stretch
text-overflow
navigator.doNotTrack
text-overflow: ellipsis
http://
prefix in address barwindow.matchMedia
setTimeout
and setInterval
clamped to 1000msmozRequestAnimationFrame
<video buffered>
<script async>
Shortcut | \nDescription | \n
---|---|
Alt ← / Alt → | \n Move word | \n
^U | \n Delete to beginning | \n
^W | \n Delete to previous / | \n
^D | \n Delete next character | \n
Alt D | \n Delete next word | \n
^C | \n Cancel line | \n
Alt P | \n Page output | \n
Alt ↑ / Alt ↓ | \n Previous / next arguments | \n
Alt E / Alt V | \n Open in external editor | \n
^L | \n Repaint screen | \n
Alt H | \n Help on word (man) | \n
Alt W | \n Help on word (short descriptions) | \n
Alt L | \n List directory on cursor | \n
function my_function --description \"My description\"\n ···\nend\n
\n\nif test -f foo.txt\n ···\nelse if test -f bar.txt\n ···\nelse\n ···\nend\n
\n\nif test -f foo.txt && test -f bar.txt\n
\n\nif test -f foo.txt -a -f bar.txt\n
\n\nif test \\( -f foo.txt \\) -a -f \\( bar.txt \\)\n
\n\nemit my_event\n
\n\nfunction myhook --on-event my_event\n ···\nend\n
\n\nThis lets you hook onto events, such as fish_prompt
.
complete -c mycommand ...\ncomplete -c mycommand ...\ncomplete -c mycommand ...\n
\n\ncomplete \\\n -c # command\n -s # short option\n -l # long option\n -r, --require-parameter\n -f, --no-files\n -x # exclusive (-r -f)\n -n '__fish_use_subcommand' # condition\n --description \"..\"\n
\n\n complete -c $cmd \\\n-n '__fish_use_subcommand' \\\n-x -a hello \\\n--description 'lol'\n
\n\nCondition | \nDescription | \n
---|---|
-n __fish_complete_directories STRING DESCRIPTION | \n performs path completion on STRING, allowing only directories, and giving them the description DESCRIPTION. | \n
-n __fish_complete_path STRING DESCRIPTION | \n performs path completion on STRING, giving them the description DESCRIPTION. | \n
-n __fish_complete_groups | \n prints a list of all user groups with the groups members as description. | \n
-n __fish_complete_pids | \n prints a list of all processes IDs with the command name as description. | \n
-n __fish_complete_suffix SUFFIX | \n performs file completion allowing only files ending in SUFFIX. The mimetype database is used to find a suitable description. | \n
-n __fish_complete_users | \n prints a list of all users with their full name as description. | \n
-n __fish_print_filesystems | \n prints a list of all known file systems. Currently, this is a static list, and not dependent on what file systems the host operating system actually understands. | \n
-n __fish_print_hostnames | \n prints a list of all known hostnames. This functions searches the fstab for nfs servers, ssh for known hosts and checks the /etc/hosts file. | \n
-n __fish_print_interfaces | \n prints a list of all known network interfaces. | \n
-n __fish_print_packages | \n prints a list of all installed packages. This function currently handles Debian, rpm and Gentoo packages. | \n
-n __fish_use_subcommand | \n \n |
-n __fish_seen_subcommand_from init | \n \n |
complete -c ruby -s X -x -a '(__fish_complete_directories (commandline -ct))' --description 'Directory'\n
\n\nStart each example with complete -c cmdname
-x\n # no filename completion\n
\n\n-s d -x -a \"read skip\"\n # -d {read|skip}\n
\n\n-s d -x\n # -d <something>\n
\n\n-s f -r\n # -f FILE\n
\n\n-s f -l force\n # -f, --force\n
\n\n-a \"(cat /etc/passwd | cut -d : -f 1)\"\n # first argument as filename\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2018-01-31"
},{
"id": "flashlight",
"title": "Flashlight",
"url": "/flashlight",
"category": "Apps",
"keywords": null,
"content_html": "add Dinner with Rico 5 pm tomorrow
remind Go to school at 2:30pm
remind Go to school in 15 mins
!g foo
!mdn settimeout
shutdown
restart
logout
sleep
ejall
screen saver
emoji grin
:rocket:
/react
Prefix with /
to do a web search.
/* @flow */\nfunction square (n: number) {\n return n * n\n}\n\nconst four = square(2)\n
\n\nMost of what you need to do is to simply add annotations to function arguments!
\n\nSee: flow.org docs
\n\nfunction square (n: number) {\n const result = n * n\n}\n
\n\nresult
is inferred to be a number because number * number
will result in a number. There’s no need to give it annotations.
type Person = {\n name: string,\n age: number,\n isAdmin: boolean,\n likes: Array<string>\n}\n
\n\nfunction greet(user: Person) {\n console.log('hello', user.name)\n}\n
\n\ngreet({ name: 'Miles Davis', ··· })\n
\n\nThis is the typical way to define the shape of complex objects.
\n\nconst count: number = 200\n
\n\nYou typically don’t need to do this, function args are often enough.
\n\nSee: Variable types
\n\nimport type { Person } from './types'\n
\n\nexport type Person = {\n ···\n}\n
\n\nSee: Module types
\n\ntype Action = number | string\n
\n\ntype Direction = 'left' | 'right'\n
\n\nSee: Unions
\n\ntype Album = {\n name: ?string\n}\n
\n\nconst a: Album = { } // ✗ Error\nconst a: Album = { name: 'Blue' } // ✓ OK\nconst a: Album = { name: null } // ✓ OK\nconst a: Album = { name: undefined } // ✓ OK\n
\n\nThis makes name
either a string or null.
See: Maybe types
\n\ntype Album = {\n name?: string\n}\n
\n\nconst a: Album = { } // ✓ OK\na.name = 'Blue' // ✓ OK\na.name = null // ✗ Error\na.name = undefined // ✓ OK\n
\n\nThis makes an Album
valid even if name
is not part of the keys. This is different from “maybe” types.
See: Optional properties
\n\ntype Artist = {\n name: string,\n label: string\n}\n
\n\nconst a: Artist = {\n name: 'Miguel Migs',\n label: 'Naked Music',\n genre: 'House' // ✓ OK\n}\n
\n\nA type with more properties is “wider” and is a subtype of a “narrower” type.
\n\nSee: Width subtyping
\n\ntype Artist = {|\n name: string,\n label: string\n|}\n
\n\nconst a: Artist = {\n name: 'Miguel Migs',\n label: 'Naked Music',\n genre: 'House' // ✗ Error\n}\n
\n\nExact object types prevent extra properties from being added to an object.
\n\nSee: Exact object types
\n\ntype Items = {\n [key: string]: Item\n}\n
\n\nSee: Dynamic object keys
\n\nType | \nDescription | \n
---|---|
any | \n \n |
boolean | \n \n |
mixed | \n \n |
number | \n \n |
string | \n \n |
void | \n undefined | \n
null | \n null (but not undefined) | \n
{a: Number} | \n Object with a shape | \n
[any, number] | \n Tuples (fixed-length arrays) | \n
Array<T> | \n \n |
Class<T> | \n \n |
Function | \n \n |
Object | \n \n |
?number | \n Maybe (number, void, null) | \n
a | b | \n Union types | \n
type Suit = \"Diamonds\" | \"Clubs\" | \"Hearts\" | \"Spades\"\n\nconst countries = {\n US: \"United States\",\n IT: \"Italy\",\n FR: \"France\"\n}\n\ntype Country = $Keys<typeof countries>\n
\n\nSee: Enums
\n\ntype Tree = {\n foo: string,\n bar: number,\n qux: (foo: string, bar: number) => boolean\n}\n\ntype Generic<T> = {\n foo: T\n}\n
\n\nSee: Type aliases
\n\nclass GenericClass<T> {\n x: T\n constructor (x: T) { ... }\n}\n\nvar n: GenericClass<number> = new GenericClass(0)\n
\n\nSee: Generic classes
\n\ninterface Jsonable {\n toJSON(): string\n}\n\nclass Foo {\n toJSON() { return '{}' }\n}\n\n(new Foo: Jsonable)\n
\n\nSee: Interfaces
\n\nconst callback: () => void = function () {}\n
\n\nfunction filter<T> (\n list: Array<T>,\n callback: (item: T) => boolean\n): Array<T> {\n ···\n}\n
\n\nSee: Functions
\n\nimport type { Person } from '../person'\nimport typeof Config from '../config'\n
\n\nexport type Person = { id: string }\n
\n\n/*::\n export type Foo = { ... }\n*/\n\nfunction add(n /*: number */) { ... }\n
\n\ntype Props = {\n bar: number,\n}\n\ntype State = {\n open: boolean,\n}\n\nclass Foo extends React.Component<Props, State> {\n // Component code\n}\n
\n\nvar myNumbers: Array<number> = [42]\nfunction foo(): any { return 42 }\nvar b: boolean = false\nvar b: ?boolean = false /* maybe */\nvar b: string | boolean = false\n\nvar a: Class<MyClass> = MyClass\nvar b: MyClass = new a()\n
\n\ntype Callback = (?Error, string) => any\n\nfunction fetch (callback: Callback) {\n ···\n}\n
\n\nDispatchers receive actions that get dispatched to its listeners.
\nStores are objects that store data, usually changed from a dispatcher listener.
\nViews are React components that listen to Store changes, or emit actions to the dispatcher.
\nA dispatcher emits events (.dispatch()
) to its listeners (.register(fn)
).
var Dispatcher = require('flux').Dispatcher;\n\nd = new Dispatcher();\n\n// send\nd.dispatch({ action: 'edit', ... };\n\n// receive\ntoken = d.register(function (payload) {\n payload.action === 'edit'\n})\n
\n\nWith multiple listeners, you can ensure one is fired after another using .waitFor()
.
token1 = d.register(...);\n\ntoken2 = d.register(function (payload) {\n\n // ensure receiver 1 is fired before this\n d.waitFor([ token1 ]);\n \n // process here\n})\n
\n\nObject.assign is the preferred way to subclass Dispatcher (think $.extend
).
\nYou can also make action creators, which are shortcuts for dispatch()
.
var Dispatcher = require('flux').Dispatcher;\nvar assign = require('object-assign');\n\nvar AppDispatcher = assign({}, Dispatcher.prototype, {\n\n // action creator\n handleViewAction(action) {\n this.dispatch({\n source: 'VIEW_ACTION',\n action: action\n })\n } \n\n})\n
\n\nStores are just like objects.
\n\nvar TodoStore = { list: [] };\n
\n\nSometimes they’re eventemitters, too. Usually it’s used to emit change
events for views to pick up.
var TodoStore = assign({}, EventEmitter.prototype, {\n ...\n});\n\nTodoStore.emit('change');\nTodoStore.on('change', function () { ... });\n
\n\nLogic can sometimes belong in stores.
\n\n{\n isAllActive() {\n return this.list.every(item => item.active);\n }\n}\n
\n\nMake a Dispatcher and Stores.
\n\nd = new Dispatcher();\nTabStore = { tab: 'home' };\n
\n\nDispatch events to alter the store.
\n\nd.dispatch({ action: 'tab.change', tab: 'timeline' });\n\nd.register(function (data) {\n if (data.action === 'tab.change') {\n TabStore.tab = data.tab;\n }\n});\n
\n\nViews (React Components) can listen to Dispatchers.
\n\nvar TodoApp = React.createClass({\n\n componentDidMount() {\n this.token = AppDispatcher.register((payload) => {\n switch (payload.action) {\n case 'tab.change':\n this.render();\n // ...\n }\n });\n },\n \n componentDidUnmount() {\n AppDispatcher.unregister(this.token);\n }\n \n});\n
\n\nOr to Stores’s change
events.
{\n componentDidMount() {\n TodoStore.on('change', this.onChange);\n },\n \n componentDidUnmount() {\n TodoState.removeListener('change', this.onChange);\n },\n \n onChange(data) {\n // ...\n }\n}\n
\n\nflynn cluster add
to add that clusterflynn create NAME
in your appgit push flynn master
to deployflynn install # (provisions AWS EC2 stuff)\nflynn key add # (adds your pubkey to AWS)\n
\n\nXXXX.flynnhub.com
dashboard.XXXX.flynnhub.com
flynn -a dashboard env get LOGIN_TOKEN
to get login tokenAPP.XXXX.flynnhub.com
Managed in ~/.flynnrc
:
flynn cluster\nflynn cluster add [-g githost] [-p pin] NAME URL KEY\nflynn cluster remove NAME\nflynn cluster default NAME # use this current\n
\n\ncd ~/project\nflynn create example # adds the `flynn` remote\nflynn route # prints http routes\ngit push flynn master\n
\n\nflynn env\nflynn env set FOO=bar BAZ=foobar\nflynn env unset FOO\n
\n\nflynn ps\nflynn scale web=3\n
\n\nflynn log\nflynn log flynn-d55c7a...\n
\n\nflynn run rake db:migrate\n
\n\nflynn route\nflynn route add http example.com\n# then make a CNAME from example.com to myapp.xxxx.flynnhub.com\n
\n\nflynn ps\nflynn kill <job>\n\nflynn meta\nflynn meta set foo=baz\n
\n\nirc.freenode.net\n
\n\n/msg nickserv identify [nick] <password>\n/msg nickserv info <nick>\n
\n\n/nick newnick\n/msg nickserv identify <oldnick> <password>\n/msg nickserv group\n
",
"intro_html": "",
"description_html": "",
"tags": ["WIP"],
"updated": null
},{
"id": "frequency-separation-retouching",
"title": "Frequency separation retouching",
"url": "/frequency-separation-retouching",
"category": "Others",
"keywords": null,
"content_html": "Duplicate the layer twice. Perform these in each layer:
\n\nSubtract
2
128
max heart rate = (220 - age)\n
\n\n“The target heart rate method is a simple formula: take 220 and minus your age.\nThen take that number and multiply it by .75 - .85, which will give you your\npercentages of 75% – 85% of your Max. HR.”
\n\nSee: http://www.bodybuilding.com/fun/mike1.htm
\n\nJennifer Thompson video: http://www.youtube.com/watch?v=34XRmd3a8_0
\n\nAt rest, 33% of the body’s energy comes from carbohydrates, or glycogen, \nstored within the muscles and liver. 66% comes from fat.
\nDuring aerobic work, 50-60% of the energy comes from fats
\nPrimarily carbohydrates are used during the first several minutes of exercise
\nFor an average fit person, it takes 20 to 30 minutes of continuous aerobic \nactivity to burn 50% fat and 50% carbohydrate
\nThere is approximately a 7 fold increase of fat mobilization after 1 hour of \nexercise
\nLow intense exercise (less than 30% VO2 max) relies primarily on fat whereas \nhigh intense exercise (greater than 70% VO2 max) primarily utilized \ncarbohydrate.
\nSee: Substrates (exrx.net)
\n\n“I would never recommend traditional style deloads on a cut, regardless of \n training regimen.”
\n“increase the rest day interval between sessions”
\nSee: Link (facebook.com)
\n\nSee: 531 and Bodybuilding (jimwendler.com)
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "gh-pages", "title": "GitHub pages", "url": "/gh-pages", "category": "Jekyll", "keywords": null, "content_html": "$ echo \"foobar.com\" > CNAME\n$ git commit && git push\n
\n\nCreate a CNAME
file with your domain on it.
See: Setting up a custom domain (github.com)
\n\nSubdomain (like www):
\n\n CNAME => username.github.io\n
\n\nApex domains:
\n\n ALIAS => username.github.io\n
\n\nApex domains (alternative):
\n\nA => 192.30.252.153\nA => 192.30.252.154\n
\n\ngit checkout -b $branchname\ngit push origin $branchname --set-upstream\n
\n\nCreates a new branch locally then pushes it.
\n\ngit fetch origin\ngit checkout --track origin/$branchname\n
\n\nGets a branch in a remote.
\n\ngit remote prune origin\n
\n\nDeletes origin/*
branches in your local copy. Doesn’t affect the remote.
git branch --list\n
\n\nExisting branches are listed. Current branch will be highlighted with an asterisk.
\n\ngit branch -a --merged\n
\n\nList outdated branches that have been merged into the current one.
\n\ngit branch -d $branchname\n
\n\nDeletes the branch only if the changes have been pushed and merged with remote.
\n\ngit branch -D $branchname\n
\n\ngit branch -d $branchname\n
\n\n\n\n\nNote: You can also use the -D flag which is synonymous with –delete –force instead of -d. This will delete the branch regardless of its merge status.\nDelete a branch irrespective of its merged status.
\n
git push origin --delete :$branchname\n
\n\nWorks for tags, too!
\n\ngit show-ref HEAD -s\n
\ngit reset --hard\n
\n\ngit reset --hard $commit_id\n\n# Now push to your branch\ngit push --force\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2020-02-13"
},{
"id": "git-extras",
"title": "Git extras",
"url": "/git-extras",
"category": "Git",
"keywords": null,
"content_html": "$ git feature myfeature\n switched to branch 'feature/rofl'\n\n$ ...\n$ git checkout develop\n$ git feature finish myfeature\n merging 'feature/rofl' into develop\n deleted branch 'feature/rofl'\n
\n\nAlso git-bug
and git-refactor
.
$ git delete-merged-branches\n # hint: do `git remote prune origin` after\n\n$ git create-branch development\n$ git delete-branch development\n\n$ git fresh-branch gh-pages\n
\n\n$ git summary # repo age, commits, active days, etc\n$ git impact # impact graph\n$ git effort # commits per file\n
\n\n$ git fork strongloop/express\n# sync your fork with the original repository:\n$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git\n$ git fetch upstream; git merge upstream/master\n
\n\n$ git release v1.0.0 # commit, tag, push-tags\n$ git delete-tag v1.0.0\n
\n\n$ git ignore \"*.log\"\n
\n\nAssumes that changes will not be committed.
\n\n$ git lock config/database.yml\n$ git unlock config/database.yml\n
\n\n$ git obliterate secret.yml # remove all references to it\n
\n\nQuick reference to some utilities in the git-extras utilities.
", "description_html": "", "tags": null, "updated": null },{ "id": "git-log-format", "title": "Git log format string", "url": "/git-log-format", "category": "Git", "keywords": ["git log --pretty=format:%H","%H - Commit hash","%an - Author","%aD - Author date"], "content_html": "git log --pretty=\"format:%H\"\n
\n\nSee the next tables on format variables.
\n\nVariable | \nDescription | \n
---|---|
%H | \n commit hash | \n
%h | \n (abbrev) commit hash | \n
Variable | \nDescription | \n
---|---|
%T | \n tree hash | \n
%t | \n (abbrev) tree hash | \n
Variable | \nDescription | \n
---|---|
%P | \n parent hash | \n
%p | \n (abbrev) parent hash | \n
Variable | \nDescription | \n
---|---|
%s | \n commit subject | \n
%f | \n commit subject, filename style | \n
%b | \n commit body | \n
%d | \n ref names | \n
%e | \n encoding | \n
Variable | \nDescription | \n
---|---|
%an | \n author | \n
%aN | \n author, respecting mailmap | \n
Variable | \nDescription | \n
---|---|
%ae | \n author email | \n
%aE | \n author email, respecting mailmap | \n
Variable | \nDescription | \n
---|---|
%aD | \n author date (rfc2882) | \n
%ar | \n author date (relative) | \n
%at | \n author date (unix timestamp) | \n
%ai | \n author date (iso8601) | \n
Variable | \nDescription | \n
---|---|
%cn | \n committer name | \n
%cN | \n committer name, respecting mailmap | \n
Variable | \nDescription | \n
---|---|
%ce | \n committer email | \n
%cE | \n committer email, respecting mailmap | \n
Variable | \nDescription | \n
---|---|
%cD | \n committer date (rfc2882) | \n
%cr | \n committer date (relative) | \n
%ct | \n committer date (unix timestamp) | \n
%ci | \n committer date (iso8601) | \n
git log master # branch\ngit log origin/master # branch, remote\ngit log v1.0.0 # tag\n\ngit log master develop\n\ngit log v2.0..master # reachable from *master* but not *v2.0*\ngit log v2.0...master # reachable from *master* and *v2.0*, but not both\n
\n\nSee gitrevisions.
\n\n-n, --max-count=2\n --skip=2\n
\n\n --since=\"1 week ago\"\n --until=\"yesterday\"\n
\n\n --author=\"Rico\"\n --committer=\"Rico\"\n
\n\n --grep=\"Merge pull request\" # in commit messages\n -S\"console.log\" # in code\n -G\"foo.*\" # in code (regex)\n
\n\n --invert-grep\n --all-match # AND in multi --grep\n
\n\n --merges\n --no-merges\n
\n\n --first-parent # no stuff from merged branches\n
\n\n --branches=\"feature/*\"\n --tags=\"v*\"\n --remotes=\"origin\"\n
\n\ngit log -- app/file.rb # only file\n --simplify-by-decoration # tags and branches\n
\n\n --date-order\n --author-date-order\n --topo-order # \"smart\" ordering\n --reverse\n
\n\n --abbrev-commit\n --oneline\n --graph\n
\n\n --pretty=\"format:%H\"\n
\n\nSee: Git log format cheatsheet
\n\ngit log master...develop | \n inspect differences in branches | \n
git rebase -i HEAD~3 | \n rebase last 3 commits | \n
git reset --hard HEAD@{2} | \n undo last operation that changed HEAD | \n
git checkout v2^{} | \n checkout the v2 tag (not v2 branch) | \n
The 3rd argument in each of these commands is a gitrevision
. These gitrevisions can be passed to many Git commands.
Reference | \nDescription | \n
---|---|
git show dae68e1 | \n sha1 | \n
git show HEAD | \n reference | \n
git show v1.0.0 | \n tag | \n
git show master | \n local branch | \n
git show origin/master | \n remote branch | \n
git show master~2 | \n 2 commits back from master | \n
git show master..fix | \n reachable from fix but not master | \n
git show master...fix | \n reachable from fix and master, but not both | \n
These are just the common ones, there’s a lot more below! (These work in many other commands, not just git show
.)
git checkout dae68e1 | \n sha1 | \n
Example | \nDescription | \n
---|---|
git checkout HEAD | \n reference | \n
git checkout master | \n branch | \n
git checkout v1.0.0 | \n tag | \n
git checkout origin/master | \n aka, refs/remotes/origin/master | \n
git checkout heads/master | \n aka, refs/heads/master | \n
Example | \nDescription | \n
---|---|
git checkout master@{yesterday} | \n also 1 day ago, etc | \n
git checkout master@{2} | \n 2nd prior value | \n
git checkout master@{push} | \n where master would push to | \n
git checkout master^ | \n parent commit | \n
git checkout master^2 | \n 2nd parent, eg, what it merged | \n
git checkout master~5 | \n 5 parents back | \n
git checkout master^0 | \n this commit; disambiguates from tags | \n
git checkout v0.99.8^{tag} | \n can be commit, tag, tree, object | \n
git checkout v0.99.8^{} | \n defaults to {tag} | \n
git checkout \":/fix bug\" | \n searches commit messages | \n
HEAD:README | \n … | \n
0:README | \n (0 to 3) … | \n
git log master | \n reachable parents from master | \n
git log ^master | \n exclude reachable parents from master | \n
git log master..fix | \n reachable from fix but not master | \n
git log master...fix | \n reachable from fix and master, but not both | \n
git log HEAD^@ | \n parents of HEAD | \n
git log HEAD^! | \n HEAD, then excluding parents’s ancestors | \n
git log HEAD^{:/fix} | \n search previous HEADs matching criteria | \n
A ─┬─ E ── F ── G master\n │\n └─ B ── C ── D fix\n
\n\ngit log master..fix | \n BCD | \n
git log master...fix | \n BCD and EFG | \n
A list of revision specifications you can use with git log
and many other Git commands. Summarized from gitrevisions(7)
man page.
HEAD^ # 1 commit before head\nHEAD^^ # 2 commits before head\nHEAD~5 # 5 commits before head\n
\n\n# create a new branch\n git checkout -b $branchname\n git push origin $branchname --set-upstream\n\n# get a remote branch\n git fetch origin\n git checkout --track origin/$branchname\n\n# delete local remote-tracking branches (lol)\n git remote prune origin\n\n# list merged branches\n git branch -a --merged\n\n# delete remote branch\n git push origin :$branchname\n \n# go back to previous branch\n git checkout -\n
\n\n# Rebase your changes on top of the remote master\n git pull --rebase upstream master\n \n# Squash multiple commits into one for a cleaner git log\n# (on the following screen change the word pick to either 'f' or 's')\n git rebase -i $commit_ref\n
\n\n# Import .gitmodules\n git submodule init\n\n# Clone missing submodules, and checkout commits\n git submodule update --init --recursive\n\n# Update remote URLs in .gitmodules\n# (Use when you changed remotes in submodules)\n git submodule sync\n
\n\ngit diff --stat\napp/a.txt | 2 +-\napp/b.txt | 8 ++----\n2 files changed, 10 insertions(+), 84 deletions(-)\n
\n\ngit diff --summary\n
\n\n--oneline\n e11e9f9 Commit message here\n\n--decorate\n shows \"(origin/master)\"\n\n--graph\n shows graph lines\n\n--date=relative\n \"2 hours ago\"\n
\n\ngit rebase 76acada^\n
\n\n# get current sha1 (?)\n git show-ref HEAD -s\n\n# show single commit info\n git log -1 f5a960b5\n\n# Go back up to root directory\n cd \"$(git rev-parse --show-top-level)\"\n
\n\n $ git shortlog\n $ git shortlog HEAD~20.. # last 20 commits\n\n James Dean (1):\n Commit here\n Commit there\n\n Frank Sinatra (5):\n Another commit\n This other commit\n
\n\ngit bisect start HEAD HEAD~6\ngit bisect run npm test\ngit checkout refs/bisect/bad # this is where it screwed up\ngit bisect reset\n
\n\ngit bisect start\ngit bisect good # current version is good\n\ngit checkout HEAD~8\nnpm test # see if it's good\ngit bisect bad # current version is bad\n\ngit bisect reset # abort\n
\n\ngit log --grep=\"fixes things\" # search in commit messages\ngit log -S\"window.alert\" # search in code\ngit log -G\"foo.*\" # search in code (regex)\n
\n\ngit config set user.signingkey <GPG KEY ID> # Sets GPG key to use for signing\n\ngit commit -m \"Implement feature Y\" --gpg-sign # Or -S, GPG signs commit\n\ngit config set commit.gpgsign true # Sign commits by default\ngit commit -m \"Implement feature Y\" --no-gpg-sign # Do not sign\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "gnupg",
"title": "GnuPG",
"url": "/gnupg",
"category": "CLI",
"keywords": null,
"content_html": "gpg -o key.gpg --export <KEY ID>\n
\n\nExport key in ASCII:
\n\ngpg -o key.asc --armor --export <KEY ID>\n
\n\nNote: Omitting the -o|--output
option will print the key to stdout
.
gpg --import key.gpg\ngpg --import key.asc\n
\n\nOnly merge updates for keys already in key-ring:
\n\ngpg --import key.asc --merge-options merge-only\n
\n\nGenerate a new key:
\n\ngpg --gen-key\n# or, generate a new key with dialogs for all options\ngpg --full-gen-key\n
\n\nList public keys:
\n\ngpg -k\ngpg --list-keys\n
\n\nList secret keys:
\n\ngpg -K\ngpg --list-secret-keys\n
\n\nImport keys from keyserver:
\n\ngpg --receive-keys <KEY IDS>\n
\n\nUpload keys to keyserver:
\n\ngpg --send-keys <KEY IDS>\n
\n\nRequest updates from keyserver for keys already in your keyring:
\n\ngpg --refresh-keys\n
\n\nSearch keys from keyserver:
\n\ngpg --search-keys \"<SEARCH STRING>\"\n
\n\nOverride keyserver from ~/.gnupg/gpg.conf
gpg --keyserver <URL> ...\n
\n\ngpg --edit-key <KEY ID>\n# In the interactive prompt:\ngpg> sign\ngpg> save\n
\n\nNOTE: You can use the owner’s email or name (or part thereof) instead of the key ID for --edit-key
This will produce an encrypted file, secret.txt.gpg
, that can only be decrypted by the recipient:
gpg -e -o secret.txt.gpg -r <RECIPIENT> secret.txt\n
\n\nFor <RECIPIENT>
you can use their key ID, their email, or their name (or part thereof).
gpg -e -r <KEY ID> ...\ngpg -e -r \"Bez\" ...\ngpg -e -r \"bezalelhermoso@gmail.com\" ...\n
\n\nSpecifying multiple recipients
\n\ngpg -e -r <RECIPIENT> -r <ANOTHER RECIPIENT> ... secret.txt\n
\n\nNOTE: Omitting -o|--output
will produce an encrypted file named <ORIGINAL FILENAME>.gpg
by default.
Encrypt file using a shared key. You will be prompted for a passphrase.
\n\ngpg --symmetric secret.txt\n# or\ngpg -c secret.txt\n
\n\ngpg -d -o secret.txt secret.txt.gpg\n
\n\nIf the file is encrypted via symmetric encryption, you will be prompted for the passphrase.
\n\nNOTE: Omitting -o|--output
will print the unencrypted contents to stdout
gpg -o signed-file.txt.gpg -s file.txt\n
\n\nThis can be used during encryption to also sign encrypted files:
\n\ngpg -s -o secret.txt.gpg \\\n -r <RECIPIENT> secret.txt\n
\n\ngpg --verify file.txt.gpg\n
\n\ngpg -d signed-file.txt.gpg\n
\n\nList all components:
\n\ngpgconf --list-components\n
\n\nKill a component:
\n\ngpgconf --kill <COMPONENT> # i.e. gpgconf --kill dirmngr\n
\n\nKill all components:
\ngpgconf --kill all\n
\n\nUse --with-colons
to produce an output that can easily be parsed i.e. with awk
, grep
. Fields are colon-separated.
gpg -k --with-colons\n
\n\nField Quick Reference:
\n\nField # | \nDescription | \n
1 | \nRecord type | \n
2 | \nValidity | \n
3 | \nKey length in bits | \n
4 | \nPublic key algorithm | \n
5 | \nKey ID | \n
6 | \nCreation date | \n
7 | \nExpiry date | \n
8 | \nCertificate S/N, UID hash, trust signature info | \n
9 | \nOwnertrust | \n
10 | \nUser ID | \n
11 | \nSignature class | \n
12 | \nKey capabilities | \n
13 | \nIssuer fingerprint | \n
14 | \nFlag field | \n
15 | \nS/N of token | \n
16 | \nHash algorithm | \n
17 | \nCurve name | \n
18 | \nCompliance flags | \n
19 | \nLast update timestamp | \n
20 | \nOrigin | \n
See GnuPG Details for more details.
", "intro_html": "GnuPG is a complete and free implementation of the OpenPGP standard.
", "description_html": "", "tags": [], "updated": "2017-10-22" },{ "id": "go", "title": "Go", "url": "/go", "category": "C-like", "keywords": null, "content_html": "package main\n\nimport \"fmt\"\n\nfunc main() {\n message := greetMe(\"world\")\n fmt.Println(message)\n}\n\nfunc greetMe(name string) string {\n return \"Hello, \" + name + \"!\"\n}\n
\n\n$ go build\n
\n\nOr try it out in the Go repl, or A Tour of Go.
\n\nvar msg string\nmsg = \"Hello\"\n
\n\nmsg := \"Hello\"\n
\n\nconst Phi = 1.618\n
\n\nConstants can be character, string, boolean, or numeric values.
\n\nSee: Constants
\n\nstr := \"Hello\"\n
\n\nstr := `Multiline\nstring`\n
\n\nStrings are of type string
.
num := 3 // int\nnum := 3. // float64\nnum := 3 + 4i // complex128\nnum := byte('a') // byte (alias for uint8)\n
\n\nvar u uint = 7 // uint (unsigned)\nvar p float32 = 22.7 // 32-bit float\n
\n\n// var numbers [5]int\nnumbers := [...]int{0, 0, 0, 0, 0}\n
\n\nArrays have a fixed size.
\n\nslice := []int{2, 3, 4}\n
\n\nslice := []byte(\"Hello\")\n
\n\nSlices have a dynamic size, unlike arrays.
\n\nfunc main () {\n b := *getPointer()\n fmt.Println(\"Value is\", b)\n}\n
\n\nfunc getPointer () (myPointer *int) {\n a := 234\n return &a\n}\n
\n\na := new(int)\n*a = 234\n
\n\nPointers point to a memory location of a variable. Go is fully garbage-collected.
\n\nSee: Pointers
\n\ni := 2\nf := float64(i)\nu := uint(i)\n
\n\nSee: Type conversions
\n\nif day == \"sunday\" || day == \"saturday\" {\n rest()\n} else if day == \"monday\" && isTired() {\n groan()\n} else {\n work()\n}\n
\n\nSee: If
\n\nif _, err := doThing(); err != nil {\n fmt.Println(\"Uh oh\")\n}\n
\n\nA condition in an if
statement can be preceded with a statement before a ;
. Variables declared by the statement are only in scope until the end of the if
.
See: If with a short statement
\n\nswitch day {\n case \"sunday\":\n // cases don't \"fall through\" by default!\n fallthrough\n\n case \"saturday\":\n rest()\n\n default:\n work()\n}\n
\n\nSee: Switch
\n\nfor count := 0; count <= 10; count++ {\n fmt.Println(\"My counter is at\", count)\n}\n
\n\nSee: For loops
\n\nentry := []string{\"Jack\",\"John\",\"Jones\"}\nfor i, val := range entry {\n fmt.Printf(\"At position %d, the character %s is present\\n\", i, val)\n}\n
\n\nSee: For-Range loops
\n\nmyfunc := func() bool {\n return x > 10000\n}\n
\n\nFunctions are first class objects.
\n\na, b := getMessage()\n
\n\nfunc getMessage() (a string, b string) {\n return \"Hello\", \"World\"\n}\n
\n\nfunc split(sum int) (x, y int) {\n x = sum * 4 / 9\n y = sum - x\n return\n}\n
\n\nBy defining the return value names in the signature, a return
(no args) will return variables with those names.
See: Named return values
\n\nimport \"fmt\"\nimport \"math/rand\"\n
\n\nimport (\n \"fmt\" // gives fmt.Println\n \"math/rand\" // gives rand.Intn\n)\n
\n\nBoth are the same.
\n\nSee: Importing
\n\nimport r \"math/rand\"\n
\n\nr.Intn()\n
\n\nfunc Hello () {\n ···\n}\n
\n\nExported names begin with capital letters.
\n\nSee: Exported names
\n\npackage hello\n
\n\nEvery package file has to start with package
.
func main() {\n // A \"channel\"\n ch := make(chan string)\n\n // Start concurrent routines\n go push(\"Moe\", ch)\n go push(\"Larry\", ch)\n go push(\"Curly\", ch)\n\n // Read 3 results\n // (Since our goroutines are concurrent,\n // the order isn't guaranteed!)\n fmt.Println(<-ch, <-ch, <-ch)\n}\n
\n\nfunc push(name string, ch chan string) {\n msg := \"Hey, \" + name\n ch <- msg\n}\n
\n\nChannels are concurrency-safe communication objects, used in goroutines.
\n\nSee: Goroutines, Channels
\n\nch := make(chan int, 2)\nch <- 1\nch <- 2\nch <- 3\n// fatal error:\n// all goroutines are asleep - deadlock!\n
\n\nBuffered channels limit the amount of messages it can keep.
\n\nSee: Buffered channels
\n\nch <- 1\nch <- 2\nch <- 3\nclose(ch)\n
\n\nfor i := range ch {\n ···\n}\n
\n\nok == false
v, ok := <- ch\n
\n\nSee: Range and close
\n\nimport \"sync\"\n\nfunc main() {\n var wg sync.WaitGroup\n \n for _, item := range itemList {\n // Increment WaitGroup Counter\n wg.Add(1)\n go doOperation(item)\n }\n // Wait for goroutines to finish\n wg.Wait()\n \n}\n
\n\nfunc doOperation(item string) {\n defer wg.Done()\n // do operation on item\n // ...\n}\n
\n\nA WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. The goroutine calls wg.Done()
when it finishes.\nSee: WaitGroup
func main() {\n defer fmt.Println(\"Done\")\n fmt.Println(\"Working...\")\n}\n
\n\nDefers running a function until the surrounding function returns.\nThe arguments are evaluated immediately, but the function call is not ran until later.
\n\n\n\nfunc main() {\n defer func() {\n fmt.Println(\"Done\")\n }()\n fmt.Println(\"Working...\")\n}\n
\n\nLambdas are better suited for defer blocks.
\n\nfunc main() {\n var d = int64(0)\n defer func(d *int64) {\n fmt.Printf(\"& %v Unix Sec\\n\", *d)\n }(&d)\n fmt.Print(\"Done \")\n d = time.Now().Unix()\n}\n
\nThe defer func uses current value of d, unless we use a pointer to get final value at end of main.
\n\ntype Vertex struct {\n X int\n Y int\n}\n
\n\nfunc main() {\n v := Vertex{1, 2}\n v.X = 4\n fmt.Println(v.X, v.Y)\n}\n
\n\nSee: Structs
\n\nv := Vertex{X: 1, Y: 2}\n
\n\n// Field names can be omitted\nv := Vertex{1, 2}\n
\n\n// Y is implicit\nv := Vertex{X: 1}\n
\n\nYou can also put field names.
\n\nv := &Vertex{1, 2}\nv.X = 2\n
\n\nDoing v.X
is the same as doing (*v).X
, when v
is a pointer.
type Vertex struct {\n X, Y float64\n}\n
\n\nfunc (v Vertex) Abs() float64 {\n return math.Sqrt(v.X * v.X + v.Y * v.Y)\n}\n
\n\nv := Vertex{1, 2}\nv.Abs()\n
\n\nThere are no classes, but you can define functions with receivers.
\n\nSee: Methods
\n\nfunc (v *Vertex) Scale(f float64) {\n v.X = v.X * f\n v.Y = v.Y * f\n}\n
\n\nv := Vertex{6, 12}\nv.Scale(0.5)\n// `v` is updated\n
\n\nBy defining your receiver as a pointer (*Vertex
), you can do mutations.
See: Pointer receivers
\n\nclass Greet\n attr_accessor :audience, :head, :tail\n \n def initialize\n @head = \"Hello, \"\n @tail = \"!\"\n end\n\n def name\n audience.name\n end\n\n def say\n puts head + name + tail\n end\nend\n\nmodule MyName\n attr_reader :name\n\n def initialize\n @name = self.class.to_s\n end\nend\n\nclass World\n include MyName\nend\n\ngreet = Greet.new\ngreet.audience = World.new\ngreet.say\n
\n\nThen run:
\n\n$ goby hello.gb\n#=> Hello, World!\n
\n\n$ goby -i\n
\n\nreset
: reset the VMexit
: exit REPLhelp
: show helpSee igb manual & test script. You can use readline
features such as command history by arrow keys.
zip101 = \"233-7383\"\nmagic_number = 42\n
\n\nShould be “[a-z][a-z0-9_]+
“(snake_case).
module State\n def initialize(state)\n @state = state # declaring an instance variable by assignment\n end\n def show\n @state # accessible from other instance methods\n end\nend\n\nstate = State.new \"success\"\nstate.show\n#=> success\n
\n\nShould be “@[a-z][a-z0-9_]+
“(snake_case).
# array literal\na, b, c = [1, 2, 3]\n\n# array with '*'\na = [1, 2, 3]\nx, y, z = *a\n\n# array literal with '*'\na, b, c = *[1, 2, 3]\n\n# bare assignment: unsupported\na, b, c = 1, 2, 3 #=> unexpected 3 Line: 0\n
\n\n# '_' is write-only\na, _ = [1, 2]\n
\n\nUnsupported.
\n\nUnsupported.
\n\ndef foo_bar?(baz)\n if baz == \"Hi, Goby!\"\n true\n else\n false\n end\nend\n\nfoo_bar? \"Hi, Goby!\" #=> true\n
\n\nMethod name should be “[a-z][a-z0-9_]+\\??
” (snake_case). You can omit the trailing “()
” only if no parameters are taken. Trailing using “!
” is unsupported.
def foo(normal, default=\"value\", hash={}, ary=[], keyword:, keyword_default:\"key\", *sprat)\nend\n
\n\nIf a default value is provided to a parameter, the parameter can be omitted when calling. ()
can be omitted. The order of parameters in method definition is restricted as follows:
a
)a=1
)ary=[]
or hs={}
)kwd:
)kwd: 1
or ary: [1,2,3]
or hsh: {key: \"value\"}
)*sp
)Or you will receive an error.
\n\ndef foo(process:, verb: :GET, opt:{ csp: :enabled }, ary: [1, 2, 3])\nend\n
\n\nPI = 3.14\ndef area(radius)\n radius * PI # returns the result of evaluation\nend\n\narea 6 #=> 18.84\n
\n\ndef my_array\n [1, 2, 3]\nend\n\nmy_array #=> [1, 2, 3]\n
\n\nmodule Foo\n def bar # defining instance method\n puts \"bar\"\n end\n \n def baz(count, email: \"goby@example.com\")\n count.times do\n puts email\n end\n end\nend\n\nfoo = Foo.new\nfoo.bar #=> bar\nfoo.baz(3) #↓\ngoby@example.com\ngoby@example.com\ngoby@example.com\n
\n\nstr = \"Goby\"\ndef str.foo #1 singleton method on the object\n self * 2\nend\n\nstr.foo\n#=> GobyGoby\n
\n\nmodule Foo\n def self.bar #2 singleton method with `self.`\n 92\n end\nend\n
\n\nmodule Foo \n def Foo.bar #3 singleton method with a class name (unrecommended)\n 88\n end\nend\n
\n\nmodule Foo end\n\ndef Foo.bar #4 singleton methods outside the Foo\n 9999\nend\n\nFoo.bar #=> 9999\n
\n\nclass Foo\n attr_accessor :bar, :baz\n\n def initialize\n @bar = 42\n @baz = 99\n end\nend\n\nfoo = Foo.new\n\nfoo.bar = 77\nfoo.baz = 88\n
\n\nYou can use the following shorthands to declare attribute accessor methods in classes/modules:
\n\nattr_accessor
attr_reader
attr_writer
class Foo\n def bar\n 42\n end\n \n def _baz # leading '_' means private method\n 99\n end\nend\n
\n\ninclude
module Foo\n def foo\n \"Foo's instance method\"\n end\nend\n\nclass Bar\n include Foo # to include Foo\nend\n\nBar.new.foo #=> Foo's instance method\n
\n\nModule names should be “[A-Z][A-Za-z0-9_]+
” (UpperCamelCase). Modules cannot be inherited.
extend
module Foo\n def foo\n \"Foo's instance method will be a singleton method\"\n end\nend\n\nclass Bar\n extend Foo # to extend Foo \nend\n\nBar.foo #=> Foo's instance method will be a singleton method\n
\n\nextend
is to use the instance methods in the specified modules as singleton methods in your class or module.
module Foo #module definition\n def foo \n 99\n end\nend\n\nFoo.new.foo #=> 99\n
\n\nActually, Goby’s module can be even instantiated via “new
” like “Foo.new
”.
class Foo # class definition\n def bar\n 99\n end\nend\n\nclass Baz < Foo # inheritance\nend\n\nBaz.new.bar #=> 99\n
\n\nClass names should be “[A-Z][A-Za-z0-9]+
” (UpperCamelCase). Inheritance with “<
” is supported.
HTTP_ERROR_404 = 404\nHTTP_ERROR_404 = 500 # error\n
\n\nConstants should be “[A-Z][A-Za-z0-9_]+
” (UPPER_SNAKECASE). Constants are not reentrant and the scope is global.
class Foo\n def bar\n 99\n end\nend\n\nclass Foo\n def bar # redefining is possible\n 77\n end\nend\n
\n\nclass Foo\n module Bar\n MAGIC = 99\n def baz\n 99\n end\n end\nend\n\nFoo::Bar.new.baz # Use '::' for namespacing\nFoo::Bar::MAGIC # Use '::' for namespacing\n
\n\nrequire
require(\"uri\") # to activate URL class\n\nu = URI.parse(\"http://example.com\")\nu.scheme #=> \"http\"\n
\n\nrequire_relative
require_relative(\"bar\") # loading the local bar.gb\n\nclass Foo\n def self.bar(x)\n Bar.foo do |ten|\n x * ten\n end\n end\n\n def self.baz\n yield(100)\n end\nend\n
\n\ndef
, true
, false
, nil
, if
, elsif
, else
, case
, when
, return
, self
, end
, while
, do
, yield
, get_block
, next
, class
, module
, break
\"double quote\"\n'single quote'\n
\n\nDouble and single quotation can be used.
\n\n:symbol # equivalent to \"symbol\"\n{ symbol: \"value\" }\n
\n\nGoby’s symbol (using :
) is always String
class.
year = 2018 # Integer\noffset = -42 # Integer\nPI = 3.14 # Float\nG = -9.8 # Float\n
\n\n[1, 2, 3, \"hello\", :goby, { key: \"value\"}]\n[1, 2, [3, 4], 5, 6]\n
\n\nh = { key: \"value\", key2: \"value2\" }\nh[:key2] #=> value2\n
\n\nHash literal’s keys should always be symbol literals.
\n\n(1..10).each do |x| # '..' represents a range\n puts x*x\nend\n
\n\nnil
true # Boolean class\nfalse # Boolean class\nnil # Null class\n\n!nil #=> true\n
\n\nAny objects except nil
and false
will be treated as true
on conditionals.
+ # unary\n** # power\n- # unary\n* / % # multiplication, division, modulus\n+ - # addition, subtraction\n! # logical inversion\n> >= < <= # inequality comparison\n== != # equality comparison, negative comparison\n&& # logical AND\n|| # logical OR\n+= -= # shorthand of addition/subtraction\n= # assignment\n
\n\n*Priority of operators are TBD
\n\n() # chaning priority of interpretation\n[] # array literal\n* # multiple assignment\n.. # range\n
\n\n*Priority of operators are TBD
\n\nclass Foo; end # ';' to delimit\n\nclass Bar end # recommended\n
\n\nputs \"Error: #{error_message}\" # double quotation is required\n
\n\nputs \"Goby\" # comments\n
\n\nUse the annotations to keep the comments concise.
\n\nTODO
FIXME
OPTIMIZE
HACK
REVIEW
#puts
special constants: ARGV
, STDIN
, STDOUT
, STDERR
, ENV
if
, else
, elsif
def foo(str)\n if str.size > 10\n puts \"too big!\"\n elsif str.size < 3\n puts \"too short!\"\n else\n puts \"moderate\"\n end\nend\n
\n\nthen
is not supported.
def foo(tail)\n (5..tail).each do |t|\n if t % 2 == 0 && t % 5 == 0\n puts \"ouch!\"\n break # finish the block\n else\n puts t\n end\n end\n puts \"out of the block\"\nend\n\nfoo 20\n#=> 5 6 7 8 9\n#=> ouch!\n#=> out of the block\n
\n\ndef foo(str)\n case str\n when \"Elf\"\n puts \"You might be Aragorn II!\"\n when \"Aragorn\"\n puts \"Long time no see, Aragorn!\"\n when \"Frodo\", \"Sam\", \"Gandalf\"\n puts \"One of us!\"\n else\n puts \"You're not yourself\"\n end\nend\n
\n\ndecr = 10\nwhile decr do\n if decr < 1\n break\n end\n puts decr\n decr -= 1\nend\n
\n\nwhile
, conditional and a do
/end
block can be used for a loop.
Under construction. Join #605.
\n\ndef foo(ary: [1, 2, 3])\n ary.each do |s| # start of the block with |block variable|\n puts s\n end # end of the block\nend\n
\n\n{ }
cannot be used for forming a block.
yield
def foo\n yield(10) # executes the block given\nend\n\nfoo do |ten|\n ten + 20\nend\n
\n\ncall
b = Block.new do\n 100\nend\n\nb.call #=> 100\n
\n\nBlock.new
can take a block and then call
.
def baz\n 1000\nend\n\nclass Foo\n def exec_block(block)\n\tblock.call\n end\n\n def baz\n 100\n end\nend\n\nb = Block.new do\n baz\nend\n\nf = Foo.new\nf.exec_block(b)\n
\n\nb = Block.new do |arg, offset|\n arg + 1000 - offset\nend\n\nb.call(49, 500) #=> 549\n
\n\nget_block
keyworddef bar(block)\n # runs the block object and the block arg simultaneously\n block.call + get_block.call\nend\n\ndef foo\n bar(get_block) do # passes two blocks to `bar`\n 20\n end\nend\n\nfoo do\n 10\nend\n
\n\nget_block
is not a method but a keyword to retrive a given block argument as a block object. By this, you can pass around or call
the given block arguments as block objects.
count = 0 # the declaration is used\nb = Block.new do\n count += 1 # the block looks preserving the `count`\nend\n\nclass Foo\n def bar(blk)\n count = 9 # (does not affect)\n puts blk.call # local variable is resolved to the one above\n end\nend\n\nFoo.new.bar b #=> 1\nFoo.new.bar b #=> 2\nFoo.new.bar b #=> 3\n
\n\nGoby’s most “native” classes cannot instantiate with new
in principle.
Object
Bar.ancestors\n#» [Bar, Foo, Object]\nBar.singleton_class.ancestors\n#» [#<Class:Bar>, #<Class:Object>, Class, Object]\n
\n\nObject
is actually just for creating singleton classes. See Class
.
Object.methods
: !
, !=
, ==
, block_given?
, class
, exit
, instance_eval
, instance_variable_get
, instance_variable_set
, is_a?
, methods
, nil?
, object_id
, puts
, raise
, require
, require_relative
, send
, singleton_class
, sleep
, thread
, to_s
, <
, <=
, >
, >=
, ancestors
, attr_accessor
, attr_reader
, attr_writer
, extend
, include
, name
, new
, superclass
Object.new.methods
: !
, !=
, ==
, block_given?
, class
, exit
, instance_eval
, instance_variable_get
, instance_variable_set
, is_a?
, methods
, nil?
, object_id
, puts
, raise
, require
, require_relative
, send
, singleton_class
, sleep
, thread
, to_s
Class
String.ancestors #=> [String, Object]\n
\n\nClass
and Object
can actually be regarded as the same and you don’t need to distinguish them in almost all the cases.
Class.methods
: <
, <=
, >
, >=
, ancestors
, attr_accessor
, attr_reader
, attr_writer
, extend
, include
, name
, new
, superclass
, !
, !=
, ==
, block_given?
, class
, exit
, instance_eval
, instance_variable_get
, instance_variable_set
, is_a?
, methods
, nil?
, object_id
, puts
, raise
, require
, require_relative
, send
, singleton_class
, sleep
, thread
, to_s
String
puts \"Hello\" + ' ' + 'world' #=> Hello world\n
\n\nFixed to UTF-8 with mb4 support.
\n\nString.methods
: fmt
,\n Class.methods
\"a\".methods
: !=
, *
, +
, <
, <=>
, ==
, =~
, >
, []
, []=
, capitalize
, chop
, concat
, count
, delete
, downcase
, each_byte
, each_char
, each_line
, empty?
, end_with?
, eql?
, fmt
, include?
, insert
, length
, ljust
, match
, new
, replace
, replace_once
, reverse
, rjust
, size
, slice
, split
, start_with
, strip
, to_a
, to_bytes
, to_d
, to_f
, to_i
, to_s
, upcase
,\n Object.new.methods
Integer
37037 * 27 #=> 999999\n
\n\nInteger.methods
: the same as Class.methods
1.methods
: !=
, %
, *
, **
, +
, -
, /
, <
, <=
, <=>
, ==
, >
, >=
, even?
, new
, next
, odd?
, pred
, ptr
, times
, to_f
, to_float32
, to_float64
, to_i
, to_int
, to_int16
, to_int32
, to_int64
, to_int8
, to_s
, to_uint
, to_uint16
, to_uint32
, to_uint64
, to_uint8
\n Object.new.methods
Array
[1, \"2\", :card, [4, 5], { john: \"doe\" }]\n
\n\nArray.methods
: the same as Class.methods
[1].methods
: *
, +
, []
, []=
, any?
, at
, clear
, concat
, count
, delete_at
, dig
, each
, each_index
, empty?
, first
, flatten
, include?
, join
, last
, lazy
, length
, map
, new
, pop
, push
, reduce
, reverse
, reverse_each
, rotate
, select
, shift
, to_enum
, unshift
, values_at
\n Object.new.methods
Hash
h = { key: \"value\" }\nh = { \"key\": \"value\" } #=> error\n\nh[\"key\"] #=> value\nh[:key] #=> value\n
\n\nKeys in hash literals should be symbol literals, while Hash index can be either string or symbol literals.
\n\nHash.methods
: the same as Class.methods
{ key: \"value\" }.methods
: []
, []=
, any?
, clear
, default
, default=
, delete
, delete_if
, dig
, each
, each_key
, each_value
, empty?
, eql?
, fetch
, fetch_values
, has_key?
, has_value?
, keys
, length
, map_values
, merge
, new
, select
, sorted_keys
, to_a
, to_json
, to_s
, transform_values
, values
, values_at
\n Object.new.methods
Range
(1..10).each do |i|\n puts i ** 2\nend\n
\n\nRange.methods
: the same as Class.methods
(1..10).methods
: !=
, ==
, bsearch
, each
, first
, include?
, last
, lazy
, map
, new
, size
, step
, to_a
, to_enum
\n Object.new.methods
Block
b = Block.new do\n 100\nend\n\nb.call #=> 100\n
\n\nBlock.methods
: the same as Class.methods
(Block.new do end).methods
: call
\n Object.new.methods
Float
1.1 + 1.1 # => -2.2\n2.1 * -2.1 # => -4.41\n
\n\nFloat literals like 3.14
or -273.15
. Float
class is based on Golang’s float64
type.
Float.methods
: the same as Class.methods
3.14.methods
: !=
, %
, *
, **
, +
, -
, /
, <
, <=
, <=>
, ==
, >
, >=
, new
, ptr
, to_d
, to_i
\n Object.new.methods
Decimal
\"3.14\".to_d # => 3.14\n\"-0.7238943\".to_d # => -0.7238943\n\"355/113\".to_d \n# => 3.1415929203539823008849557522123893805309734513274336283185840\n\na = \"16.1\".to_d\nb = \"1.1\".to_d\ne = \"17.2\".to_d\na + b # => 0.1\na + b == e # => true\n\n('16.1'.to_d + \"1.1\".to_d).to_s #=> 17.2\n('16.1'.to_f + \"1.1\".to_f).to_s #=> 17.200000000000003\n
\n\nExperimental: the size is arbitrary and internally a fraction from Golang’s big.Rat
type. Decimal literal is TBD for now and you can get Decimal
number via to_d
method from Integer
/Float
/String
.
Decimal.methods
: the same as Class.methods
(1.1).to_d.methods
: !=
, *
, **
, +
, -
, /
, <
, <=
, <=>
, ==
, >
, >=
, denominator
, fraction
, inverse
\n Object.new.methods
Regexp
a = Regexp.new(\"orl\")\na.match?(\"Hello World\") #=> true\na.match?(\"Hello Regexp\") #=> false\n\nb = Regexp.new(\"😏\")\nb.match?(\"🤡 😏 😐\") #=> true\nb.match?(\"😝 😍 😊\") #=> false\n\nc = Regexp.new(\"居(ら(?=れ)|さ(?=せ)|る|ろ|れ(?=[ばる])|よ|(?=な[いかくけそ]|ま[しすせ]|そう|た|て))\")\nc.match?(\"居られればいいのに\") #=> true\nc.match?(\"居ずまいを正す\") #=> false\n
\n\nUsing / /
is to be implemented.
Regexp.methods
: the same as Class.methods
Regexp.new(\"^aa$\").methods
: ==
, match?
\n Object.new.methods
MatchData
# numbered capture\n'abcd'.match(Regexp.new('(b.)'))\n#=> #<MatchData 0:\"bc\" 1:\"bc\">\n\n# named capture\n'abcd'.match(Regexp.new('a(?<first>b)(?<second>c)'))\n#=> #<MatchData 0:\"abc\" first:\"b\" second:\"c\">\n\n# converting to hash\n» 'abcd'.match(Regexp.new('a(?<first>b)(?<second>c)')).to_h\n#» { 0: \"abc\", first: \"b\", second: \"c\" }\n
\n\nThe number keys in the captures are actually String
class.The key 0
is the mached string.
MatchData.methods
: the same as Class.methods
'abcd'.match(Regexp.new('(b.)')).methods
: captures
, length
, new
, to_a
, to_h
\n Object.new.methods
File
f = File.new(\"../test_fixtures/file_test/size.gb\")\nf.name #=> \"../test_fixtures/file_test/size.gb\"\n
\n\nFile.methods
: basename
, chmod
, delete
, exist?
, extname
, join
\n Class.methods
File.new.methods
: basename
, chmod
, close
, delete
, exist?
, extname
, join
, name
\n Object.new.methods
GoMap
h = { foo: \"bar\" }\nm = GoMap.new(h) # to pass values to Golang's code\nh2 = m.to_hash\nh2[:foo] #=> \"bar\"\n
\n\nGoMap.methods
: the same as Class.methods
GoMap.new.methods
: get
, set
, to_hash
\n Object.new.methods
Channel
c = Channel.new\n\n1001.times do |i| # i start from 0 to 1000\n thread do\n \tc.deliver(i)\n end\nend\n\nr = 0\n1001.times do\n r = r + c.receive\nend\n\nr #=> 500500\n
\n\nChannel
class is to hold channels to work with #thread
. See thread
.
Channel.methods
: the same as Class.methods
Channel.new.methods
: close
, deliver
, new
, receive
\n Object.new.methods
Pretty new experimental library.
\n\nLazyEnumerator
# creating a lazy enumerator\nenumerator = LazyEnumerator.new(ArrayEnumerator.new([1, 2, 3])) do |value|\n\t2 * value\nend\nresult = []\n\nenumerator.each do |value|\n\tresult.push(value)\nend\n\nresult #=> [2, 4, 6]\n
\n\nA shorthand #lazy
method is also provided in Array
and Range
by now. See “Tips & tricks” below.
LazyEnumerator.methods
: the same as Class.methods
[1, 2].lazy
: each
, first
, has_next?
, initialize
, map
, next
\n Object.new.methods
ArrayEnumerator
iterated_values = []\n\nenumerator = ArrayEnumerator.new([1, 2, 4])\n\nwhile enumerator.has_next? do\n\titerated_values.push(enumerator.next)\nend\n\niterated_values #=> [1, 2, 4]\n
\n\nArrayEnumerator.methods
: the same as Class.methods
ArrayEnumerator.new([1, 2, 3]).methods
: has_next?
, initialize
, next
\n Object.new.methods
RangeEnumerator
iterated_values = []\n\nenumerator = RangeEnumerator.new((1..4))\n\nwhile enumerator.has_next? do\n\titerated_values.push(enumerator.next)\nend\n\niterated_values #=> [1, 2, 3, 4]\n
\n\nRangeEnumerator.methods
: the same as Class.methods
RangeEnumerator.new(1..2).methods
: has_next?
, initialize
, next
\n Object.new.methods
Boolean
true.class #=> Boolean\nfalse.class #=> Boolean\n
\n\nA special class that just to hold true
and false
. Cannot be instantiate.
Null
nil.class #=> Null\n
\n\nA special class that just to hold nil
. Cannot be instantiate.
Method
(A special dummy class that just holds methods defined by Goby code.)
\n\nDiggable
Provides #dig
method. Currently. Array
and Hash
classes’ instance can be Diggable
.
[1, 2].dig(0, 1) #=> TypeError: Expect target to be Diggable, got Integer\n
\n\nSpec
require \"spec\"\n\nSpec.describe Spec do\n it \"fails and exit with code 1\" do\n\texpect(1).to eq(2)\n end\nend\n\nSpec.run\n
\n\nSpec.methods
: describe
, describes
, instance
, run
\n Object.methods
Spec.new.methods
: describes
, initialize
, run
, session_successful
, session_successful=
\n Hash.new.methods
» \"string\".methods\n#» [\"!=\", \"*\", \"+\", \"<\", \"<=>\", \"==\", \"=~\", \">\", \"[]\", \"[]=\", \"capitalize\", \"chop\", \"concat\", \"count\", \"delete\", \"downcase\", \"each_byte\", \"each_char\", \"each_line\", \"empty?\", \"end_with?\", \"eql?\", \"fmt\", \"include?\", \"insert\", \"length\", \"ljust\", \"match\", \"new\", \"replace\", \"replace_once\", \"reverse\", \"rjust\", \"size\", \"slice\", \"split\", \"start_with\", \"strip\", \"to_a\", \"to_bytes\", \"to_d\", \"to_f\", \"to_i\", \"to_s\", \"upcase\", \"!\", \"block_given?\", \"class\", \"exit\", \"instance_eval\", \"instance_variable_get\", \"instance_variable_set\", \"is_a?\", \"methods\", \"nil?\", \"object_id\", \"puts\", \"raise\", \"require\", \"require_relative\", \"send\", \"singleton_class\", \"sleep\", \"thread\"]\n
\n\n» \"string\".class\n#» String\n
\n\n» \"moji\".singleton_class\n#» #<Class:#<String:842352325152>>\n\n» \"moji\".class.singleton_class\n#» #<Class:String>\n
\n\n» Integer.ancestors\n#» [Integer, Object]\n\n» \"moji\".class.ancestors\n#» [String, Object]\n
\n\n» \"moji\".class.singleton_class.ancestors\n#» [#<Class:String>, #<Class:Object>, Class, Object]\n
\n\n» \"moji\".object_id\n#» 842352977920\n
\n\n#to_json
h = { a: 1, b: [1, \"2\", [4, 5, nil]]}\nh.to_json # converts hash to JSON\n#=> {\"a\":1, \"b\":[1, \"2\", [4, 5, null]]}\n
\n\n#to_json
Overwrite the #to_json
in your class:
class JobTitle\n def initialize(name)\n @name = name\n end\n\n def to_json\n { title: @name }.to_json\n end\nend\n\nclass Person\n def initialize(name, age)\n @name = name\n @age = age\n @job = JobTitle.new(\"software engineer\")\n end\n\n def to_json\n { name: @name, age: @age, job: @job }.to_json\n end\nend\n\nstan = Person.new(\"Stan\", 23)\nh = { person: stan }\nh.to_json #=> {\"person\":{\"name\":\"Stan\",\"job\":{\"title\":\"software engineer\"},\"age\":23}}\n
\n\nTo avoid N + 1 query.
\n\nenumerator = [1, 2, 3].lazy.map do |value|\n\t2 * value\nend\nresult = []\n\nenumerator.each do |value|\n\tresult.push(value)\nend\n\nresult #=> [2, 4, 6]\n
\n\nYou can call #lazy.map
on Array
, Range
, or JSON
objects.
Class#instance_method
– use #
to represent instance methods in documentsClass.class_method
Module.module_method
Ready for Vim and Sublime text. You can also use Ruby’s syntax highlighting so far.
\n\nGoby’s language design is based on Ruby language’s, slim and shaped up. Differences in syntax between them is very small.
", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "google-webfonts", "title": "Google Webfonts", "url": "/google-webfonts", "category": "Others", "keywords": null, "content_html": "<link href=\"http://fonts.googleapis.com/css?family=Open+Sans\" rel=\"stylesheet\" type=\"text/css\" />\n
\n\n/* One font */\n@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');\n\n/* Combining multiple fonts */\n@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,400italic|Montserrat:400,700'');\n
\n\nGreat for using with Codepen.io or similar websites!
", "intro_html": "Short snippets on using Google Webfonts in a web page.
", "description_html": "", "tags": null, "updated": null },{ "id": "google_analytics", "title": "Google Analytics", "url": "/google_analytics", "category": "Others", "keywords": null, "content_html": "// Analytics.js\nga('create', 'UA-XXXX-Y', 'auto');\nga('send', 'pageview');\n
\n\n// ga.js\n// [..., category, action, label, value (int), noninteraction (bool)]\n_gaq.push(['_trackEvent', 'Videos', 'Play', 'Birthday video', true])\n_gaq.push(['_trackEvent', 'Projects', 'Donate', 'Project name'])\n_gaq.push(['_trackEvent', 'Accounts', 'Login'])\n\n// Analytics.js\n// , , category, action, label, value (int)\nga('send', 'event', 'button', 'click', 'nav buttons', 4);\n
\n\n// [..., index, name, value, scope (optional)]\n_gaq.push(['_setCustomVar', 1, 'Logged in', 'Yes', 2]);\n\n// Scope = 1 (visitor), 2 (session), 3 (page, default)\n
\n\nhttps://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables\nhttps://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "graphql", "title": "GraphQL", "url": "/graphql", "category": "API", "keywords": null, "content_html": "{ status }\n
\n\n{ status: 'available' }\n
\n\n{ hero { name height } }\n
\n\n{ hero:\n { name: \"Luke Skywalker\",\n height: 1.74 } }\n
\n\n{ friends { name } }\n
\n\n{ friends:\n [ { name: \"Luke Skywalker\" },\n { name: \"Han Solo\" },\n { name: \"R2D2\" } ] }\n
\n\nGraphQL queries look the same for both single items or lists of items.
\n\n{\n hero(id: \"1000\") { id name }\n}\n
\n\n{ hero:\n { id: \"1000\",\n { name: \"Luke Skywalker\" } }\n
\n\n{\n luke: hero(id: \"1000\") { name }\n han: hero(id: \"1001\") { name }\n}\n
\n\n{ luke:\n { name: \"Luke Skywalker\" },\n han:\n { name: \"Han Solo\" } }\n
\n\nquery FindHero($id: String!) {\n hero(id: $id) { name }\n}\n
\n\nJust to make things less ambiguous. Also, to use variables, you need an operation name.
\n\n{ id: '1000' }\n
\n\n{ createReview($review) { id } }\n
\n\n{ review: { stars: 5 } }\n
\n\n{ createReview: { id: 5291 } }\n
\n\nMutations are just fields that do something when queried.
\n\n{\n search(q: \"john\") {\n id\n ... on User { name }\n ... on Comment { body author { name } }\n }\n}\n
\n\nGreat for searching.
\n\nfetch('http://myapi/graphql?query={ me { name } }')\n
\n\nfetch('http://myapi/graphql', {\n body: JSON.stringify({\n query: '...',\n operationName: '...',\n variables: { ... }\n })\n})\n
\n\ntype Query {\n me: User\n users(limit: Int): [User]\n}\n\ntype User {\n id: ID!\n name: String\n}\n
\n\nSee: sogko/graphql-shorthand-notation-cheat-sheet
\n\nInt | \n Integer | \n
Float | \n Float | \n
String | \n String | \n
Boolean | \n Boolean | \n
ID | \n ID | \n
scalar | \n Scalar type | \n
type | \n Object type | \n
interface | \n Interface type | \n
union | \n Union type | \n
enum | \n Enumerable type | \n
input | \n Input object type | \n
String | \n Nullable string | \n
String! | \n Required string | \n
[String] | \n List of strings | \n
[String]! | \n Required list of strings | \n
[String!]! | \n Required list of required strings | \n
type Mutation {\n users(params: ListUsersInput) [User]!\n}\n
\n\ninterface Entity {\n id: ID!\n}\n\ntype User implements Entity {\n id: ID!\n name: String\n}\n
\n\nenum DIRECTION {\n LEFT\n RIGHT\n}\n\ntype Root {\n direction: DIRECTION!\n}\n
\n\ntype Artist { ··· }\ntype Album { ··· }\n\nunion Result = Artist | Album\n\ntype Query {\n search(q: String) [Result]\n}\n
\n\n<script src='https://cdn.jsdelivr.net/npm/gremlins/dist/gremlins.js'></script>\n<script>\ngremlins.createHorde().unleash()\n</script>\n
\n\ngremlins.createHorde()\n .allGremlins()\n .gremlin(function () {\n document.activeElement.blur()\n })\n
\n\nRuns the given function at regular intervals.
\n\ngremlins.createHorde()\n .gremlin(gremlins.species.formFiller())\n .gremlin(gremlins.species.clicker()\n .clickTypes(['click'])\n .canClick(element => { ··· })\n .showAction((x, y) => { ··· }))\n .gremlin(gremlins.species.scroller())\n .mogwai(gremlins.mogwais.alert())\n .mogwai(gremlins.mogwais.fps())\n .mogwai(gremlins.mogwais.gizmo().maxErrors(2))\n .unleash()\n
\n\nBy default, all gremlins and mogwais species are added to the horde. Do it this way to customize gremlins.
\n\nSee: Specifying gremlins
\n\ngremlins.createHorde()\n .before(function () {\n this.log('sync')\n console.profile('gremlins')\n })\n .after(function () {\n this.log('done')\n console.profileEnd()\n })\n
\n\ngremlins.createHorde()\n .before(function (done) {\n setTimeout(() => {\n this.log('async')\n done()\n }, 500)\n })\n
\n\nGremlins is a JavaScript library to do “monkey-testing” by providing random user input (clicks, scrolls, and so on).
", "description_html": "", "tags": null, "updated": "2017-10-22" },{ "id": "gulp", "title": "Gulp", "url": "/gulp", "category": "JavaScript libraries", "keywords": null, "content_html": "gulp-notify
\n// gulpfile.js\n// Load plugins\nvar gulp = require('gulp'),\n sass = require('gulp-ruby-sass'),\n autoprefixer = require('gulp-autoprefixer'),\n minifycss = require('gulp-minify-css'),\n jshint = require('gulp-jshint'),\n uglify = require('gulp-uglify'),\n imagemin = require('gulp-imagemin'),\n rename = require('gulp-rename'),\n clean = require('gulp-clean'),\n concat = require('gulp-concat'),\n notify = require('gulp-notify'),\n cache = require('gulp-cache'),\n livereload = require('gulp-livereload'),\n lr = require('tiny-lr'),\n server = lr();\n\n// Styles\ngulp.task('styles', function() {\n return gulp.src('src/styles/main.scss')\n .pipe(sass({ style: 'expanded', }))\n .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))\n .pipe(gulp.dest('dist/styles'))\n .pipe(rename({ suffix: '.min' }))\n .pipe(minifycss())\n .pipe(livereload(server))\n .pipe(gulp.dest('dist/styles'))\n .pipe(notify({ message: 'Styles task complete' }));\n});\n\n// Scripts\ngulp.task('scripts', function() {\n return gulp.src('src/scripts/**/*.js')\n .pipe(jshint('.jshintrc'))\n .pipe(jshint.reporter('default'))\n .pipe(concat('main.js'))\n .pipe(gulp.dest('dist/scripts'))\n .pipe(rename({ suffix: '.min' }))\n .pipe(uglify())\n .pipe(livereload(server))\n .pipe(gulp.dest('dist/scripts'))\n .pipe(notify({ message: 'Scripts task complete' }));\n});\n\n// Images\ngulp.task('images', function() {\n return gulp.src('src/images/**/*')\n .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))\n .pipe(livereload(server))\n .pipe(gulp.dest('dist/images'))\n .pipe(notify({ message: 'Images task complete' }));\n});\n\n// Clean\ngulp.task('clean', function() {\n return gulp.src(['dist/styles', 'dist/scripts', 'dist/images'], {read: false})\n .pipe(clean());\n});\n\n// Default task\ngulp.task('default', ['clean'], function() {\n gulp.start('styles', 'scripts', 'images');\n});\n\n// Watch\ngulp.task('watch', function() {\n\n // Listen on port 35729\n server.listen(35729, function (err) {\n if (err) {\n return console.log(err)\n };\n\n // Watch .scss files\n gulp.watch('src/styles/**/*.scss', ['styles']);\n\n // Watch .js files\n gulp.watch('src/scripts/**/*.js', ['scripts']);\n\n // Watch image files\n gulp.watch('src/images/**/*', ['images']);\n\n });\n\n});\n
\n\nhttps://github.com/gulpjs/gulp/blob/master/docs/getting-started.md#getting-started
\n\nvar lr = require('tiny-lr')();\n\nfunction notify (lr, root) {\n return function (event) {\n var fname = require('path').relative(root, event.path);\n lr.changed({ body: { files: [ fname ] }});\n };\n}\n\ngulp.task('livereload', function () {\n lr.listen(35729)\n gulp.watch('public/**/*', notify(lr, __dirname+'/public'));\n});\n\n// Express\napp.use(require('connect-livereload')())\n<!-- livereload --><script>document.write('<script src=\"'+(location.protocol||'http:')+'//'+(location.hostname||'localhost')+':35729/livereload.js?snipver=1\"><\\/scr'+'ipt>')</script>\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "haml",
"title": "Haml",
"url": "/haml",
"category": "Markup",
"keywords": null,
"content_html": "!!! 5\n
\n\n%html\n %head\n %title\n %body\n %h1 Hello World\n %br/\n
\n\n%p.class-example\n.no-tag-defaults-to-div\n%div#butItCanBeIncluded\n
\n\nEither hash syntax works
\n\n%meta{ name: \"viewport\", content: \"width=device-width, initial-scale=1.0\" }\n%input{ :type => \"text\", :required => true }\n
\n\n-# This is a comment\n-# Anything starting with a hyphen signals to Haml that Ruby is coming\n- @arr = [1, 2, 3]\n- @str = \"test\"\n-# Equal signals output\n= render partial: \"shared/header\"\n= yield\n= link_to page_url\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "handlebars.js",
"title": "Handlebars.js",
"url": "/handlebars.js",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "Handlebars.registerHelper('link_to', function() {\n return \"<a href='\" + this.url + \"'>\" + this.body + \"</a>\";\n})\n
\n\nvar context = { posts: [{url: \"/hello-world\", body: \"Hello World!\"}] }\nvar source = \"<ul>{{#posts}}<li>{{{link_to}}}</li>{{/posts}}</ul>\"\n
\n\nvar template = Handlebars.compile(source)\ntemplate(context)\n
\n\nWould render:
\n\n<ul>\n <li><a href='/hello-world'>Hello World!</a></li>\n</ul>\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "harvey.js",
"title": "Harvey.js",
"url": "/harvey.js",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "Harvey.attach('(min-width: 600px)', {\n setup: function () {\n // Called on first enter\n },\n on: function () {\n // Called on every enter\n },\n off: function () {\n // Called on every exit\n }\n})\n
\n\nHarvey.js hasn’t been updated in a while, as of time of writing. Consider enquire.js instead.
\n\nHarvey.js helps you build responsive interfaces.
", "description_html": "", "tags": null, "updated": null },{ "id": "heroku", "title": "Heroku", "url": "/heroku", "category": "Devops", "keywords": null, "content_html": "create
- Create an appheroku create sushi\n
\n\ngit push heroku master\n
\n\naccess
- Collaborationheroku access # List\nheroku access:add me@xy.com\nheroku access:remove me@xy.com\n
\n\nheroku apps:transfer new@owner.com\n
\n\nlogs
- Show logsheroku logs\nheroku logs -t # --tail (stream)\nheroku logs -s app # --source (only on app logs)\n
\n\nreleases
heroku releases\nheroku releases:info v25\nheroku rollback\n
\n\npg
- PostgreSQLheroku addons:add heroku-postgresql\n
\n\nheroku addons:add pgbackups:auto-month\n
\n\nSee: Heroku PostgreSQL (devcenter.heroku.com)
\n\nconfig
- Environment var configurationheroku config # List\nheroku config -s # List in shell format\n
\n\nheroku config:get KEY\n
\n\nheroku config:set KEY=val\nheroku config:set KEY1=val KEY2=val ...\n
\n\nheroku config:unset KEY1\n
\n\napps
- Applicationsheroku apps # list\nheroku apps:create [NAME]\nheroku apps:destroy --app APP\nheroku apps:info\nheroku apps:open # open in browser\nheroku apps:rename NEWNAME\n
\n\nmaintenance
heroku maintenance:on\n
\n\nheroku maintenance:off\n
\n\nps
- Managing processesheroku ps # list\nheroku ps:scale web=1 # spawn more dynos\n
\n\nrestart
heroku restart\n
\n\nrun
- Running tasksheroku run bash\nheroku run console # Rails console\nheroku run rake assets:precompile\n
\n\ndomains
- Custom domainsheroku domains:add example.com\nheroku domains:add www.example.com\n
\n\nheroku domains:clear\nheroku domains:remove example.com\n
\n\nSee: Custom domains (devcenter.heroku.com)
\n\nheroku addons:add wildcard_domains\n
\n\n*.yourdomain.com => heroku.com\n
\n\nCreate an .htaccess
file in the webroot:
AuthUserFile /app/www/.htpasswd\nAuthType Basic\nAuthName \"Restricted Access\"\nRequire valid-user\n
\n\nCreate a .htpasswd
file:
$ htpasswd -c .htpasswd [username]\n
\n\nSee: gist.github.com
\n\nHeroku is a web hosting platform supporting many languages, and this guide is a reference to Heroku’s command-line interface.
", "description_html": "A one-page reference to common Heroku-CLI commands.
", "tags": null, "updated": "2017-10-11" },{ "id": "hledger", "title": "Hledger", "url": "/hledger", "category": "Ledger", "keywords": null, "content_html": "hledger bal {query}\nhledger reg {query}\n
\n\nQueries are used on all commands (bal
, reg
, etc). (docs)
Assets # An account (regex)\nacct:Assets # same\n^Assets # Starting with Assets (eg, not 'Expenses:Assets')\n\nacctonly:A # no subaccounts\n\namt:2000 # amount (in absolute value)\namt:<200 # amount comparison (in absolute value)\namt:<+200 # amount comparison\n # also: <=, >, >=\n\ndesc:REGEX # description\ncode:REGEX # transaction code (check number?)\ntag:REGEX\ncur:'\\$'\n\nreal: # real posts\nreal:0 # virtual posts\n\ndepth:N # --depth 2\nnot:... # eg, not:status:!\n
\n\nreal:1 # -R, --real, no virtuals\nstatus:! # --pending\nstatus:* # -C, --cleared\nstatus: # --uncleared\n
\n\nFor dates and intervals (see above).
\n\ndate:2015/01/01\ndate:2015/01/01- # -b, --begin\ndate:-2015/01/01 # -e, --end\ndate2:PERIODEXPR\n
\n\n-p, --period=...\n -p \"2009/01/01\"\n -p \"2009/01/01 to 2009/12/31\"\n -p \"2009/01/01to2009/12/31\" # spaces optional\n -p \"1/1 to 12/31\"\n -p \"to 2009\"\n -p \"weekly\" # -W, --weekly\n -p \"weekly 2009/01/01 to 2009/12/31\"\n
\n\nUsed on all commands (bal
, reg
, etc). Displays in multi-column mode. In ledger-cli
, only reg
is supported. Can also specified via -p
(period).
-D, --daily\n-W, --weekly\n-M, --monthly\n-Q, --quarterly\n-Y, --yearly\n
\n\nUsed for --period
, --begin
and --end
(-p
-b
-e
).
-p 2015/01/01\n-p 2015/01\n-p 2015\n-p january\n-p jan\n-p 05/25\n
\n\n-b today\n-b yesterday\n-e tomorrow\n
\n\n-p this week\n-p last month\n-p this year\n
\n\n --tree # only in bal\n --flat\n\n --depth 2 # collapse those under this depth\n --drop 1 # drop top-level accounts\n-B, --cost # convert to default currency\n-E, --empty # don't strip out $0 accounts\n --date2 # use date2 when available\n
\n\nWhen used with intervals (like --weekly
):
-T, --row-total\n-N, --no-total\n
\n\nAlso: (only in bal
)
--cumulative # show ending balance per period\n-I, --historical # like --cumulative but only for --begin\n-A, --average\n
\n\nhledger accounts [--tree]\n
\n\nhledger balancesheet # bs\nhledger incomestatement # is\nhledger cashflow # cf\nhledger print\nhledger activity\nhledger stats\n
\n\n# Current balance\n hledger bal Assets\n hledger balancesheet\n\n hledger balancesheet Assets [--cleared --cost --empty -e tomorrow]\n # ...discard future stuff; convert foreign currencies\n\n# Monthly changes in assets\n hledger bal Assets Liabilities --monthly --tree --historical [--cleared --cost --empty -e tomorrow]\n\n# Weekly expenses\n hledger bal Expenses --weekly --average --tree -b 'last month' [--cleared --cost --empty -e tomorrow]\n
\n\nCommand | \nDescription | \n
---|---|
brew install git | \n Install a package | \n
brew uninstall git | \n Remove/Uninstall a package | \n
brew upgrade git | \n Upgrade a package | \n
brew unlink git | \n Unlink | \n
brew link git | \n Link | \n
brew switch git 2.5.0 | \n Change versions | \n
brew list --versions git | \n See what versions you have | \n
Command | \nDescription | \n
---|---|
brew info git | \n List versions, caveats, etc | \n
brew cleanup git | \n Remove old versions | \n
brew edit git | \n Edit this formula | \n
brew cat git | \n Print this formula | \n
brew home git | \n Open homepage | \n
brew search git | \n Search for formulas | \n
Command | \nDescription | \n
---|---|
brew update | \n Update brew and cask | \n
brew upgrade | \n Upgrade all packages | \n
brew list | \n List installed | \n
brew outdated | \n What’s due for upgrades? | \n
brew doctor | \n Diagnose brew issues | \n
Command | \nDescription | \n
---|---|
brew cask install firefox | \n Install the Firefox browser | \n
brew cask list | \n List installed applications | \n
Cask commands are used for interacting with graphical applications.
\n\nProperty | \nWhere | \n
---|---|
position | \n (Outlook, Gmail, Yahoo) | \n
display | \n (Outlook, Gmail) | \n
float | \n (Outlook) | \n
height | \n (Outlook) | \n
width in p/div | \n (Outlook) | \n
padding in p/div | \n (Outlook) | \n
background | \n (Outlook, Gmail) | \n
min-width | \n (Outlook) | \n
max-width | \n (Outlook) | \n
opacity | \n (Outlook, Gmail, Yahoo) | \n
box-shadow | \n (Outlook, Gmail, Yahoo) | \n
rgba() | \n (Outlook) | \n
data-uri | \n (all webmail) | \n
E[attr] | \n (Outlook, Gmail) | \n
E:nth-child(n) | \n (Outlook, Gmail) | \n
::before and ::after | \n (Outlook, Yahoo, Gmail) | \n
E F | \n (Gmail) | \n
E + F , E > F etc | \n (Outlook, Gmail) | \n
Inline your CSS as much as possible.
\n\n<table cellpadding=\"0\" cellspacing=\"0\">\n <tr>\n <td width=\"auto\"></td>\n <td width=\"600\" background=\"#ffffff\">\n ···\n </td>\n <td width=\"auto\"></td>\n </tr>\n</table>\n
\n\n<style>\n@media only screen and (max-device-width: 480px)\n</style>\n
\n\n<style>
is supported in the head and body by everything except Gmail. Only use them for responsive styles.
<input ...\n disabled\n required\n checked\n
\n\n autofocus\n
\n\n autocomplete='off' <!-- autocomplete -->\n autocompletetype='cc-exp'\n autocapitalize='off' <!-- for mobiles -->\n pattern='\\d*' <!-- force numeric input in iOS -->\n
\n\nType | \nExample | \n
---|---|
type='date' | \n \n |
type='time' | \n \n |
Type | \nExample | \n
---|---|
type='datetime' | \n \n |
type='datetime-local' | \n \n |
datetime
and datetime-local
fields are not widely supported.
Type | \nExample | \n
---|---|
type='number' | \n \n |
type='range' | \n \n |
Type | \nExample | \n
---|---|
type='text' | \n \n |
type='password' | \n \n |
type='search' | \n \n |
type='tel' | \n \n |
<meta charset='utf-8'>\n
\n\n<!-- title -->\n<title>···</title>\n<meta property='og:title' content='···'>\n<meta name='twitter:title' content='···'>\n
\n\n<!-- url -->\n<link rel='canonical' href='http://···'>\n<meta property='og:url' content='http://···'>\n<meta name='twitter:url' content='http://···'>\n
\n\n<!-- description -->\n<meta name='description' content='···'>\n<meta property='og:description' content='···'>\n<meta name='twitter:description' content='···'>\n
\n\n<!-- image -->\n<meta property=\"og:image\" content=\"http://···\">\n<meta name=\"twitter:image\" content=\"http://···\">\n
\n\n<!-- ua -->\n<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>\n
\n\n<!-- viewport -->\n<meta name='viewport' content='width=device-width'>\n<meta name='viewport' content='width=1024'>\n
\n\n<meta property='og:site_name' content='···'>\n<meta property='og:type' content='website'>\n
\n\n<meta property='fb:app_id' content='···'>\n<meta property='fb:admins' content='UID1,UID2'>\n<!-- ···unless there's app_id -->\n
\n\n<meta property='og:audio' content='http://···/theme.mp3'>\n<meta property='og:video' content='http://···/trailer.swf'>\n
\n\nSee: OpenGraph protocol (developers.facebook.com)
\n\narticle:published_time
article:modified_time
article:expiration_time
article:author
article:section
article:tag
<meta name='format-detection' content='telephone=no'>\n
\n\n<meta name='mobile-web-app-capable' content='yes'>\n<meta name='apple-mobile-web-app-capable' content='yes'>\n
\n\n<meta name='apple-mobile-web-app-status-bar-style' content='black'>\n<!-- black | black-translucent | default -->\n
\n\n<meta name='theme-color' content='#ff00ff'>\n
\n\nAndroid-only.\nSee: Theme color
\n\n<link rel='manifest' href='/manifest.json'>\n
\n\nAndroid-only.\nSee: Manifest
\n\n<!-- Minimal -->\n<link rel='icon' type='image/png' href='favicon@32.png'>\n<link rel='icon' sizes='192x192' href='icon@192.png'>\n<link rel='apple-touch-icon' href='icon@152.png'>\n<meta name='msapplication-square310x310logo' content='icon@310.png'>\n
\n\n<!-- Apple -->\n<link rel='apple-touch-icon' href='touch-icon-iphone.png'>\n<link rel='apple-touch-icon' sizes='76x76' href='touch-icon-ipad.png'>\n<link rel='apple-touch-icon' sizes='120x120' href='touch-icon-iphone-retina.png'>\n<link rel='apple-touch-icon' sizes='152x152' href='touch-icon-ipad-retina.png'>\n
\n\n<!-- Microsoft -->\n<meta name='msapplication-square70x70logo' content='icon_smalltile.png'>\n<meta name='msapplication-square150x150logo' content='icon_mediumtile.png'>\n<meta name='msapplication-wide310x150logo' content='icon_widetile.png'>\n
\n\nChrome on Android recommends 192x192.\nSee: Icons
\n\n<span class=\"entry-author\" itemprop=\"author\" itemscope=\"itemscope\" itemtype=\"http://schema.org/Person\">\n <a href=\"http://AUTHORPAGE\" class=\"entry-author-link\" itemprop=\"url\" rel=\"author\">\n <span class=\"entry-author-name\" itemprop=\"name\">AUTHORNAME</span>\n </a>\n</span>\n
\n\n<time class=\"entry-time\" itemprop=\"datePublished\" datetime=\"2009-02-09T20:04:00+00:00\">February 9, 2009</time>\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "html-share",
"title": "Share links",
"url": "/html-share",
"category": "HTML",
"keywords": null,
"content_html": "Facebook:
\n\n<a href='https://www.facebook.com/sharer/sharer.php?u=URL' target='share'>\n
\n\nTwitter:
\n\n<a href='https://twitter.com/intent/tweet?text=DESCRIPTION+URL' target='share'>\n
\n\nGoogle Plus:
\n\n<a href='https://plus.google.com/share?url=URL' target='share'>\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2017-09-04"
},{
"id": "html",
"title": "HTML",
"url": "/html",
"category": "HTML",
"keywords": null,
"content_html": "<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/favicon.ico\">\n<link rel=\"shortcut icon\" type=\"image/png\" href=\"/favicon.png\">\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n
\n\n<meta name=\"viewport\" content=\"initial-scale=1.0, maximum-scale=1.0\">\n<meta name=\"viewport\" content=\"width=device-width\">\n<meta name=\"viewport\" content=\"width=320, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\"/> <!-- full example -->\n
\n\n<meta content=\"...\" name=\"description\">\n<meta content=\"...\" property=\"og:description\">\n<meta content=\"http://.../preview.jpg\" property=\"og:image\">\n<meta content=\"Hello There\" property=\"og:title\">\n<meta content=\"Hello There\" property=\"og:site_name\">\n<meta content=\"hellothere\" property=\"fb:admins\">\n<meta content=\"website\" property=\"og:type\">\n
\n\n<script>WebFontConfig={ },function(a,b){var c=a.createElement(b);c.src=\"//ajax.googleapis.com/ajax/libs/webfont/1/webfont.js\",c.async=1;var d=a.getElementsByTagName(b)[0];d.parentNode.insertBefore(c,d)}(document,\"script\")</script>\n\n// {typekit{id:\"...\"}}\n// {google:{families:['Exo:400']}}\n
\n\n<script>location.hostname.match(/helloworld\\.com/)&&(_gaq=[[\"_setAccount\",\"UA-XXXXX-1\"],[\"_trackPageview\"]],function(a,b){var c=a.createElement(b),d=a.getElementsByTagName(b)[0];c.async=1,c.src=(\"https:\"==location.protocol?\"//ssl\":\"//www\")+\".google-analytics.com/ga.js\",d.parentNode.insertBefore(c,d)}(document,\"script\"))</script>\n
\n\n<div id=\"fb-root\"></div><script>fbAsyncInit=function(){FB.init({\"appId\":\"___APPIDGOESHERE___\",\"status\":true,\"cookie\":true,\"xfbml\":true})};!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.async=1;js.src='//connect.facebook.net/en_US/all.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','facebook-jssdk');</script>\n\n<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.async=1;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");</script>\n
\n\n<!--[if lte IE 8]><script src='//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.6.1/html5shiv.js'></script><![endif]-->\n
\n\n<!--[if lte IE 8]><html class=\"ie8\"><![endif]--><!--[if IE 9]><html class=\"ie9\"><![endif]--><!--[if gt IE 9]><!-->\n<html><!--<![endif]-->\n
\n\n<link rel=\"shortcut icon\" type=\"image/png\" href=\"favicon.png\">\n<link href=\"apple-touch-icon-precomposed.png\" rel=\"apple-touch-icon\">\n<link href=\"apple-touch-icon-57x57-precomposed.png\" size=\"57x57\" rel=\"apple-touch-icon\">\n<link href=\"apple-touch-icon-72x72-precomposed.png\" size=\"72x72\" rel=\"apple-touch-icon\">\n<link href=\"apple-touch-icon-114x114-precomposed.png\" size=\"114x114\" rel=\"apple-touch-icon\">\n<link href=\"apple-touch-icon-144x144-precomposed.png\" size=\"144x144\" rel=\"apple-touch-icon\">\n
\n\nOnly do this if you’re not placing the site in the root!
\n\n<!--[if lt IE 7 ]> <html class=\"ie6\"> <![endif]-->\n<!--[if IE 7 ]> <html class=\"ie7\"> <![endif]-->\n<!--[if IE 8 ]> <html class=\"ie8\"> <![endif]-->\n<!--[if IE 9 ]> <html class=\"ie9\"> <![endif]-->\n<!--[if (gt IE 9)|!(IE)]><!--> <html class=\"\"> <!--<![endif]-->\n
\n\n<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"></script>\n
\n\n<!--[if lt IE 8]>\n<div class=\"unsupported-browser\">\n <strong>\n You are using an outdated browser.\n </strong>\n <span>\n Please <a class=\"upgrade-browser\"\n href=\"http://browsehappy.com/\">\n upgrade your browser</a> or <a class=\"chrome-frame\"\n href=\"http://www.google.com/chromeframe/?redirect=true\">activate Google \n Chrome Frame</a> to improve your experience.\n </span>\n</div>\n<![endif]-->\n
\n\n<script src=\"http://ie.microsoft.com/testdrive/HTML5/CompatInspector/inspector.js\"></script>\n
\n\nMore info here: microsoft.com
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "http-status", "title": "HTTP Status", "url": "/http-status", "category": "API", "keywords": null, "content_html": "Code | \nName | \n? | \n
---|---|---|
100 | \n Continue | \n? | \n
101 | \n Switching Protocols | \n? | \n
Code | \nName | \n? | \n
---|---|---|
200 | \n OK | \n? | \n
201 | \n Created | \n? | \n
202 | \n Accepted | \n? | \n
203 | \n Non-Authoritive Information | \n? | \n
204 | \n No Content | \n? | \n
205 | \n Reset Content | \n? | \n
206 | \n Partial Content | \n? | \n
226 | \n IM Used | \n? | \n
Code | \nName | \n? | \n
---|---|---|
300 | \n Multiple Choices | \n? | \n
301 | \n Moved Permanently | \n? | \n
302 | \n Found | \n? | \n
303 | \n See Other | \n? | \n
304 | \n Not Modified | \n? | \n
305 | \n Use Proxy | \n? | \n
306 | \n Switch Proxy | \n? | \n
307 | \n Temporary Redirect | \n? | \n
308 | \n Permanent Redirect | \n? | \n
Code | \nName | \n? | \n
---|---|---|
400 | \n Bad Request | \n? | \n
401 | \n Unauthorized | \n? | \n
402 | \n Payment Required | \n? | \n
403 | \n Forbidden | \n? | \n
404 | \n Not Found | \n? | \n
405 | \n Method Not Allowed | \n? | \n
406 | \n Not Acceptable | \n? | \n
407 | \n Proxy Authentication Required | \n? | \n
408 | \n Request Timeout | \n? | \n
409 | \n Conflict | \n? | \n
410 | \n Gone | \n? | \n
411 | \n Length Required | \n? | \n
412 | \n Precondition Failed | \n? | \n
413 | \n Payload Too Large | \n? | \n
414 | \n URI Too Long | \n? | \n
415 | \n Unsupported Media Type | \n? | \n
416 | \n Range Not Satisfiable | \n? | \n
417 | \n Expectation Failed | \n? | \n
418 | \n I’m a teapot | \n? | \n
421 | \n Misdirected Request | \n? | \n
426 | \n Upgrade Required | \n? | \n
428 | \n Precondition Required | \n? | \n
429 | \n Too Many Requests | \n? | \n
431 | \n Request Header Fields Too Large | \n? | \n
451 | \n Unavailable For Legal Reasons | \n? | \n
Code | \nName | \n? | \n
---|---|---|
500 | \n Internal Server Error | \n? | \n
501 | \n Not Implemented | \n? | \n
502 | \n Bad Gateway | \n? | \n
503 | \n Service Unavailable | \n? | \n
504 | \n Gateway Timeout | \n? | \n
505 | \n HTTP Version Not Supported | \n? | \n
506 | \n Variant Also Negotiates | \n? | \n
510 | \n Not Extended | \n? | \n
511 | \n Network Authentication Required | \n? | \n
WebDAV is an extension of HTTP that allows clients to perform remote Web content authoring operations. It provides a framework for users to create, change and move documents on a server. It adds the following status codes on top of HTTP.
\n\n\n\nCode | \nName | \n? | \n
---|---|---|
102 | \n Processing | \n? | \n
207 | \n Multi-Status | \n? | \n
208 | \n Already Reported | \n? | \n
422 | \n Unprocessable Entity | \n? | \n
423 | \n Locked | \n? | \n
424 | \n Failed Dependency | \n? | \n
507 | \n Insufficient Storage | \n? | \n
508 | \n Loop Detected | \n? | \n
List of HTTP Status codes and links to description.
", "tags": null, "updated": null },{ "id": "httpie", "title": "httpie", "url": "/httpie", "category": "CLI", "keywords": null, "content_html": "HTTPie is a command-line HTTP client.
\n\n$ http POST http://example.com/posts/3 \\\n Origin:example.com \\ # : HTTP headers\n name=\"John Doe\" \\ # = string\n q==\"search\" \\ # == URL parameters (?q=search)\n age:=29 \\ # := for non-strings\n list:='[1,3,4]' \\ # := json\n file@file.bin \\ # @ attach file\n token=@token.txt \\ # =@ read from file (text)\n user:=@user.json # :=@ read from file (json)\n
\n\n$ http --form POST example.com \\\n name=\"John Smith\" \\\n cv=@document.txt\n
\n\n$ echo '{\"hello\": \"world\"}' | http POST example.com/post\n
\n\n-v, --verbose # same as --print=HhBb --all\n-h, --headers # same as --print=h\n-b, --body # same as --print=b\n --all # print intermediate requests\n --print=HhBb # H: request headers\n # B: request body\n # h: response headers\n # b: response body\n --pretty=none # all | colors | format\n --json | -j # Response is serialized as a JSON object.\n
\n\n --session NAME\n-a, --auth USER:PASS\n --auth-type basic\n --auth-type digest\n
\n\n --session NAME # store auth and cookies\n --session-read-only NAME\n
\n\n-d, --download # like wget\n-c, --continue\n-o, --output FILE\n
\n\n-F, --follow # follow redirects\n --max-redirects N # maximum for --follow\n --timeout SECONDS\n --verify no # skip SSL verification\n --proxy http:http://foo.bar:3128\n
\n\n$ http POST http://example.com name=”John” Host:example.com — JSON, cookies, files, auth, and other httpie examples.
", "tags": null, "updated": "2020-07-05" },{ "id": "ie", "title": "Internet Explorer", "url": "/ie", "category": "HTML", "keywords": null, "content_html": "Feature | \nIE6 | \nIE7 | \nIE8 | \nIE9 | \nIE10 | \n
---|---|---|---|---|---|
> (descendant) | \n \n | 7 ✓ | \n✓ | \n✓ | \n✓ | \n
[attr] (attribute) | \n \n | 7 ✓ | \n✓ | \n✓ | \n✓ | \n
.class1.class2 (multiple classes) | \n \n | 7 ✓ | \n✓ | \n✓ | \n✓ | \n
~ (sibling) | \n \n | 7 ✓ | \n✓ | \n✓ | \n✓ | \n
+ (adjacent) | \n \n | 7 ✓ | \n✓ | \n✓ | \n✓ | \n
:first-child * | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n
:focus | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n
:before :after (single colon only) | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n
:lang | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n
:first-of-type , :last-of-type | \n \n | \n | \n | 9 ✓ | \n✓ | \n
:last-child | \n \n | \n | \n | 9 ✓ | \n✓ | \n
:empty | \n \n | \n | \n | 9 ✓ | \n✓ | \n
:enabled :disabled :checked | \n \n | \n | \n | 9 ✓ | \n✓ | \n
:not() | \n \n | \n | \n | 9 ✓ | \n✓ | \n
:nth-child() :nth-last-child() | \n \n | \n | \n | 9 ✓ | \n✓ | \n
:nth-of-type() :nth-last-of-type() :only-of-type() | \n \n | \n | \n | 9 ✓ | \n✓ | \n
:only-child() | \n \n | \n | \n | 9 ✓ | \n✓ | \n
:target | \n \n | \n | \n | 9 ✓ | \n✓ | \n
::selection | \n \n | \n | \n | 9 ✓ | \n✓ | \n
:root | \n \n | \n | \n | 9 ✓ | \n✓ | \n
first-child:
doesn’t work for elements inserted via JS.
Feature | \nIE6 | \nIE7 | \nIE8 | \nIE9 | \nIE10 | \nIE11 | \n
---|---|---|---|---|---|---|
max-width | \n \n | 7 ✓ | \n✓ | \n✓ | \n✓ | \n✓ | \n
position: fixed | \n \n | 7 ✓ | \n✓ | \n✓ | \n✓ | \n✓ | \n
outline | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
display: inline-block * | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
display: table | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
border-collapse , border-spacing , table-layout , … | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
whitespace: pre-wrap | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
whitespace: pre-line | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
box-sizing | \n \n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
background-clip | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
background-origin | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
background-size | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
background: x, y, z (multiple backgrounds) | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
opacity | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
border-radius | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
box-shadow | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
rgba() | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
transform | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
animation | \n \n | \n | \n | \n | 10 ✓ | \n✓ | \n
transition | \n \n | \n | \n | \n | 10 ✓ | \n✓ | \n
linear-gradient() | \n \n | \n | \n | \n | 10 ✓ | \n✓ | \n
text-shadow — polyfill | \n \n | \n | \n | \n | 10 ✓ | \n✓ | \n
border-image | \n \n | \n | \n | \n | \n | 11 ✓ | \n
inline-block:
IE6/7 can only support inline-block for elements that are naturally inline, like span
Feature | \nIE6 | \nIE7 | \nIE8 | \nIE9 | \nIE10 | \nIE11 | \n
---|---|---|---|---|---|---|
PNG alpha transparency | \n\n | 7 ✓ | \n✓ | \n✓ | \n✓ | \n✓ | \n
data URI ⊙ | \n\n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
JS: JSON parsing ⊙ | \n\n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
JS: Cross-origin resource sharing ⊙ | \n\n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
JS: Local storage ⊙ | \n\n | \n | 8 ✓ | \n✓ | \n✓ | \n✓ | \n
CSS: @media queries — polyfill | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
HTML: new HTML5 elements - polyfill | \n\n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
HTML: <canvas> | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
HTML: <svg> | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
HTML: <img src='image.svg'> | \n \n | \n | \n | 9 ✓ | \n✓ | \n✓ | \n
CSS: flexbox ⊙ * | \n\n | \n | \n | \n | 10 ✓ | \n✓ | \n
HTML: <input placeholder='..'> ⊙ | \n \n | \n | \n | \n | 10 ✓ | \n✓ | \n
HTML: <input type='range'> | \n \n | \n | \n | \n | 10 ✓ | \n✓ | \n
HTML: <input required> ⊙ | \n \n | \n | \n | \n | 10 ✓ | \n✓ | \n
JS: Web sockets | \n\n | \n | \n | \n | 10 ✓ | \n✓ | \n
JS: Fullscreen mode | \n\n | \n | \n | \n | \n | 11 ✓ | \n
flexbox:
IE10 only supports the 2012 syntax with -ms- prefix.
Always install these in almost every project:
\n\n<!--[if lt IE 9]>\n<script src='https://cdnjs.cloudflare.com/ajax/libs/nwmatcher/1.2.5/nwmatcher.min.js'></script>\n<script src='https://cdnjs.cloudflare.com/ajax/libs/json2/20140204/json2.min.js'>\n<script src='https://cdn.rawgit.com/gisu/selectivizr/1.0.3/selectivizr.js'></script>\n<script src='https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js'>\n<script src='https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.js'>\n<![endif]--> \n
\n\nSee: Cross-browser polyfills list
\n\n<!--[if lt IE 7 ]> <html class=\"ie6\"> <![endif]-->\n<!--[if IE 7 ]> <html class=\"ie7\"> <![endif]-->\n<!--[if IE 8 ]> <html class=\"ie8\"> <![endif]-->\n<!--[if IE 9 ]> <html class=\"ie9\"> <![endif]-->\n<!--[if (gt IE 9)|!(IE)]><!--> <html class=\"\"> <!--<![endif]-->\n
\n\n<!--[if IE]> I'm IE <![endif]-->\n<!--[if !IE]> --> Not IE <!-- <![endif]-->\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2018-03-06"
},{
"id": "ie_bugs",
"title": "Legacy IE bugs",
"url": "/ie_bugs",
"category": "HTML",
"keywords": null,
"content_html": "The ‘change’ event doesn’t always fire. Not for checkboxes, radios, multi-select lists. Use the click
handler instead.
Clicking label with input inside doesn’t focus the input.
\n\nAn element’s ‘opacity’ value isn’t propagated to its positioned descendants.
\n\nA bunch of bugs to take care of if you’re going to target legacy IE browsers.
", "description_html": "", "tags": null, "updated": "2018-03-06" },{ "id": "imagemagick", "title": "Imagemagick", "url": "/imagemagick", "category": "Others", "keywords": null, "content_html": "Option | \nDescription | \n
---|---|
-resize 100x40 | \n Resize to a dimension | \n
-crop 40x30+10+10 | \n (width)x(height)+(x)+y | \n
-crop 40x30-10-10 | \n (width)x(height)+(x)+y | \n
-flip | \n Vertical | \n
-flop | \n Horizontal | \n
-transpose | \n Flip vertical + rotate 90deg | \n
-transverse | \n Flip horizontal + rotate 270deg | \n
-trim | \n Trim image edges | \n
-rotate 90 | \n Rotate 90 degrees | \n
convert input.jpg -resize 80x80^ -gravity center -extent 80x80 icon.png\n
\n\nmogrify -format jpg -quality 85 *.png\n
\n\nconvert *.jpg hello.pdf\n
\n\nA quick reference for common Imagemagick commands and switches.
", "description_html": "", "tags": null, "updated": null },{ "id": "immutable.js", "title": "Immutable.js", "url": "/immutable.js", "category": "JavaScript libraries", "keywords": null, "content_html": "var map = Immutable.Map({ a: 1, b: 2, c: 3 })\n
\n\nmap\n .set('b', 50)\n .get('b') // 50\n
\n\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\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
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "inkscape",
"title": "Inkscape",
"url": "/inkscape",
"category": "Apps",
"keywords": null,
"content_html": "- / = | \n Zoom in/out | \n
3 / 4 | \n Zoom to selection / drawing | \n
5 / 6 | \n Zoom to page / page width | \n
[ ] | \n Rotate | \n
Ctrl | \n constraint | \n
Ctrl | \n snap to 15 degrees | \n
Alt | \n ? | \n
const date = new Date(2012, 11, 20, 3, 0, 0)\n
\n\nconst date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0))\n
\n\nconst date = new Date('2018-04-20T12:00:00Z')\n
\n\nNote that JavaScript doesn’t “store” timezones in a date object. All these date objects, when expressed via .toString()
or similar, will show the local timezone of the browser, regardless if you parsed UTC dates.
console.log(new Intl.DateTimeFormat().format(date))\n// → '12/19/2012' (assuming America/Los_Angeles)\n
\n\nconsole.log(new Intl.DateTimeFormat('en-GB').format(date))\n// → '19/12/2012' (date-first)\n
\n\nconsole.log(new Intl.DateTimeFormat('en-AU', {\n timeZone: 'Australia/Sydney'\n}).format(date))\n// → '19/12/2012'\n
\n\nconsole.log(new Intl.DateTimeFormat('default', {\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric'\n}).format(date))\n// → '2:00:00 pm'\n
\n\nconsole.log(new Intl.DateTimeFormat('en-US', {\n year: 'numeric',\n month: 'numeric',\n day: 'numeric'\n}).format(date))\n// → '12/19/2012'\n
\n\nTo specify options without a locale, use 'default'
as a locale.
{\n weekday: 'narrow' | 'short' | 'long',\n era: 'narrow' | 'short' | 'long',\n year: 'numeric' | '2-digit',\n month: 'numeric' | '2-digit' | 'narrow' | 'short' | 'long',\n day: 'numeric' | '2-digit',\n hour: 'numeric' | '2-digit',\n minute: 'numeric' | '2-digit',\n second: 'numeric' | '2-digit',\n timeZoneName: 'short' | 'long',\n\n // Time zone to express it in\n timeZone: 'Asia/Shanghai',\n // Force 12-hour or 24-hour\n hour12: true | false,\n\n // Rarely-used options\n hourCycle: 'h11' | 'h12' | 'h23' | 'h24',\n formatMatcher: 'basic' | 'best fit'\n}\n
\n\nIntl.DateTimeFormat
is used to format date strings in JavaScript.
What | \nDev | \nAdhoc | \nAppstore | \n
---|---|---|---|
CSR file | \n\n | √ | \n√ | \n
Device UDIDs | \n√ | \n√ | \n\n |
Developers list | \n√ | \n\n | \n |
Needed for Adhoc & Appstore builds.
\n\n.cer
filesNeeded for Adhoc & Appstore builds.
\n\nNeeded for Dev and Adhoc builds.
\n\nDon’t ever ask Xcode to Fix issue… for you.
\n\nNo need to use .mobileprovision
files since XCode 5.
*.mobileprovision
file using Finderdescribe('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 uses Jasmine, and therefore has similar API.
\n\nexpect(true).toBe(true)\nexpect(true).not.toBe(true)\n
\n\nexpect(a).toEqual(bar)\n
\n\nexpect(message).toMatch(/bar/)\nexpect(message).toMatch('bar')\n
\n\nexpect(a.foo).toBeDefined()\nexpect(a.foo).toBeUndefined()\nexpect(a.foo).toBeNull()\n
\n\nexpect(a.foo).toBeTruthy()\nexpect(a.foo).toBeFalsy()\n
\n\nexpect(message).toContain('hello')\n
\n\nexpect(pi).toBeGreaterThan(3)\nexpect(pi).toBeLessThan(4)\nexpect(pi).toBeCloseTo(3.1415, 0.1)\n
\n\nexpect(func).toThrow()\n
\n\nbeforeEach(() => {\n ···\n})\n
\n\nafterEach(() => {\n ···\n})\n
\n\nxit('this is a pending test', () => {\n ···\n})\n
\n\nxdescribe('this is a pending block', () => {\n ···\n})\n
\n\nspyOn(foo, 'setBar')\nspyOn(foo, 'setBar').andReturn(123)\nspyOn(foo, 'getBar').andCallFake(function() { return 1001; })\nfoo.setBar(123)\n
\n\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\nstub = jasmine.createSpy('stub')\nstub('hello')\n
\n\nexpect(stub.identity).toEqual('stub')\nexpect(stub).toHaveBeenCalled()\n
\n\ntest('works with promises', () => {\n return new Promise((resolve, reject) => {\n ···\n })\n})\n
\n\nMake your test return a promise.
\n\nvar jasmineEnv = jasmine.getEnv()\njasmineEnv.updateInterval = 250\n\nvar htmlReporter = new jasmine.HtmlReporter()\njasmineEnv.addReporter(htmlReporter)\n\n$(function() { jasmineEnv.execute() })\n
\n\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\nexpect($('#toolbar')).toBeHidden()\nexpect($('#toolbar')).toBeVisible()\n
\n\nexpect($('#popup')).toHaveCss({ margin: \"10px\" })\nexpect($('option')).toBeSelected()\n
\n\nexpect($('.foo')).toExist()\n
\n\nexpect($('a')).toHaveAttr('rel')\nexpect($('a')).toHaveAttr('rel', 'nofollow')\n
\n\nexpect($('a')).toHaveClass('rel')\nexpect($('a')).toHaveId('home')\n
\n\nexpect($('a')).toHaveHtml('<span></span>')\nexpect($('a')).toContainHtml('<span></span>')\nexpect($('a')).toHaveText('hi')\n
\n\nexpect($form).toHandle('submit') // event\nexpect($form).toHandleWith('submit', onSumbit)\n
\n\nSee: jasmine-jquery
\n\nspyOnEvent($('#some_element'), 'click')\n$('#some_element').click()\nexpect('click').toHaveBeenPreventedOn($('#some_element'))\nexpect('click').toHaveBeenTriggeredOn($('#some_element'))\n
\n\nAs of github-pages v156. For an updated list, see: Dependency versions (pages.github.com)
\n\nplugins:\n - jekyll-github-metadata\n\nrepository: username/project\n
\n\nPut this in your _config.yml
.\nSee: Repository metadata on GitHub pages
{% for repository in site.github.public_repositories %}\n <a href='{{ repository.html_url }}'>\n {{ repository.name }}\n </a>\n{% endfor %}\n
\n\n<a href='{{ site.github.repository_url }}'>\n {{ site.github.project_title }}\n</a>\n
\n\nplugins:\n - jekyll-gist\n
\n\nSee: jekyll-gist
\n\n{% gist parkr/c08ee0f2726fd0e3909d %}\n
\n\nThis places a Gist in your page.
\n\nplugins:\n - jekyll-mentions\n
\n\nSee: jekyll-mentions
\n\nHey @rstacruz, what do you think of this?\n
\n\nJust mention anyone in any page. Their names will be turned into links.
\n\nplugins:\n - jekyll-redirect-from\n
\n\nSee: jekyll-redirect-from
\n\n---\nredirect_from:\n - /foo\n---\n
\n\nPlace on any page.
\n\n---\nredirect_to:\n - /foo\n---\n
\n\nPlace on any page.\nSee: redirect to
", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": "2017-11-17" },{ "id": "jekyll", "title": "Jekyll", "url": "/jekyll", "category": "Jekyll", "keywords": null, "content_html": "# Install the gems\ngem install jekyll bundler\n
\n\n# Create a new site at `./myblog`\njekyll new myblog\ncd myblog\n
\n\n# Optional: if you're targeting github-pages,\n# use this Gemfile instead.\ncat > Gemfile <<-END\nsource 'https://rubygems.org'\ngem 'github-pages', group: :jekyll_plugins\nEND\n
\n\nbundle exec jekyll serve\n
\n\nSee: Jekyll quickstart
\nSee: github/pages-gem
./\n├── _config.yml\n│\n├── _data/\n│ └── ...\n│\n├── _drafts/\n│ └── ...\n│\n├── _posts/\n│ └── 2014-01-01-hello.md\n│\n├── _layouts/\n│ ├── default.html\n│ └── post.html\n│\n├── _includes/ - partials\n│ ├── header.html\n│ └── footer.html\n│\n└── _site/\n └── ...\n
\n\n---\nlayout: post\ntitle: Hello\n---\nHello! this is my post.\n
\n\nAttach metadata to a page by adding them on top of the page, delimited by ---
.\nSee: Front-matter
permalink: '/hello'\npublished: false\ncategory: apple\ncategories: ['html', 'css']\ntags: ['html', 'css']\n
\n\nIn _config.yml
:
source: .\ndestination: _site\nexclude:\n- Gemfile\n- Gemfile.lock\ninclude: ['.htaccess']\n
\n\nAll config keys are optional.\nSee: Configuration
\n\n<title>\n {{ page.title }}\n</title>\n
\n\n<p>\n {{ page.description | truncate_words: 20 }}\n</p>\n
\n\n{% for post in site.posts %}\n <a href=\"{{ post.url }}\">\n <h2>{{ post.title }}</h2>\n <p>{{ post.date | date_to_string }}</p>\n </a>\n{% endfor %}\n
\n\n{{ page.date | date: \"%b %d, %Y\" }}\n
\n\n{% if page.image.feature %}\n ...\n{% elsif xyz %}\n ...\n{% else %}\n ...\n{% endif %}\n
\n\n{% if page.category == 'React' %}\n{% if page.category == 'React' or page.featured %}\n{% if page.tags contains 'Featured' %}\n
\n\n{% case shipping.title %}\n {% when 'international' %}\n Arriving in 2-3 weeks\n {% when 'Domestic' %}\n Arriving in 2-3 days\n {% else %}\n Thank you for your order!\n{% endcase %}\n
\n\n{% include header.html %}\n
\n\n<!-- Including local vars -->\n{% include header.html page=page %}\n
\n\n{% comment %}\n This is a comment!\n{% endcomment %}\n
\n\n{{ site }} | \n Data from config.yml | \n
{{ page }} | \n From frontmatter, and page-specific info | \n
{{ content }} | \n HTML content (use in layouts) | \n
{{ paginator }} | \n Paginator | \n
See: Variables
\n\n{{ site.time }}\n
\n\nsite.time | \n Current time | \n
site.pages | \n List of pages | \n
site.posts | \n List of blog posts | \n
site.related_posts | \n List of posts related to current | \n
site.categories.CATEGORY | \n List | \n
site.tags.TAG | \n List | \n
site.static_files | \n List | \n
{{ page.content }} - un-rendered content\n{{ page.title }}\n{{ page.excerpt }} - un-rendered excerpt\n{{ page.url }}\n{{ page.date }}\n{{ page.id }} - unique id for RSS feeds\n{{ page.categories }}\n{{ page.tags }}\n{{ page.path }}\n{{ page.dir }}\n{{ page.excerpt | remove: '<p>' | remove: '</p>' }}\n{{ page.excerpt | strip_html }}\n
\n\n<!-- blog pagination: -->\n{{ page.next }}\n{{ page.previous }}\n
\n\n{{ site.time | date: \"%Y %m %d\" }}\n
\n\ndate_to_xmlschema | \n → 2008-11-07T13:07:54-08:00 | \n
date_to_rfc822 | \n → Mon, 07 Nov 2008 13:07:54 -0800 | \n
date_to_string | \n → 07 Nov 2008 | \n
date_to_long_string | \n → 07 November 2008 | \n
date: ‘%Y %m %d’ | \n → 2017 Nov 7 | \n
{{ page.description | markdownify }}\n
\n\nFilter | \nDescription | \n
---|---|
textilize | \n Textile | \n
markdownify | \n Markdown | \n
jsonify | \n JSON | \n
sassify | \n Sass | \n
scssify | \n SCSS | \n
smartify | \n Smartypants | \n
{{ site.pages | where: \"year\", \"2014\" }}\n
\n\nFilter | \nDescription | \n
---|---|
where: “year”, “2014” | \n \n |
where_exp: “item”, “item.year >= 2014” | \n \n |
group_by: “genre” | \n → {name, items} | \n
group_by_exp: “item”, “item.genre” | \n → {name, items} | \n
sort | \n \n |
sort: ‘author’ | \n \n |
uniq | \n \n |
first | \n \n |
last | \n \n |
join: ’,’ | \n \n |
array_to_sentence_string | \n → \"X, Y and Z\" | \n
map: ‘post’ | \n Works like ‘pluck’ | \n
size | \n \n |
push: ‘xxx’ | \n Adds an item | \n
{{ page.title | default: \"xxx\" }}\n
\n\nFilter | \nDescription | \n
---|---|
default: ‘xxx’ | \n \n |
upcase | \n \n |
downcase | \n \n |
remove: ‘p’ | \n \n |
replace: ‘super’, ‘mega’ | \n \n |
remove_first: ‘p’ | \n \n |
replace_first: ‘super’, ‘mega’ | \n \n |
truncate: 5 | \n \n |
truncatewords: 20 | \n \n |
prepend: ‘Mr. ‘ | \n \n |
append: ‘Jr.’ | \n \n |
camelize | \n \n |
capitalize | \n \n |
strip_html | \n \n |
strip_newlines | \n \n |
newlines_to_br | \n \n |
split: ’,’ | \n \n |
escape | \n \n |
escape_once | \n \n |
slice: -3, 3 | \n \n |
See: String filters
\n\n{{ page.excerpt | number_of_words }}\n
\n\nFilter | \nDescription | \n
---|---|
number_of_words | \n \n |
slugify | \n \n |
xml_escape | \n → CDATA | \n
cgi_escape | \n → foo%2Cbar | \n
uri_escape | \n → foo,%20bar | \n
{{ site.posts.size | minus: 2 }}\n
\n\nFilter | \nDescription | \n
---|---|
minus: 2 | \n \n |
plus: 2 | \n \n |
times: 2 | \n \n |
divided_by: 2 | \n \n |
modulo: 2 | \n \n |
ceil | \n \n |
floor | \n \n |
round | \n \n |
Add this to _config.yml
:
paginate: 5\npaginate_path: \"blog/:num\"\n
\n\nSee: Paginator
\n\n{{ paginator.page }} - page number\n{{ paginator.total_posts }}\n{{ paginator.total_pages }}\n{{ paginator.per_page }}\n
\n\n{% for post in paginator.posts %} ... {% endfor %}\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{{ paginator.next_page }} - page number\n{{ paginator.next_page_path }}\n
\n\n_posts/YEAR-MONTH-DAY-title.md\n
\n\nSee: Blogging
\n\n\n
\n\nSee: Image paths
\n\nvi _drafts/a-draft-post.md\njekyll build --drafts\n
\n\nPosts in _drafts
only show up in development, but not production.\nSee: Drafts
---\ntitle: My blog post\nexcerpt: This post is about cats\n---\n\nHello, let's talk about cats. (···)\n
\n\nPut a key excerpt
in the frontmatter.\nSee: Excerpts
{{ post.excerpt }}\n
\n\n{{ post.excerpt | remove: '<p>' | remove: '</p>' }}\n{{ post.excerpt | strip_html }}\n
\n\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
.
# _config.yml\npermalink: date # /:categories/:year/:month/:day/:title.html\npermalink: pretty # /:categories/:year/:month/:day/:title/\npermalink: none # /:categories/:title.html\npermalink: \"/:title\"\n
\n\nSee: Permalinks
\n\n_data/members.yml\n
\n\n{% for member in site.data.members %}\n ...\n{% endfor %}\n
\n\nSee: Data
\n\n# _config.yml\ncollections:\n - authors\n
\n\n# _/authors/a-n-roquelaire.md\n---\nname: A. N. Roquelaire\nreal_name: Anne Rice\n---\n
\n\n{% for author in site.authors %}\n
\n\nSee: Collections
\n\n{% highlight ruby linenos %}\ndef show\n ...\nend\n{% endhighlight %}\n
\n\nIn _plugins/bundler.rb
:
require \"bunder/setup\"\nBundler.require :default\n
\n\nnpm install --save-dev jest babel-jest\n
\n\n/* Add to package.json */\n\"scripts\": {\n \"test\": \"jest\"\n}\n
\n\n# Run your tests\nnpm test -- --watch\n
\n\nSee: Getting started
\n\ndescribe('My work', () => {\n test('works', () => {\n expect(2).toEqual(2)\n })\n})\n
\n\nSee: describe(), test(), expect()
\n\ndescribe('My work', () => {\n it('works', () => {\n ···\n })\n})\n
\n\nit
is an alias for test
.\nSee: test()
beforeEach(() => { ... })\nafterEach(() => { ... })\n
\n\nbeforeAll(() => { ... })\nafterAll(() => { ... })\n
\n\nSee: afterAll() and more
\n\ndescribe.only(···)\nit.only(···) // alias: fit()\n
\n\nSee: test.only
\n\ndescribe.skip(···)\nit.skip(···) // alias: xit()\n
\n\nSee: test.skip
\n\nFlag | \nDescription | \n
---|---|
--coverage | \n See a summary of test coverage | \n
--detectOpenHandles | \n See a summary of ports that didn’t close | \n
--runInBand | \n Run all tests one after the other | \n
expect(value)\n .not\n .toBe(value)\n .toEqual(value)\n .toBeTruthy()\n
\n\nNote that toEqual
is a deep equality check.\nSee: expect()
expect(value)\n .toMatchSnapshot()\n .toMatchInlineSnapshot()\n
\n\nNote that toMatchInlineSnapshot()
requires Prettier to be set up for the project.\nSee: Inline snapshots
expect(value)\n .toThrow(error)\n .toThrowErrorMatchingSnapshot()\n
\n\nexpect(value)\n .toBeFalsy()\n .toBeNull()\n .toBeTruthy()\n .toBeUndefined()\n .toBeDefined()\n
\n\nexpect(value)\n .toBeCloseTo(number, numDigits)\n .toBeGreaterThan(number)\n .toBeGreaterThanOrEqual(number)\n .toBeLessThan(number)\n .toBeLessThanOrEqual(number)\n
\n\nexpect(value)\n .toBeInstanceOf(Class)\n .toMatchObject(object)\n .toHaveProperty(keyPath, value)\n
\n\nexpect(value)\n .toContain(item)\n .toContainEqual(item)\n .toHaveLength(number)\n
\n\nexpect(value)\n .toMatch(regexpOrString)\n
\n\nexpect.extend(matchers)\nexpect.any(constructor)\nexpect.addSnapshotSerializer(serializer)\n\nexpect.assertions(1)\n
\n\ntest('works with promises', () => {\n return new Promise((resolve, reject) => {\n ···\n })\n})\n
\n\ntest('works with async/await', async () => {\n const hello = await foo()\n ···\n})\n
\n\nReturn promises, or use async/await.\nSee: Async tutorial
\n\nit('works', () => {\n const output = something()\n expect(output).toMatchSnapshot()\n})\n
\n\nFirst run creates a snapshot. Subsequent runs match the saved snapshot.\nSee: Snapshot testing
\n\nimport renderer from 'react-test-renderer'\n
\n\nit('works', () => {\n const tree = renderer.create(\n <Link page=\"http://www.facebook.com\">Facebook</Link>\n ).toJSON()\n\n expect(tree).toMatchSnapshot()\n})\n
\n\nReact’s test renderer can be used for Jest snapshots.\nSee: Snapshot test
\n\njest.useFakeTimers()\n
\n\nit('works', () => {\n jest.runOnlyPendingTimers()\n jest.runTimersToTime(1000)\n jest.runAllTimers()\n})\n
\n\nSee: Timer Mocks
\n\nconst fn = jest.fn()\n
\n\nconst fn = jest.fn(n => n * n)\n
\n\nSee: Mock functions
\n\nexpect(fn)\n .toHaveBeenCalled()\n .toHaveBeenCalledTimes(number)\n .toHaveBeenCalledWith(arg1, arg2, ...)\n .toHaveBeenLastCalledWith(arg1, arg2, ...)\n
\n\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\nconst Fn = jest.fn()\n\na = new Fn()\nb = new Fn()\n
\n\nFn.mock.instances\n// → [a, b]\n
\n\nSee: .mock property
\n\nconst fn = jest.fn()\nfn(123)\nfn(456)\n
\n\nfn.mock.calls.length // → 2\nfn.mock.calls[0][0] // → 123\nfn.mock.calls[1][0] // → 456\n
\n\nSee: .mock property
\n\nconst fn = jest.fn(() => 'hello')\n
\n\njest.fn().mockReturnValue('hello')\njest.fn().mockReturnValueOnce('hello')\n
\n\nconst fn = jest.fn()\n .mockImplementationOnce(() => 1)\n .mockImplementationOnce(() => 2)\n
\n\nfn() // → 1\nfn() // → 2\n
\n\nA quick overview to Jest, a test framework for Node.js. This guide targets Jest v20.
", "description_html": "", "tags": ["Featurable"], "updated": "2020-06-17" },{ "id": "jquery-cdn", "title": "jQuery CDN", "url": "/jquery-cdn", "category": "JavaScript libraries", "keywords": null, "content_html": "<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n
",
"intro_html": "",
"description_html": "",
"tags": ["Archived"],
"updated": null
},{
"id": "jquery",
"title": "jQuery",
"url": "/jquery",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "$('.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$.expr[':'].inline = function (el) {\n return $(el).css('display') === 'inline'\n}\n
\n\nEnables $(':inline')
$.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.step.someWhatever = function(fx) {\n // ...\n}\n
",
"intro_html": "",
"description_html": "",
"tags": ["WIP"],
"updated": null
},{
"id": "js-appcache",
"title": "applicationCache",
"url": "/js-appcache",
"category": "JavaScript",
"keywords": null,
"content_html": "if (window.applicationCache) {\n // \"Naturally\" reload when an update is available\n var reload = false\n\n window.applicationCache.addEventListener('updateready', () => {\n if (window.applicationCache.status === window.applicationCache.UPDATEREADY) {\n window.applicationCache.swapCache()\n reload = true\n }\n }, false)\n\n setInterval(() => {\n try {\n // There's nothing to update for first-time load, browser freaks out :/\n window.applicationCache.update()\n } catch (e) { }\n }, 1000 * 60 * 60) // Every hour\n}\n
\n\nThis is a deprecated HTML feature. See: Using the application cache (developer.mozilla.org)
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "js-array", "title": "JavaScript Arrays", "url": "/js-array", "category": "JavaScript", "keywords": null, "content_html": "list = [a,b,c,d,e]\n
\n\nlist[1] // → b\nlist.indexOf(b) // → 1\n
\n\nlist.slice(0,1) // → [a ]\nlist.slice(1) // → [ b,c,d,e]\nlist.slice(1,2) // → [ b ]\n
\n\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\nlist.concat([X,Y]) // → [_,_,_,_,_,X,Y]\n
\n\nlist.push(X) // list == [_,_,_,_,_,X]\nlist.unshift(X) // list == [X,_,_,_,_,_]\nlist.splice(2, 0, X) // list == [_,_,X,_,_,_]\n
\n\n// after -- [_,_,REF,NEW,_,_]\nlist.splice(list.indexOf(REF)+1, 0, NEW))\n
\n\n// before -- [_,_,NEW,REF,_,_]\nlist.splice(list.indexOf(REF), 0, NEW))\n
\n\nlist.splice(2, 1, X) // list == [a,b,X,d,e]\n
\n\nlist.pop() // → e list == [a,b,c,d]\nlist.shift() // → a list == [b,c,d,e]\nlist.splice(2, 1) // → [c] list == [a,b,d,e]\n
\n\n.filter(n => ...) => array\n
\n\n.find(n => ...) // es6\n.findIndex(...) // es6\n
\n\n.every(n => ...) => Boolean // ie9+\n.some(n => ..) => Boolean // ie9+\n
\n\n.map(n => ...) // ie9+\n.reduce((total, n) => total) // ie9+\n.reduceRight(...)\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "js-date",
"title": "JavaScript Date",
"url": "/js-date",
"category": "JavaScript",
"keywords": null,
"content_html": "// Now\nnew Date()\n
\n\n// ms since epoch\nnew Date(1419785527580)\n
\n\n// Date format\nnew Date(\"May 17, 1995 03:24:00\")\n
\n\n// ISO date format\nnew Date(\"2013-03-01T01:10:00\")\n
\n\nnew Date(2014, 2, 1, 13, 0, 59, 0)\n
\n\nnew Date( | \n 2014, | \n 2, | \n 1, | \n 13, | \n 0, | \n 59, | \n 0) | \n
Date | \nYear | \nMonth | \nDay | \nHour | \nMin | \nSec | \nMilli | \n
Months are zero-indexed (eg, January is 0
).
Method | \nResult | \n
---|---|
d.toString() | \n \"Mon Dec 29 2014 00:58:28 GMT+0800 (PHT)\" | \n
d.toTimeString() | \n \"00:58:46 GMT+0800 (PHT)\" | \n
d.toUTCString() | \n \"Sun, 28 Dec 2014 16:58:59 GMT\" | \n
d.toDateString() | \n \"Thu Jan 10 2013\" | \n
d.toISOString() | \n \"2013-01-09T16:00:00.000Z\" | \n
d.toLocaleString() | \n \"12/29/2014, 12:57:31 AM\" | \n
d.toLocaleTimeString() | \n \"12:57:31 AM\" | \n
d.getTime() | \n 1419785527580 | \n
Method | \nResult | \n
---|---|
.getDate() | \n 1..31 | \n
.getDay() | \n 0..6 (sun..sat) | \n
.getFullYear() | \n 2014 | \n
.getMonth() | \n 0..11 | \n
.getHours() | \n \n |
.getMinutes() | \n \n |
.getSeconds() | \n \n |
.getMilliseconds() | \n \n |
.getTime() | \n ms since epoch | \n
.getTimezoneOffset() | \n \n |
UTC versions are also available (eg, .getUTCDate()
, .getUTCDay()
, etc).
Method | \nResult | \n
---|---|
.setDate (val) | \n \n |
.setDay (val) | \n \n |
.setFullYear (val) | \n \n |
.setMonth (val) | \n \n |
.setHours (val) | \n \n |
.setMinutes (val) | \n \n |
.setSeconds (val) | \n \n |
.setMilliseconds (val) | \n \n |
.setTime (val) | \n \n |
.setTimezoneOffset (val) | \n \n |
See the getters list.
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "js-fetch", "title": "fetch()", "url": "/js-fetch", "category": "JavaScript", "keywords": null, "content_html": "fetch('/data.json')\n .then(response => response.json())\n .then(data => {\n console.log(data)\n })\n .catch(err => ...)\n
\n\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\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\nfetch('/data.json')\n .then(checkStatus)\n
\n\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\nconst fetch = require('isomorphic-fetch')\n
\n\nSee: isomorphic-fetch (npmjs.com)
\n\nn = +'4096' // n === 4096\ns = '' + 200 // s === '200'\n
\n\nnow = +new Date()\nisPublished = !!post.publishedAt\n
\n\nWhat | \nLazy mode | \n“The right way” | \n
---|---|---|
String to number | \n+str | \n parseInt(str, 10) or parseFloat() | \n
Math floor | \nnum | 0 | \n Math.floor(num) | \n
Number to string | \n'' + num | \n num.toString() | \n
Date to UNIX timestamp | \n+new Date() | \n new Date().getTime() | \n
Any to boolean | \n!!value | \n Boolean(value) | \n
Check array contents | \nif (~arr.indexOf(v)) | \n if (arr.includes(v)) | \n
.includes
is ES6-only, otherwise use .indexOf(val) !== -1
if you don’t polyfill.
Project = Model \"project\", ->\n @extend\n findByTitle: (title) -> ...\n\n @include\n markAsDone: -> ...\n\n # ActiveRecord::Base.include_root_in_json = false\n
\n\nproject = Project.find(1)\nproject = Project.findByTitle(\"hello\")\n\nproject.markAsDone()\n
\n\nProject \"hi\", ->\n @persistence Model.REST, \"/projects\"\n @persistence Model.localStorage\n
\n\nProject.load ->\n # loaded\n
\n\nproject = new Project(name: \"Hello\")\n\nproject.attr('name', \"Hey\")\nproject.attr('name')\n\nproject.save()\nproject.destroy()\n
\n\nFood.add(egg)\nFood.all()\nFood.select (food) -> ...\nFood.first()\n
\n\nFood.find(id)\n
\n\n# Classes\nProject.bind \"add\", (obj) ->\nProject.bind \"remove\", (obj) ->\n
\n\n# Instances\nproject.bind \"update\", ->\nproject.bind \"destroy\", ->\n
\n\nproject.trigger \"turn_blue\"\n
\n\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\nspeak('Hello, world')\n
\n\nSee: SpeechSynthesisUtterance (developer.mozilla.org)
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "jscoverage", "title": "jscoverage", "url": "/jscoverage", "category": "JavaScript libraries", "keywords": null, "content_html": "npm install --save-dev jscoverage\n
\n\necho coverage.html >> .gitignore\n
\n\nThe coverage
task injects your source files (lib
) with jscoverage hooks, runs mocha -R html-cov
, then restores later.
/* directory */\n\"coverage\": \"mv lib lib~; (jscoverage lib~ lib; mocha -R html-cov > coverage.html); rm -rf lib; mv lib~ lib\"\n
\n\n/* single file */\n\"coverage\": \"(cp index.js index.js~; jscoverage index.js; mv index-cov.js index.js; mocha -R html-cov > coverage.html); mv index.js~ index.js\"\n
\n\nnpm run coverage\n
\n\nopen coverage.html\n
\n\nIf you’re using jsdom, be sure to expose the window._$jscoverage
variable into \nthe global
scope.
A small guide into installing jscoverage. Also see mocha-blanket.
", "description_html": "", "tags": null, "updated": null },{ "id": "jsdoc", "title": "Jsdoc", "url": "/jsdoc", "category": "JavaScript", "keywords": null, "content_html": "/**\n * This is a function.\n *\n * @param {string} n - A string param\n * @return {string} A good string\n *\n * @example\n *\n * foo('hello')\n */\n\nfunction foo(n) {\n return n\n}\n
\n\nSee: http://usejsdoc.org/index.html
\n\nType | \nDescription | \n
---|---|
@param {string=} n | \n Optional | \n
@param {string} [n] | \n Optional | \n
@param {(string|number)} n | \n Multiple types | \n
@param {*} n | \n Any type | \n
@param {...string} n | \n Repeatable arguments | \n
@param {string} [n=\"hi\"] | \n Optional with default | \n
@param {string[]} n | \n Array of strings | \n
@return {Promise<string[]>} n | \n Promise fulfilled by array of strings | \n
See: http://usejsdoc.org/tags-type.html
\n\n/**\n * @type {number}\n */\nvar FOO = 1\n
\n\n/**\n * @const {number}\n */\nconst FOO = 1\n
\n\n/**\n * A song\n * @typedef {Object} Song\n * @property {string} title - The title\n * @property {string} artist - The artist\n * @property {number} year - The year\n */\n
\n\n/**\n * Plays a song\n * @param {Song} song - The {@link Song} to be played\n */\n\nfunction play(song) {}\n
\n\nSee: http://usejsdoc.org/tags-typedef.html
\n\n/**\n * A song\n * @typedef {{title: string, artist: string, year: number}} Song\n */\n
\n\n/**\n * Plays a song\n * @param {Song} song - The {@link Song} to be played\n */\n\nfunction play(song) {}\n
\n\nSee: http://usejsdoc.org/tags-typedef.html
\n\n/**\n * @typedef {import('./Foo').default} Bar\n */\n\n/**\n * @param {Bar} x\n */\n\nfunction test(x) {}\n
\n\nThis syntax is TypeScript-specific.
\n\n/**\n * @throws {FooException}\n * @private\n * @deprecated\n * @see\n *\n * @function\n * @class\n */\n
\n\nSee the full list: https://jsdoc.app/index.html#block-tags
\n\n/*\n * @alias Foo.bar\n * @name Foo.bar\n */\n
\n\nPrefer alias
over name
. See: http://usejsdoc.org/tags-alias.html
Enable these options to not throw errors in these conditions.\nSee: Relaxing
\n\n/* jshint asi: true */\nallow()\nmissing_semicolons()\n
\n\n/* jshint boss: true */\nif (m = str.match(/.../))\n
\n\n/* jshint debug: true */\ndebugger;\n
\n\n/* jshint eqnull: true */\nif (x == null)\n
\n\n/* jshint evil: true */\neval('...')\n
\n\n/* jshint expr: true */\nproduction && minify = true;\ndiv.innerWidth;\nexpect(x).be.true;\n
\n\n/* jshint laxcomma: true */\nvar one = 1\n , two = 2;\n
\n\n/* jshint loopfunc: true */\nfor (i=0; i<10; x++) {\n (function(i) { ... })(i);\n}\n
\n\n/* jshint sub: true */\nprocess.env['name_here']\n
\n\n/* jshint strict: \"global\" */\n\"use strict\";\n
\n\nEnable these options to catch more errors.\nSee: Enforcing
\n\n/* jshint curly: true */\nwhile (day) // err: use { }'s\n shuffle();\n
\n\n/* jshint eqeqeq: true */\nif (a == null) // err: use ===\n
\n\n/* jshint es3: true */\n// ...for legacy IE compatibility\na.default = function() { ... }; // err: reserved word\narray = [ 1, 2, 3, ]; // err: extra comma\n
\n\n/* jshint forin: true */\nfor (key in obj) { ... } // err: check obj.hasOwnProperty(key)\n
\n\n/* jshint freeze: true */\nArray.prototype.count = ...; // err: don't modify native prototypes\n
\n\n/* jshint indent: 4 */\nif (x) { // err: expected indent of 4, found 2\n ...;\n}\n
\n\n/* jshint quotmark: single */\n/* jshint quotmark: double */\nalert(\"hi\"); // err: only single allowed\n
\n\n/* jshint strict: true */\nfunction() { ... } // err: need \"use strict\"\n
\n\n/* jshint white: true, indent: 4 */\n/* jshint maxdepth: 2 */\n/* jshint maxparams: 3 */\n/* jshint maxstatements: 4 */\n/* jshint maxcomplexity: 5 */\n/* jshint maxlen: 80 */\n
\n\n/* jshint ignore:start */\n/* jshint ignore:end */\n
\n\n/* jshint undef: true */\n/* global jQuery */\n/* global -BAD_LIB */\n
\n\n/* jshint devel: true */ console, alert, ...\n/* jshint browser: true */ window, document, location, ...\n/* jshint node: true */ module, exports, console, process, ...\n/* jshint jquery: true */ jQuery, $\n
\n\nSee: Environments
\n\nrequire('knex')({\n client: 'pg',\n connection: 'postgres://user:pass@localhost:5432/dbname'\n})\n
\n\nSee: Connect
\n\nknex.schema.createTable('user', (table) => {\n table.increments('id')\n table.string('name')\n table.integer('age')\n})\n.then(() => ···)\n
\n\nSee: Schema
\n\nknex('users')\n .where({ email: 'hi@example.com' })\n .then(rows => ···)\n
\n\nSee: Select
\n\nknex('users')\n .insert({ email: 'hi@example.com' })\n
\n\nSee: Insert
\n\nknex('users')\n .where({ id: 135 })\n .update({ email: 'hi@example.com' })\n
\n\nSee: Update
\n\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
\n\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
\n\npg | \n PostgreSQL | \n
mysql | \n MySQL or MariaDB | \n
sqlite3 | \n Sqlite3 | \n
mssql | \n MSSQL | \n
Install any of these packages along with knex
.
See: Node.js installation
\n\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\n\n\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\nvar knex = require('knex')({\n client: 'sqlite3',\n connection: { filename: './mydb.sqlite' }\n})\n
\n\nknex\n .from('books')\n .select('title', 'author', 'year')\n
\n\n .where('title', 'Hello')\n .where({ title: 'Hello' })\n .whereIn('id', [1, 2, 3])\n .whereNot(···)\n .whereNotIn('id', [1, 2, 3])\n
\n\n .whereNull('updated_at')\n .whereNotNull(···)\n
\n\n .whereExists('updated_at')\n .whereNotExists(···)\n
\n\n .whereBetween('votes', [1, 100])\n .whereNotBetween(···)\n
\n\n .whereRaw('id = ?', [1])\n
\n\n .where(function () {\n this\n .where('id', 1)\n .orWhere('id', '>', 10)\n })\n
\n\nSee: Where clauses
\n\nknex('users')\n
\n\n .join('contacts', 'users.id', '=', 'contacts.id')\n .join('contacts', {'users.id': 'contacts.id'})\n
\n\n .join('accounts', 'accounts.type', '=', knex.raw('?', ['admin']))\n
\n\n .leftJoin(···)\n .leftOuterJoin(···)\n .rightJoin(···)\n .rightOuterJoin(···)\n .outerJoin(···)\n .fullOuterJoin(···)\n .crossJoin(···)\n
\n\n .joinRaw('natural full join table1')\n
\n\n .join('accounts', function () {\n this\n .on('accounts.id', '=', 'users.account_id')\n .orOn('accounts.owner_id', '=', 'users.id')\n\n .onIn('accounts.id', [1, 2, 3, 5, 8])\n .onNotIn(···)\n\n .onNull('accounts.email')\n .onNotNull(···)\n\n .onExists(function () {\n this.select(···)\n })\n .onNotExists(···)\n })\n
\n\nSee: Join methods
\n\nknex('users')\n .distinct()\n
\n\n .groupBy('count')\n .groupByRaw('year WITH ROLLUP')\n
\n\n .orderBy('name', 'desc')\n .orderByRaw('name DESC')\n
\n\n .offset(10)\n .limit(20)\n
\n\n .having('count', '>', 100)\n .havingIn('count', [1, 100])\n
\n\n .union(function() {\n this.select(···)\n })\n .unionAll(···)\n
\n\nSee: Query builder
\n\nknex('users')\n .pluck('id')\n .then(ids => { ··· })\n
\nknex('users')\n .first()\n .then(user => { ··· })\n
\n\n .count('active')\n .count('active as is_active')\n
\n\n .min('age')\n .max('age')\n .sum('age')\n .sumDistinct('age')\n .avg('age')\n
\n\nSee: Query builder
\n\nknex.schema.createTable('accounts', table => {\n
\n\n table.increments('id')\n table.string('account_name')\n table.integer('age')\n table.float('age')\n table.decimal('balance', 8, 2)\n table.boolean('is_admin')\n table.date('birthday')\n table.time('created_at')\n table.timestamp('created_at').defaultTo(knex.fn.now())\n table.json('profile')\n table.jsonb('profile')\n table.uuid('id').primary()\n
\n\n table.unique('email')\n table.unique(['email', 'company_id'])\n table.dropUnique(···)\n
\n\n table.foreign('company_id')\n .references('companies.id')\n table.dropForeign(···)\n
\n\n table.integer('user_id')\n .unsigned()\n .references('users.id')\n
\n\n})\n.then(() => ···)\n
\n\nSee: Schema builder
\n\nknex.schema.table('accounts', table => {\n
\n\n table.string('first_name')\n
\n\n table.string('first_name').alter()\n table.renameColumn('admin', 'is_admin')\n
\n\n table.dropColumn('admin')\n table.dropTimestamps('created_at')\n
\n\n})\n
\n\nSee: Schema builder
\n\nknex.schema\n .renameTable('persons', 'people')\n .dropTable('persons')\n
\n\n .hasTable('users').then(exists => ···)\n .hasColumn('users', 'id').then(exists => ···)\n
\n\nSee: Schema builder
\n\nknex('users')\n
\n\n .insert({ name: 'John' })\n
\n\n .insert([\n { name: 'Starsky' },\n { name: 'Hutch' }\n ])\n
\n\nSee: Insert
\n\nknex('users')\n .where({ id: 2 })\n .update({ name: 'Homer' })\n
\n\nSee: Update
\n\nknex('users')\n .where({ id: 2 })\n .del()\n
\n\nSee: Delete
\n\n./node_modules/.bin/knex init\n
\n\nknex migrate:make migration_name\nknex migrate:make migration_name --env production\n
\n\nknex migrate:latest\nknex migrate:latest --env production\n
\n\nknex migrate:rollback\nknex migrate:rollback --env production\n
\n\nSee: Migrations
", "intro_html": "Knex is an SQL query builder for Node.js.\nThis guide targets v0.13.0.
", "description_html": "", "tags": null, "updated": "2020-06-03" },{ "id": "koa", "title": "Koa", "url": "/koa", "category": "JavaScript libraries", "keywords": null, "content_html": "app.use(function * (next) {\n var ctx = this\n\n ctx.request\n ctx.response\n\n ctx.body = 'hello'\n\n ctx.state.user = yield User.find(id).fetch()\n\n ctx.cookies.set('foo', 'hello', { signed: true })\n ctx.cookies.get('foo')\n\n ctx.throw(403)\n
\n\n 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 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\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
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "kotlin",
"title": "Kotlin",
"url": "/kotlin",
"category": "Java & JVM",
"keywords": null,
"content_html": "var mutableString: String = \"Adam\"\nval immutableString: String = \"Adam\"\nval inferredString = \"Adam\"\n
\n\nval name = \"Adam\"\nval greeting = \"Hello, \" + name\nval greetingTemplate = \"Hello, $name\"\n
\n\nval intNum = 10\nval doubleNum = 10.0\nval longNum = 10L\nval floatNum = 10.0F\n
\n\nval trueBoolean = true\nval falseBoolean = false\nval andCondition = trueBoolean && falseBoolean\nval orCondition = trueBoolean || falseBoolean\n
\n\nclass Person {\n companion object {\n val NAME_KEY = \"name_key\"\n }\n}\n\nval key = Person.NAME_KEY\n
\n\nval cannotBeNull: String = null // Invalid\nval canBeNull: String? = null // Valid\n\nval cannotBeNull: Int = null // Invalid\nval canBeNull: Int? = null // Valid\n
\n\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\nval nullableStringLength: Int? = nullableString?.length\nval nullableDepartmentHead: String? = person?.department?.head?.name\n
\n\nval nonNullStringLength: Int = nullableString?.length ?: 0\nval nonNullDepartmentHead: String = person?.department?.head?.name ?: \"\"\nval nonNullDepartmentHead: String = person?.department?.head?.name.orEmpty()\n
\n\n// Will not throw ClassCastException\nval nullableCar: Car? = (input as? Car)\n
\n\nval numArray = arrayOf(1, 2, 3)\nval numList = listOf(1, 2, 3)\nval mutableNumList = mutableListOf(1, 2, 3)\n
\n\nval firstItem = numList[0]\nval firstItem = numList.first()\nval firstItem = numList.firstOrNull()\n
\n\nval faceCards = mutableMapOf(\"Jack\" to 11, \"Queen\" to 12, \"King\" to 13)\nval jackValue = faceCards[\"Jack\"] // 11\nfaceCards[\"Ace\"] = 1\n
\n\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\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\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 }\n
\n\nNote: it
is the implicit name for a single parameter.
fun printName() {\n print(\"Adam\")\n}\n\nfun printName(person: Person) {\n print(person.name)\n}\n\nfun getGreeting(person: Person): String {\n return \"Hello, ${person.name}\"\n}\n\nfun getGreeting(person: Person): String = \"Hello, ${person.name}\"\nfun getGreeting(person: Person) = \"Hello, ${person.name}\"\n
\n\nfun callbackIfTrue(condition: Boolean, callback: () -> Unit) {\n if (condition) {\n callback()\n }\n}\n\ncallbackIfTrue(someBoolean) {\n print(\"Condition was true\")\n}\n
\n\nfun Int.timesTwo(): Int {\n return this * 2\n}\n\nval four = 2.timesTwo()\n
\n\nfun getGreeting(person: Person, intro: String = \"Hello,\") {\n return \"$intro ${person.name}\"\n}\n\n// Returns \"Hello, Adam\"\nval hello = getGreeting(Person(\"Adam\"))\n\n// Returns \"Welcome, Adam\"\nval welcome = getGreeting(Person(\"Adam\"), \"Welcome,\")\n
\n\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\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\nclass Person(val name: String, val age: Int)\nval adam = Person(\"Adam\", 100)\n
\n\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\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\nif (someBoolean) {\n doThing()\n} else {\n doOtherThing()\n}\n
\n\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\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\nwhile (x > 0) {\n x--\n}\n\ndo {\n x--\n} while (x > 0)\n
\n\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\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\nKotlin is a statically typed programming language for modern multiplatform applications.
", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "kramdown", "title": "Kramdown", "url": "/kramdown", "category": "Markup", "keywords": null, "content_html": "parse_block_html
- process kramdown syntax inside blocksparse_span_html
- process kramdown syntax inside inlineshtml_to_native
- convert html elements to native elements
For the GFM parser:
\n\nhard_wrap
http://kramdown.gettalong.org/parser/gfm.html
\n\n# _config.yml\nmarkdown: kramdown\nkramdown:\n input: GFM\n
\n\nThis is some text.[^1]. Other text.[^footnote].\n\n[^1]: Some *crazy* footnote definition.\n
\n\nThis is some text not written in HTML but in another language!\n\n*[another language]: It's called Markdown\n*[HTML]: HyperTextMarkupLanguage\n
\n\nA 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\nThese are CSS properties that will cause “layout thrashing”. Avoid changing them to prevent bottlenecks in your UI performance.
", "description_html": "", "tags": null, "updated": "2017-10-19" },{ "id": "ledger-csv", "title": "Ledger CSV format", "url": "/ledger-csv", "category": "Ledger", "keywords": null, "content_html": "$ ledger csv\n
\n\ndate , ? , desc , account , currency , amt , pending/cleared , ?\n\"2013/09/02\" , \"\" , \"things\" , \"Assets:Cash\" , \"P\" , \"-2000\" , \"*\" , \"\"\n\"2013/09/02\" , \"\" , \"things\" , \"Liabilities:Card\" , \"P\" , \"-200\" , \"*\" , \"\"\n\"2013/09/02\" , \"\" , \"things\" , \"Expenses:Things\" , \"P\" , \"2200\" , \"*\" , \"\"\n\"2013/09/04\" , \"\" , \"stuff\" , \"Assets:Cash\" , \"P\" , \"-20\" , \"*\" , \"\"\n\"2013/09/04\" , \"\" , \"stuff\" , \"Expneses:Others\" , \"P\" , \"20\" , \"*\" , \"\"\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "ledger-examples",
"title": "Ledger examples",
"url": "/ledger-examples",
"category": "Ledger",
"keywords": null,
"content_html": "Inspecting transactions:
\n\n# show me expenses for october (--period)\n ledger r Expenses -p oct\n\n# what's the most expensive? (--sorted)\n ledger r Expenses -S amount --tail 10\n\n# how much was spent on grocery? (--weekly, --monthly)\n ledger r Grocery\n ledger r Grocery -W\n ledger r Grocery -M\n\n# what did I spend my Mastercard on? (--period, --begin, --end)\n ledger r mastercard\n ledger r mastercard -p \"january\"\n ledger r mastercard -b 01/25 -e 01/31\n
\n\nGraphing:
\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\nSimple:
\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\nSwitches:
\n\n# what's everything I got in USD? (--exchange)\n ledger b Assets -X USD\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "ledger-format",
"title": "Ledger format",
"url": "/ledger-format",
"category": "Ledger",
"keywords": null,
"content_html": "2015/01/01 Pay rent\n Assets:Savings -$300\n Expenses:Rent\n
\n\n2015/01/01 * Pay rent ; tagname:\n^ ^ ^\nDate Flag Description ^ comment/tag\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* cleared\n! pending\n
\n\nOnly relevant with --strict
or --pedantic
account Expenses:Food\n note This account is all about the chicken!\n alias food\n payee ^(KFC|Popeyes)$\n check commodity == \"$\"\n assert commodity == \"$\"\n eval print(\"Hello!\")\n default\n
\n\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\naccount Home\ninclude home.journal\nend\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "ledger-periods",
"title": "Ledger periods",
"url": "/ledger-periods",
"category": "Ledger",
"keywords": null,
"content_html": "[INTERVAL] [BEGIN] [END]\n
\n\nInterval:
\n\nevery day\nevery week\nevery month\nevery quarter\nevery year\nevery N days # N is any integer\nevery N weeks\nevery N months\nevery N quarters\nevery N years\ndaily\nweekly\nbiweekly\nmonthly\nbimonthly\nquarterly\nyearly\n
\n\nBegin:
\n\nfrom <SPEC>\nsince <SPEC>\n
\n\nThe end time can be either of:
\n\nto <SPEC>\nuntil <SPEC>\n
\n\nSpec:
\n\n2004\n2004/10\n2004/10/1\n10/1\noctober\noct\nthis week # or day, month, quarter, year\nnext week\nlast week\n
\n\nExamples:
\n\n$ ledger r -p \"since last month\"\n
\n\nSee: http://ledger-cli.org/3.0/doc/ledger3.html#Period-Expressions
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ledger-query", "title": "Ledger queries", "url": "/ledger-query", "category": "Ledger", "keywords": null, "content_html": "Query | \nDescription | \n
---|---|
@payee | \n Payee | \n
%tag | \n Tag | \n
=note | \n Note | \n
#code | \n Code | \n
TERM and TERM | \n Boolean and | \n
TERM or TERM | \n Boolean or | \n
not TERM | \n Boolean not | \n
ledger r @taco\nledger r comment =~ /landline/\n
\n\n$ ledger bal\n$ ledger reg\n
\n\n$ ledger reg grocery # show entries for 'grocery'\n$ ledger bal assets # check if i'm broke\n
\n\n -b 01/01 # --begin\n -e 01/31 # --end\n -S date # --sort\n -S amount\n
\n\n# any/all matches\n ledger bal Rent Transportation # any\n ledger bal Income and Job # all\n ledger bal Expenses and not (Drinks or Food)\n
\n\n# what did I spend on most? (--sorted)\n ledger reg Expenses -S amount\n
\n\n# how much did I have at this date? (--end)\n ledger bal -e 01/15 ^Assets ^Liabilities\n
\n\n# how much did I spend and earn this month?\n ledger bal ^Expenses ^Income --invert\n
\n\n# how much was spent over the course of 3 days? (totalled)\n ledger reg -b 01/25 -e 01/27 --subtotal\n ledger reg -b 01/25 -e 01/27 --subtotal grocery\n
\n\n2013/01/03 * Rent for January\n Expenses:Rent $600.00\n Assets:Savings\n
\n\n*
= cleared, !
= pending
2008/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\n2008/01/01 * KFC\n Expenses:Food $20\n Assets:Cash $-20 = $500\n
\n\nCash $X = $500
ensures Cash is at $500 after the transaction.
2008/01/01 * Cash balance\n Assets:Cash = $500\n Equity:Adjustments\n\n2008/01/01 * KFC\n Expenses:Food $20\n Assets:Cash = $500\n
\n\nACCOUNT = $500
figures out what’s needed to make it $500.
2008/04/25 * Rent\n (Assets:Checking) -$200\n Expenses:Rent\n
\n\n; cost per item\n2010/05/31 * Market\n Assets:Fridge 35 apples @ $0.42\n Assets:Cash\n
\n\n; total cost\n2010/05/31 * Market\n Assets:Fridge 35 apples @@ $14.70\n Assets:Cash\n
\n\n; fixed lot prices\n2010/05/31 * Gas\n Expenses:Gasoline 11 GAL {=$2.299}\n Assets:Cash\n
\n\ncommodity $\n note American Dollars\n format $1,000.00\n nomarket\n default\n
\n\n~ Monthly\n Expenses:Rent $500\n Expenses:Food $100\n Expenses $40 ; everything else\n Assets\n\n~ Yearly\n
\n\nledger bal --budget Expenses\nledger bal --unbudgeted Expenses\n
\n\n; line comment\n# also line comment\n% also line comment\n| also line comment\n* also line comment\n
\n\n[interval] [begin] [end]\n
\n\ninterval:\n every day|week|month|quarter|year\n every N days|weeks|...\n daily|weekly|...\n
\n\nbegin:\n from <spec>\nend:\n to <spec>\n
\n\nspec:\n 2004\n 2004/10/1\n
\n\n$ ledger bal|reg --period \"until aug\"\n$ ledger bal|reg --period \"last oct\"\n$ ledger bal|reg --period \"every week\"\n
\n\n$ ledger reg\n
\n\n -D, --daily\n -W, --weekly\n -M, --monthly\n --quarterly\n -Y, --yearly\n -s, --subtotal\n --start-of-week monday\n
\n\n -S, --sort date\n -S, --sort amount\n
\n\n-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^regex$\n@payee\n%tag\n%tag=value\n=note\n#code\nterm and term\nterm or term\nnot term\n\\( term \\)\n
\n\nExample:
\n\nledger r ^expenses and @Denny's\nledger r food and @Starbucks and not dining\n
\n\n-n, --collapse # [register] collapse entries\n # [balance] no grand total\n-s, --subtotal # [balance] show sub-accounts\n # [other] show subtotals\n--flat\n
\n\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\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\n2008/01/01=2008/01/15 Client invoice ; actual date money received\n Assets:Accounts Receivable $100.00\n Income: Client name\n
\n\nunit(30px / 5px) #=> 6\nunit(5, px) #=> 5px\n\ne(\"ms:stuff()\") #=> ms:stuff() (unquote)\n\n%(\"count: %d\", 1+2) #=> \"count: 3\"\n\niscolor(@x)\nisstring(@x)\nisnumber(@x)\niskeyword(@x)\nisurl(url(...))\nispixel()\nisem()\nispercentage()\nisunit()\n\nhue(@color)\nsaturation(@color)\nlightness(@color)\nluma(@color)\nluminance(@color)\n\nfade(@color, amount)\nfadein(@color, amount)\nfadeout(@color, amount)\nspin(@color, degrees)\nmix(@a, @b, amount)\n
\n\n.image when (luma(@color) > 50%) { }\n.image when (not(...)) { }\n.image when (default()) {}\n.image when (e(@shape) = 'circle') { }\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "licenses",
"title": "Licenses",
"url": "/licenses",
"category": "Others",
"keywords": null,
"content_html": "The MIT License (MIT)\n\nCopyright (c) 2015 $NAME\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n
\n\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\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\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
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2017-08-30"
},{
"id": "linux",
"title": "Linux",
"url": "/linux",
"category": "Others",
"keywords": null,
"content_html": "$ mount -t tmpfs -o size=5G,nr_inodes=5k,mode=700 tmpfs /tmp\n
\n\nsudo visudo\n\nusername ALL=(ALL) NOPASSWD:/sbin/restart whatever\n
\n\ndf\ndf -h # human-readable format\ndf -a # all filesystems\n
\n\ndu\ndu -hsx * | sort -rh | head -10 # largest 10 folders\n
\n\nyes | /your/command\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "lodash",
"title": "Lodash",
"url": "/lodash",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "_.filter(list, (n) => n % 2) // → Array\n_.find(list, (n) => n % 2) // → item\n_.findLast(list, ...) // → item\n
\n\nWorks for both arrays and objects.
\n\n_.at([ abcd ], 0) // → [ a ] - same as list[0]\n_.at([ abcd ], [ 0, 1 ]) // → [ ab ]\n
\n\n_.set(object, 'users[0].name', value)\n_.get(object, 'users[0].name')\n_.get(object, ['users', 0, 'name'])\n
\n\n_.forEach(list, (item, i) => ...)\n_.forEachRight(list, ...)\n\n_.map(list, ...)\n
\n\n_.every(users, (u) => u.active) // → true|false (aka _.all)\n_.any(users, ...) // → true|false (aka _.some)\n
\n\n_.chunk([ abcd ], 2) // → [ [ab], [cd] ]\n_.compact(list)\n\n_.fill(Array(4), 'x') // → [ 'x', 'x', 'x', 'x' ]\n_.flatten\n_.flattenDeep\n
\n\n_.drop([ abcdef ], 2) // → [ cdef ]\n_.dropRight([ abcdef ], 2) // → [ abcd ]\n_.take([ abcdef ], 2) // → [ ab ]\n_.takeRight([ abcdef ], 2) // → [ de ]\n_.slice([ abcdef ], 2, 4) // → [ cd ]\n
\n\n_.initial([ abcdef ]) // → [ abcde ] - dropRight(list, 1)\n_.rest([ abcdef ]) // → [ bcdef ] - takeRight(list, 1)\n
\n\n_.dropWhile(list, 'active') // works like filter\n_.dropWhile(list, 'active', true)\n_.dropWhile(list, { active: true })\n_.dropWhile(list, (n) => ...)\n_.dropRightWhile(list, ...)\n
\n\n_.without([ abcde ], b) // → [ acde ]\n
\n\n_.remove(list, (n) => n % 2)\n
\n\n_.first([ abcdef ]) // → a\n_.last([ abcdef ]) // → f\n
\n\n_.uniq()\n_.difference([ abc ], [ bc ]) // → [ a ]\n_.intersection([ abc ], [ bcd ]) // → [ bc ]\n_.union([ abc ], [ bcd ]) // → [ abcd ] (unique)\n
\n\nArray#concat()\n
\n\n_.findIndex(list, fn)\n_.findLastIndex(list, fn)\n
\n\n_.sortedIndex(list, val)\n_.sortedLastIndex(list, val)\n
\n\n_.indexOf(list, val)\n
\n\ngreet = (greeting, name) => `${greeting}, ${name}!`\n
\n\nfn = _.partial(fn, 'hi')\nfn('joe') // → 'hi, joe!'\n\nfn = _.partial(fn, 'joe')\nfn('yo') // → 'yo, joe!'\n
\n\n_.curry(greet)('hi') // → function(name)\n_.curryRight(greet)('joe') // → function(greet)\n
\n\n_.throttle(fn)\n_.debounce(fn)\n
\n\n_.before(5, fn) // only works 5 times\n_.after(5, fn) // works only after 5 times\n_.once(fn) // like _.before(fn, 1)\n
\n\n_.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_.capitalize('hello world') // → 'Hello world'\n_.startCase('hello_world') // → 'Hello World'\n_.snakeCase('hello world') // → 'hello_world'\n_.kebabCase('hello world') // → 'hello-world'\n_.camelCase('hello world') // → 'helloWorld'\n
\n\n_.pad('abc', 3) // → 'abc'\n_.pad('abc', 8) // → ' abc '\n_.pad('abc', 8, '_-') // → '_-abc_-_'\n_.padStart('abc', 3) // → 'abc'\n_.padStart('abc', 6) // → ' abc'\n_.padStart('abc', 6, '_-')// → '_-_abc'\n_.padEnd('abc', 3) // → 'abc'\n_.padEnd('abc', 6) // → 'abc '\n_.padEnd('abc', 6, '_-') // → 'abc_-_'\n
\n\n_.trim(' str ') // → 'str' \n_.trimLeft(' str ') // → 'str '\n_.trimRight(' str ') // → ' str'\n
\n\n_.repeat('-', 2) // → '--'\n_.deburr('déjà vu') // → 'deja vu'\n_.trunc('hello world', 5) // → 'hello...'\n
\n\n_.startsWith('abc', 'a') // → true\n_.endsWith('abc', 'c') // → true\n
\n\n_.keys(obj)\n_.values(obj)\n
\n\n_([1, 2, 3])\n .reduce((total, n) => total + n)\n .map((n) => n * n)\n .tap(console.log)\n .thru((n) => n.reverse())\n .value()\n
",
"intro_html": "",
"description_html": "This is not a complete list.
", "tags": null, "updated": "2020-06-24" },{ "id": "lua", "title": "Lua", "url": "/lua", "category": "Others", "keywords": null, "content_html": "-- comment\n--[[ Multiline\n comment ]]\n
\n\nprint()\nprint(\"Hi\")\n\n-- You can omit parentheses if the argument is one string or table literal\nprint \"Hello World\" <--> print(\"Hello World\")\ndofile 'a.lua' <--> dofile ('a.lua')\nprint [[a multi-line <--> print([[a multi-line\n message]] message]])\nf{x=10, y=20} <--> f({x=10, y=20})\ntype{} <--> type({})\n
\n\nt = {}\nt = { a = 1, b = 2 }\nt.a = function() ... end\n\nt = { [\"hello\"] = 200 }\nt.hello\n\n-- Remember, arrays are also tables\narray = { \"a\", \"b\", \"c\", \"d\" }\nprint(array[2]) -- \"b\" (one-indexed)\nprint(#array) -- 4 (length)\n
\n\nwhile condition do\nend\n\nfor i = 1,5 do\nend\n\nfor i = start,finish,delta do\nend\n\nfor k,v in pairs(tab) do\nend\n\nrepeat\nuntil condition\n\n-- Breaking out:\nwhile x do\n if condition then break end\nend\n
\n\nif condition then\n print(\"yes\")\nelseif condition then\n print(\"maybe\")\nelse\n print(\"no\")\nend\n
\n\nlocal x = 2\ntwo, four = 2, 4\n
\n\nfunction myFunction()\n return 1\nend\n\nfunction myFunctionWithArgs(a, b)\n -- ...\nend\n\nmyFunction()\n\nanonymousFunctions(function()\n -- ...\nend)\n\n-- Not exported in the module\nlocal function myPrivateFunction()\nend\n\n-- Splats\nfunction doAction(action, ...)\n print(\"Doing '\"..action..\"' to\", ...)\n --> print(\"Doing 'write' to\", \"Shirley\", \"Abed\")\nend\n\ndoAction('write', \"Shirley\", \"Abed\")\n
\n\nmytable = { x = 2, y = function() .. end }\n\n-- The same:\nmytable.x\nmytable['x']\n\n-- Syntactic sugar, these are equivalent:\nmytable.y(mytable)\nmytable:y()\n\nmytable.y(mytable, a, b)\nmytable:y(a, b)\n\nfunction X:y(z) .. end\nfunction X.y(self, z) .. end\n
\n\nmt = {}\n\n-- A metatable is simply a table with functions in it.\nmt.__tostring = function() return \"lol\" end\nmt.__add = function(b) ... end -- a + b\nmt.__mul = function(b) ... end -- a * b\nmt.__index = function(k) ... end -- Lookups (a[k] or a.k)\nmt.__newindex = function(k, v) ... end -- Setters (a[k] = v)\n\n-- Metatables allow you to override behavior of another table.\nmytable = {}\nsetmetatable(mytable, mt)\n\nprint(myobject)\n
\n\nAccount = {}\n\nfunction Account:new(balance)\n local t = setmetatable({}, { __index = Account })\n\n -- Your constructor stuff\n t.balance = (balance or 0)\n return t\nend\n\nfunction Account:withdraw(amount)\n print(\"Withdrawing \"..amount..\"...\")\n self.balance = self.balance - amount\n self:report()\nend\n\nfunction Account:report()\n print(\"Your current balance is: \"..self.balance)\nend\n\na = Account:new(9000)\na:withdraw(200) -- method call\n
\n\nnil\nfalse\ntrue\n
\n\n-- Relational (binary)\n-- __eq __lt __gt __le __ge\n == < > <= >=\n~= -- Not equal, just like !=\n\n-- Arithmetic (binary)\n-- __add __sub __muv __div __mod __pow\n + - * / % ^\n\n-- Arithmetic (unary)\n-- __unm (unary minus)\n -\n\n-- Logic (and/or)\nnil and false --> nil\nfalse and nil --> false\n0 and 20 --> 20\n10 and 20 --> 20\n\n\n-- Length\n-- __len(array)\n#array\n\n\n-- Indexing\n-- __index(table, key)\nt[key]\nt.key\n\n-- __newindex(table, key, value)\nt[key]=value\n\n-- String concat\n-- __concat(left, right)\n\"hello, \"..name\n\n-- Call\n-- __call(func, ...)\n
\n\ndofile(\"hello.lua\")\nloadfile(\"hello.lua\")\n\nassert(x) -- x or (raise an error)\nassert(x, \"failed\")\n\ntype(var) -- \"nil\" | \"number\" | \"string\" | \"boolean\" | \"table\" | \"function\" | \"thread\" | \"userdata\"\n\n-- Does /not/ invoke meta methods (__index and __newindex)\nrawset(t, index, value) -- Like t[index] = value\nrawget(t, index) -- Like t[index]\n\n_G -- Global context\nsetfenv(1, {}) -- 1: current function, 2: caller, and so on -- {}: the new _G\n\npairs(t) -- iterable list of {key, value}\nipairs(t) -- iterable list of {index, value}\n\ntonumber(\"34\")\ntonumber(\"8f\", 16)\n
\n\n'string'..'concatenation'\n\ns = \"Hello\"\ns:upper()\ns:lower()\ns:len() -- Just like #s\n\ns:find()\ns:gfind()\n\ns:match()\ns:gmatch()\n\ns:sub()\ns:gsub()\n\ns:rep()\ns:char()\ns:dump()\ns:reverse()\ns:byte()\ns:format()\n
\n\ntable.foreach(t, function(row) ... end)\ntable.setn\ntable.insert(t, 21) -- append (--> t[#t+1] = 21)\ntable.insert(t, 4, 99)\ntable.getn\ntable.concat\ntable.sort\ntable.remove(t, 4)\n
\n\nmath.abs math.acos math.asin math.atan math.atan2\nmath.ceil math.cos math.cosh math.deg math.exp\nmath.floor math.fmod math.frexp math.ldexp math.log\nmath.log10 math.max math.min math.modf math.pow\nmath.rad math.random math.randomseed math.sin math.sinh\nmath.sqrt math.tan math.tanh\n\nmath.sqrt(144)\nmath\n
\n\nio.output(io.open(\"file.txt\", \"w\"))\nio.write(x)\nio.close()\n\nfor line in io.lines(\"file.txt\")\n\nfile = assert(io.open(\"file.txt\", \"r\"))\nfile:read()\nfile:lines()\nfile:close()\n
\n\nhttp://www.lua.org/pil/13.html\n http://lua-users.org/wiki/ObjectOrientedProgramming
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "machinist", "title": "Machinist", "url": "/machinist", "category": "Ruby libraries", "keywords": null, "content_html": "# Gemfile\ngem 'machinist', '>= 2.0.0.beta2', group: 'test'\n\n# ~$ bundle\n# ~$ rails generate machinist:install\n
\n\nUser.make\n\n# `make` builds it, and `make!` builds+saves it\nUser.make!\nUser.make! name: \"David\"\nUser.make!(:admin)\n
\n\nUser.blueprint do\n name { \"User #{sn}\" }\n email { \"user-#{sn}@example.com\" }\nend\n\nUser.blueprint(:admin) do\n name { \"Admin User #{sn}\" }\n admin { true }\nend\n
\n\nPost.blueprint do\n author { User.make }\n\n comments(3) # Makes 3 comments (has_many / habtm)\n\n author # autodetect (Assumes there's User.blueprint)\n\nend\n
\n\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\nUnder System Preferences → Mouse, change Tracking Speed.
\n\ndefaults write .GlobalPreferences com.apple.trackpad.scaling -1\n
\n\nWorks the same way, but only affects trackpads.
\n\nDisable mouse acceleration with this one weird trick.
", "description_html": "", "tags": null, "updated": "2018-03-20" },{ "id": "make-assets", "title": "Make for assets", "url": "/make-assets", "category": "Others", "keywords": null, "content_html": "bin := ./node_modules/.bin\n\nall: build/foo.js\n\nbuild/%.js: src/%.coffee\n @$(bin)/coffee < $^ > $@\n
\n\nbin := ./node_modules/.bin\nstylus := $(bin)/stylus\nautoprefixer := $(bin)/autoprefixer\nstyl_files := $(shell find web/ -name \"*.styl\")\n\nall: public/app.css\n\npublic/app.css: css/app.styl\n\n%.css: %.styl $(styl_files)\n @$(stylus) $< | $(autoprefixer) -b \"> 1%\" > $@\n
\n\nhint:\n $(js_files)\n
\n\nwatch:\n @echo \"... watching for changes\"\n @while true; do make -s; sleep 1; done\n
\n\njs_files := $(shell find web/ -name \"*.js\")\n\npublic/app.js: web/app.js\npublic/vendor.js: web/vendor.js\n\npublic/%.js: web/%.js $(js_files)\n $(browserify) -t [ cssify -x .css ] $< > $@\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "makefile",
"title": "Makefile",
"url": "/makefile",
"category": "CLI",
"keywords": null,
"content_html": "uglify = $(uglify) # lazy assignment\ncompressor := $(uglify) # immediate assignment\nprefix ?= /usr/local # safe assignment\nhello += world # append\n
\n\n=
expressions are only evaluated when they’re being used.
out.o: src.c src.h\n $@ # \"out.o\" (target)\n $< # \"src.c\" (first prerequisite)\n $^ # \"src.c src.h\" (all prerequisites)\n\n%.o: %.c\n $* # the 'stem' with which an implicit rule matches (\"foo\" in \"foo.c\")\n\nalso:\n $+ # prerequisites (all, with duplication)\n $? # prerequisites (new ones)\n $| # prerequisites (order-only?)\n\n $(@D) # target directory\n
\n\nPrefix | \nDescription | \n
---|---|
- | \n Ignore errors | \n
@ | \n Don’t print command | \n
+ | \n Run even if Make is in ‘don’t execute’ mode | \n
build:\n @echo \"compiling\"\n -gcc $< $@\n\n-include .depend\n
\n\njs_files := $(wildcard test/*.js)\nall_files := $(shell find images -name \"*\")\n
\n\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$(strip $(string_var))\n\n$(filter %.less, $(files))\n$(filter-out %.less, $(files))\n
\n\n%.o: %.c\n ffmpeg -i $< > $@ # Input and output\n foo $^\n
\n\n-include foo.make\n
\n\nmake\n -e, --environment-overrides\n -B, --always-make\n -s, --silent\n\n -j, --jobs=N # parallel processing\n
\n\nfoo: $(objects)\nifeq ($(CC),gcc)\n $(CC) -o foo $(objects) $(libs_for_gcc)\nelse\n $(CC) -o foo $(objects) $(normal_libs)\nendif\n
\n\ndeploy:\n $(MAKE) deploy2\n
\n\n1 | \n General User Commands | \n
2 | \n System Calls | \n
3 | \n Library Routines | \n
4 | \n Special Files and Sockets | \n
5 | \n File formats and Conventions | \n
6 | \n Games and Fun Stuff | \n
7 | \n Miscellaneous Documentation | \n
8 | \n System Administration | \n
9 | \n Kernel and Programming Style | \n
n | \n Tcl/Tk | \n
# h1\n## h2\n### h3\n#### h4\n##### h5\n###### h6\n
\n\nHeader 1\n========\n
\n\nHeader 2\n--------\n
\n\n*italic*\n_italic_\n
\n\n**bold**\n__bold__\n
\n\n`code`\n
\n\n* Item 1\n* Item 2\n
\n\n- Item 1\n- Item 2\n
\n\n- [ ] Checkbox off\n- [x] Checkbox on\n
\n\n1. Item 1\n2. Item 2\n
\n\n[link](http://google.com)\n
\n\n[link][google]\n[google]: http://google.com\n
\n\n<http://google.com>\n
\n\n\n\n![Image alt text][img]\n
\n\n[img]: http://foo.com/img.jpg\n
\n\n 4 space indent\n makes a code block\n
\n\n```\ncode fences\n```\n
\n\n```js\ncodeFences.withLanguage()\n```\n
\n\n> This is\n> a blockquote\n>\n> > Nested\n> > Blockquote\n
\n\n----\n
\n\n****\n
\n\n| Column 1 Heading | Column 2 Heading |\n| ---------------- | ---------------- |\n| Some content | Other content |\n
\n\nColumn 1 Heading | Column 2 Heading\n--- | ---\nSome content | Other content\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2020-07-01"
},{
"id": "meow",
"title": "Meow",
"url": "/meow",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "const cli = require('meow')(`\n Usage: appname [options]\n\n Options:\n --lang LANG set the language\n\n Other options:\n -h, --help show usage information\n -v, --version print version info and exit\n`, {\n string: ['lang'],\n boolean: ['help', 'version'],\n alias: { h: 'help', v: 'version' }\n})\n
\n\nstring
and boolean
lets meow/minimist know which flags expect arguments (string
) and which don’t (boolean
).
cli.flags // { lang: 'en' }\ncli.input // []\n
\n\nYes, flags are automatically camelCased!
\n\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.
", "intro_html": "meow is the easiest way to write command line apps for Node.js.
", "description_html": "", "tags": null, "updated": "2017-10-30" },{ "id": "meta-tags", "title": "Meta-tags gem", "url": "/meta-tags", "category": "Ruby libraries", "keywords": null, "content_html": "set_meta_tags title: 'Member Login'\n# <title>Some Page Title</title>\n
\n\nset_meta_tags site: 'Site Title', title: 'Member Login'\n# <title>Site Title | Page Title</title>\n
\n\nset_meta_tags(\n site: 'Site Title',\n title: 'Member Login',\n reverse: true,\n separator: '·'.html_safe\n)\n# <title>Page Title · Site Title</title>\n
\n\nWorks in a controller or a view.
\n\nrails generate meta_tags:install\n
\n\nThis creates config/initializers/meta_tags.rb
that you can edit.
set_meta_tags site: 'Site name'\nset_meta_tags title: 'Title'\nset_meta_tags description: \"All text about keywords\"\n
\n\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\nset_meta_tags noindex: true\nset_meta_tags nofollow: true\nset_meta_tags follow: true\n
\n\nset_meta_tags og: { image: ['...'] }\nset_meta_tags twitter: { description: '...' }\n
\nset_meta_tags separator: '·' # Site · Page title\nset_meta_tags prefix: ' ' # Around the separator\nset_meta_tags suffix: ' '\n
\n\nset_meta_tags lowercase: true # Lowercase page title\nset_meta_tags reverse: true # Site name last\n
\n\n# Displaying tags\n<%= display_meta_tags %>\n
\n\n# Displaying tags individually\n<h1><%= title %></h1>\n
\n\n# Setting tags\n<% title 'Member Login' %>\n<% description 'My page' %>\n<% keywords '..' %>\n
\n\nSee: Examine.com
\n\nSee: Examine.com
\n\nSee: Examine.com
\n\nSee: Examine.com
\n\nSee: nih.gov
\n\nSee: Examine.com
\n\nSee: Examine.com
\n\nSee: nih.gov
\n\nSee: whfoods.com
\n\nSee: nih.gov
\n\nSee: whfoods.com
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "middleman", "title": "Middleman 3", "url": "/middleman", "category": "JavaScript libraries", "keywords": null, "content_html": "NB: This is for Middleman 3, not Middleman 4+.
\n\ncompass_config do |config|\n config.output_style = :compact\nend\n
\n\n# Automatic image dimensions on image_tag helper\nactivate :automatic_image_sizes\n
\n\n# Susy grids in Compass\n# First: gem install compass-susy-plugin\nrequire 'susy'\n\n# CodeRay syntax highlighting in Haml\n# First: gem install haml-coderay\nrequire 'haml-coderay'\n\n# CoffeeScript filters in Haml\n# First: gem install coffee-filter\nrequire 'coffee-filter'\n
\n\n# With no layout\npage \"/path/to/file.html\", :layout => false\n\n# With alternative layout\npage \"/path/to/file.html\", :layout => :otherlayout\n\n# A path which all have the same layout\nwith_layout :admin do\n page \"/admin/*\"\nend\n\n# Proxy (fake) files\npage \"/this-page-has-no-template.html\", :proxy => \"/template-file.html\" do\n @which_fake_page = \"Rendering a fake page with a variable\"\nend\n
\n\nhelpers do\n def some_helper\n \"Helping\"\n end\nend\n
\n\nset :css_dir, \"alternative_css_directory\"\nset :js_dir, \"alternative_js_directory\"\nset :images_dir, \"alternative_image_directory\"\n
\n\nconfigure :build do\n activate :minify_css\n activate :minify_javascript\n\n # Enable cache buster\n activate :cache_buster\n\n # Use relative URLs\n activate :relative_assets\n\n # Compress PNGs after build\n # First: gem install middleman-smusher\n # require \"middleman-smusher\"\n activate :smusher\n\n # Or use a different image path\n set :http_path, \"/Content/images/\"\nend\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "minimist",
"title": "minimist",
"url": "/minimist",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "var minimist = require('minimist')\n
\n\nvar args = minimist(process.argv.slice(2), {\n string: 'lang', // --lang xml\n boolean: ['version'], // --version\n alias: { v: 'version' }\n})\n
\n\nconsole.log(args)\n
\n\nAll options are optional, but it’s recommended you set string
and boolean
at least.
var args = minimist(process.argv.slice(2), {\n string: [ 'lang' ],\n boolean: [ 'pager' ],\n alias: { h: 'help', v: 'version' },\n default: { lang: 'en' },\n '--': true,\n stopEarly: true, /* populate _ with first non-option */\n unknown: function () { ... } /* invoked on unknown param */\n})\n
\n\nAll options are optional.
\n\nWith --lang xml --no-pager -h index.js package.json
, you get:
args == {\n lang: 'xml',\n version: false,\n h: true,\n help: true,\n _: [ 'index.js', 'package.json' ]\n}\n
\n\nUse meow to automatically add support for --help
, --version
and more.
meow(`\n Usage:\n $0 FILES [options]\n\n Options:\n -h, --help print usage information\n -v, --version show version info and exit\n`, {\n alias: { h: 'help', v: 'version' }\n /* minimist options */\n})\n
\n\nrequire 'minitest/autorun'\n\ndescribe \"X\" do\n before do .. end\n after do .. end\n subject { .. }\n let(:list) { Array.new }\n\n it \"should work\" do\n assert true\n end\nend\n
\n\nexpect(x)\n.must_be :==, 0\n.must_equal b\n.must_be_close_to 2.99999\n.must_be_same_as b\n\n.must_include needle\n.must_be_empty\n\n.must_be_kind_of\n.must_be_instance_of\n.must_be_nil\n.must_match /regex/\n.must_be :<=, 42\n.must_respond_to msg\n\n.must_be_silent ( proc { \"no stdout or stderr\" }.must_be_silent)\n.must_output \"hi\"\n\nproc { ... }.must_output out_or_nil [, err]\nproc { ... }.must_raise exception\nproc { ... }.must_throw sym\n
\n\nclass TestHipster < Minitest::Test\n def setup\n @subject = [\"silly hats\", \"skinny jeans\"]\n end\n\n def teardown\n @hipster.destroy!\n end\n\n def test_for_helvetica_font\n assert_equal \"helvetica!\", @hipster.preferred_font\n end\n\n def test_not_mainstream\n refute @hipster.mainstream?\n end\nend\n
\n\nassert\nassert_block { ... }\nassert_empty\nassert_equal 2, @size\nassert_in_delta @size, 1, 1\nassert_in_epsilon\nassert_includes @list, \"item\"\nassert_instance_of Array, @list\nassert_kind_of Enumerable, @list\nassert_match @str, /regex/\nassert_nil\nassert_operator @n, :==, 0\nassert_output\nassert_raises\nassert_respond_to\nassert_same\nassert_send\nassert_silent\nassert_throws\n
\n\nA simple and clean mock system. There two essential methods at our disposal: expect and verify.
\n\nrequire 'minitest/autorun'\n\ndescribe Twipster, \"Make every tweet a hipster tweet.\" do\n before do\n @twitter = Minitest::Mock.new\n @twipster = Twipster.new(@twitter)\n end\n\n it \"should append a #lolhipster hashtag and update Twitter with our status\" do\n tweet = \"Skyrim? Too mainstream.\"\n @twitter.expect :update, true, [\"#{tweet} #lolhipster\"]\n @twipster.submit(tweet)\n assert @twitter.verify # verifies tweet and hashtag was passed to `@twitter.update`\n end\nend\n
\n\ngem 'minitest-reporters'\n\nrequire 'minitest/reporters'\nMinitest::Reporters.use! Minitest::Reporters::SpecReporter.new\n\n[Default, Spec, Progress, RubyMate, RubyMine, JUnit]\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "mixpanel",
"title": "Mixpanel",
"url": "/mixpanel",
"category": "Analytics",
"keywords": null,
"content_html": "mixpanel.identify('284')\nmixpanel.people.set({ $email: 'hi@gmail.com' })\n
\n\n// Set common properties\nmixpanel.register({ age: 28, gender: 'male' })\n
\n\nmixpanel.track('Login success')\nmixpanel.track('Search', { query: 'cheese' })\n
\n\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\nclass Page {\n @action publish () {\n this.published = true\n // do ajax/async here if you like\n }\n}\n
\n\nconst person = observable({\n name: 'Ella Fitzgerald'\n})\n
\n\nconst temp = observable(23)\ntemp.get()\ntemp.set(25)\ntemp.observe(...)\n
\n\nimport {autorun, autorunAsync, when} from 'mobx'\n
\n\n// Runs it, finds out what it accessed, then observe those\nautorun(() => {\n console.log(page.title)\n})\n
\n\nclass Foo {\n constructor () {\n when(\n () => !this.isVisible,\n () => this.doSomething())\n }\n}\n
\n\n// A temporary computed value. Its result is cached.\nrender () {\n const isPublished = expr(() => page.published === true)\n if (isPublished) { ... }\n}\n
\n\nasMap(obj)
- JS map (dynamic keys)asReference(fn)
- don’t observe measStructure(obj)
- JS object (observe as deepEqual)asFlat(array)
- JS array (observe its children)import { observer } from 'mobx-react'\n\n@observer\nclass PageView extends React.Component {\n render () {\n return <div>{this.props.page.title}</div>\n }\n}\n\n<PageView page={page} />\n
\n\nimport { observer } from 'mobx-react'\n\nconst PageView = observer(({page}) => {\n <div>{page.title}</div>\n})\n\n<PageView page={page} />\n
\n\nInstall blanket:
\n\nnpm i --save-dev blanket\n
\n\nIn your test helpers, use Blanket before require
ing:
if (process.env.COVERAGE) {\n require('blanket')({\n pattern: require('path').resolve('./index.js')\n });\n}\nthing = require('../index');\n
\n\nAdd to package.json
:
\"scripts\": {\n \"coverage\": \"env COVERAGE=1 mocha -R html-cov > coverage.html && open coverage.html\"\n}\n
\n\nBe sure to ignore it:
\n\necho \"coverage.html\" >> .gitignore\n
\n\nThen run:
\n\nnpm run coverage\n
\n\nVisit coveralls.io then activate your repo. Then install the appropriate packages:
\n\nnpm i --save-dev mocha-lcov-reporter coveralls\n
\n\nAdd this to .travis.yml
:
after_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.
", "intro_html": "Use blanket for easy coverage reporting for Mocha JavaScript tests.
", "description_html": "", "tags": null, "updated": null },{ "id": "mocha-html", "title": "Mocha HTML", "url": "/mocha-html", "category": "JavaScript libraries", "keywords": null, "content_html": "This is a mocha template that loads js/css from cdn.
\n\n<!doctype html>\n<html>\n<head>\n <meta charset='utf-8'>\n <title>Mocha</title>\n <meta name='viewport' content='width=device-width, initial-scale=1.0'>\n <link href='https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css' rel='stylesheet' />\n</head>\n<body>\n <div id='mocha'></div>\n <script src='https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js'></script>\n <script src='https://cdn.rawgit.com/chaijs/chai/2.3.0/chai.js'></script>\n <script>window.onerror=function(msg,url,line){document.getElementById('mocha').innerHTML+='<h1>'+msg+'</'+'h1>'+'<h2>'+url+':'+line+'</'+'h2>';return false}</script>\n <script>mocha.setup('bdd')</script>\n <!-- what to test: -->\n <script src='../index.js'></script>\n <!-- tests to run: -->\n <script src='first_test.js'></script>\n <script src='second_test.js'></script>\n <script>mocha.run()</script>\n</body>\n</html>\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "mocha-tdd",
"title": "Mocha.js TDD interface",
"url": "/mocha-tdd",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "mocha.setup('tdd');\n\nsuite('something', function() {\n setup(function() {\n });\n\n test('should work', function() {\n });\n\n teardown(function() {\n });\n});\n
\n\ntest('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\nvar expect = chai.expect;\n\nexpect(foo).to.be.a('string');\nexpect(foo).to.equal('bar');\nexpect(foo).to.have.length(3);\nexpect(tea).to.have.property('flavors').with.length(3);\n
\n\nmocha.setup('bdd');\n\ndescribe('something', function() {\n beforeEach(function() {\n });\n\n it('should work', function() {\n });\n});\n
\n\nit('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\nchai.should();\n\nfoo.should.be.a('string');\nfoo.should.equal('bar');\nfoo.should.have.length(3);\ntea.should.have.property('flavors').with.length(3);\n
\n\nUser = Modella('User')\n
\n\n .attr('name')\n .attr('email', { required: true })\n .use(require('modella-validators'))\n
\n\n .validator (u) ->\n u.error('username', 'is required') unless u.has('username')\n
\n\nuser\n .name()\n .name('John')\n .set(name: 'John')\n
\n\n .has('name') # → true\n .isNew()\n .isValid()\n
\n\n .save (err) ->\n .remove (err) ->\n .removed\n .model # === User\n
\n\nModel.emit('event', [data...])\n
\n\nrecord.emit('event', [data...])\n
\n\nuser\n .on 'save', ->\n .on 'create', ->\n .on 'saving', (data, done) -> done()\n
\n\n .on 'remove', ->\n .on 'removing', (data, done) -> done()\n
\n\n .on 'valid', ->\n .on 'invalid', ->\n
\n\n .on 'change', ->\n .on 'change email', ->\n
\n\n .on 'initializing', (instance, attrs) ->\n .on 'initialize', ->\n
\n\n .on 'error', -> failed to save model\n
\n\n .on 'setting', (instance, attrs) -> # on Model#set()\n .on 'attr', -> # new attr via Model.attr()\n
\n\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\nUser\n .all (err, users) ->\n .find id, (err, user) ->\n
\n\n .remove ->\n .save ->\n .update ->\n
",
"intro_html": "Modella allows you to create simple models in JavaScript. This is a guide on basic usage of Modella in CoffeeScript.
", "description_html": "", "tags": null, "updated": null },{ "id": "modernizr", "title": "Modernizr", "url": "/modernizr", "category": "JavaScript libraries", "keywords": null, "content_html": "<script src='//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js'></script>\n
\n\nJavaScript
\n\nCSS
\n\nHTML5
\n\nm = moment('2013-03-01', 'YYYY-MM-DD')\n
\n\nThis parses the given date using the given format. Returns a moment object.
\n\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\nm.add(1, 'day')\nm.subtract(2, 'days')\n
\n\nm.startOf('day')\nm.endOf('day')\nm.startOf('hour')\n
\n\n.format('L') // 06/09/2014\n.format('l') // 6/9/2014\n.format('LL') // June 9 2014\n.format('ll') // Jun 9 2014\n.format('LLL') // June 9 2014 9:32 PM\n.format('lll') // Jun 9 2014 9:32 PM\n.format('LLLL') // Monday, June 9 2014 9:32 PM\n.format('llll') // Mon, Jun 9 2014 9:32 PM\n
\n\nSee datetime for more.
\n\nExample | \nOutput | \n
---|---|
YYYY-MM-DD | \n 2014-01-01 | \n
dddd, MMMM Do YYYY | \n Friday, May 16th 2014 | \n
Example | \nOutput | \n
---|---|
hh:mm a | \n 12:30 pm | \n
Used by Moment.js and date-fns/format. Similar to Java SimpleDateFormat.
\n\nSymbol | \nExample | \nArea | \n
---|---|---|
d | \n 0 ..6 | \n Weekday | \n
dd | \n Su | \n \n |
ddd | \n Sun | \n \n |
dddd | \n Sunday | \n \n |
YY | \n 13 | \n Year | \n
YYYY | \n 2013 | \n \n |
M | \n 1 ..12 (Jan is 1) | \n Month | \n
Mo | \n 1st ..12th | \n \n |
MM | \n 01 ..12 (Jan is 1) | \n \n |
MMM | \n Jan | \n \n |
MMMM | \n January | \n \n |
Q | \n 1 ..4 | \n Quarter | \n
Qo | \n 1st ..4th | \n \n |
D | \n 1 ..31 | \n Day | \n
Do | \n 1st ..31st | \n \n |
DD | \n 01 ..31 | \n \n |
DDD | \n 1 ..365 | \n Day of year | \n
DDDo | \n 1st ..365th | \n \n |
DDDD | \n 001 ..365 | \n \n |
w | \n 1 ..53 | \n Week of year | \n
wo | \n 1st ..53rd | \n \n |
ww | \n 01 ..53 | \n \n |
Symbol | \nExample | \nArea | \n
---|---|---|
H | \n 0 ..23 | \n 24h hour | \n
HH | \n 00 ..23 | \n \n |
h | \n 1 ..12 | \n 12h hour | \n
hh | \n 01 ..12 | \n \n |
m | \n 0 ..59 | \n Minutes | \n
mm | \n 00 ..59 | \n \n |
s | \n 0 ..59 | \n Seconds | \n
ss | \n 00 ..59 | \n \n |
a | \n am | \n AM/PM | \n
A | \n AM | \n \n |
Z | \n +07:00 | \n Timezone offset | \n
ZZ | \n +0730 | \n \n |
S | \n 0 ..9 | \n Deciseconds | \n
SS | \n 00 ..99 | \n Centiseconds | \n
SSS | \n 000 ..999 | \n Milliseconds | \n
X | \n \n | Unix timestamp | \n
x | \n \n | Millisecond Unix timestamp | \n
Example | \nOutput | \n
---|---|
LT | \n 8:30 PM | \n
LTS | \n 8:30:25 PM | \n
LL | \n August 2 1985 | \n
ll | \n Aug 2 1985 | \n
LLL | \n August 2 1985 08:30 PM | \n
lll | \n Aug 2 1985 08:30 PM | \n
LLLL | \n Thursday, August 2 1985 08:30 PM | \n
llll | \n Thu, Aug 2 1985 08:30 PM | \n
SHOW DATABASES;\nSHOW TABLES;\nSHOW FIELDS FROM table / DESCRIBE table;\nSHOW CREATE TABLE table;\nSHOW PROCESSLIST;\nKILL process_number;\n
\n\nSELECT * FROM table;\nSELECT * FROM table1, table2;\nSELECT field1, field2 FROM table1, table2;\nSELECT ... FROM ... WHERE condition\nSELECT ... FROM ... WHERE condition GROUPBY field;\nSELECT ... FROM ... WHERE condition GROUPBY field HAVING condition2;\nSELECT ... FROM ... WHERE condition ORDER BY field1, field2;\nSELECT ... FROM ... WHERE condition ORDER BY field1, field2 DESC;\nSELECT ... FROM ... WHERE condition LIMIT 10;\nSELECT DISTINCT field1 FROM ...\nSELECT DISTINCT field1, field2 FROM ...\n
\n\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\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\nCREATE DATABASE DatabaseName;\nCREATE DATABASE DatabaseName CHARACTER SET utf8;\nUSE DatabaseName;\nDROP DATABASE DatabaseName;\nALTER DATABASE DatabaseName CHARACTER SET utf8;\n
\n\nmysqldump -u Username -p dbNameYouWant > databasename_backup.sql\n
\n\nmysql - u Username -p dbNameYouWant < databasename_backup.sql;\n
\n\nmysqlcheck --all-databases;\nmysqlcheck --all-databases --fast;\n
\n\nINSERT INTO table1 (field1, field2) VALUES (value1, value2);\n
\n\nDELETE FROM table1 / TRUNCATE table1\nDELETE FROM table1 WHERE condition\nDELETE FROM table1, table2 FROM table1, table2 WHERE table1.id1 =\n table2.id2 AND condition\n
\n\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\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\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\nCREATE TABLE table1 (fk_field1 type1, fk_field2 type2, ...,\n FOREIGN KEY (fk_field1, fk_field2) REFERENCES table2 (t2_fieldA, t2_fieldB))\n
\n\nCREATE TABLE table IF NOT EXISTS;\n
\n\nCREATE TEMPORARY TABLE table;\n
\n\nDROP TABLE table;\nDROP TABLE IF EXISTS table;\nDROP TABLE table1, table2, ...\n
\n\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\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\nCREATE TABLE table (..., PRIMARY KEY (field1, field2))\nCREATE TABLE table (..., FOREIGN KEY (field1, field2) REFERENCES table2\n(t2_field1, t2_field2))\n
\n\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\nSET PASSWORD = PASSWORD('new_pass');\nSET PASSWORD FOR 'user'@'host' = PASSWORD('new_pass');\nSET PASSWORD = OLD_PASSWORD('new_pass');\n
\n\nDROP USER 'user'@'host';\n
\n\nHost ‘%’ indicates any host.
\n\nTINYINT (1o: -217+128)\nSMALLINT (2o: +-65 000)\nMEDIUMINT (3o: +-16 000 000)\nINT (4o: +- 2 000 000 000)\nBIGINT (8o: +-9.10^18)\n
\n\nPrecise interval: -(2^(8*N-1)) -> (2^8*N)-1\n
\n\n⚠ INT(2) = “2 digits displayed” – NOT “number with 2 digits max”
\n\nFLOAT(M,D)\nDOUBLE(M,D)\nFLOAT(D=0->53)\n
\n\n⚠ 8,3 -> 12345,678 – NOT 12345678,123!
\n\nTIME (HH:MM)\nYEAR (AAAA)\nDATE (AAAA-MM-JJ)\nDATETIME (AAAA-MM-JJ HH:MM; années 1000->9999)\nTIMESTAMP (like DATETIME, but 1970->2038, compatible with Unix)\n
\n\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
ENUM ('value1', 'value2', ...) -- (default NULL, or '' if NOT NULL)\n
\n\n$ /etc/init.d/mysql stop\n
\n\n$ mysqld_safe --skip-grant-tables\n
\n\n$ mysql # on another terminal\nmysql> UPDATE mysql.user SET password=PASSWORD('new_pass') WHERE user='root';\n
\n\n## Switch back to the mysqld_safe terminal and kill the process using Control + \\\n$ /etc/init.d/mysql start\n
\n\nYour commands may vary depending on your OS.
", "intro_html": "", "description_html": "", "tags": null, "updated": "2020-07-05" },{ "id": "ncftp", "title": "ncftp", "url": "/ncftp", "category": "CLI", "keywords": null, "content_html": "$ ncftp\n$ open -u username ftp.host.com\n$ bookmark bookmarkname\n
\n\n$ ncftpget -R bookmarkname /www/ .\n
\n\n$ ncftpput -R bookmarkname /www/ .\n
\n\n$ git show --pretty=\"format:\" --name-only HEAD~1\n$ ncftpget -R -C log bookmarkname /www/ .\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "nock",
"title": "Nock",
"url": "/nock",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "scope = nock('http://foo.com')\nscope = nock('http://foo.com', { allowUnmocked: true })\n
\n\nnock('http://foo.com')\n .get('/user')\n .reply(200, { id: 1234 })\n
\n\nnock('http://foo.com')\n .filteringPath(/[&\\?]token=[^&]*/g, '')\n .get('/user')\n\n// catches \"/user?token=...\" as well\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "nocode",
"title": "Nocode",
"url": "/nocode",
"category": "Others",
"keywords": null,
"content_html": "Nocode is the best way to write secure and reliable applications. Write nothing; deploy nowhere.
", "description_html": "", "tags": null, "updated": "2018-03-17" },{ "id": "nodejs-assert", "title": "assert", "url": "/nodejs-assert", "category": "Node.js", "keywords": null, "content_html": "assert(val)\nassert.equal(actual, expected)\nassert.notEqual(a, e)\n
\n\nassert.deepEqual(a, e)\nassert.notDeepEqual(a, e)\n
\n\nassert.throws(fn)\n
\n\nfs.readFile('file.txt', function(err, data) { .. });\nfs.readFile('file.txt', {encoding: 'utf-8'}, function(err, data) { .. });\n
\n\nfs.writeFile('output.txt', function(err) { .. });\nfs.appendFile('output.txt', function(err) { .. });\n
\n\nfs.watch('dir OR file.txt', { persistent: true }, function(event, file) {\n event; /* rename | change */\n});\n
\n\nfs.exists('file.txt', function(exists /*bool*/) { ... });\n\nfs.stat('file.txt', function(stats) {\n stats.isFile();\n stats.isDirectory();\n stats.isSymbolicLink();\n});\n
\n\nfs.rename('old.txt', 'new.txt', function(){});\nfs.chown('file.txt', uid, gid, function(){});\nfs.symlink('src', 'dest', function(){});\nfs.unlink('path', function(){});\nfs.rmdir('path', function(){});\n\nfs.readdir('path', function(err, files) { .. }); /* `files` = array of names */\n
\n\nfs.realpath('/etc/passwd', function(err, path) { /* \"/private/etc/passwd\" */ });\n
\n\ndata = fs.readFileSync('input.txt');\nfs.writeFileSync('output.txt', data);\nfs.appendFileSync('output.txt', data);\nfs.existsSync('file.txt');\n
\n\nconst fs = require('fs')\n\nfs.realpath('/etc/passwd', function (err, path) {\n path // => \"/private/etc/passwd\"\n})\n
\n\nconst path = require('path')\ndir = path.join('etc', 'passwd')\ndir = path.resolve('/etc', 'passwd', '..', 'var')\n
\n\npath.dirname('/etc/passwd') // => \"/etc\"\npath.basename('/etc/passwd') // => \"passwd\"\npath.basename('/etc/rc.d', '.d') // => \"rc\"\n
\n\nQuick reference to the Node.js path API.
", "description_html": "", "tags": null, "updated": null },{ "id": "nodejs-process", "title": "process", "url": "/nodejs-process", "category": "Node.js", "keywords": null, "content_html": "process.stdout.write('...');\nprocess.stderr.write('...');\n\nfunction stdin(fn) {\n var data = '';\n\n process.stdin.setEncoding('utf8');\n process.stdin.on('readable', function() {\n var chunk = process.stdin.read();\n if (chunk !== null) data += chunk;\n });\n\n process.stdin.on('end', function() {\n fn(null, data);\n });\n}\n
\n\nprocess.argv; //=> ['node', 'file.js', 'one', 'two']\nprocess.env; //=> {TERM: 'screen-256color', SHELL: '/bin/bash', ...}\n\nprocess.exit();\nprocess.exit(1);\n
\n\nprocess.cwd(); //=> \"/tmp\"\nprocess.chdir('dir');\n
\n\nStream | \nDescription | \n
---|---|
Readable | \n Data emitter | \n
Writable | \n Data receiver | \n
Transform | \n Emitter and receiver | \n
Duplex | \n Emitter and receiver (independent) | \n
See: Stream (nodejs.org)
\n\nconst Readable = require('stream').Readable\nconst Writable = require('stream').Writable\nconst Transform = require('stream').Transform\n
\n\nclock() // Readable stream\n .pipe(xformer()) // Transform stream\n .pipe(renderer()) // Writable stream\n
\n\nstream.push(/*...*/) // Emit a chunk\nstream.emit('error', error) // Raise an error\nstream.push(null) // Close a stream\n
\n\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.
// Toggle flowing mode\nst.resume()\nst.pause()\n
\n\n// Automatically turns on flowing mode\nst.on('data', /*...*/)\n
\n\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()
.
function xformer () {\n let count = 0\n\n return new Transform({\n objectMode: true,\n transform: (data, _, done) => {\n done(null, { ...data, index: count++ })\n }\n })\n}\n
\n\nPass the updated chunk to done(null, chunk)
.
function renderer () {\n return new Writable({\n objectMode: true,\n write: (data, _, done) => {\n console.log('<-', data)\n done()\n }\n })\n}\n
\n\nclock() // Readable stream\n .pipe(xformer()) // Transform stream\n .pipe(renderer()) // Writable stream\n
\n\n__filename\n__dirname\n
\n\nvar exec = require('child_process').exec,\n\nvar child = exec('cat *.js bad_file | wc -l',\n function (error, stdout, stderr) {\n console.log('stdout: ' + stdout);\n console.log('stderr: ' + stderr);\n if (error !== null) {\n console.log('exec error: ' + error);\n }\n});\n
\n\ninfo = require('../package.json')\ninfo.version\n\nprocess.stdout.write(util.inspect(objekt, false, Infinity, true) + '\\n');\n
\n\nvar spawn = require('child_process').spawn;\nvar proc = spawn(bin, argv, { stdio: 'inherit' });\nproc.on('error', function(err) {\n if (err.code == \"ENOENT\") { \"does not exist\" }\n if (err.code == \"EACCES\") { \"not executable\" }\n});\nproc.on('exit', function(code) { ... });\n\n// also { stdio: ['pipe', 'pipe', process.stdout] }\n// also { stdio: [process.stdin, process.stderr, process.stdout] }\n\nproc.stdout.on('data', function (data) {\n});\nproc.stderr.on('data', function (data) {\n});\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "nopt",
"title": "Nopt",
"url": "/nopt",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "var args = require('nopt')({\n foo: [String, null],\n size: ['big', 'medium', 'small'],\n many: [String, Array],\n debug: Boolean,\n version: Boolean,\n help: Boolean\n}, {\n h: '--help',\n v: '--version'\n}, process.argv);\n\nargs == {\n debug: true,\n version: true,\n size: 'big',\n argv: {\n remain: ['...', '...'],\n cooked: ...,\n original: ...\n }\n}\n
\n\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
\n\nhttps://www.npmjs.org/package/nopt
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "npm", "title": "npm", "url": "/npm", "category": "JavaScript", "keywords": null, "content_html": "Command | \nDescription | \n
---|---|
npm i | \n Alias for npm install | \n
npm install | \n Install everything in package.json | \n
npm install --production | \n Install everything in package.json, except devDependecies | \n
npm install lodash | \n Install a package | \n
npm install --save-dev lodash | \n Install as devDependency | \n
npm install --save-exact lodash | \n Install with exact | \n
--save
is the default as of npm@5. Previously, using npm install
without --save
doesn’t update package.json.
Command | \nDescription | \n
---|---|
npm i sax | \n NPM package | \n
npm i sax@latest | \n Specify tag latest | \n
npm i sax@3.0.0 | \n Specify version 3.0.0 | \n
npm i sax@\">=1 <2.0\" | \n Specify version range | \n
npm i @org/sax | \n Scoped NPM package | \n
npm i user/repo | \n GitHub | \n
npm i user/repo#master | \n GitHub | \n
npm i github:user/repo | \n GitHub | \n
npm i gitlab:user/repo | \n GitLab | \n
npm i /path/to/repo | \n Absolute path | \n
npm i ./archive.tgz | \n Tarball | \n
npm i https://site.com/archive.tgz | \n Tarball via HTTP | \n
Command | \nDescription | \n
---|---|
npm list | \n Lists the installed versions of all dependencies in this software | \n
npm list -g --depth 0 | \n Lists the installed versions of all globally installed packages | \n
npm view | \n Lists the latest versions of all dependencies in this software | \n
npm outdated | \n Lists only the dependencies in this software which are outdated | \n
Command | \nDescription | \n
---|---|
npm update | \n Update production packages | \n
npm update --dev | \n Update dev packages | \n
npm update -g | \n Update global packages | \n
npm update lodash | \n Update a package | \n
# Add someone as an owner\nnpm owner add USERNAME PACKAGENAME\n
\n\n# list packages\nnpm ls\n
\n\n# Adds warning to those that install a package of old versions\nnpm deprecate PACKAGE@\"< 0.2.0\" \"critical bug fixed in v0.2.0\"\n
\n\n# update all packages, or selected packages\nnpm update [-g] PACKAGE\n
\n\n# Check for outdated packages\nnpm outdated [PACKAGE]\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2019-12-24"
},{
"id": "org-mode",
"title": "Org Mode",
"url": "/org-mode",
"category": "Apps",
"keywords": null,
"content_html": "* 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\nTo buy:\n1. Milk\n2. Eggs\n - Organic\n3. Cheese\n + Parmesan\n + Mozarella\n
\n\n*bold*\n/italic/\n_underline_\n=code=\n~verbatim~\n+strike-through+\n
\n\n* TODO buy airplane\n
\n\nCycle by using S-LEFT
/ S-RIGHT
. List all TODO’s via C-c C-v
.
Description | \nShortcut | \n
---|---|
(Un) fold | \nTAB / S-TAB | \n
Move up | \nM-UP / M-DOWN | \n
New headline | \nM-RET | \n
Cycle workflow | \nS-LEFT / S-RIGHT | \n
Cycle priority | \nS-UP / S-DOWN | \n
Description | \nShortcut | \n
---|---|
Start timer | \nC-c C-x 0 | \n
Stop timer | \nC-c C-x _ | \n
Pause timer | \nC-c C-x , | \n
Start countdown | \nC-c C-x ; | \n
You can use this for Pomodoro!
\n\nDescription | \nShortcut | \n
---|---|
Agenda menu | \nC-c a | \n
Add document | \nC-c [ | \n
Remove document | \nC-c ] | \n
Add date | \nC-c . | \n
Add time & date | \nC-u C-c . | \n
Start by adding the current file to the agenda (C-c [
), then use the agenda menu to navigate.
Description | \nShortcut | \n
---|---|
Export menu | \nC-c C-e | \n
Lets you export the document as Markdown, HTML, and others.
\n\nOrg mode is for keeping hierarchal notes (and more) in Emacs.
", "description_html": "", "tags": ["WIP"], "updated": "2018-02-19" },{ "id": "osx", "title": "OS X", "url": "/osx", "category": "macOS", "keywords": null, "content_html": "~/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\ndefaults write com.apple.finder CreateDesktop -bool false\nkillall Finder\n
\n\ndefaults write com.apple.dock single-app -bool TRUE\nkillall Dock\n\ndefaults delete com.apple.dock single-app\nkillall Dock\n
\n\nkillall -HUP mDNSResponder # 10.8+\ndscacheutil -flushcache # 10.7 below\n
\n\nmdutil -a -i off # disable indexing for all volumes\nmdutil -i off MOUNT_POINT # disable for specific volume\ntouch FOLDER/.metadata_never_index # disable for FOLDER\n
\n\nsudo networksetup -setsocksfirewallproxystate Wi-Fi off\nsudo networksetup -setsocksfirewallproxystate Ethernet off\nsudo networksetup -setsocksfirewallproxy Wi-Fi 127.0.0.1 9999\nsudo networksetup -setsocksfirewallproxy Ethernet 127.0.0.1 9999\nsudo networksetup -setsocksfirewallproxystate Wi-Fi on\nsudo networksetup -setsocksfirewallproxystate Ethernet on\n
\n\nnetworksetup
- 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”open
- open files and directories (man)textutil
- manipulate text files of various formats (man)pbcopy
/ pbpaste
- provide copying and pasting to the pasteboard (man)sips
- scriptable image processing system (man)mdfind
- finds files matching a given query (man)screencapture
- capture images from the screen (man)defaults
- access the Mac OS X user defaults system (man)/usr/libexec/airportd
scutil
INFO: brew
(link) is highly recommended utility
{\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\nHighlighted lines are required.
\n\n\"dependencies\": {\n \"colors\": \"*\",\n \"flatiron\": \"0.1.x\",\n \"flatiron\": \"~0.1.0\",\n \"plates\": \"https://github.com/user/project/tarball/branch\",\n \"stuff\": \"git://github.com/user/project.git#commit-ish\"\n},\n
\n\n\"devDependencies\": { ··· },\n\"peerDependencies\": { ··· },\n\"optionalDependencies\": { ··· },\n
\n\nSee Semver cheatsheet for explanation of version ranges.
\n\n\"scripts\": {\n \"start\": \"node ./bin/xxx\", /* npm start */\n \"test\": \"vows --spec --isolate\", /* npm test */\n \"postinstall\": \"...\",\n \"prepublish\": \"grunt build\", /* after 'npm install' and before 'npm \n publish' */\n}\n
\n\n\"private\": true,\n\"preferGlobal\": true\n
\n\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.
npm help package.json
Command | \nDescription | \n
---|---|
pacman -Syu <pkg> | \n Install (and update package list) | \n
pacman -S <pkg> | \n Install only | \n
pacman -Rsc <pkg> | \n Uninstall | \n
pacman -Ss <keywords> | \n Search | \n
pacman -Syu | \n Upgrade everything | \n
Command | \nDescription | \n
---|---|
pacman -Qe | \n List explictly-installed packages | \n
pacman -Ql <pkg> | \n What files does this package have? | \n
pacman -Qii <pkg> | \n List information on package | \n
pacman -Qo <file> | \n Who owns this file? | \n
pacman -Qs <query> | \n Search installed packages for keywords | \n
Command | \nDescription | \n
---|---|
pacman -Qdt | \n List unneeded packages | \n
pacman -Rns $(pacman -Qdtq) | \n Uninstall unneeded packages | \n
Avoid orphans by using pacman -Rsc
to remove packages, which will remove unneeded dependencies.
Command | \nDescription | \n
---|---|
pactree <pkg> | \n What does pkg depend on? | \n
pactree -r <pkg> | \n What depends on pkg? | \n
Pacman is the package manager for Arch linux and its derivatives.
", "description_html": "", "tags": null, "updated": "2018-07-07" },{ "id": "parsimmon", "title": "Parsimmon", "url": "/parsimmon", "category": "JavaScript libraries", "keywords": null, "content_html": "const P = require('parsimmon')\n\nP.regexp(/[a-z]+/)\n.parse('hello')\n//=> { status: true, value: ['hello'] }\n
\n\nP.regexp(/[a-z]+/)\nP.string('hello')\nP.oneOf('abc') // like P.regexp(/[abc]/)\n\nP.whitespace\nP.optWhitespace\nP.eof\n
\n\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\nP.seq(P.number, P.oneOf('+-*/'), P.number)\n.map(([left, oper, right]) => ({ oper, left, right }))\n
\n\nnpm install --save parsleyjs\n
\n\nparsleyjs is the Parsley form validator. (‘parsley’ is a different package)
\n\n<form data-parsley-validate>\n<!-- ✗ not preferred -->\n
\n\n$('#form').parsley(/* options */)\n
\n\nIt’s preferable to explicitly call $.fn.parsley()
.
$('#myform').parsley()\n .isValid() // → true | null\n .validate()\n .reset()\n .destroy()\n
\n\n$('#myform input').parsley()\n .isValid()\n .validate() // returns errors\n
\n\n<input ...>\n
\n\n required\n
\n\n type='email'\n
\n\n type='url'\n data-parsley-type='url'\n
\n\n maxlength='6'\n data-parsley-maxlength='6'\n minlength='10'\n data-parsley-minlength='10'\n
\n\n pattern='\\d+'\n data-parsley-pattern='\\d+'\n
\n\n type='number'\n data-parsley-type='number'\n data-parsley-type='integer'\n data-parsley-type='digits'\n data-parsley-type='alphanum'\n
\n\n type='range'\n data-parsley=range='[6, 10]'\n
\n\n max='10'\n data-parsley-max='10'\n min='6'\n data-parsley-min='6'\n
\n\n data-parsley-mincheck='1'\n data-parsley-maxcheck='3'\n data-parsley-check='[1, 3]'\n
\n\n data-parsley-equalto='#confirm'\n
\n\n// Supported & excluded inputs by default\n inputs: 'input, textarea, select'\n excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]'\n
\n\n// Stop validating field on highest priority failing constraint\n priorityEnabled: true\n
\n\nSee: Options
\n\n// identifier used to group together inputs\n// (e.g. radio buttons…)\n multiple: null\n
\n\n// identifier (or array of identifiers) used to\n// validate only a select group of inputs\n group: null\n
\n\nThese options are only available for fields.
\n\n// Enable/disable error messages\n uiEnabled: true\n
\n\n// Key events threshold before validation\n validationThreshold: 3\n
\n\n// Focused field on form validation error. ‘first’|’last’|’none’\n focus: 'first'\n
\n\n// $.Event() that will trigger validation. eg: keyup, change…\n trigger: false\n
\n\n// Class that would be added on every failing validation\n// Parsley field\n errorClass: 'parsley-error'\n successClass: 'parsley-success'\n
\n\n// Return the $element that will receive these above\n// success or error classes. Could also be (and given\n// directly from DOM) a valid selector like '#div'\n classHandler: function (ParsleyField) {}\n
\n\n// Return the $element where errors will be appended.\n// Could also be (and given directly from DOM) a valid\n// selector like '#div'\n errorsContainer: function (ParsleyField) {}\n
\n\n// ul elem that would receive errors’ list\n errorsWrapper: '<ul class=\"parsley-errors-list\"></ul>'\n
\n\n// li elem that would receive error message\n errorTemplate: '<li></li>'\n
\n\n$('[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
.
$('[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$('[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.
<input type='text' data-parsley-multiple-of='3' />\n
\n\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
\n\nParsley provides frontend form validation.
", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "pass", "title": "Pass", "url": "/pass", "category": "CLI", "keywords": null, "content_html": "$ 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$ pass insert [-m] twitter.com/rsc\n$ pass generate [-n] twitter.com/rsc length\n
\n\n$ pass ls twitter.com/\n$ pass show twitter.com/rsc\n$ pass -c twitter.com/rsc\n
\n\n$ pass find twitter.com\n
\n\n$ pass mv twitter.com twitter.com/rsc\n$ pass rm [-rf] twitter.com\n$ pass cp twitter.com/rsc twitter.com/ricosc\n
\n\n$ pass edit twitter.com/rsc\n
\n\n$ pass git push\n$ pass git pull\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.
", "intro_html": "", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "perl-pie", "title": "Perl-pie", "url": "/perl-pie", "category": "Development", "keywords": null, "content_html": "perl -p -i -e 's/hello/hola/g' *.txt\n
\n\nUse \\1
et al.
# '@include align-items(center);' => 'align-items: center;'\nperl -p -i -e \"s/\\@include (align-items)\\((.*)\\);/\\1: \\2;/g\"\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "ph-food-delivery",
"title": "Food delivery (Philippines)",
"url": "/ph-food-delivery",
"category": "Others",
"keywords": null,
"content_html": "Restaurant | \nOnline order | \nPhone | \n
---|---|---|
Army Navy | \narmynavy.com.ph | \n331-3131 | \n
Burger King | \nburgerkingdelivery.com.ph | \n #2-22-22 | \n
KFC | \nkfc.com.ph | \n887-8888 | \n
Kenny Rogers | \nkennys.com.ph | \n555-9000 | \n
McDonald’s | \nmcdonalds.com.ph | \n8-6236 | \n
Pancake House | \npancakehouse.com.ph | \n7-9000 | \n
Wendy’s | \nwendys.com.ph | \n533-3333 | \n
Restaurant | \nOnline order | \nPhone | \n
---|---|---|
Angel’s Pizza | \nangelspizza.com.ph | \n922-2222 | \n
Domino’s | \ndominospizza.ph | \n997-3030 | \n
Greenwich | \ngreenwichdelivery.com | \n5-5555 | \n
Papa John’s | \npapajohns.com.ph | \n887-7272 | \n
Pizza Hut | \npizzahut.com.ph | \n911-1111 | \n
Shakey’s | \nshakeyspizza.ph | \n77-7777 | \n
Yellow Cab | \nyellowcabpizza.com | \n789-9999 | \n
Restaurant | \nOnline order | \nPhone | \n
---|---|---|
Bonchon | \nbonchon.com.ph (menu) | \n633-1818 | \n
Chowking | \nchowkingdelivery.com | \n9-8888 | \n
North Park | \nnorthparkdelivery.com | \n7-3737 | \n
Yoshinoya | \nyoshinoya.ph | \n288-2888 | \n
Restaurant | \nOnline order | \nPhone | \n
---|---|---|
Amber’s | \namber.com.ph | \n884-8888 | \n
Goldilock’s | \ngoldilocksdelivery.com.ph | \n888-1-999 | \n
Jollibee | \njollibeedelivery.com | \n#8-7000 | \n
Mang Inasal | \nmanginasal.com (menu) | \n733-1111 | \n
Max’s | \nmaxschicken.com | \n7-9000 | \n
Restaurant | \nOnline order | \nPhone | \n
---|---|---|
Krispy Kreme | \nnow.krispykreme.com.ph | \n7-9000 | \n
Red Ribbon | \nredribbononlinestore.com | \n8-7777 | \n
Hint: you can get to this page via devhints.io/gutom 🍅🍟
", "intro_html": "Food delivery numbers & sites for top restaurant chains in Metro Manila. For numbers outside Metro Manila, check their websites.
", "description_html": "", "tags": null, "updated": null },{ "id": "fitness/phat", "title": "Phat", "url": "/fitness/phat", "category": "Fitness", "keywords": null, "content_html": "Purpose | \nMovement | \nSets x Reps | \n
---|---|---|
Pull: power | \nBent over / Pendlay rows | \n3 x 3-5 | \n
Pull: assistance | \nWeighted Pull ups | \n2 x 6-10 | \n
Pull: auxiliary | \nRack chins | \n2 x 6-10 | \n
Press: power | \nFlat dumbbell presses | \n3 x 3-5 | \n
Press: assistance | \nWeighted dips | \n2 x 6-10 | \n
Press: assistance | \nSeated dumbbell shoulder presses | \n3 x 6-10 | \n
Aux: curling | \nCambered bar curls | \n3 x 6-10 | \n
Aux: extension | \nSkull crushers | \n3 x 6-10 | \n
Purpose | \nMovement | \nSets x Reps | \n
---|---|---|
Press: Power | \nSquats | \n3 x 3-5 | \n
Press: Assistance | \nHack Squats | \n2 x 6-10 | \n
Ext: Assistance | \nLeg extensions | \n2 x 6-10 | \n
Pull: Assistance | \nStiff legged deadlifts | \n3 x 5-8 | \n
Pull: Assistance (curl) | \nGlute ham raises or lying leg curls | \n2 x 6-10 | \n
Aux: calf | \nStanding calf raise | \n3 x 6-10 | \n
Aux: calf | \nSeated calf raise | \n2 x 6-10 | \n
Purpose | \nMovement | \nSets x Reps | \n
---|---|---|
Pull: speed work | \nBent over / Pendlay rows | \n6 x 3 | \n
Pull | \nRack chins | \n3 x 8-12 | \n
Pull | \nSeated cable row | \n3 x 8-12 | \n
Pull | \nDumbbell rows / shrugs against incline bench | \n2 x 12-15 | \n
Pull | \nClose grip pulldowns | \n2 x 15-20 | \n
Shoulder | \nSeated dumbbell presses | \n3 x 8-12 | \n
Shoulder | \nUpright rows | \n2 x 12-15 | \n
Shoulder | \nSide lateral raises with dumbbells or cables | \n3 x 12-20 | \n
Speed work: with 65-70% of normal 3-5 rep max
\n\nPurpose | \nMovement | \nSets x Reps | \n
---|---|---|
Legs: speed work | \nSquats | \n6 x 3 | \n
Press | \nHack squats | \n3 x 8-12 | \n
Press | \nLeg presses | \n2 x 12-15 | \n
Extension | \nLeg extensions | \n3 x 15-20 | \n
Pull | \nRomanian deadlifts | \n3 x 8-12 | \n
Pull/curling | \nLying leg curls | \n2 x 12-15 | \n
Pull/curling | \nSeated leg curls | \n2 x 15-20 | \n
Calf | \nDonkey calf raises | \n4 x 10-15 | \n
Calf | \nSeated calf raises | \n3 x 15-20 | \n
Purpose | \nMovement | \nSets x Reps | \n
---|---|---|
Press: speed work | \nFlat dumbbell presses | \n6 x 3 | \n
Press | \nIncline dumbbell presses | \n3 x 8-12 | \n
Press | \nHammer strength chest press | \n3 x 12-15 | \n
Fly | \nIncline cable flyes | \n2 x 15-20 | \n
Curl | \nCambered bar preacher curls | \n3 x 8-12 | \n
Curl | \nDumbbell concentration curls | \n2 x 12-15 | \n
Curl | \nSpider curls against incline bench | \n2 x 15-20 | \n
Extension | \nSeated tricep extension with cambered bar | \n3 x 8-12 | \n
Extension | \nCable pressdowns with rope attachment | \n2 x 12-15 | \n
Extension | \nCable kickbacks | \n2 x 15-20 | \n
conn.host # → \"example.com\"\nconn.method # → \"GET\"\nconn.path_info # → [\"posts\", \"1\"]\nconn.request_path # → \"/posts/1\"\nconn.query_string # → \"utm_source=twitter\"\nconn.port # → 80\nconn.scheme # → :http\nconn.peer # → { {127, 0, 0, 1}, 12345 }\nconn.remote_ip # → { 151, 236, 219, 228 }\nconn.req_headers # → [{\"content-type\", \"text/plain\"}]\n
\n\nconn |> get_req_header(\"content-type\")\n# → [\"text/plain\"]\n
\n\nconn\n|> put_req_header(\"accept\", \"application/json\")\n
\n\nUsually only useful for tests.
\n\nconn.resp_body # → \"...\"\nconn.resp_charset # → \"utf-8\"\nconn.resp_cookies # → ...\nconn.resp_headers # → ...\nconn.status # → ...\n
\n\n# Plug.Conn\nconn\n|> html(\"<html><head>...\")\n|> json(%{ message: \"Hello\" })\n|> text(\"Hello\")\n
\n\n|> redirect(to: \"/foo\")\n|> redirect(external: \"http://www.google.com/\")\n|> halt()\n
\n\n|> put_resp_content_type(\"text/plain\")\n|> put_resp_cookie(\"abc\", \"def\")\n|> put_resp_header(\"X-Delivered-By\", \"myapp\")\n|> put_status(202)\n|> put_status(:not_found)\n
\n\n|> put_private(:plug_foo, \"...\") # reserved for libraries\n
\n\n|> send_resp(201, \"\")\n
\n\n# Phoenix.Controller\nconn\n|> render(\"index.html\")\n|> render(\"index.html\", hello: \"world\")\n|> render(MyApp.ErrorView, \"404.html\")\n
\n\n|> put_layout(:foo)\n|> put_layout(false)\n|> put_view(ErrorView)\n
\n\n|> put_secure_browser_headers()\n# prevent clickjacking, nosniff, and xss protection\n# x-frame-options, x-content-type-options, x-xss-protection\n
\n\n|> put_new_view(ErrorView) # if not set yet\n|> put_new_layout(:foo)\n
\n\nlayout(conn)\n
\n\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\nplug :accepts, [\"html\", \"json\"]\nconn |> accepts([\"html\", \"json\"])\nget_format(conn) # → \"html\"\nconn.accepts\n
\n\nconn.assigns[:hello]\nconn |> assign(:user_id, 100)\n
\n\nconn = async_assign(conn, :location, fn -> geoip_lookup() end)\nawait_assign(conn, :location)\n
\n\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\nconn\n|> put_flash(:info, \"Success\")\n|> put_flash(:error, \"Oh no\")\n
\n\nAlso available: flash
cookie
params
$ mix phx.gen.html \\\n Accounts \\ # domain\n Profile \\ # schema\n profiles \\ # table name\n email:string \\\n age:integer\n
\n\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\nField | \n
---|
:id | \n
:binary | \n
:boolean | \n
:string | \n
:integer | \n
:float | \n
:decimal | \n
{:array, inner_type} | \n
:map | \n
def changeset(user, params \\\\ :empty) do\n %User{}\n |> Ecto.Changeset.change # basic casting to changeset\n\n user\n |> cast(params, ~w(name email), ~w(age)) # params to Changeset\n\n |> validate_format(:email, ~r/@/)\n\n |> validate_inclusion(:age, 18..100)\n |> validate_exclusion(:role, ~w(admin superadmin))\n |> validate_subset(:pets, ~w(cat dog parrot whale))\n\n |> validate_length(:body, min: 1)\n |> validate_length(:body, min: 1, max: 160)\n |> validate_length(:partners, is: 2)\n\n |> validate_number(:pi, greater_than: 3)\n |> validate_number(:pi, less_than: 4)\n |> validate_number(:pi, equal_to: 42)\n\n |> validate_change(:title, fn _, _ -> [])\n |> validate_confirmation(:password, message: \"does not match\")\n\n |> unique_constraint(:email)\n |> foreign_key_constraint(:post_id)\n |> assoc_constraint(:post) # ensure post_id exists\n |> no_assoc_constraint(:post) # negative (useful for deletions)\nend\n
\n\nchangeset.valid?\nchangeset.errors #=> [title: \"empty\"]\n\nchangeset.changes #=> %{}\nchangeset.params[:title]\n\nchangeset.required #=> [:title]\nchangeset.optional #=> [:body]\n
\n\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\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\nRepo.get(User, id)\nRepo.get_by(User, email: \"john@hello.com\") #=> %User{} | nil\n\n# also get! get_by!\n
\n\nchangeset |> Repo.update\nchangeset |> Repo.insert\nchangeset |> Repo.insert_or_update\n
\n\nUser\n|> Ecto.Changeset.change(%{name: \"hi\"})\n|> Repo.insert\n
\n\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\nRepo.all(User)\n
\n\nRepo.update_all(Post, set: [title: \"Title\"])\nRepo.update_all(Post, inc: [views: 1])\n
\n\n_all
with queriesfrom(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\nThis is for Phoenix 1.2 and below. Phoenix 1.3 has a new API..
\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\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\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\nchangeset.valid?\nchangeset.errors #=> [title: \"empty\"]\n\nchangeset.changes #=> %{}\nchangeset.params[:title]\n\nchangeset.required #=> [:title]\nchangeset.optional #=> [:body]\n
\n\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\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\nRepo.get(User, id)\nRepo.get_by(User, email: \"john@hello.com\") #=> %User{} | nil\n\n# also get! get_by!\n
\n\nchangeset |> Repo.update\nchangeset |> Repo.insert\nchangeset |> Repo.insert_or_update\n
\n\nUser\n|> Ecto.Changeset.change(%{name: \"hi\"})\n|> Repo.insert\n
\n\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\nRepo.all(User)\n
\n\nRepo.update_all(Post, set: [title: \"Title\"])\nRepo.update_all(Post, inc: [views: 1])\n
\n\n_all
with queriesfrom(p in Post, where: p.id < 10)\n|> Repo.update_all(...)\n\nfrom(p in Post, where: p.id < 10)\n|> Repo.all()\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "phoenix-ecto@1.3",
"title": "Phoenix: Ecto models",
"url": "/phoenix-ecto@1.3",
"category": "Hidden",
"keywords": null,
"content_html": "",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "phoenix-migrations",
"title": "Phoenix: Ecto migrations",
"url": "/phoenix-migrations",
"category": "Elixir",
"keywords": null,
"content_html": "$ mix ecto.gen.migration update_posts_table\n creating priv/repo/migrations/20160602085927_update_posts_table.exs\n ···\n
\n\n$ mix ecto.migrate\n$ mix ecto.rollback\n
\n\nCreates a migration (no models).
\n\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$ mix phx.gen.context Images Album albums title:string subtitle:string privacy:string\n
\n\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\nalter table(:posts) do\n add :summary, :text\n modify :title, :text\n remove :views\nend\n
\n\nrename table(:posts), :title, to: :summary\nrename table(:posts), to: table(:new_posts)\n
\n\ndrop table(:documents)\ndrop_if_exists table(:documents)\n
\n\ntable(:documents)\ntable(:weather, prefix: :north_america)\n
\n\ncreate index(:posts, [:slug], concurrently: true)\ncreate unique_index(:posts, [:slug])\ndrop index(:posts, [:name])\n
\n\nexecute \"UPDATE posts SET published_at = NULL\"\nexecute create: \"posts\", capped: true, size: 1024\n
\n\nmix phx.routes # 1.3+\nmix phoenix.routes # 1.2 and below\n
\n\nSee: Mix.Tasks.Phoenix.Routes (hexdocs.pm)
\n\nget \"/\", PageController, :index\n
\n\nAlso: put
post
patch
options
delete
head
resources \"/users\", UserController\nresources \"/users\", UserController, only: [:index, :show]\nresources \"/users\", UserController, except: [:delete]\n
\n\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\nMethod | \nPath | \nHelper | \n
---|---|---|
GET | \n/users | \n user_path(:index) | \n
GET | \n/users/new | \n user_path(:new) | \n
GET | \n/users/:id | \n user_path(:show, user) | \n
GET | \n/users/:id/edit | \n user_path(:edit, user) | \n
POST | \n/users | \n user_path(:create, user) | \n
PATCH/PUT | \n/users/:id | \n user_path(:update, user) | \n
DELETE | \n/users/:id | \n user_path(:delete, user) | \n
See: resources/4 (hexdocs.pm)
\n\nuser_path(conn, :index) # → /users\nuser_path(conn, :show, 17) # → /users/17\nuser_path(conn, :show, %User{id: 17}) # → /users/17\nuser_path(conn, :show, 17, admin: true) # → /users/17?admin=true\n
\n\nuser_url(conn, :index) # → \"http://localhost:4000/users\"\n
\n\nMyApp.Router.Helpers.user_path(MyApp.Endpoint, :index)\n
\n\nSee: Helpers (hexdocs.pm)
\n\nresources \"/users\", UserController do\n resources \"/posts\", PostController\nend\n
\n\nuser_post_path(:index, 17) # → /users/17/posts\nuser_post_path(:show, 17, 12) # → /users/17/posts/12\n
\n\nSee: Scopes and resources (hexdocs.pm)
\n\nscope \"/admin\" do\n pipe_through :browser\n resources \"/reviews\", MyApp.Admin.ReviewController\nend\n# reviews_path() -> /admin/reviews\n
\n\nscope \"/admin\", as: :admin do: ... end\n# admin_reviews_path() -> /admin/reviews\n
\n\nSee: scope/2 (hexdocs.pm)
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "phoenix", "title": "Phoenix", "url": "/phoenix", "category": "Elixir", "keywords": null, "content_html": "# Install Phoenix\nmix local.hex\nmix archive.install https://github.com/phoenixframework/archives/raw/master/phx_new.ez\n
\n\n# Create a new project\nmix phx.new hello\n
\n\n# Start the application\nmix phx.server\n
\n\nInstall Erlang, Elixir, Node.js, PostgreSQL first.\nSee: Installation (hexdocs.pm)
\n\n./\n├── _build\n├── assets/\n│ ├── css/\n│ ├── js/\n│ ├── static/\n│ └── node_modules/\n├── config/\n├── deps/\n├── lib/\n│ ├── hello/\n│ ├── hello.ex\n│ ├── hello_web/\n│ │ ├── channels/\n│ │ ├── controllers/\n│ │ ├── templates/\n│ │ ├── views/\n│ │ ├── router.ex\n│ │ └── gettext.ex\n│ └── hello_web.ex\n├── priv/\n└── test/\n
\n\nSee: Adding pages (hexdocs.pm)
\n\n$ mix ecto.gen.migration update_posts_table\n creating priv/repo/migrations/20160602085927_update_posts_table.exs\n ···\n
\n\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\n\nget \"/\", PageController, :index\n\nresources \"/users\", UserController do\n resources \"/posts\", PostController\nend\n
\n\nuser_post_path(conn, :index, 17) # → /users/17/posts\nuser_post_path(conn, :show, 17, 12) # → /users/17/posts/12\n
\n\n\n\nconn.host # → \"example.com\"\nconn.method # → \"GET\"\nconn.path_info # → [\"posts\", \"1\"]\nconn.request_path # → \"/posts/1\"\n
\n\nconn\n|> put_status(202)\n|> html(\"<html><head>···\")\n|> json(%{ message: \"Hello\" })\n|> text(\"Hello\")\n|> redirect(to: \"/foo\")\n|> render(\"index.html\")\n|> render(\"index.html\", hello: \"world\")\n|> render(MyApp.ErrorView, \"404.html\")\n
\n\n\n\n$ mix phx.gen.html \\\n Accounts \\ # domain\n Profile \\ # schema\n profiles \\ # table name\n email:string \\\n age:integer\n
\n\n\n\nSee Phoenix for a more updated cheatsheet.
\n\n├── _build\n├── config/\n├── deps/\n├── lib/\n│ ├── hello/\n│ ├── hello.ex\n├── node_modules/\n├── priv/\n├── test/\n└── web/\n│ ├── channels/\n│ ├── controllers/\n│ ├── models/\n│ ├── static/\n│ ├── templates/\n│ ├── views/\n│ ├── gettext.ex\n│ ├── router.ex\n│ ├── web.ex\n├── mix.exs\n
\n\nThis is Phoenix 1.2’s structure. Phoenix 1.3 has no models
.
<?php\nfunction greetMe($name) {\n return \"Hello, \" . $name . \"!\";\n}\n\n$message = greetMe($name);\necho $message;\n
\n\nAll PHP files start with <?php
.
See: PHP tags
\n\n<?php\n\n$fruitsArray = array(\n \"apple\" => 20,\n \"banana\" => 30\n);\necho $fruitsArray['banana'];\n
\n\nOr cast as object
\n\n<?php\n\n$fruitsObject = (object) $fruits;\necho $fruitsObject->banana;\n
\n\n<?php\nvar_dump($object)\n
\n\nPrints the contents of a variable for inspection.
\n\nSee: var_dump
\n\nclass Person {\n public $name = '';\n}\n\n$person = new Person();\n$person->name = 'bob';\n\necho $person->name;\n
\n\nclass Person \n{\n public $name = '';\n\n public function getName()\n {\n return $this->name;\n }\n\n public function setName($name)\n {\n $this->name = $name;\n return $this;\n }\n}\n\n$person = new Person();\n$person->setName('bob');\n\necho $person->getName();\n
\n\n\n$options = [\n 'key' => 'value',\n 'blank' => '',\n 'nothing' => null,\n];\n\nvar_dump(isset($options['key']), empty($options['key'])); // true, false\nvar_dump(isset($options['blank']), empty($options['blank'])); // true, true\nvar_dump(isset($options['nothing']), empty($options['nothing'])); // false, true\n\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "plantuml",
"title": "PlantUML",
"url": "/plantuml",
"category": "Others",
"keywords": null,
"content_html": "@startuml\nCar : drive()\nDog : bark()\n@enduml\n\n# plantuml file.uml && open file.png\n
\n\nCar : drive()\n
\n\nclass 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\nclass 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\nCar <|-- SmallCar # extension\nCar *-- Engine # composition\nCars o-- Car # aggregation\nCar <|.. SmallCar # dotted line (use .. instead of --)\nCar <|--* Car\n\n-left->\n-right->\n
\n\nDriver - Car : drives >\nCar -- Owner : < owns\nCar *-- Wheel : has 4 >\n
\n\nclass Car {\n}\nnote left: Something something\n\nnote top of Car : This is a car.\n
\n\nnamespace Client {\n class Driver {\n }\n}\n\nCar -- Client.Driver : owns >\n
\n\n(*) --> \"First Activity\"\n-->[You can put also labels] \"Second Activity\"\n--> (*)\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "pm2",
"title": "pm2",
"url": "/pm2",
"category": "CLI",
"keywords": null,
"content_html": "Command | \nDescription | \n
---|---|
pm2 start app.js --name my-api | \n Start and name a process | \n
Command | \nDescription | \n
---|---|
pm2 start app.js -i 0 | \n Will start maximum processes with LB depending on available CPUs | \n
Command | \nDescription | \n
---|---|
pm2 list | \n Display all processes status | \n
pm2 jlist | \n Print process list in raw JSON | \n
pm2 prettylist | \n Print process list in beautified JSON | \n
pm2 describe 0 | \n Display all information about a specific process | \n
pm2 monit | \n Monitor all processes | \n
Command | \nDescription | \n
---|---|
pm2 logs [--raw] | \n Display all processes logs in streaming | \n
pm2 flush | \n Empty all log files | \n
pm2 reloadLogs | \n Reload all logs | \n
Command | \nDescription | \n
---|---|
pm2 stop all | \n Stop all processes | \n
pm2 restart all | \n Restart all processes | \n
pm2 reload all | \n Will 0s downtime reload (for NETWORKED apps) | \n
pm2 stop 0 | \n Stop specific process id | \n
pm2 restart 0 | \n Restart specific process id | \n
pm2 delete 0 | \n Will remove process from pm2 list | \n
pm2 delete all | \n Will remove all processes from pm2 list | \n
pm2 save | \n Save processes list to respawn at reboot | \n
Command | \nDescription | \n
---|---|
pm2 reset <process> | \n Reset meta data (restarted time…) | \n
pm2 updatePM2 | \n Update in memory pm2 | \n
pm2 ping | \n Ensure pm2 daemon has been launched | \n
pm2 sendSignal SIGUSR2 my-app | \n Send system signal to script | \n
pm2 start app.js --no-daemon | \n Run pm2 daemon in the foreground if it doesn’t exist already | \n
pm2 start app.js --no-vizion | \n Skip vizion features (versioning control) | \n
pm2 start app.js --no-autorestart | \n Do not automatically restart app | \n
<script src=\"https://cdn.polyfill.io/v2/polyfill.min.js\"></script>\n
\n\nThis is the default script for Polyfill.io.
\n\n<script>if(!(window.Promise&&[].includes&&Object.assign&&window.Map)){document.write('<script src=\"https://cdn.polyfill.io/v2/polyfill.min.js\"></scr'+'ipt>')}</script>\n
\n\nThis only includes polyfill.io when necessary, skipping it for modern browsers for faster load times.
\n\n<script>if(!(window.fetch&&window.Promise&&[].includes&&Object.assign&&window.Map)){document.write('<script src=\"https://cdn.polyfill.io/v2/polyfill.min.js?features=default,fetch\"></scr'+'ipt>')}</script>\n
\n\nThis is the same as the previous, but also adds a polyfill for window.fetch()
. We add a window.fetch
check and loads the additional fetch
feature.
Polyfill.io is a service that serves JavaScript polyfills.
", "description_html": "", "tags": null, "updated": "2018-08-20" },{ "id": "postgresql-json", "title": "PostgreSQL JSON", "url": "/postgresql-json", "category": "Databases", "keywords": null, "content_html": "SELECT * FROM users WHERE data->>'name' = 'John';\nSELECT data->>'name' AS name FROM users;\n
\n\nOperator | \nDescription | \nExample | \nReturns | \n
---|---|---|---|
-> int | \n Get array element 2 | \n data->2 | \n JSON | \n
-> text | \n Get object key name | \n data->'name' | \n JSON | \n
#> text[] | \n Get keypath a,b (eg, data.a.b ) | \n data#>'{a,b}' | \n JSON | \n
->> int | \n Get array element 2 | \n data->>2 | \n Text | \n
->> text | \n Get object key name | \n data->>'name' | \n Text | \n
#>> text[] | \n Get keypath a,b (eg, data.a.b ) | \n data#>>'{a,b}' | \n Text | \n
>
returns JSON, >>
returns text.
SELECT * FROM users WHERE data->tags ? 'admin';\nSELECT data->tags ? 'admin' AS is_admin FROM users;\n
\n\nOperator | \nDescription | \nExample | \n
---|---|---|
? str | \n Does data have key name ? | \n data ? 'name' | \n
?| text[] | \n Does data have a or b ? | \n data ?| array['a','b'] | \n
?& text[] | \n Does data have a and b ? | \n data ?& array['a','b'] | \n
@> jsonb | \n Does left include right ? | \n data @> '{\"b\":2}'::jsonb | \n
<@ jsonb | \n Does right include left ? | \n data <@ '{\"a\":1,\"b\":2}'::jsonb | \n
When ?
/?|
/?&
works on objects, it checks keys; when it works on arrays, it checks for elements.
UPDATE users SET tags = tags || array['admin'];\n
\n\nOperator | \nExample | \nDescription | \n
---|---|---|
|| json | \n data || array['a','b'] | \n Concatenate | \n
- str | \n data - 'a' | \n Delete a key | \n
- int | \n data - 1 | \n Delete an array item | \n
#- text[] | \n data #- '{us,name}' | \n Delete a path | \n
Only available in PostgreSQL 9.5+.
\n\nUPDATE users SET data = jsonb_set(data, '{name}', '\"John\"');\n
\n\nOnly available in PostgreSQL 9.5+.
\n\njsonb_set(data, '{path}', value)\njsonb_strip_nulls(data)\n
\n\nto_json(\"Hello\"::text)\narray_to_json('{1,2}'::int[])\n
\n\nSELECT * from json_each('{\"a\":1, \"b\":2}')\nSELECT * from json_each_text('{\"a\":1, \"b\":2}')\n-- key | value\n
\n\nThis is an incomplete list, there’s way too many!
\n\nSee: JSON functions
\n\n'{\"a\":1}'::jsonb ? 'a'
'[\"a\"]'::jsonb ? 'a'
Replace anything within <placeholder>
accordingly
$ psql #logs in to default database & default user\n$ sudo -u <rolename:postgres> psql #logs in with a particular user\n
\n\n\\du
\\dt
\\l
\\c <database>
\\d <table>
or \\d+ <table>
\\q
$ createdb databasename\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "premailer",
"title": "Premailer",
"url": "/premailer",
"category": "Others",
"keywords": null,
"content_html": "table, th, td {\n /* Available on table, th and td elements */\n -premailer-width: 32px;\n}\n\ntable, tr, th, td {\n /* Available on table, tr, th and td elements */\n -premailer-height: 32px;\n}\n\ntable {\n /* Available on table elements */\n -premailer-cellpadding: 32px;\n -premailer-cellspacing: 32px;\n}\n
",
"intro_html": "Premailer is a Ruby library that inlines CSS into HTML.
", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "projectionist", "title": "Projectionist", "url": "/projectionist", "category": "Vim", "keywords": null, "content_html": "/* .projectionist.vim */\n{\n \"app/assets/react/components/*.jsx\": {\n \"type\": \"component\",\n \"template\": [\n \"import React from 'react'\",\n \"export default {} = React.createClass({ ... })\"\n ]\n }\n
\n\n{\n \"lib/*.rb\": {\n \"type\": \"lib\", /* enables :Elib */\n \"alternate\": \"test/{}_spec.rb\", /* for :A */\n \"template\": [ ... ],\n\n \"path\": \"include\", /* for `gf` i think */\n\n \"console\": \"node\", /* for :Console */\n \"dispatch\": \"node\", /* for :Dispatch (dispatch.vim) */\n \"start\": \"rails server\", /* for :Start (dispatch.vim) */\n \"make\": \"node\", /* for makeprg */\n }\n}\n
\n\nCommand | \nDescription | \n
---|---|
:A | \n Edit alternate | \n
:A {file} | \n Edit file | \n
:AS | \n Edit in split | \n
:AV | \n Edit in vsplit | \n
:AT | \n Edit in tab | \n
:AD | \n Replace with template | \n
:Cd | \n cd to root | \n
:Cd {path} | \n cd to path in root | \n
:Lcd | \n cd to root using :lcd | \n
:ProjectDo {cmd} | \n run command in root | \n
See vim-projectionist.
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "promise", "title": "Promises", "url": "/promise", "category": "JavaScript", "keywords": null, "content_html": "intro: A quick reference to the JavaScript Promise API.
\n\nnew Promise((resolve, reject) => {\n doStuff(() => {\n if (success) {\n resolve('good')\n } else {\n reject(new Error('oops'))\n }\n })\n})\n
\n\nUse new Promise to create new promises.
\n\npromise\n .then((result) => {\n /* success */\n })\n .catch((error) => {\n /* failure */\n })\n
\n\nthen() runs a function when a promise resolves. catch() runs when a promise fails.
\n\nconst promises = [promise1(), promise2() /* ... */]\n
\n\n// Succeeds when all succeed\nPromise.all(promises).then((results) => {\n /* ... */\n})\n
\n\n// Succeeds when one finishes first\nPromise.race(promises).then((result) => {\n /* ... */\n})\n
\n\nreturn Promise.resolve('result')\nreturn Promise.resolve(promise)\nreturn Promise.resolve(thenable)\n\nreturn Promise.reject('reason')\n\nPromise.resolve(result).then(() => {\n /* ... */\n})\n
\n\nPromise.resolve(val)
will return a promise that resolves to the value given to it.
> cd Array\n
\n\n> ls\n Array.methods: [] try_convert\n Array#methods: & * + abbrev assoc at ...\n
\n\n> show-source\n
\n\n> show-method Array#select\n
\n\n> ri Array\n> ri Array#each\n\n> cd Gem\n> show-doc try_activate\n
\n\n> find-method each\n Array#each\n Array#each_index\n Enumerable#each_slice\n ...\n
\n\n> edit Pry#repl\n
\n\n> gem-cd foo # Switch to gem's dir\n> gem-install foo\n> gem-list\n
\n\n> hist # History\n> wtf? # Trace of recent exception\n
\n\nAlso consider pry-rails.
\n\n$ pry -r ./config/environment\n
\n\n> show-models\n> show-routes\n> show-middleware\n
\n\n> ls # All\n\n> ls -m # Methods\n> ls -M # Instance methods\n\n> ls -g # Globals\n> ls -l # Local vars\n> ls -c # Constants\n\n> ls -i # Instance vars\n\n> ls -G xx # Grey by regex\n
\n\nshell-mode adds dir to the prompt.
\n\npry(main)> shell-mode\npry(main):/home/x $\n
\n\nCommands with .
are shell commands.
pry(main)> .cat hello.txt\n
\n\nAdd the hirb gem.
\n\n> table User.all\n> view User.all\n> view User.all, fields: %w[id name email]\n
\n\nAdd the pry-rescue gem.
\n\nPry::rescue {\n # raise exceptions here\n}\n
\n\nOr run:
\n\nbundle exec rescue rspec\n
\n\nAdditional commands:
\n\npry(main)> cd-cause\npry(main)> try-again\n
\n\nAdd the pry-remote gem.
\n\n# In your code:\nbinding.remote_pry\n\n# In the shell:\nbundle exec pry-remote\n
\n\npsd = PSD.new(file, parse_layer_images: true)\npsd.parse!\n
\n\n# Gets the root node.\n# A #<Node> can be a Group or a Layer.\nnode = psd.tree\n
\n\nnode.root\nnode.descendants\nnode.ancestors\nnode.siblings\nnode.subtree\n
\n\nnode.descendant_groups\nnode.descendant_layers\n
\n\nnode.name #=> \"Layer 2\"\n
\n\nnode.top #=> 3\nnode.left #=> 3\nnode.bottom\nnode.right\n
\n\n# Note: these are interchanged (?)\nnode.width\nnode.height\n
\n\nnode.visible?\nnode.hidden?\n
\n\nnode.layer?\nnode.group?\n
\n\nnode.blending_mode #=> \"normal\"\nnode.opacity #=> 0..255\nnode.fill_opacity #=> 0..255\n
\n\nnode.text #=> (Hash)\nnode.text[:value] #=> \"Text here\"\nnode.text[:font][:name] #=> \"Arial\"\nnode.text[:font][:sizes] #=> [6.9]\nnode.text[:font][:colors] #=> [[255,255,255,255]]\nnode.text[:font][:css] #=> \"font-family: ...;\"\nnode.text[:left] #=> 3\nnode.text[:top]\nnode.text[:right]\nnode.text[:bottom]\nnode.text[:transform] #=> (Hash)\n
\n\nfx = node.info[:object_effects]\n
\n\nfx.data['Scl '] # ?\nfx.data['GrFl'] # Gradient fill\n
\n\nnode.mask[\"mask_size\"] == 0 # No mask\nnode.mask[\"mask_size\"] == 20 # Has mask\nnode.mask[\"top\"]\nnode.mask[\"left\"]\nnode.mask[\"bottom\"]\nnode.mask[\"right\"]\n
\n\nPSD.rb parses Photoshop documents in Ruby.
", "description_html": "", "tags": null, "updated": null },{ "id": "pug", "title": "Pug", "url": "/pug", "category": "JavaScript libraries", "keywords": null, "content_html": "doctype html\nhtml(lang='en')\n h1.class#id(name='hi')\n | This is some text, hello there,\n = name\n\n - javascript()\n
\n\ndiv\n | Just a div\n
\n\n.search\n | A div, with class 'search'\n
\n\nh1 A heading with text\n
\n\nh1= page.title\n
\n\ndiv.class\ndiv.class1.class2\nh1.header\n
\n\ninput(type='text' name='q' autofocus)\n
\n\n- var authenticated = true\nbody(class=authenticated ? 'authed' : 'anon')\n
\n\nSee: Attributes
\n\n// This comment will appear in the HTML\n
\n\n//- This is a silent comment\n
\n\n//-\n Nesting inside a comment creates\n a comment block\n
\n\nSee: Comments
\n\nul\n each user in users\n li= user\n
\n\n//- page.pug\nextends layout.pug\n\nblock title\n | hello\n\nblock content\n | hello\n
\n\n//- layout.pug\ntitle\n block title\nbody\n block content\n
\n\ninclude ./includes/head.pug\n
\n\ninclude:markdown article.md\n
\n\nSee: Includes
\n\np.\n This is text that doesn't need to\n be prefixed by pipes.\n
\n\nscript.\n // It's great for raw\n // JavaScript and stuff\n alert('hello')\n
\n\nif authenticated\n a(href='/logout') Sign out\nelse\n a(href='/login') Sign in\n
\n\nSee: Conditionals
\n\nmixin list\n ul\n ···\n
\n\n+list\n
\n\nMixins allow you to create reusable code blocks.\nSee: Mixins
\n\nmixin pet(name)\n span.pet= name\n
\n\n+pet('cat')\n
\n\nSee: Mixin attributes
\n\nmixin article(title)\n article\n h2.title= title\n block\n
\n\n+article('hello there')\n p Content goes here\n
\n\nSee: Mixin blocks
", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2017-10-30" },{ "id": "python", "title": "Python", "url": "/python", "category": "Python", "keywords": null, "content_html": "list = []\nlist[i:j] # returns list subset\nlist[-1] # returns last element\nlist[:-1] # returns all but the last element\n\nlist[i] = val\nlist[i:j] = otherlist # replace ith to jth-1 elements with otherlist\ndel list[i:j]\n\nlist.append(item)\nlist.extend(another_list)\nlist.insert(index, item)\nlist.pop() # returns and removes last element from the list\nlist.pop(i) # returns and removes i-th element from the list\nlist.remove(i) # removes the first item from the list whose value is i\nlist1 + list2 # combine two list \nset(list) # remove duplicate elements from a list\n\nlist.reverse() # reverses the elements of the list in-place\nlist.count(item)\nsum(list)\n\nzip(list1, list2) # returns list of tuples with n-th element of both list1 and list2\nlist.sort() # sorts in-place, returns None\nsorted(list) # returns sorted copy of list\n\",\".join(list) # returns a string with list elements seperated by comma\n
\n\ndict.keys()\ndict.values()\n\"key\" in dict # let's say this returns False, then...\ndict[\"key\"] # ...this raises KeyError\ndict.get(\"key\") # ...this returns None\ndict.setdefault(\"key\", 1)\n
\n\nfor item in [\"a\", \"b\", \"c\"]:\nfor i in range(4): # 0 to 3\nfor i in range(4, 8): # 4 to 7\nfor i in range(1, 9, 2): # 1, 3, 5, 7\nfor key, val in dict.items():\nfor index, item in enumerate(list):\n
\n\nstr[0:4]\nlen(str)\n\nstring.replace(\"-\", \" \")\n\",\".join(list)\n\"hi {0}\".format('j')\nf\"hi {name}\" # same as \"hi {}\".format('name')\nstr.find(\",\")\nstr.index(\",\") # same, but raises IndexError\nstr.count(\",\")\nstr.split(\",\")\n\nstr.lower()\nstr.upper()\nstr.title()\n\nstr.lstrip()\nstr.rstrip()\nstr.strip()\n\nstr.islower()\n\n/* escape characters */\n>>> 'doesn\\'t' # use \\' to escape the single quote...\n \"doesn't\"\n>>> \"doesn't\" # ...or use double quotes instead\n \"doesn't\"\n>>> '\"Yes,\" they said.'\n '\"Yes,\" they said.'\n>>> \"\\\"Yes,\\\" they said.\"\n '\"Yes,\" they said.'\n>>> '\"Isn\\'t,\" they said.'\n '\"Isn\\'t,\" they said.'\n
\n\nint(str)\nfloat(str)\nstr(int)\nstr(float)\n'string'.encode()\n
\n\n[fn(i) for i in list] # .map\nmap(fn, list) # .map, returns iterator\n\nfilter(fn, list) # .filter, returns iterator\n[fn(i) for i in list if i > 0] # .filter.map\n
\n\nimport re\n\nre.match(r'^[aeiou]', str)\nre.sub(r'^[aeiou]', '?', str)\nre.sub(r'(xyz)', r'\\1', str)\n\nexpr = re.compile(r'^...$')\nexpr.match(...)\nexpr.sub(...)\n
\n\nfile = open(\"hello.txt\", \"r\") # open in read mode 'r'\nfile.close() \n
\n\nprint(file.read()) # read the entire file and set the cursor at the end of file\nprint file.readline() # Reading one line\nfile.seek(0, 0) # place the cursor at the beggining of the file\n
\n\nfile = open(\"hello.txt\", \"w\") # open in write mode 'w'\nfile.write(\"Hello World\") \n\ntext_lines = [\"First line\", \"Second line\", \"Last line\"] \nfile.writelines(text_lines)\n\nfile.close()\n
\n\nfile = open(\"Hello.txt\", \"a\") # open in append mode\nfile.write(\"Hello World again\") \nfile.close()\n
\n\nwith open(\"welcome.txt\", \"r\") as file:\n # 'file' refers directly to \"welcome.txt\"\n data = file.read()\n\n# It closes the file automatically at the end of scope, no need for `file.close()`.\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "qjs",
"title": "Q.js",
"url": "/qjs",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "Q.promise (ok, fail) =>\n asyncFunction ->\n if error\n fail new Error(\"Failure\")\n else\n ok(data)\n
\n\npromises = [saveDisk(), saveCloud()]\n\n# When all succeeds, or *at least one* error\nQ.all(promises).done ->\n alert \"Saved\"\n\n# Same, but get the values\nQ.all(promises).spread (a, b) ->\n alert \"Result A:\" + a\n alert \"Result B:\" + b\n\n# When all either succeeds or errors\nQ.allSettled(promises).done -> ...\n
\n\n# Works like .call() or .apply()\n\nQ.nfcall(FS.readFile, 'foo.txt', 'utf-8')\n.then -> ...\n\nQ.nfapply(FS.readFile, ['foo.txt', 'utf-8'])\n.then -> ...\n\nQ.npost(FS, 'readFile', ['foo.txt, 'utf-8'])\n.then -> ...\n\nQ.npost(FS, 'readFile', 'foo.txt, 'utf-8')\n.then -> ...\n\nreadFile = Q.denodeify(FS.readFile)\nreadFile('foo.txt').then -> ...\n
\n\ncreateUser = (next) ->\n promiseMaker()\n .nodeify(next)\n
\n\n# Shortcut for .then(ok, fail, progress)\npromise\n.then (data) ->\n.catch (err) ->\n.progress (percent) ->\n
\n\nQ.try ->\n promise()
\n\n.catch (e) ->\n console.error “Oh well”, e
\n\nQUnit.module('a')\nQUnit.test('ok', function (t) {\n /* ... */\n})\n
\n\n// each test\nQUnit.testStart(function)\nQUnit.testEnd(function)\n
\n\n// each module\nQUnit.moduleStart(function)\nQUnit.moduleEnd(function)\n
\n\n// all\nQUnit.begin(function)\nQUnit.done(function)\n
\n\nt.equal(actual, expected)\nt.deepEqual(actual, expected)\nt.strictEqual(actual, expected)\nt.propEqual(actual, expected)\nt.notEqual(actual, expected)\nt.expect(amount)\n
",
"intro_html": "A quick reference for the QUnit testing library in JavaScript.
", "description_html": "", "tags": null, "updated": null },{ "id": "rack-test", "title": "rack-test", "url": "/rack-test", "category": "Ruby libraries", "keywords": null, "content_html": "get 'url'\npost 'url', 'name' => 'john'\nput\npatch\ndelete\noptions\nhead\n
\n\nauthorize 'user', 'pass'\nenv 'rack.session', csrf: 'token'\nheader 'Content-Type', 'text/html'\n
\n\nSee rack/test.rb.
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "ractive", "title": "Ractive.js", "url": "/ractive", "category": "JavaScript libraries", "keywords": null, "content_html": "new Ractive({\n el: $('..'),\n el: '#box',\n template: '...', // required\n\n // callbacks\n init: function() {}, // on instantiate\n complete: function() {}, // on finish animations\n\n // objs\n data: { ... },\n partials: { ... }, // global: Ractive.partials\n transitions: { ... }, // global: Ractive.transitions\n components: { ... },\n adaptors: [ ... ],\n\n // options\n magic: false\n modifyArrays: true\n twoway: true\n noIntro: true // true = disable transition on initial render\n lazy: false // false = use keyevents, true = use change/blur\n append: false // false = overwrite element, true = append\n debug: false\n sanitize: false\n})\n
\n\nview.add('count', 1) //=> promise\nview.subtract('count', 1) //=> promise\nview.toggle('shown') //=> promise\n\nview.set('a', true)\nview.set({ a: true })\nview.reset({ a: true })\nview.merge('list', [a,b,c])\n\nview.get('a')\nview.data.a\n
\n\nview.find('.klass')\nview.findAll('.klass')\nview.nodes\nview.nodes['hello'] // .find('#hello')\n\nview.findComponent('photo')\nview.findAllComponents('photo')\n
\n\nview.on('event', function() { ... })\nview.off('event', fn)\nview.fire('event')\n
\n\nview.update()\nview.updateModel()\n\nview.insert('.node .path')\n\nview.observe({ 'name': function() { ... } })\n\nview.toHTML() //=> String\nview.render()\n
\n\nView = Ractive.extend({\n ...\n})\nnew View()\n
\n\nSee: https://github.com/RactiveJS/Ractive/issues/74
\n\nWidget = Ractive.extend({ ... })\n\nractive = new Ractive({\n el: 'main',\n template: '<widget foo=\"bar\"/>',\n components: {\n widget: Widget\n }\n});\n
\n\n// Global partials\nRactive.partials.x = \"<..>\"\n
\n\nview.on('teardown')\n
\n\n<button on-click='activate'>Activate!</button>\n\nview.on({\n activate: function () { ... }\n});\n\n<button on-click='sort:name'>Sort by name</button>\nview.on('sort', function (e, column) {\n console.log('sorting by #{column}');\n});\n
\n\n view.observe(\"name\", function (name) {\n console.log(\"Changed name to\", name);\n }, { init: false });\n
\n\nHello, {{name}}\nBody: {{{unescaped}}}\n\n<!-- each -->\n{{#mylist:i}}\n <li>{{this.name}}</li>\n <li>{{name}}</li>\n <li>{{.}}</li> <!-- same as 'this' -->\n{{/mylist}}\n\n{{^user}}Not logged in{{/user}} <!-- if false -->\n{{#user}}Welcome, sire{{/user}} <!-- if true -->\n\n{{>partialName}}\n<component>\n\n{{#statusDogs[selected]}}\n
\n\nThis transforms the list
attribute via a helper function called sort()
.
{{# sort(list, \"name\") :num }}\n <li>{{num}} - {{name}}</li>\n{{/ end. any text goes here }}\n\ndata: {\n sort: function(array, column) { return array.whatever(); }\n}\n
\n\n<div intro=\"fade\">\n<div intro=\"bump\">\n<div intro=\"bump:{duration:400}\">\n\nRactive.transitions.bump = function(t, params) {\n params = t.processParams( params, {\n duration: 400,\n color: t.isIntro ? 'rgb(0,255,0)' : 'rgb(255,0,0)'\n });\n\n if (t.isIntro) {\n /* enter */\n } else {\n /* exit */\n }\n\n t.complete();\n};\n
\n\n<span decorator=\"tooltip:hello there\">Hover me</span>\n\ndecorators: {\n tooltip: function (node, content) {\n // setup code here\n return {\n teardown: function () {\n // cleanup code here\n }\n }\n }\n}\n\n<span decorator=\"tooltip:'a','b',2,'c'\">Hover me</span>\n\ntooltip: function (node, a, b, two, c) { ... }\n
\n\nmyAdaptor = {\n filter: function (object, keypath, ractive) {\n // return `true` if a particular object is of the type we want to adapt\n },\n wrap: function (ractive, object, keypath, prefixer) {\n // set up event bindings here\n object.on('change', function () { ractive.set(prefixer({...})); });\n // then return a wrapper:\n return {\n teardown: function () { .. },\n // json representation\n get: function () { return { a:2, b:3, c:4, ... }; },\n // called on ractive.set\n set: function (key, val) { },\n // called on ractive.set on root (return false = die)\n reset: function (data) { return false; }\n };\n }\n};\n
\n\nnew Ractive({\n template: '{{area}}',\n computed: {\n area: function () { return this.get('width') * this.get('height'); }\n area: '${width} * ${height}'\n fullname: {\n get: '${first} + \" \" + ${last}\"\n set: function (name) { ... }\n }\n }\n});\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rails-controllers",
"title": "Controllers",
"url": "/rails-controllers",
"category": "Rails",
"keywords": null,
"content_html": "redirect_to root_url\nredirect_to root_url, notice: \"Good.\"\n
\n\nsession[:user_id] = nil\n\nflash[:notice] = \"Hello\" # Gets flushed on next request\nflash.keep # Persist flash values\nflash.now[:error] = \"Boo\" # Available on the same request\n\ncookies[:hello] = \"Hi\"\n\nparams[:page]\n\n# params is a combination of:\nquery_parameters\npath_parameters\nrequest_parameters\n
\n\nrespond_to do |format|\n format.html\n format.xml { render xml: @users }\n format.json { render json: @users }\n format.js # Will be executed by the browser\nend\n
\n\n# The options parameter is the hash passed in to 'url_for'\ndef default_url_options(options)\n {:locale => I18n.locale}\nend\n
\n\n# Filter with callbacks\nbefore_filter :authenticate\nbefore_filter :authenticate, except: [:login]\nbefore_filter :authenticate, only: [:login]\ndef authenticate\n redirect_to login_url unless controller.logged_in?\nend\n\n# Filter with inline\nbefore_filter do |controller|\n redirect_to login_url unless controller.logged_in?\nend\n\n# Filter with external classes\nbefore_filter LoginFilter\nclass LoginFilter\n def self.filter(controller) ...; end\nend\n\n# Filter exceptions\nskip_before_filter :require_login, only: [:new, :create]\n\n# Before/after filters\naround_filter :wrap_in_transaction\ndef wrap_in_transaction(&blk)\n ActiveRecord::Base.transaction { yield }\nend\n
\n\nbefore_filter :authenticate\n\n# Basic authentication:\ndef authenticate\n authenticate_or_request_with_http_basic { |u, p|\n u == \"root\" && p == \"alpine\"\n }\nend\n\n# ...or digest (hashed) authentication:\n# uses the ha1 hash (username:realm:password)\ndef authenticate_by_digest\n realm = \"Secret3000\"\n users = {\n \"rsc\" => Digest::MD5.hexdigest(\"rsc:#{realm}:passwordhere\")\n }\n\n authenticate_or_request_with_http_digest(realm) { |user|\n users[user]\n }\nend\n\n# For integration tests\ndef test_access\n auth = ActionController::HttpAuthentication::Basic.encode_credentials(user, pass)\n get \"/notes/1.xml\", nil, 'HTTP_AUTHORIZATION' => auth\nend\n\n# Token auth\nis_logged_in = authenticate_with_http_token do |token, options|\n token == our_secret_token\nend\n\nrequest_http_token_authentication unless is_logged_in\n
\n\nrequest.host #=> \"www.example.com\"\nrequest.domain #=> \"www.example.com\"\nrequest.domain(n=2) #=> \"example.com\"\nrequest.port #=> 80\nrequest.protocol #=> \"http://\"\nrequest.query_string #=> \"q=duck+tales\"\nrequest.url #=> \"http://www.example.com/search?q=duck+tales\"\nrequest.fullpath #=> \"/search?q=duck+tales\"\n\nrequest.headers # Returns a hash\n\nrequest.format #=> \"text/html\"\nrequest.remote_ip #=> \"203.167.220.220\"\nrequest.local? #=> true (if localhost/127.0.0.1)\n\nrequest.xhr?\n\nrequest.method #=> \"POST\"\nrequest.method_symbol #=> :post\nrequest.get?\nrequest.post?\nrequest.put?\nrequest.delete?\nrequest.head?\n
\n\nresponse.body\nresponse.status #=> 404\nresponse.location # Redirect location\nresponse.content_type\nresponse.charset\nresponse.headers\n\nresponse.headers[\"Content-Type\"] = \"application/pdf\"\n
\n\nsend_data pdfdata, filename: \"foo.pdf\", type: \"application/pdf\"\nsend_file Rails.root.join('public','filename.txt') [filename: '..', type: '..']\n
\n\n- form_for @post do |f|\n
\n\nField names will be prefixed with post
(the class name), and values will be derived from this object (eg, f.text_field :name
from @post.name
).
- form_for @post, |\n url: { method: 'put', action: 'create' }, |\n html: { class: 'nifty_form' } |\n do |f|\n
\n\nf.text_field :title\nf.text_area :body, size: '60x12'\n
\n\nf.check_box :remember_me\nf.label :remember_me, \"Remember me\"\n
\n\nf.radio_button :gender, 'male'\nf.label :gender_male, \"Male\"\n\nf.radio_button :gender, 'female'\nf.label :gender_female, \"Female\"\n
\n\nf.label :title\nf.label :title, \"Title\"\nf.label :title, \"Title\", class: \"title\"\nf.label(:post, :terms) { \"Accept terms\" }\n
\n\nf.submit \"Create\"\n
\n\nf.hidden_field :id\n
\n\nf.object\n
\n\n= form_for @post do |f|\n = fields_for :author, @post.author do |ff|\n = ff.text_field :name\n
\n\nf.select :city_id, [['Lisbon',1], ['Madrid',2], ...], 4\n# (4 = selected)\n\noptions_for_select [['Lisbon',1], ['Madrid',2], ...], 4\n# Just makes <option> tags\n
\n\nf.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial\nf.collection_select :city_id, City.all, :id, :name\n# (field, collection, value_key, label_key)\n
\n\nf.time_zone_select :time_zone\nf.date_select :birthday\n
\nhelpers:\n submit:\n # helpers.submit.<action>\n create: \"Create a %{model}\"\n update: \"Confirm changes to %{model}\"\n\n # helpers.submit.<model>.<action>\n article:\n create: \"Publish article\"\n update: \"Update article\"\n\n # helpers.label.<model>.<field>\n label:\n post:\n body: \"Your body text\"\n
\n\nf
radio_button(\"post\", \"category\", \"rails\")\nradio_button(\"post\", \"category\", \"java\")\n\n# picks from @post.category\n# <input type=\"radio\" id=\"post_category_rails\" name=\"post[category]\"\n# value=\"rails\" checked=\"checked\" />\n
\n\nselect(method, choices = nil, options = {}, html_options = {}, &block)\n choices == [ ['label', id], ... ]\n\nsubmit(value=nil, options={})\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rails-helpers",
"title": "Helpers",
"url": "/rails-helpers",
"category": "Rails",
"keywords": null,
"content_html": "distance_of_time_in_words(Time.now, project.end_date) #=> 3 hours\ndistance_of_time_in_words_to_now(project.end_date) #=> 3 hours\n\ntime_ago_in_words 3.minutes.ago #=> \"3 minutes\"\n
\n\nnumber_to_currency 20.33\nnumber_to_currency 20.33, precision: 0\nnumber_with_precision 3.14159, precision: 2\nnumber_to_percentage 32 #=> \"32%\"\nnumber_with_delimiter 2048 #=> \"2,048\"\nnumber_to_human 12000000 #=> \"12 million\"\nnumber_to_human_size 12000000 #=> \"12 MB\"\nnumber_to_phone \"5551234\" #=> \"555-1234\"\n
\n\n<% cache project do %>\n<% cache [project, current_user] do %>\n\n<% cache_if admin?, project do %>\n<% cache_unless admin?, project do %>\n
\n\ntag(\"br\")\ntag(\"img\", src: \"image.jpg\")\ncontent_tag(:p, \"Hello\")\n
\n\n# Creates a time select tag that, when POSTed, will be stored in the article\n# variable in the sunrise attribute.\ntime_select \"article\", \"start_time\"\n\n# All options are optional\ntime_select \"article\", \"start_time\", \\\n include_seconds: true,\n minute_step: 15,\n prompt: true,\n prompt: { hour: \"Choose hr\", minute: \"Choose min\", second: \"Choose sec\" },\n ampm: true\n\n# For dates (all options are optional)\ndate_select \"article\", \"written_on\", \\\n start_year: 1995,\n use_month_numbers: true,\n discard_day: true,\n include_blank: true,\n order: [:day, :month, :year],\n default: 3.days.from_now,\n default: { day: 20 },\n prompt: { day: 'Select day', month: 'Select month', year: 'Select year' }\n
\n\ntime_tag Date.today \n#=> '<time datetime=\"2010-11-04\">November 04, 2010<%rtime>'\n\ntime_tag Time.now\n#=> '<time datetime=\"2010-11-04T17:55:45+01:00\">November 04, 2010 17:55</time>'\n\ntime_tag Date.yesterday, 'Yesterday'\n#=> '<time datetime=\"2010-11-03\">Yesterday<%rtime>'\n\ntime_tag Date.today, pubdate: true\n#=> '<time datetime=\"2010-11-04\" pubdate=\"pubdate\">November 04, 2010</time>'\n\ntime_tag Date.today, \\\n format: :short_date # (en.time.formats.short_date)\n
\n\n= form_for @post, multipart: true do |f|\n = f.file_field :picture\n
\n\nt('folders')\nt('folders.save')\n\nl(Time.now)\n\nt('x_files', count: files.count)\n# files:\n# one: 'one file'\n# other: '%{count} files'\n
\n\n* http://api.rubyonrails.org/classes/ActionView/Helpers.html\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rails-i18n",
"title": "i18n",
"url": "/rails-i18n",
"category": "Rails",
"keywords": null,
"content_html": "t('my.messages.hello')\n\n# same as 'my.messages.hello'\nt(:hello, scope: 'my.messages')\nt(:hello, scope: [:my, :messages])\n\nt('my.messages.hello', default: \"Hello\")\n
\n\nen:\n my:\n messages:\n hello: \"Hello\"\n
\n\nt('hello', name: \"John\")\n
\n\nhello: \"Hello %{name}\"\n
\n\n# from the 'books/index' view\nt('.title')\n
\n\nen:\n books:\n index:\n title: \"Título\"\n
\n\nt(:inbox, count: 1) #=> 'one message'\nt(:inbox, count: 2) #=> '2 messages'\n
\n\ninbox:\n one: 'one message',\n other: '%{count} messages'\n
\n\nl(Time.now)\nl(Time.now, format: :short)\n
\n\nen:\n time:\n formats:\n default: \"%a, %d %b %Y %H:%M:%S %z\"\n long: \"%B %d, %Y %H:%M\"\n short: \"%d %b %H:%M\"\n
\n\nl(Date.today)\n
\n\nen:\n date:\n formats:\n default: \"%Y-%m-%d\" # 2015-06-25\n long: \"%B %d, %Y\" # June 25, 2015\n short: \"%b %d\" # Jun 25\n
\n\nUser.model_name.human #=> \"User\"\nChild.model_name.human(count: 2) #=> \"Children\"\n
\n\nen:\n activerecord:\n models:\n user: \"User\"\n child:\n one: \"Child\"\n other: \"Children\"\n
\n\nUser.human_attribute_for :name #=> \"Name\"\n
\n\nen:\n activerecord:\n attributes:\n user:\n # activerecord.attributes.<model>.<field>\n name: \"Name\"\n email: \"Email\"\n
\n\nerror_messages_for(...)\n
\n\nactiverecord:\n errors:\n models:\n venue:\n attributes:\n name:\n blank: \"Please enter a name.\"\n
\n\nPossible scopes (in order):
\n\nactiverecord.errors.models.[model_name].attributes.[attribute_name].[error]\nactiverecord.errors.models.[model_name].[error]\nactiverecord.errors.messages.[error]\nerrors.attributes.[attribute_name].[error]\nerrors.messages.[error]\n
\n\nWhere [error]
can be:
validates\n confirmation - :confirmation\n acceptance - :accepted\n presence - :blank\n length - :too_short (%{count})\n length - :too_long (%{count})\n length - :wrong_length (%{count})\n uniqueness - :taken\n format - :invalid\n numericality - :not_a_number\n
\n\nform_for @post do\n f.label :body\n
\n\nhelpers:\n # helpers.label.<model>.<field>\n label:\n post:\n body: \"Your body text\"\n
\n\nform_for @post do\n f.submit\n
\n\nhelpers:\n submit:\n # helpers.submit.<action>\n create: \"Create a %{model}\"\n update: \"Confirm changes to %{model}\"\n\n # helpers.submit.<model>.<action>\n article:\n create: \"Publish article\"\n update: \"Update article\"\n
\n\nnumber_to_delimited(2000) #=> \"2,000\"\nnumber_to_currency(12.3) #=> \"$12.30\"\nnumber_to_percentage(0.3) #=> \"30%\"\nnumber_to_rounded(3.14, precision: 0) #=> \"3\"\nnumber_to_human(12_000) #=> \"12 Thousand\"\nnumber_to_human_size(12345) #=> \"12.3 kb\"\n
\n\nnumber_to_delimited(n)\n
\n\nnumber:\n format:\n separator: '.'\n delimiter: ','\n precision: 3\n significant: false\n strip_insignificant_zeroes: false\n
\n\nnumber_to_currency(n)\n
\n\nnumber:\n currency:\n format:\n format: \"%u%n\" # %u = unit, %n = number\n unit: \"$\"\n separator: '.'\n delimiter: ','\n precision: 3\n # (see number.format)\n
\n\nnumber_to_percentage(n)\n
\n\nnumber:\n percentage:\n format:\n format: \"%n%\"\n # (see number.format)\n
\n\nI18n.backend.store_translations :en, ok: \"Ok\"\nI18n.locale = :en\nI18n.default_locale = :en\n\nI18n.available_locales\n\nI18n.translate :ok # aka, I18n.t\nI18n.localize date # aka, I18n.l\n
\n\n$ rails generate migration RemovePartNumberFromProducts part_number:string\n$ rails generate migration remove_part_number_from_products part_number # rails assumes string if not type given - and you can use snake_case\n\n$ rails generate migration AddNameToWidgets name:string\n$ rails g migration add_name_to_widgets name:string # you can use the short cut 'g' instead of generate - they both do the same thing\n
\n\n$ rake db:migrate\n
\n\ncreate_table :users do |t|\n t.string :name\n t.text :description\n\n t.primary_key :id\n t.string :title\n t.text :description\n t.integer :games_count\n t.float :lol\n t.decimal :price\n t.decimal :price, :precision => 2, :scale => 10\n t.datetime :expiration\n t.timestamp :time_in\n t.time :time_in\n t.date :expiry\n t.binary :image_data\n t.boolean :is_admin\nend\n\n# Options:\n :null (boolean)\n :limit (integer)\n :default\n
\n\nadd_column :users, :first_name, :string\nremove_column :users, :first_name, :string\n\nchange_column :users, :first_name, :text\n\nchange_column_default :users, :admin, nil\nchange_column_null :users, :email, false # adds NOT NULL constraint\n\ncreate_table\nchange_table\ndrop_table\n\nadd_column\nchange_column\nrename_column\nremove_column\n\nadd_index\nremove_index\n
\n\nclass AddFlagToProduct < ActiveRecord::Migration\n class Product < ActiveRecord::Base\n end\n \n def change\n add_column :products, :flag, :boolean\n Product.reset_column_information\n reversible do |dir|\n dir.up { Product.update_all flag: false }\n end\n end\nend\n
\n\nt.references :category # kinda same as t.integer :category_id\n\n# Can have different types\nt.references :category, polymorphic: true\n
\n\n$ rails generate migration RemovePartNumberFromProducts part_number:string\n
\n\n# Simple\nadd_index :suppliers, :name\n\n# Unique\nadd_index :accounts, [:branch_id, :party_id], :unique => true\n\n# Named (:name => ...)\nadd_index :accounts, [:branch_id, :party_id], :unique => true, :name => \"by_branch_party\"\n\n# Length\nadd_index :accounts, :name, :name => ‘by_name’, :length => 10\nadd_index :accounts, [:name, :surname], :name => ‘by_name_surname’,\n :length => {\n :name => 10,\n :surname => 15\n }\n\n# Sort order (no MySQL support)\nadd_index :accounts, [:branch_id, :party_id, :surname],\n :order => {:branch_id => :desc, :part_id => :asc}\n
\n\nUse ActiveRecord::Migration
.
ActiveRecord::Migration.add_index :posts, :slug\n
\n\n$ rails g model User\n
\n\nitems = Model\n .where(first_name: 'Harvey')\n .where('id = 3')\n .where('id = ?', 3)\n
\n\n .order(:title)\n .order(title: :desc)\n .order(\"title DESC\")\n
\n\n .reorder(:title) # discards other .order's\n .rewhere(...) # discards other .where's\n
\n\n .limit(2)\n .offset(1)\n .uniq\n
\n\nSee: QueryMethods
\n\nitems = Model\n .select(:id)\n .select([:id, :name])\n
\n\n .group(:name) # GROUP BY name\n .group('name AS grouped_name, age')\n .having('SUM(price) > 30') # needs to be chained with .group\n
\n\n .includes(:user)\n .includes(user: [:articles])\n
\n\n .references(:posts)\n # aka: .where(\"posts.name = 'foo'\").references(:posts)\n
\n\nitem = Model.find(id)\nitem = Model.find_by_email(email)\nitem = Model.where(email: email).first\n
\n\nModel\n .exists?(5)\n .exists?(name: \"David\")\n
\n\n .first\n .last\n .find_nth(4, [offset])\n
\n\nSee: FinderMethods
\n\nitem.new_record?\nitem.persisted?\nitem.destroyed?\n\nitem.serialize_hash\n
\n\nitem.save\nitem.save! # Same as above, but raises an Exception\n
\n\nitem.update name: 'John' # Saves immediately\nitem.update! name: 'John'\n
\n\nitem.update_column :name, 'John' # skips validations and callbacks\nitem.update_columns name: 'John'\nitem.update_columns! name: 'John'\n
\n\nitem.touch # updates :updated_at\nitem.touch :published_at\n
\n\nitem.destroy\nitem.delete # skips callbacks\n
\n\nModel.create # Same an #new then #save\nModel.create! # Same as above, but raises an Exception\n
\n\nSee: Persistence
\n\nitem.attributes # #<Hash>\n
\n\nitem.attributes = { name: 'John' } # Merges attributes in. Doesn't save.\nitem.assign_attributes name: 'John' # Same as above\n
\n\nSee: AttributeAssignment
\n\nitem.changed?\nitem.changed # ['name']\nitem.changed_attributes # { 'name' => 'Bob' } - original values\nitem.changes # { 'name' => ['Bob', 'Robert'] }\nitem.previous_changes # available after #save\nitem.restore_attributes\n
\n\nitem.name = 'Robert'\nitem.name_was # 'Bob'\nitem.name_change # [ 'Bob', 'Robert' ]\nitem.name_changed? # true\nitem.name_changed?(from: 'Bob', to: 'Robert')\n
\n\nSee: Dirty
\n\nitem.valid?\nitem.invalid?\n
\n\nSee: Validations
\n\nPerson.count\nPerson.count(:age) # counts non-nil's\n
\n\nPerson.average(:age)\nPerson.maximum(:age)\nPerson.minimum(:age)\nPerson.sum('2 * age')\n
\n\nPerson.calculate(:count, :all)\n
\n\nAdvanced:
\n\nPerson.distinct.count\nPerson.group(:city).count\n
\n\nSee: Calculations
\n\nGiven a field called name
:
# Returns one record\nPerson.find_by_name(name)\nPerson.find_last_by_name(name)\nPerson.find_or_create_by_name(name)\nPerson.find_or_initialize_by_name(name)\n
\n\n# Returns a list of records\nPerson.find_all_by_name(name)\n
\n\n# Add a bang to make it raise an exception\nPerson.find_by_name!(name)\n
\n\n# You may use `scoped` instead of `find`\nPerson.scoped_by_user_name\n
\n\nbelongs_to
has_one
has_many
has_many :through
has_one :through
has_and_belongs_to_many
belongs_to :parent, :foreign_key => 'parent_id' class_name: 'Folder'\nhas_many :folders, :foreign_key => 'parent_id', class_name: 'Folder'\n\nhas_many :comments, -> { order('posted_on DESC') }\nhas_many :comments, :include => :author\nhas_many :people, :class_name => \"Person\"\nhas_many :people, :conditions => \"deleted = 0\"\nhas_many :tracks, -> { order(:position) }\nhas_many :comments, :dependent => :nullify\nhas_many :comments, :dependent => :destroy\nhas_many :tags, :as => :taggable\nhas_many :reports, :readonly => true\nhas_many :subscribers, :through => :subscriptions, class_name: \"User\", :source => :user\nhas_many :subscribers, :finder_sql =>\n 'SELECT DISTINCT people.* ' +\n 'FROM people p, post_subscriptions ps ' +\n 'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +\n 'ORDER BY p.first_name'\n
\n\nbelongs_to :author,\n :dependent => :destroy # or :delete\n\n :class_name => \"Person\"\n :select => \"*\"\n :counter_cache => true\n :counter_cache => :custom_counter\n :include => \"Book\"\n :readonly => true\n\n :conditions => 'published = true'\n\n :touch => true\n :touch => :authors_last_updated_at\n\n :primary_key => \"name\"\n :foreign_key => \"author_name\"\n
\n\nIf you have a join model:
\n\nclass Programmer < ActiveRecord::Base\n has_many :assignments\n has_many :projects, :through => :assignments\nend\n
\n\nclass Project < ActiveRecord::Base\n has_many :assignments\n has_many :programmers, :through => :assignments\nend\n
\n\nclass Assignment\n belongs_to :project\n belongs_to :programmer\nend\n
\n\nhas_and_belongs_to_many :projects\nhas_and_belongs_to_many :projects, :include => [ :milestones, :manager ]\nhas_and_belongs_to_many :nations, :class_name => \"Country\"\nhas_and_belongs_to_many :categories, :join_table => \"prods_cats\"\nhas_and_belongs_to_many :categories, :readonly => true\nhas_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>\n\"DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}\"\n
\n\nclass Post\n has_many :attachments, as: :parent\nend\n
\n\nclass Image\n belongs_to :parent, polymorphic: true\nend\n
\n\nAnd in migrations:
\n\ncreate_table :images do |t|\n t.references :post, polymorphic: true\nend\n
\n\nclass Person < ActiveRecord::Base\n
\n\n # Presence\n validates :name, presence: true\n
\n\n # Acceptance\n validates :terms, acceptance: true\n
\n\n # Confirm\n validates :email, confirmation: true\n
\n\n # Unique\n validates :slug, uniqueness: true\n validates :slug, uniqueness: { case_sensitive: false }\n validates :holiday, uniqueness: { scope: :year, message: 'yearly only' }\n
\n\n # Format\n validates :code, format: /regex/\n validates :code, format: { with: /regex/ }\n
\n\n # Length\n validates :name, length: { minimum: 2 }\n validates :bio, length: { maximum: 500 }\n validates :password, length: { in: => 6..20 }\n validates :number, length: { is: => 6 }\n
\n\n # Include/exclude\n validates :gender, inclusion: %w(male female)\n validates :gender, inclusion: { in: %w(male female) }\n validates :lol, exclusion: %w(xyz)\n
\n\n # Numeric\n validates :points, numericality: true\n validates :played, numericality: { only_integer: true }\n # ... greater_than, greater_than_or_equal_to,\n # ... less_than, less_than_or_equal_to\n # ... odd, even, equal_to\n
\n\n # Validate the associated records to ensure they're valid as well\n has_many :books\n validates_associated :books\n
\n\n # Length (full options)\n validates :content, length: {\n minimum: 300,\n maximum: 400,\n tokenizer: lambda { |str| str.scan(/\\w+/) },\n too_short: \"must have at least %{count} words\",\n too_long: \"must have at most %{count} words\" }\n
\n\n # Multiple\n validates :login, :email, presence: true\n
\n\n # Conditional\n validates :description, presence: true, if: :published?\n validates :description, presence: true, if: lambda { |obj| .. }\n
\n\n validates :title, presence: true, on: :save # :save | :create | :update\n
\n\nend\n
\n\nclass Person < ActiveRecord::Base\n validate :foo_cant_be_nil\n\n def foo_cant_be_nil\n errors.add(:foo, 'cant be nil') if foo.nil?\n end\nend\n
\n\nrecord.errors.valid? # → false\nrecord.errors # → { :name => [\"can't be blank\"] }\nrecord.errors.messages # → { :name => [\"can't be blank\"] }\n
\n\nrecord.errors[:name].any?\n
\n\n# Updates person id 15\nPerson.update 15, name: \"John\", age: 24\nPerson.update [1,2], [{name: \"John\"}, {name: \"foo\"}]\n
\n\n# Basic joins\nStudent.joins(:schools).where(schools: { type: 'public' })\nStudent.joins(:schools).where('schools.type' => 'public' )\n
\n\n# Multiple associations\nArticle.joins(:category, :comments)\n
\n\n# Nested associations\nArticle.joins(comments: :guest)\n
\n\n# SQL\nAuthor.joins(\n 'INNER JOIN posts ' +\n 'ON posts.author_id = authors.id ' +\n 'AND posts.published = \"t\"'\n)\n
\n\nwhere('name = ?', 'John')\nwhere(['name = :name', { name: 'John' }])\n
\n\nclass User < ActiveRecord::Base\n serialize :preferences\nend\n
\n\nuser = User.create(\n preferences: {\n 'background' => 'black',\n 'display' => 'large'\n }\n)\n
\n\nYou can also specify a class option as the second parameter that’ll raise an \nexception if a serialized object is retrieved as a descendant of a class not in \nthe hierarchy.
\n\n# Only Hash allowed!\nclass User < ActiveRecord::Base\n serialize :preferences, Hash\nend\n
\n\n# Reading it raises SerializationTypeMismatch\nuser = User.create(preferences: %w(one two three))\nUser.find(user.id).preferences\n
\n\nclass Song < ActiveRecord::Base\n # Uses an integer of seconds to hold the length of the song\n\n def length=(minutes)\n write_attribute(:length, minutes.to_i * 60)\n end\n\n def length\n read_attribute(:length) / 60\n end\nend\n
\n\nSee: http://api.rubyonrails.org/classes/ActiveRecord/Base.html
\n\nGenerate a Rails Engine plugin:
\n\nrails plugin new myplugin --skip-bundle --full\n
\n\nSubclass Railtie and provide an initializer
method.
module NewPlugin\n class Railtie < Rails::Railtie\n initializer \"newplugin.initialize\" do |app|\n \n # subscribe to all rails notifications: controllers, AR, etc.\n ActiveSupport::Notifications.subscribe do |*args|\n event = ActiveSupport::Notifications::Event.new(*args)\n puts \"Got notification: #{event.inspect}\"\n end\n \n end\n end\nend\n
\n\nTo create custom routes.rb
keywords:
# # routes.rb:\n# myplugin_for x\n#\nclass ActionDispatch::Routing\n class Mapper\n def myplugin_for(*x)\n end\n end\nend\n
\n\nExample with a block:
\n\n# authenticated do\n# resources :users\n# end\n#\ndef authenticated\n constraint = lambda { |request| request... }\n\n constraints(constraint) { yield }\nend\n
\n\n# rails g initializer\n# lib/generators/initializer_generator.rb\nclass InitializerGenerator < Rails::Generators::Base\n def create_initializer_file\n create_file \"config/initializers/initializer.rb\", \"# Add initialization content here\"\n end\nend\n
\n\nRails::Generators::Base
.$ rails generate generator initializer\n
\n\nUse NamedBase
instead if you want to take an argument. It will be available as \nfile_name
.
class InitializerGenerator < Rails::Generators::Base\n def lol\n puts file_name\n end\nend\n
\n\nclass InitializerGenerator < Rails::Generators::NamedBase\n # \n source_root File.expand_path(\"../templates\", __FILE__)\n desc \"Description goes here.\"\nend\n
\n\nWhen invoking rails g XXX
:
[rails/]generators/XXX/XXX_generator.rb\n[rails/]generators/XXX_generator.rb\n
\n\nWhen invoking rails g XXX:YYY
:
[rails/]generators/XXX/YYY_generator.rb\n
\n\n# yaffle/lib/yaffle/acts_as_yaffle.rb\nmodule Yaffle\n module ActsAsYaffle\n extend ActiveSupport::Concern\n \n included do\n end\n \n module ClassMethods\n def acts_as_yaffle(options = {})\n # your code will go here\n end\n end\n end\nend\n \nActiveRecord::Base.send :include, Yaffle::ActsAsYaffle\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rails-routes",
"title": "Routes",
"url": "/rails-routes",
"category": "Rails",
"keywords": null,
"content_html": "resources
)resources :photos\n\n# PhotosController:\n# index => GET /photos\n# new => GET /photos/new\n# create => POST /photos/new\n# show => GET /photos/:id\n# edit => GET /photos/:id/edit\n# update => PUT /photos/:id\n# delete => DELETE /photos/:id\n#\n# Helpers:\n# new_photo_path\n# photo_path(id)\n# edit_photo_path(id)\n
\n\nresources :photos do\n member { get 'preview' } # /photo/1/preview\n collection { get 'search' } # /photos/search\n\n get 'preview', on: :member # (..same as the first)\nend\n
\n\nresources :photos,\n path_names: { new: 'brand_new' } # /photos/1/brand_new\n path: 'postings' # /postings\n only: :index\n only: [:index, :show]\n except: :show\n except: [:index, :show]\n\n shallow: true # also generate shallow routes\n shalow_path: 'secret'\n shallow_prefix: 'secret'\n
\n\nresource
)resource :coder\n\n# CodersController:\n# new => GET /coder/new\n# create => POST /coder/new\n# show => GET /coder\n# edit => GET /coder/edit\n# update => PUT /coder\n# delete => DELETE /coder\n
\n\nmatch
)match 'photo/:id' => 'photos#show' # /photo/what-is-it\nmatch 'photo/:id', id: /[0-9]+/ # /photo/0192\nmatch 'photo/:id' => 'photos#show', constraints: { id: /[0-9]+/ }\nmatch 'photo/:id', via: :get\nmatch 'photo/:id', via: [:get, :post]\n\nmatch 'photo/*path' => 'photos#unknown' # /photo/what/ever\n\n# params[:format] == 'jpg'\nmatch 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' }\n
\n\nget
is the same as match via: :get
.
get 'photo/:id' => 'photos#show'\n# same as match 'photo/:id' => 'photos#show', via: :get\n\npost 'photo/:id' => 'photos#update'\n# same as match 'photo/:id' => 'photos#show', via: :post\n
\n\nmatch '/stories' => redirect('/posts')\nmatch '/stories/:name' => redirect('/posts/%{name}')\n
\n\n# logout_path\nmatch 'exit' => 'sessions#destroy', as: :logout\n
\n\nmatch '/', constraints: { subdomain: 'admin' }\n\n# admin.site.com/admin/photos\nnamespace 'admin' do\n constraints subdomain: 'admin' do\n resources :photos\n end\nend\n
\n\nclass BlacklistConstraint\n def initialize\n @ips = Blacklist.retrieve_ips\n end\n \n def matches?(request)\n @ips.include?(request.remote_ip)\n end\nend\n \nTwitterClone::Application.routes.draw do\n match \"*path\" => \"blacklist#index\",\n :constraints => BlacklistConstraint.new\nend\n
\n\nscope 'admin', constraints: { subdomain: 'admin' } do\n resources ...\nend\n
\n\n# Yes, Sprockets is middleware\nmatch '/application.js' => Sprockets\n
\n\nprojects_path # /projects\nprojects_url # http://site.com/projects\n
\n\n# The priority is based upon order of creation:\n# first created -> highest priority.\n\n# Sample of regular route:\nmatch 'products/:id' => 'catalog#view'\n\n# Keep in mind you can assign values other than :controller and :action\n\n# Sample of named route:\nmatch 'products/:id/purchase' => 'catalog#purchase', :as => :purchase\n\n# This route can be invoked with purchase_url(:id => product.id)\n\n# Sample resource route (maps HTTP verbs to controller actions automatically):\nresources :products\n\n# Sample resource route with options:\nresources :products do\n member do\n get 'short'\n post 'toggle'\n end\n\n collection do\n get 'sold'\n end\nend\n\n# Sample resource route with sub-resources:\nresources :products do\n resources :comments, :sales\n resource :seller\nend\n\n# Sample resource route with more complex sub-resources\nresources :products do\n resources :comments\n resources :sales do\n get 'recent', :on => :collection\n end\nend\n\n# Sample resource route within a namespace:\nnamespace :admin do\n # Directs /admin/products/* to Admin::ProductsController\n # (app/controllers/admin/products_controller.rb)\n resources :products\nend\n\n# You can have the root of your site routed with \"root\"\n# just remember to delete public/index.html.\nroot :to => 'welcome#index'\n\n# See how all your routes lay out with \"rake routes\"\n\n# This is a legacy wild controller route that's not recommended for RESTful applications.\n# Note: This route will make all actions in every controller accessible via GET requests.\nmatch ':controller(/:action(/:id(.:format)))'\n
\n\nActionDispatch::Routing::Mapper\n (See included modules)
\nin config/environments/development.rb:
\n\n# Source maps for Sass\nconfig.sass.debug_info = true\nconfig.sass.line_comments = false\n\n# Don't break apart\nconfig.assets.debug = false\n
\n\nPartial locals
\n\n<%= render 'article', full: true %>\n<%= render 'article' %>\n\n<% if local_assigns[:full] %>\n ...\n<% end %>\n
\n\nHTML in i18n
\n\nen:\n read_more_html: \"read <b>more</b>...\"\n
\n\nException handling:
\n\n# config/application.rb\nconfig.exceptions_app = self.routes\n\nget '/404', to: 'errors#not_found'\nget '/500', to: 'errors#server_error'\n\nclass ErrorsController\n def not_found\n render status: :not_found\n end\n end\n
\n\nRails updating:
\n\nrake rails:update\n
\n\nDistinct pluck:
\n\nArticle.distinct.pluck('author')\n
\n\nRelation#merge
\n\nscope :with_drafts, -> {\n uniq.joins(:articles).merge(Article.draft)\n}\n
\n\nOrder
\n\nscope :recent, -> { order created_at: :desc }\n
\n\nGroup by month
\n\n.group(\"to_char(created_at, 'YYYY-MM')\")\n.group(\"to_char(created_at, 'YYYY-MM')\").count\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rails",
"title": "Rails",
"url": "/rails",
"category": "Rails",
"keywords": null,
"content_html": "class ApplicationController\n helper_method :logged_in?\n\n def logged_in?\n \"Something\"\n end\nend\n
\n\nstylesheet_link_tag :monkey\njavascript_link_tag :monkey\n
\n\n# http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html\n\n- form_for @person do |f|\n = f.label :first_name\n = f.label :first_name, \"First name\"\n = f.text_field :first_name\n\n = f.label :last_name>\n = f.text_field :last_name>\n\n - fields_for @person.permission do |fields|\n = fields.checkbox :admin\n\n -# name=\"person[admin]\"\n - fields_for :person, @client do |fields|\n = fields.checkbox :admin\n\n = f.submit\n\n# Also: check_box, email_field, fields_for\n# file_field, hidden_field, label, number_field, password_field\n# radio_button, range_field, search_field, telephonen_field,\n# text_area, text_field, url_field\n
\n\nhttp://apidock.com/rails/ActionController/Base
\n\nclass ProjectsController\n layout 'project' # Actually defaults to `projects` based\n # on the controller name\n\n def save\n end\n\n def edit\n end\nend\n
\n\nclass ApplicationController < ActionController::Base\n before_filter :validate, only: [:save, :edit]\n before_filter :ensure_auth, except: [:logout]\n\n before_filter :require_login\n \n private\n \n def require_login\n unless logged_in?\n flash[:error] = \"You must be logged in to access this section\"\n redirect_to new_login_url # halts request cycle\n end\n end\nend\n
\n\nclass ApplicationController < ActionController::Base\n # The options parameter is the hash passed in to 'url_for'\n def default_url_options(options)\n {:locale => I18n.locale}\n end\nend\n
\n\nsession[:what]\nflash[:notice] = \"Your session expired\"\nparams[:id]\n
\n\nclass UsersController < ApplicationController\n def index\n @users = User.all\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @users}\n format.json { render :json => @users}\n end\n end\nend\n
\n\nredirect_to action: 'show', id: @entry.id\nredirect_to root_url # a path\n
\n\nrender nothing: true\nrender template: 'products/show'\nrender status: 500\nrender status: :forbidden\nrender text: '...'\nrender layout: 'special_layout'\nrender layout: false\nrender action: 'something' # same as `file: 'my/something'`\n # Renders the template only, does not execute\n # the action\n\nrender json: object\nrender xml: object\n\nrender location: photo_url(photo)\n
\n\nhead :bad_request\nhead :created, location: photo_path(@photo)\n
\n\n# app/views/layouts/application.html.erb\n<%= content_for?(:content) ? yield :content : yield %>\n\n# app/views/layouts/news.html.erb\n<% content_for :content do %>\n ...\n<% end %>\n<% render template: :'layouts/application' %>\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rake",
"title": "Rake",
"url": "/rake",
"category": "Ruby",
"keywords": null,
"content_html": "namespace :foo do\n desc \"Description\"\n task :bar do\n ...\n end\n\n task :baz => :dependency do\n end\n\n task :baz => [:dep1, :dep2, :dep3] do\n end\nend\n\n# rake foo:bar\n
\n\ndesc \"Do something\"\ntask :workit, [:id] => :environment do |_, args|\n id = args[:id]\nend\n\n# rake workit[234]\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rbenv",
"title": "rbenv",
"url": "/rbenv",
"category": "Ruby",
"keywords": null,
"content_html": "git clone https://github.com/sstephenson/rbenv.git ~/.rbenv\ngit clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build\n
\n\necho 'export PATH=\"$HOME/.rbenv/bin:$PATH\"' >> ~/.bash_profile\necho 'eval \"$(rbenv init -)\"' >> ~/.bash_profile\n
\n\ntype rbenv # → \"rbenv is a function\"\n
\n\nThese are generic instructions; there may be rbenv packages available for your OS.
\n\nSee: Installation
\n\nCommand | \nDescription | \n
---|---|
rbenv install -l | \n List all available versions | \n
rbenv install 2.2.1 | \n Install Ruby 2.2.1 | \n
rbenv uninstall 2.2.1 | \n Uninstall Ruby 2.2.1 | \n
rbenv versions | \n See installed versions | \n
rbenv version | \n See current version | \n
rbenv which <NAME> | \n Display path to executable | \n
rbenv rehash | \n Re-write binstubs | \n
Command | \nDescription | \n
---|---|
rbenv local 2.2.2 | \n Use Ruby 2.2.2 in project | \n
rbenv local --unset | \n Undo above | \n
Application-specific version numbers are stored in .ruby-version
.
Command | \nDescription | \n
---|---|
rbenv global 2.2.2 | \n Use Ruby 2.2.2 globally | \n
rbenv global --unset | \n Undo above | \n
Global version numbers are stored in ~/.rbenv/version
.
Command | \nDescription | \n
---|---|
rbenv shell 2.2.2 | \n Use Ruby 2.2.2 in shell | \n
rbenv shell --unset | \n Undo above | \n
Shell-local version numbers are stored as environment variables.
\n\nrbenv lets you manage installations of multiple Ruby versions.
", "description_html": "A one-page guide to rbenv Ruby version manager, with usage examples and more.
", "tags": null, "updated": "2018-02-20" },{ "id": "rdoc", "title": "Rdoc", "url": "/rdoc", "category": "Markup", "keywords": null, "content_html": "# Foo.\n#\n# @example\n#\n# y\n# g\n#\n# @param [String] param_name The xx and xx.\n#\n# @see http://url.com\n#\n# @return [true] if so\n
\n\n*bold*\n_emphasized_\n+code+\n
\n\nhttp://www.link.com\nSee Models::User@Examples\n{Google}[http://google.com]\n
\n\ndef input # :nodoc:\n
\n\nmodule MyModule # :nodoc: all\n
\n\n# == Definition lists\n#\n# list:: hi.\n# +foo+:: parameterized\n
\n\n# == Definition lists\n# [foo] also\n# [bar] like this\n
\n\n# @return [String]\n# @return [String, nil] the name\n
\n\n# :call-seq:\n# ARGF.readlines(sep=$/) -> array\n# ARGF.readlines(limit) -> array\n# ARGF.readlines(sep, limit) -> array\n#\n# ARGF.to_a(sep=$/) -> array\n# ARGF.to_a(limit) -> array\n# ARGF.to_a(sep, limit) -> array\n
\n\n# :category: Utilities\n
\n\n# :section: Expiry methods\n# methods relating to expiring\n\ndef expire!\ndef expired?\n...\n
\n\n# :markup: TomDoc\n
\n\nPlace this at the beginning of the file.
\n\nimport { default as Router, Route } from 'react-router'\n\nconst routes = (\n <Route>\n <Route path='*' handler={RootView} />\n </Route>\n)\n\nRouter.run(routes, Router.HashLocation, (Root) => {\n React.render(<Root />, document.getElementById('all'))\n})\n
\n\nconst routes = (\n <Route handler={Chrome}>\n <Route path='about' handler={About} />\n <Route path='inbox' handler={Inbox} />\n <Route path='messages/:id' handler={Message} />\n </Route>\n)\n\nimport { RouteHandler } from 'react-router'\n\nconst Chrome = React.createClass({\n render () {\n return (\n <div>\n <h1>App</h1>\n <RouteHandler />\n </div>\n )\n }\n})\n
\n\nvar Message = React.createClass({\n componentDidMount: function () {\n // from the path `/inbox/messages/:id`\n var id = this.props.params.id\n ...\n
\n\nimport { Link } from 'react-router'\n\n<!-- make a named route `user` -->\n<Link to='user' params={{userId: 10}} />\n\n<Link to='login'\n activeClassName='-active'\n onClick='...'>\n\n
\n\n<Route path='/'>\n <DefaultRoute handler={Home} />\n <NotFoundRoute handler={NotFound} />\n \n <Redirect from='login' to='sessions/new' />\n <Redirect from='login' to='sessions/new' params={{from: 'home'}} />\n <Redirect from='profile/:id' to='about-user' />\n\n <Route name='about-user' ... />\n
\n\nvar router = Router.create({\n routes: <Route>...</Route>,\n location: Router.HistoryLocation\n})\n\nrouter.run((Root) => { ... })\n
\n\nimport { Navigation } from 'react-router'\n\nReact.createClass({\n mixins: [ Navigation ], ...\n})\n\nthis\n .transitionTo('user', {id: 10})\n .transitionTo('/path')\n .transitionTo('http://...')\n .replaceWith('about')\n .makePath('about') // return URL\n .makeHref('about') // return URL\n .goBack()\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "react",
"title": "React.js",
"url": "/react",
"category": "React",
"keywords": ["React.Component","render()","componentDidMount()","props/state","dangerouslySetInnerHTML"],
"content_html": "import React from 'react'\nimport ReactDOM from 'react-dom'\n
\n\nclass Hello extends React.Component {\n render () {\n return <div className='message-box'>\n Hello {this.props.name}\n </div>\n }\n}\n
\n\nconst el = document.body\nReactDOM.render(<Hello name='John' />, el)\n
\n\nUse the React.js jsfiddle to start hacking. (or the unofficial jsbin)
\n\nimport React, {Component} from 'react'\nimport ReactDOM from 'react-dom'\n
\n\nclass Hello extends Component {\n ...\n}\n
\n\n<Video fullscreen={true} autoplay={false} />\n
\n\nrender () {\n this.props.fullscreen\n const { fullscreen, autoplay } = this.props\n ···\n}\n
\n\nUse this.props
to access properties passed to the component.
See: Properties
\n\nconstructor(props) {\n super(props)\n this.state = { username: undefined }\n}\n
\n\nthis.setState({ username: 'rstacruz' })\n
\n\nrender () {\n this.state.username\n const { username } = this.state\n ···\n}\n
\n\nUse states (this.state
) to manage dynamic data.
With Babel you can use proposal-class-fields and get rid of constructor
\n\nclass Hello extends Component {\n state = { username: undefined };\n ...\n}\n
\n\nSee: States
\n\nclass Info extends Component {\n render () {\n const { avatar, username } = this.props\n\n return <div>\n <UserAvatar src={avatar} />\n <UserProfile username={username} />\n </div>\n }\n}\n
\nAs of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM.
\n\nimport React, {\n Component,\n Fragment\n} from 'react'\n\nclass Info extends Component {\n render () {\n const { avatar, username } = this.props\n\n return (\n <Fragment>\n <UserAvatar src={avatar} />\n <UserProfile username={username} />\n </Fragment>\n )\n }\n}\n
\n\nNest components to separate concerns.
\n\nSee: Composing Components
\n\n<AlertBox>\n <h1>You have pending notifications</h1>\n</AlertBox>\n
\n\nclass AlertBox extends Component {\n render () {\n return <div className='alert-box'>\n {this.props.children}\n </div>\n }\n}\n
\n\nChildren are passed as the children
property.
Hello.defaultProps = {\n color: 'blue'\n}\n
\n\nSee: defaultProps
\n\nclass Hello extends Component {\n constructor (props) {\n super(props)\n this.state = { visible: true }\n }\n}\n
\n\nSet the default state in the constructor()
.
And without constructor using Babel with proposal-class-fields.
\n\nclass Hello extends Component {\n state = { visible: true }\n}\n
\n\nSee: Setting the default state
\n\nfunction MyComponent ({ name }) {\n return <div className='message-box'>\n Hello {name}\n </div>\n}\n
\n\nFunctional components have no state. Also, their props
are passed as the first parameter to a function.
See: Function and Class Components
\n\nimport React, {PureComponent} from 'react'\n\nclass MessageBox extends PureComponent {\n ···\n}\n
\n\nPerformance-optimized version of React.Component
. Doesn’t rerender if props/state hasn’t changed.
See: Pure components
\n\nthis.forceUpdate()\n
\n\nthis.setState({ ... })\nthis.setState(state => { ... })\n
\n\nthis.state\nthis.props\n
\n\nThese methods and properties are available for Component
instances.
See: Component API
\n\nMethod | \nDescription | \n
---|---|
constructor (props) | \n Before rendering # | \n
componentWillMount() | \n Don’t use this # | \n
render() | \n Render # | \n
componentDidMount() | \n After rendering (DOM available) # | \n
componentWillUnmount() | \n Before DOM removal # | \n
componentDidCatch() | \n Catch errors (16+) # | \n
Set initial the state on constructor()
.\nAdd DOM event handlers, timers (etc) on componentDidMount()
, then remove them on componentWillUnmount()
.
Method | \nDescription | \n
---|---|
componentDidUpdate (prevProps, prevState, snapshot) | \n Use setState() here, but remember to compare props | \n
shouldComponentUpdate (newProps, newState) | \n Skips render() if returns false | \n
render() | \n Render | \n
componentDidUpdate (prevProps, prevState) | \n Operate on the DOM here | \n
Called when parents change properties and .setState()
. These are not called for initial renders.
See: Component specs
\n\nimport React, { useState } from 'react';\n\nfunction Example() {\n // Declare a new state variable, which we'll call \"count\"\n const [count, setCount] = useState(0);\n\n return (\n <div>\n <p>You clicked {count} times</p>\n <button onClick={() => setCount(count + 1)}>\n Click me\n </button>\n </div>\n );\n}\n
\n\nHooks are a new addition in React 16.8.
\n\nSee: Hooks at a Glance
\n\nfunction ExampleWithManyStates() {\n // Declare multiple state variables!\n const [age, setAge] = useState(42);\n const [fruit, setFruit] = useState('banana');\n const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);\n // ...\n}\n
\n\nimport React, { useState, useEffect } from 'react';\n\nfunction Example() {\n const [count, setCount] = useState(0);\n\n // Similar to componentDidMount and componentDidUpdate:\n useEffect(() => {\n // Update the document title using the browser API\n document.title = `You clicked ${count} times`;\n }, [count]);\n\n return (\n <div>\n <p>You clicked {count} times</p>\n <button onClick={() => setCount(count + 1)}>\n Click me\n </button>\n </div>\n );\n}\n
\n\nIf you’re familiar with React class lifecycle methods, you can think of useEffect
Hook as componentDidMount
, componentDidUpdate
, and componentWillUnmount
combined.
By default, React runs the effects after every render — including the first render.
\n\nimport React, { useState, useEffect } from 'react';\n\nfunction FriendStatus(props) {\n const [isOnline, setIsOnline] = useState(null);\n\n useEffect(() => {\n function handleStatusChange(status) {\n setIsOnline(status.isOnline);\n }\n\n ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);\n return () => {\n ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);\n };\n }, [props.friend.id]);\n\n if (isOnline === null) {\n return 'Loading...';\n }\n return isOnline ? 'Online' : 'Offline';\n}\n
\n\nEffects may also optionally specify how to “clean up” after them by returning a function.
\n\nfunction FriendStatus(props) {\n const isOnline = useFriendStatus(props.friend.id);\n\n if (isOnline === null) {\n return 'Loading...';\n }\n return isOnline ? 'Online' : 'Offline';\n}\n
\n\n\n\nAlso see: Hooks FAQ
\n\nHook | \nDescription | \n
---|---|
useState (initialState) | \n \n |
useEffect (() => { … }) | \n \n |
useContext (MyContext) | \n value returned from React.createContext | \n
Full details: Basic Hooks
\n\nHook | \nDescription | \n
---|---|
useReducer (reducer, initialArg, init) | \n \n |
useCallback (() => { … }) | \n \n |
useMemo (() => { … }) | \n \n |
useRef (initialValue) | \n \n |
useImperativeHandle (ref, () => { … }) | \n \n |
useLayoutEffect | \n identical to useEffect , but it fires synchronously after all DOM mutations | \n
useDebugValue (value) | \n display a label for custom hooks in React DevTools | \n
Full details: Additional Hooks
\n\nclass MyComponent extends Component {\n render () {\n return <div>\n <input ref={el => this.input = el} />\n </div>\n }\n\n componentDidMount () {\n this.input.focus()\n }\n}\n
\n\nAllows access to DOM nodes.
\n\nSee: Refs and the DOM
\n\nclass MyComponent extends Component {\n render () {\n <input type=\"text\"\n value={this.state.value}\n onChange={event => this.onChange(event)} />\n }\n\n onChange (event) {\n this.setState({ value: event.target.value })\n }\n}\n
\n\nPass functions to attributes like onChange
.
See: Events
\n\n<VideoPlayer src=\"video.mp4\" />\n
\n\nclass VideoPlayer extends Component {\n render () {\n return <VideoEmbed {...this.props} />\n }\n}\n
\n\nPropagates src=\"...\"
down to the sub-component.
React.createClass({ ... })\nReact.isValidElement(c)\n
\n\nReactDOM.render(<Component />, domnode, [callback])\nReactDOM.unmountComponentAtNode(domnode)\n
\n\nReactDOMServer.renderToString(<Component />)\nReactDOMServer.renderToStaticMarkup(<Component />)\n
\n\nThere are more, but these are most common.
\n\nSee: React top-level API
\n\nconst style = { height: 10 }\nreturn <div style={style}></div>\n
\n\nreturn <div style={{ margin: 0, padding: 0 }}></div>\n
\n\nSee: Inline styles
\n\nfunction markdownify() { return \"<p>...</p>\"; }\n<div dangerouslySetInnerHTML={{__html: markdownify()}} />\n
\n\nSee: Dangerously set innerHTML
\n\nclass TodoList extends Component {\n render () {\n const { items } = this.props\n\n return <ul>\n {items.map(item =>\n <TodoItem item={item} key={item.key} />)}\n </ul>\n }\n}\n
\n\nAlways supply a key
property.
<Fragment>\n {showMyComponent\n ? <MyComponent />\n : <OtherComponent />}\n</Fragment>\n
\n\n<Fragment>\n {showPopup && <Popup />}\n ...\n</Fragment>\n
\n\nYou can return multiple elements as arrays or fragments.
\n\nrender () {\n // Don't forget the keys!\n return [\n <li key=\"A\">First item</li>,\n <li key=\"B\">Second item</li>\n ]\n}\n
\n\nrender () {\n // Fragments don't require keys!\n return (\n <Fragment>\n <li>First item</li>\n <li>Second item</li>\n </Fragment>\n )\n}\n
\n\n\n\nrender() {\n return 'Look ma, no spans!';\n}\n
\n\nYou can return just a string.
\n\n\n\nclass MyComponent extends Component {\n ···\n componentDidCatch (error, info) {\n this.setState({ error })\n }\n}\n
\n\nCatch errors via componentDidCatch
. (React 16+)
See: Error handling in React 16
\n\nrender () {\n return React.createPortal(\n this.props.children,\n document.getElementById('menu')\n )\n}\n
\n\nThis renders this.props.children
into any location in the DOM.
See: Portals
\n\nconst el = document.getElementById('app')\nReactDOM.hydrate(<App />, el)\n
\n\nUse ReactDOM.hydrate
instead of using ReactDOM.render
if you’re rendering over the output of ReactDOMServer.
See: Hydrate
\n\nimport PropTypes from 'prop-types'\n
\n\nSee: Typechecking with PropTypes
\n\nKey | \nDescription | \n
---|---|
any | \n Anything | \n
Key | \nDescription | \n
---|---|
string | \n \n |
number | \n \n |
func | \n Function | \n
bool | \n True or false | \n
Key | \nDescription | \n
---|---|
oneOf (any) | \n Enum types | \n
oneOfType (type array) | \n Union | \n
Key | \nDescription | \n
---|---|
array | \n \n |
arrayOf (…) | \n \n |
Key | \nDescription | \n
---|---|
object | \n \n |
objectOf (…) | \n Object with values of a certain type | \n
instanceOf (…) | \n Instance of a class | \n
shape (…) | \n \n |
Key | \nDescription | \n
---|---|
element | \n React element | \n
node | \n DOM node | \n
Key | \nDescription | \n
---|---|
(···).isRequired | \n Required | \n
MyComponent.propTypes = {\n email: PropTypes.string,\n seats: PropTypes.number,\n callback: PropTypes.func,\n isClosed: PropTypes.bool,\n any: PropTypes.any\n}\n
\n\nMyCo.propTypes = {\n name: PropTypes.string.isRequired\n}\n
\n\nMyCo.propTypes = {\n // React element\n element: PropTypes.element,\n\n // num, string, element, or an array of those\n node: PropTypes.node\n}\n
\n\nMyCo.propTypes = {\n direction: PropTypes.oneOf([\n 'left', 'right'\n ])\n}\n
\n\nMyCo.propTypes = {\n list: PropTypes.array,\n ages: PropTypes.arrayOf(PropTypes.number),\n user: PropTypes.object,\n user: PropTypes.objectOf(PropTypes.number),\n message: PropTypes.instanceOf(Message)\n}\n
\n\nMyCo.propTypes = {\n user: PropTypes.shape({\n name: PropTypes.string,\n age: PropTypes.number\n })\n}\n
\n\nUse .array[Of]
, .object[Of]
, .instanceOf
, .shape
.
MyCo.propTypes = {\n customProp: (props, key, componentName) => {\n if (!/matchme/.test(props[key])) {\n return new Error('Validation failed!')\n }\n }\n}\n
\n\nReact is a JavaScript library for building user interfaces. This guide targets React v15 to v16.
", "description_html": "", "tags": ["Featured"], "updated": "2020-07-05" },{ "id": "react@0.14", "title": "React.js (v0.14)", "url": "/react@0.14", "category": "React", "keywords": null, "content_html": "var Component = React.createClass({\n render: function () {\n return <div>Hello {this.props.name}</div>;\n }\n});\n
\n\nReactDOM.render(<Component name=\"John\" />, document.body);\n
\n\nUse the React.js jsfiddle to start hacking. (or the unofficial jsbin)
\n\nvar UserAvatar = React.createClass({...});\nvar UserProfile = React.createClass({...});\n
\n\nvar Info = React.createClass({\n render() {\n return <div>\n <UserAvatar src={this.props.avatar} />\n <UserProfile username={this.props.username} />\n </div>;\n }\n});\n
\n\nNest components to separate concerns. See multiple components.
\n\n<MyComponent fullscreen={true} />\n
\n\n// props\n this.props.fullscreen //=> true\n\n// state\n this.setState({ username: 'rstacruz' });\n this.replaceState({ ... });\n this.state.username //=> 'rstacruz'\n
\n\nrender: function () {\n return <div className={this.props.fullscreen ? 'full' : ''}>\n Welcome, {this.state.username}\n </div>;\n}\n
\n\nUse props (this.props
) to access parameters passed from the parent.\nUse states (this.state
) to manage dynamic data.
React.createClass({\n getInitialState: function () {\n return { comments: [] };\n },\n\n getDefaultProps: function () {\n return { name: \"Hello\" };\n }\n);\n
\n\nPre-populates this.state.comments
and this.props.name
.
ReactDOM.findDOMNode(c) // 0.14+\nReact.findDOMNode(c) // 0.13\nc.getDOMNode() // 0.12 below\n
\n\nc.forceUpdate()\nc.isMounted()\n\nc.state\nc.props\n\nc.setState({ ... })\nc.replaceState({ ... })\n\nc.setProps({ ... }) // for deprecation\nc.replaceProps({ ... }) // for deprecation\n\nc.refs\n
\n\nThese are methods available for Component
instances. See Component API.
Method | \nWhat | \n
---|---|
render() | \n \n |
getInitialState() | \n \n |
getDefaultProps() | \n \n |
mixins: [ ... ] | \n Mixins … more | \n
propTypes: { ... } | \n Validation … more | \n
statics: { ... } | \n Static methods | \n
displayName: \"...\" | \n Automatically filled by JSX | \n
Methods and properties you can override. See component specs.
\n\ncomponentWillMount() | \n Before rendering (no DOM yet) | \n
componentDidMount() | \n After rendering | \n
Before initial rendering occurs. Add your DOM stuff on didMount (events, timers, etc). See reference.
\n\ncomponentWillReceiveProps (newProps={}) | \n Use setState() here | \n
shouldComponentUpdate (newProps={}, newState={}) | \n Skips render() if returns false | \n
componentWillUpdate (newProps={}, newState={}) | \n Can’t use setState() here | \n
componentDidUpdate (prevProps={}, prevState={}) | \n Operate on the DOM here | \n
Called when parents change properties and .setState()
. These are not called for initial renders. See reference.
componentWillUnmount() | \n Invoked before DOM removal | \n
Clear your DOM stuff here (probably done on didMount). See reference.
\n\nReact.createClass({\n componentDidMount: function () {\n $.get(this.props.url, function (data) {\n this.setState(data);\n }.bind(this));\n },\n\n render: function () {\n return <CommentList data={this.state.data} />\n }\n});\n
\n\nSee initial AJAX data.
\n\n<input ref=\"myInput\">\n
\n\nthis.refs.myInput\nReactDOM.findDOMNode(this.refs.myInput).focus()\nReactDOM.findDOMNode(this.refs.myInput).value\n
\n\nAdd attributes like onChange
. See events.
<input type=\"text\"\n value={this.state.value}\n onChange={this.handleChange} />\n
\n\nhandleChange: function(event) {\n this.setState({ value: event.target.value });\n}\n
\n\nAllows access to DOM nodes. See References.
\n\nEmail: <input type=\"text\" valueLink={this.linkState('email')} />\n
\n\nReact.createClass({\n mixins: [React.addons.LinkedStateMixin]\n});\n
\n\nthis.state.email\n
\n\nUse LinkedStateMixin for easier two-way binding.
\n\nReact.createClass({\n propTypes: {\n email: React.PropTypes.string,\n seats: React.PropTypes.number,\n settings: React.PropTypes.object,\n callback: React.PropTypes.func,\n isClosed: React.PropTypes.bool,\n any: React.PropTypes.any,\n }\n});\n
\nPrimitive types: .string
, .number
, .func
, and .bool
. See propTypes.
propTypes: {\n requiredFunc: React.PropTypes.func.isRequired,\n requiredAny: React.PropTypes.any.isRequired,\n
\n\nAdd .isRequired
.
propTypes: {\n element: React.PropTypes.element, // react element\n node: React.PropTypes.node, // num, string, element\n // ...or array of those\n
\n\nUse .element
, .node
.
propTypes: {\n enum: React.PropTypes.oneOf(['M','F']), // enum\n union: React.PropTypes.oneOfType([ // any\n React.PropTypes.string,\n React.PropTypes.number ]),\n
\n\nUse .oneOf
, .oneOfType
.
propTypes: {\n array: React.PropTypes.array,\n arrayOf: React.PropTypes.arrayOf(React.PropTypes.number),\n object: React.PropTypes.object,\n objectOf: React.PropTypes.objectOf(React.PropTypes.number),\n\n message: React.PropTypes.instanceOf(Message),\n\n object2: React.PropTypes.shape({\n color: React.PropTypes.string,\n size: React.PropTypes.number\n }),\n
\n\nUse .array[Of]
, .object[Of]
, .instanceOf
, .shape
.
propTypes: {\n customProp: function(props, propName, componentName) {\n if (!/matchme/.test(props[propName])) {\n return new Error('Validation failed!');\n }\n }\n}\n
\n\nSupply your own function.
\n\nvar cx = require('classnames');\n\nrender: function() {\n var classes = cx({\n 'message': true,\n 'message-important': this.props.isImportant,\n 'message-read': this.props.isRead\n });\n\n return <div className={classes}>Great Scott!</div>;\n}\n
\n\nManipulate DOM classes with classnames, previously known as React.addons.classSet
. See Class set.
<VideoPlayer src=\"video.mp4\" />\n
\n\nvar VideoPlayer = React.createClass({\n render: function() {\n /* propagates src=\"...\" down to this sub component */\n return <VideoEmbed {...this.props} controls='false' />;\n }\n});\n
\n\nSee Transferring props.
\n\nvar SetIntervalMixin = {\n componentWillMount: function() { .. }\n}\n
\n\nvar TickTock = React.createClass({\n mixins: [SetIntervalMixin]\n}\n
\n\nSee addons for some built-in mixins.
\n\nReact.createClass({ ... })\n\nReact.isValidElement(c)\n\nReactDOM.findDOMNode(c) // 0.14+\nReactDOM.render(<Component />, domnode, [callback]) // 0.14+\nReactDOM.unmountComponentAtNode(domnode) // 0.14+\n\nReactDOMServer.renderToString(<Component />) // 0.14+\nReactDOMServer.renderToStaticMarkup(<Component />) // 0.14+\n
\n\nvar style = { backgroundImage: 'url(x.jpg)', height: 10 };\nreturn <div style={style}></div>;\n
\n\nSee inline styles.
\n\nfunction markdownify() { return \"<p>...</p>\"; }\n<div dangerouslySetInnerHTML={{__html: markdownify()}} />\n
\n\nSee dangerously set innerHTML.
\n\nvar TodoList = React.createClass({\n render: function() {\n function item(itemText) {\n return <li>{itemText}</li>;\n };\n return <ul>{this.props.items.map(item)}</ul>;\n }\n});\n
\n\nDeprecated: this guide targets an old version of React (v0.14). See the updated React cheatsheet for new versions.
", "description_html": "", "tags": null, "updated": null },{ "id": "redux", "title": "Redux", "url": "/redux", "category": "React", "keywords": null, "content_html": "import { createStore } from 'redux'\n
\n\n// Reducer\nfunction counter (state = { value: 0 }, action) {\n switch (action.type) {\n case 'INCREMENT':\n return { value: state.value + 1 }\n case 'DECREMENT':\n return { value: state.value - 1 }\n default:\n return state\n }\n}\n
\n\nlet store = createStore(counter)\n
\n\n// Optional - you can pass `initialState` as a second arg\nlet store = createStore(counter, { value: 0 })\n
\n\nA store is made from a reducer function, which takes the current state
, and\nreturns a new state
depending on the action
it was given.
let store = createStore(counter)\n
\n\n// Dispatches an action; this changes the state\nstore.dispatch({ type: 'INCREMENT' })\nstore.dispatch({ type: 'DECREMENT' })\n
\n\n// Gets the current state\nstore.getState()\n
\n\n// Listens for changes\nstore.subscribe(() => { ... })\n
\n\nDispatch actions to change the store’s state.
\n\nimport { Provider } from 'react-redux'\n
\n\nReact.render(\n <Provider store={store}>\n <App />\n </Provider>, mountNode)\n
\n\nThe <Provider>
component makes the store available in your React components. You need this so you can use connect()
.
import { connect } from 'react-redux'\n
\n\n// A functional React component\nfunction App ({ message, onMessageClick }) {\n return (\n <div onClick={() => onMessageClick('hello')}>\n {message}\n </div>\n )\n}\n
\n\n// Maps `state` to `props`:\n// These will be added as props to the component.\nfunction mapState (state) {\n return { message: state.message }\n}\n\n// Maps `dispatch` to `props`:\nfunction mapDispatch (dispatch) {\n return {\n onMessageClick (message) {\n dispatch({ type: 'click', message })\n }\n }\n}\n\n// Connect them:\nexport default connect(mapState, mapDispatch)(App)\n
\n\nexport default connect(\n (state) => ({\n message: state.message\n }),\n (dispatch) => ({\n onMessageClick: (message) => {\n dispatch({ type: 'click', message })\n }\n })\n)(App)\n
\n\nSame as above, but shorter.
\n\nconst reducer = combineReducers({\n counter, user, store\n})\n
\n\nCombines multiple reducers into one reducer function. See: combineReducers (redux.js.org)
\n\n// noop middleware\nconst logger = store => dispatch => action { dispatch(action) }\n
\n\nconst logger = store => {\n // This function runs on createStore().\n // It returns a decorator for dispatch().\n\n return dispatch => {\n // Runs on createStore(), too.\n // It returns a new dispatch() function\n\n return action => {\n // Runs on every dispatch()\n }\n }\n}\n
\n\nMiddlewares are simply decorators for dispatch()
to allow you to take\ndifferent kinds of actions, and to perform different tasks when receiving\nactions.
const enhancer = applyMiddleware(logger, thunk, ...)\n
\n\nconst store = createStore(reducer, {}, enhancer)\n
\n\nPattern | \nDescription | \n
---|---|
. | \n Any character, except newline | \n
\\w | \n Word | \n
\\d | \n Digit | \n
\\s | \n Whitespace | \n
\\W | \n Not word | \n
\\D | \n Not digit | \n
\\S | \n Not whitespace | \n
[abc] | \n Any of a, b, or c | \n
[a-e] | \n Characters between a and e | \n
[1-9] | \n Digit between 1 and 9 | \n
[[:print:]] | \n Any printable character including spaces | \n
[^abc] | \n Any character except a , b or c | \n
Pattern | \nDescription | \n
---|---|
\\G | \n Start of match | \n
^ | \n Start of string | \n
$ | \n End of string | \n
\\A | \n Start of string | \n
\\Z | \n End of string | \n
\\z | \n Absolute end of string | \n
\\b | \n A word boundry | \n
\\B | \n Non-word boundry | \n
^abc | \n Start with abc | \n
abc$ | \n End with abc | \n
Pattern | \nDescription | \n
---|---|
\\. \\* \\\\ | \n Escape special character used by regex | \n
\\t | \n Tab | \n
\\n | \n Newline | \n
\\r | \n Carriage return | \n
Pattern | \nDescription | \n
---|---|
(abc) | \n Capture group | \n
(a|b) | \n Match a or b | \n
(?:abc) | \n Match abc , but don’t capture | \n
Pattern | \nDescription | \n
---|---|
a* | \n Match 0 or more | \n
a+ | \n Match 1 or more | \n
a? | \n Match 0 or 1 | \n
a{5} | \n Match exactly 5 | \n
a{,3} | \n Match up to 3 | \n
a{3,} | \n Match 3 or more | \n
a{1,3} | \n Match between 1 and 3 | \n
Pattern | \nDescription | \n
---|---|
a(?=b) | \n Match a in baby but not in bay | \n
a(?!b) | \n Match a in Stan but not in Stab | \n
(?<=a)b | \n Match b in crabs but not in cribs | \n
(?<!a)b | \n Match b in fib but not in fab | \n
Basic cheatsheets for regular expression
", "tags": null, "updated": "2020-03-10" },{ "id": "rename", "title": "rename", "url": "/rename", "category": "CLI", "keywords": null, "content_html": "brew install rename\n
\n\nSee: http://plasmasturm.org/code/rename/
\n\nrename 's/hello/world/' *.txt\n
\n\nRename hello.txt
to world.txt
and so on in *.txt
.
rename -s .png .jpg.png *.png\n
\n\nReplace .png
with .jpg.png
in *.png
.
Option | \nDescription | \n
---|---|
-n | \n Simulation | \n
-l | \n Symlink instead of rename | \n
-i | \n Interactive | \n
Resolution | \nDPPX | \nActual resolution | \nDPPI | \nActual PPI | \nSize | \nDevices | \n
---|---|---|---|---|---|---|
320 x 480 | \n@1x | \n320 x 480 | \n163 ppi | \n163 ppi | \n3.5” | \niPhone 2G/3G/3GS | \n
320 x 480 | \n@2x | \n640 x 960 | \n163 ppi | \n326 ppi | \n3.5” | \niPhone 4/4S | \n
320 x 568 | \n@2x | \n640 x 1136 | \n163 ppi | \n326 ppi | \n4” | \niPhone 5/5C/5S | \n
375 x 667 | \n@2x | \n750 x 1334 | \n163 ppi | \n326 ppi | \n4.7” | \niPhone 6/6S | \n
320 x 568 | \n@2x | \n640 x 1136 | \n163 ppi | \n326 ppi | \n4” | \niPhone SE | \n
375 x 667 | \n@2x | \n750 x 1334 | \n163 ppi | \n326 ppi | \n4.7” | \niPhone 7/8/SE2 | \n
414 x 736 | \n@3x | \n1242 x 2208 | \n133 ppi | \n401 ppi | \n5.5” | \niPhone 6+/6S+/7+/8+ | \n
414 x 896 | \n@2x | \n828 x 1792 | \n162 ppi | \n326 ppi | \n6.1” | \niPhone Xr/11 | \n
375 x 812 | \n@3x | \n1125 x 2436 | \n152 ppi | \n458 ppi | \n5.8” | \niPhone X/Xs/11 Pro | \n
414 x 896 | \n@3x | \n1242 x 2688 | \n162 ppi | \n458 ppi | \n6.5” | \niPhone Xs Max/11 Pro Max | \n
360 x 640 | \n@2x | \n720 x 1280 | \n153 ppi | \n306 ppi | \n4.8” | \nGalaxy S3 | \n
360 x 640 | \n@3x | \n1080 x 1920 | \n147 ppi | \n441 ppi | \n5” | \nGalaxy S4 | \n
360 x 640 | \n@3x | \n1080 x 1920 | \n144 ppi | \n432 ppi | \n5.1” | \nGalaxy S5 | \n
360 x 640 | \n@4x | \n1440 x 2560 | \n144 ppi | \n577 ppi | \n5.1” | \nGalaxy S6/Edge | \n
Resolution | \nDPPX | \nActual resolution | \nDPPI | \nActual PPI | \nSize | \nDevices | \n
---|---|---|---|---|---|---|
1024 x 768 | \n@2x | \n2048 x 1536 | \n163 ppi | \n326 ppi | \n7.9” | \niPad Mini Retina | \n
1024 x 768 | \n@2x | \n2048 x 1536 | \n132 ppi | \n264 ppi | \n9.7” | \niPad Air | \n
Code | \nDescription | \n
---|---|
200 OK | \n Successful get, patch (return a JSON object) | \n
201 Created | \n Successful post (return a JSON object) | \n
202 Accepted | \n Successful post, delete, path - async | \n
204 No content | \n Successful delete | \n
206 Partial content | \n Successful get - async | \n
Code | \nDescription | \n
---|---|
401 Unauthorized | \n Not authenticated | \n
403 Forbidden | \n Authenticated, but no permissions | \n
422 Unprocessable entity | \n Validation | \n
HTTP/1.1 401 Unauthorized\nContent-Type: application/json\n{\n 'id': 'auth_failed',\n 'message': \"You're not logged in.\"\n}\n
\n\nHere’s an example of a possible error reply.
\n\nGET /api/foo\nAccept: application/json; version=1\n
\n\nYou can pass a version=x
to the Accept request header. Info here
curl -is https://$TOKEN@api.example.com/\n
\n\nRequest | \nDescription | \n
---|---|
GET /articles/1 | \n read, returns 200 | \n
PUT /articles/1 | \n edit (or path), returns 200 | \n
DELETE /articles/1 | \n delete, returns 200 | \n
POST /articles | \n create, returns 201 | \n
GET /articles | \n list, returns 200 | \n
/* tag-name.tag */\n<tag-name>\n <div>\n hello {name}\n </div>\n\n this.name = opts.name\n</tag-name>\n
\n\n<!-- in html -->\n<tag-name>\n<script>riot.mount('*')</script>\n<script>riot.mount('tag-name')</script>\n<script>riot.mount('tag-name', { title: 'my app', ... })</script>\n
\n\n{value}\n{value || 'its a js expression'}\n\n<input checked={null}> /* null values ignore the tag */\n<p class={ selected: true }>\n
\n\n<li each={movies}>{title}</li>\n
\n\n<div if={error}>\n<div show={error}> /* show using display: '' */\n<div hide={error}> /* hide using display: none */\n
\n\n<button onclick={go}>\n\nthis.go = function (e) { ... }\n
\n\nthis.update()\nthis.update({ data: 'hi' }\n\nthis.unmount()\nthis.unmount(true) // keep parent tag\n\nriot.update() // update all\n
\n\n<my-tag>\n <child></child>\n var child = this.tags.child\n</my-tag>\n
\n\n<my-tag>\n <child name='xyz'></child>\n var child = this.tags.xyz\n</my-tag>\n
\n\n<yield/>\n
\n\n<post>\n <yield to='title'>Hello</yield>\n <yield to='body'>Hey there world</yield>\n</post>\n
\n\n<post>\n <yield from='title'/>\n <yield from='body'/>\n</post>\n
\n\nriot.route('customers/*/edit', (id) => {\n})\nriot.route('customers/234/edit')\nriot.route.start()\nriot.route.start(true) // exec the current url\n
\n\nthis.on('before-mount', function() {\n// before the tag is mounted\n})\n\nthis.on('mount', function() {\n// right after the tag is mounted on the page\n})\n\nthis.on('update', function() {\n// allows recalculation of context data before the update\n})\n\nthis.on('updated', function() {\n// right after the tag template is updated\n})\n\nthis.on('before-unmount', function() {\n// before the tag is removed\n})\n\nthis.on('unmount', function() {\n// when the tag is removed from the page\n})\n\n// curious about all events ?\nthis.on('all', function(eventName) {\nconsole.info(eventName)\n})\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rollup",
"title": "Rollup.js",
"url": "/rollup",
"category": "JavaScript libraries",
"keywords": ["rollup.watch","bundle","rollup.config.js"],
"content_html": "export default {\n input: 'src/main.js',\n output: {\n file: 'bundle.js',\n format: 'cjs'\n }\n}\n
\nnpm install -D rollup\n
\n\nCommand | \nDescription | \n
---|---|
rollup -c -o bundle.js | \n bundle using config | \n
rollup main.js --o bundle.js --f cjs | \n bundle | \n
rollup --watch | \n bundle continuously | \n
You may need to use ./node_modules/.bin/rollup
as a command if you did not install rollup globally.
export default [\n {\n input: 'src/main.js',\n output: {\n file: __dirname + '/public/main.js',\n format: 'cjs',\n name: 'main'\n }\n },\n {\n input: 'src/vendor.js',\n output: {\n file: __dirname + 'public/vendor.js',\n format: 'cjs',\n name: 'vendor'\n }\n }\n]\n
\n\nThis creates main.js
and vendor.js
.
npm install -D @rollup/plugin-json\n
\n\nimport json from '@rollup/plugin-json'\n\nexport default {\n input: 'src/main.js',\n output: {\n file: 'bundle.js',\n format: 'cjs'\n },\n plugins: [ json() ]\n}\n\n
\n\nnpm install -D @rollup/plugin-node-resolve\n
\n\nimport resolve from '@rollup/plugin-node-resolve'\n\nexport default {\n input: 'src/main.js',\n output: {\n file: 'bundle.js',\n format: 'cjs'\n },\n plugins: [ resolve() ]\n}\n
\n\nWhen you run a npm run build, no warning is emitted and contains the imported modules.
\n\nnpm install -D @rollup/plugin-node-resolve\n
\n\nimport resolve from '@rollup/plugin-node-resolve'\n\nexport default {\n input: 'src/main.js',\n output: {\n file: 'bundle.js',\n format: 'cjs'\n },\n plugins: [resolve({\n // pass custom options to the resolve plugin\n customResolveOptions: {\n moduleDirectory: 'node_modules'\n }\n })],\n // indicate which modules should be treated as external\n external: ['lodash']\n}\n
\n\nnpm install -D rollup-plugin-babel\n
\n\nimport resolve from '@rollup/plugin-node-resolve'\nimport babel from 'rollup-plugin-babel'\n\nexport default {\n input: 'src/main.js',\n output: {\n file: 'bundle.js',\n format: 'cjs'\n },\n plugins: [\n resolve(),\n babel({\n exclude: 'node_modules/**' // only transpile our source code\n })\n ]\n}\n
\n\n{\n \"presets\": [\n [\"latest\", {\n \"es2015\": {\n \"modules\": false\n }\n }]\n ],\n \"plugins\": [\"external-helpers\"]\n}\n
",
"intro_html": "Rollup Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application.
", "description_html": "", "tags": null, "updated": "2020-01-29" },{ "id": "ronn", "title": "Ronn", "url": "/ronn", "category": "Ruby libraries", "keywords": null, "content_html": "gem install ronn\n
\n\nronn foo.1.md # creates foo.1.html\nronn -r foo.1.md # creates foo.1 (--roff)\nronn -r -h foo.1.md # builds --roff and --html\nronn -m foo.1.md # view as manpage\n
\n\nRonn is a Ruby gem.
\n\nname(1) -- short, single-sentence description\n=============================================\n\n## SYNOPSIS\n\n`name` [<optional>...] <flags>\n\n## DESCRIPTION\n\nA normal paragraph. This can span multiple lines and is terminated with two\nor more line endings just like Markdown.\n\n## OPTIONS\n\n * `-h`, `--help` :\n Displays the help screen.\n\n * `--version` : \n Displays version information.\n\n## EXAMPLES\n\nIndent examples with 4 spaces.\n\n $ ls\n $ ls -la\n\n## COPYRIGHT\n\n**PROJECTNAME** is copyright (c) 2015, Rico Sta. Cruz. Released under the MIT\nlicense.\n\n## SEE ALSO\n\nronn-format(7), ronn(1)\n
\n\n`code`\n**strong**\n
\n\n<variable>\n_emphasis_\n*emphasis*\n
\n\nsh(1)\nmarkdown(7)\n
\n\n[STANDARDS][]\n[SEE ALSO][]\n[DIFFERENT TEXT][#SEE-ALSO]\n
\n\n[URL link](http://github.com/rstacruz)\n<http://github.com>\n
\n\n## SYNOPSIS
## DESCRIPTION
## OPTIONS
## SYNTAX
## ENVIRONMENT
## RETURN VALUES
## STANDARDS
## SECURITY CONSIDERATIONS
## BUGS
## HISTORY
## AUTHOR
## COPYRIGHT
## SEE ALSO
--pipe # write to stdout\n--server, -S # serve in http://localhost:1207\n
\n\n--html, -5 # default\n--fragment, -f # html without header/title/footer\n
\n\n--style=toc,80c # toc (table of contents)\n # 80c (use 80c instead of 100c)\n # print (include print stylesheet)\n # dark\n
\n\n--manual=\"MY MANUAL\" # shown on top-center\n--organization=\"RONN 0.7.0\" # shown on bottom-left\n--date=\"YYYY-MM-DD\" # shown on bottom-center\n
\n\nSection | \nDescription | \n
---|---|
1 | \n General commands | \n
2 | \n System calls | \n
3 | \n C standard lib | \n
4 | \n Special files (/dev) and drivers | \n
5 | \n File formats | \n
6 | \n Games | \n
7 | \n Misc | \n
8 | \n System administration commands and procedures | \n
See Man page sections (december.com).
\n\nPlace manual files in man/xxx.1.md
, then in package.json:
\"scripts\": {\n \"prepublish\": \"npm run build-man\",\n \"build-man\": \"if which ronn; then ronn man/*.md --html --roff --style=toc,80c --organization=\\\"@rstacruz\\\"; fi\"\n},\n\"directories\": {\n \"man\": \"man\"\n}\n
\n\nnpm install -g marked-man\nmarked-man foo.1.md > foo.1\n
\n\n<br>
See marked-man.
", "intro_html": "Ronn generates Man pages. See ronn(1), ronn-format(7). Also see it on GitHub: rtomayko/ronn.
", "description_html": "", "tags": null, "updated": "2017-10-15" },{ "id": "rspec-rails", "title": "Rspec-rails", "url": "/rspec-rails", "category": "Ruby", "keywords": null, "content_html": "rake spec:controllers\nrake spec:helpers\nrake spec:lib\nrake spec:mailers\nrake spec:models\nrake spec:requests\nrake spec:routing\nrake spec:views\n
\n\n# spec/models/*.rb\ndescribe MyModel do\nend\n
\n\n# spec/controllers/*.rb\ndescribe MyController do\n describe \"POST update\" do\n render_views #optional\n\n it \"works\" do\n post :update, { user: { name: \"john\" } }\n\n controller\n controller.send ...\n\n response\n expect(response).to be_success\n expect(response).to have_http_status(200)\n expect(response).to render_template(\"index\")\n expect(response).to redirect_to '/..'\n\n expect(assigns :article).to eq article\n\n response.status\n end\n end\nend\n
\n\n# spec/requests/*.rb\ndescribe \"home page\" do\n it \"displays the user's username after successful login\" do\n get \"/login\"\n post \"/login\", username: \"jdoe\", password: \"secret\"\n\n expect(response.status).to eql 200\n expect(response).to redirect_to(...)\n expect(response).to render_template(:show)\n expect(response.body).to include 'hello'\n follow_redirect!\n end\nend\n
\n\n# spec/routing/*.rb\ndescribe \"routing to profiles\" do\n it \"routes /profile/:username to profile#show for username\" do\n expect(get: \"/profiles/jsmith\").to route_to(\n controller: \"profiles\",\n action: \"show\",\n username: \"jsmith\"\n )\n end\n\n it \"does not expose a list of profiles\" do\n expect(get: \"/profiles\").not_to be_routable\n end\nend\n
\n\n# spec/helpers/*.rb\ndescribe EventsHelper do\n describe \"#link_to_event\" do\n it \"displays the title, and formatted date\" do\n event = Event.new(\"Ruby Kaigi\", Date.new(2010, 8, 27))\n\n # helper is an instance of ActionView::Base configured with the\n # EventsHelper and all of Rails' built-in helpers\n expect(helper.link_to_event).to match /Ruby Kaigi, 27 Aug, 2010/\n end\n end\nend\n
\n\n# spec/features/*.rb\nfeature 'Signing in' do\n given(:something) { \"hi\" }\n\n background do\n User.make email: 'hi@gmail.com'\n end\n\n scenario 'Signing in with credentials' do\n end\nend\n
\n\nbe_a_new(Widget) # new_record?\nrender_template(\"new\")\nrender_template(partial: 'form', locals: {...})\nredirect_to(widgets_path)\nroute_to(..)\nbe_routable\nhave_http_status(500)\nhave_http_status(:created)\n
\n\ntravel_to Time.new(2014, 11, 14, 01, 04, 44)\n...\ntravel_back\n\ntravel_to Time.new(2014, 11, 14, 01, 04, 44) do\n ...\nend\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rspec",
"title": "RSpec",
"url": "/rspec",
"category": "Ruby",
"keywords": null,
"content_html": "rake -T spec # List spec tasks\n\nrake spec # Run all\n\nrake spec/models/mymodel_spec.rb\nrake spec/models/mymodel_spec.rb:27\n
\n\ndescribe \"A User (in general)\" do\n include UserSpecHelper\n\n subject { Person.new }\n\n let(:admin) { Person.new(role: :admin) }\n\n context \"setter methods\" do\n it \"should do this\" do\n pending \"some other thing\"\n\n expect(subject.name).to eq 'x'\n end\n end\nend\n
\n\nbefore :each do\n # before all tests\nend\n\nbefore do\n # before this suite\nend\n\nafter do\n # after this suite\nend\n
\n\nsubject { CheckingAccount.new }\nit { is_expected.to be_empty }\n\n# also names: subject(:account) { ... }\n
\n\ntarget.should eq 1\ntarget.should_not eq 1\n\nexpect(target).to eq 1\nexpect(target).not_to eq 1\n
\n\nexpect(5).to be < 6\nexpect(5).to == 5\nexpect(5).to equal value\nexpect(5).to be_between(1, 10)\nexpect(5).to be_within(0.05).of value\n
\n\nexpect(x).to be value\nexpect(x).to satisfy { |arg| ... }\nexpect(x).to match /regexp/\n
\n\nexpect(x).to be_zero # FixNum#zero?\nexpect(x).to be_empty # Array#empty?\nexpect(x).to have_key # Hash#has_key?\n
\n\nexpect(obj).to be_an_instance_of MyClass\nexpect(obj).to be_a_kind_of MyClass\nexpect(obj).to respond_to :save!\n
\n\nexpect { user.save! }.to raise_error\nexpect { user.save! }.to raise_error(ExceptionName, /msg/)\nexpect { user.save! }.to throw :symbol\n
\n\nexpect(list).to include(<object>)\n\nexpect(list).to have(1).things\nexpect(list).to have_at_least(2).things\nexpect(list).to have_at_most(3).things\n\nexpect(list).to have(2).errors_on(:field)\n
\n\nexpect { thing.approve! }.to \\\n change(thing, :status)\n .from(Status::AWAITING_APPROVAL)\n .to(Status::APPROVED)\n\nexpect { thing.destroy }.to \\\n change(Thing, :count)\n .by(-1)\n
\n\nbook = double('book')\nbook = instance_double('Book', pages: 250)\n
\n\nallow(die).to receive(:roll)\nallow(die).to receive(:roll) { 3 }\nallow_any_instance_of(Die).to receive(:roll)\n\nexpect(die).to receive(:roll)\n .with(1)\n .with(1, true)\n .with(boolean)\n .with(anything)\n .with(any_args)\n .with(1, any_args)\n .with(no_args)\n .with(hash_including(a: 1))\n .with(hash_excluding(a: 1))\n .with(array_including(:a, :b))\n .with(array_excluding(:a, :b))\n .with(instance_of(Fixnum))\n .with(kind_of(Numeric))\n .with(<matcher>)\n\n .once\n .twice\n .exactly(n).times\n .at_least(:once)\n .at_least(:twice)\n .at_least(n).times\n .at_most(:once)\n .at_most(:twice)\n .at_most(n).times\n
\n\nhttps://relishapp.com/rspec/rspec-mocks/docs
\n\nmodule UserSpecHelper\n def valid_user_attributes\n { :email => \"joe@bloggs.com\",\n :username => \"joebloggs\",\n :password => \"abcdefg\"}\n end\nend\n
\n\ndescribe User do\n include UserSpecHelper\n\n ...\nend\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rst",
"title": "ReStructuredText",
"url": "/rst",
"category": "Markup",
"keywords": null,
"content_html": ".. @theme 2010\n.. include:: ../themes/2010/common.rst\n.. contents::\n.. |substitute| replace:: replacement name\n
\n\nHeading\n=======\n\n.. class:: brief\n\nHello there. |substitute| **This is bold**\n\n\n - Bullet list with a link_ (or `link with words`_)\n - Yes\n\n.. _link: http://link.org\n
\n\n.. raw:: pdf\n\n PageBreak oneColumn\n
\n\nInternal link target_.\n\n.. _target:\n\nThis is where _target will end up in.\n
\n\n.. class:: hash-table\n\n.. list-table::\n\n * - :key:`Cuisine:`\n - :val:`French/fusion`\n * - :key:`Number of ingredients:`\n - :val:`8`\n * - :key:`Preparation time:`\n - :val:`30 hours`\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rsync",
"title": "Rsync",
"url": "/rsync",
"category": "CLI",
"keywords": null,
"content_html": "# syncing folder src into dest:\nrsync -avz ./src /dest\n# syncing the content of src into dest:\nrsync -avz ./src/ /dest\n
\n\n--exclude '.Trashes'\n--exclude '.Spotlight-V100'\n--exclude '.fseventsd'\n
\n\n-z, --compress\n-n, --dry-run\n --partial # allows resuming of aborted syncs\n --bwlimit=RATE # limit socket I/O bandwidth\n
\n\n-q, --quiet\n-v, --verbose\n --stats\n-h, --human-readable\n --progress\n-P # same as --partial --progress\n
\n\n-u, --update # skip files newer on dest\n-c, --checksum # skip based on checksum, not mod-time & size\n
\n\n-b, --backup # backup with suffix\n --suffix=SUFFIX # default ~ without --backup-dir\n --backup-dir=DIR\n
\n\n--exclude=PATTERN\n--include=PATTERN\n
\n\n--exclude-from=FILE\n--include-from=FILE\n--files-from=FILE # read list of filenames from FILE\n
\n\n-C, --cvs-exclude # exclude from local/global .cvsignore\n
\n\n-a, --archive # archive (-rlptgoD)\n
\n\n-r, --recursive\n-l, --links # copy symlinks as links\n-p, --perms # preserve permissions\n-t, --times # preserve times\n-g, --group # preserve group\n-o, --owner # preserve owner\n-D # --devices --specials\n
\n\n--delete # Delete extra files\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "rtorrent",
"title": "rTorrent",
"url": "/rtorrent",
"category": "CLI",
"keywords": null,
"content_html": "^q | \n Quit | \n
Shortcut | \nDescription | \n
---|---|
bksp | \n Add torrent | \n
-> | \n View download | \n
1 - 7 | \n Change view | \n
^S | \n Start download | \n
^D | \n Stop download (or remove stopped) | \n
^K | \n Close a torrent | \n
+ / - | \n Change priority | \n
a / s / d | \n Increase upload throttle by 1/5/50 KB | \n
z / x / c | \n Decrease upload throttle by 1/5/50 KB | \n
A / S / D | \n Increase download throttle by 1/5/50 KB | \n
Z / X / C | \n Decrease download throttle by 1/5/50 KB | \n
1 / 2 | \n Adjust max uploads | \n
3 / 4 | \n Adjust min peers | \n
5 / 6 | \n Adjust max peers | \n
space | \n Change priority | \n
rTorrent is a command-line torrent application. Here are some shortcut keys.
", "description_html": "", "tags": null, "updated": null },{ "id": "ruby", "title": "Ruby", "url": "/ruby", "category": "Ruby", "keywords": null, "content_html": "Code | \nDescription | \n
---|---|
$! | \n latest error message | \n
$@ | \n location of error | \n
$_ | \n string last read by gets | \n
$. | \n line number last read by interpreter | \n
$& | \n string last matched by regexp | \n
$~ | \n the last regexp match, as an array of subexpressions | \n
$n | \n the nth subexpression in the last match (same as $~[n] ) | \n
$= | \n case-insensitivity flag | \n
$/ | \n input record separator | \n
$\\ | \n output record separator | \n
$0 | \n the name of the ruby script file | \n
$* (or ARGV ) | \n the command line arguments | \n
$$ | \n interpreter’s process ID | \n
$? | \n exit status of last executed child process | \n
$-i $-l $-p $-v | \n Command line switches | \n
$-v (or $VERBOSE ) | \n verbose mode | \n
Quick reference to some features of the Ruby programming language.
", "description_html": "", "tags": ["WIP"], "updated": null },{ "id": "ruby21", "title": "Ruby 2.1", "url": "/ruby21", "category": "Ruby", "keywords": null, "content_html": "# length is required\ndef pad(num, length:, char: \"0\")\n num.to_s.rjust(length, char)\nend\n
\n\npad(42, length: 6) #=> \"000042\"\npad(42) #=> #<ArgumentError: missing keyword: length>\n
\n\nprepend(\n Module.new do\n define_method ...\n end\n)\n
\n\nQuick reference to the new features in Ruby 2.1.
", "description_html": "", "tags": ["Archived"], "updated": null },{ "id": "rubygems", "title": "Rubygems", "url": "/rubygems", "category": "Ruby", "keywords": null, "content_html": "gem build *.gemspec # Build a gem\ngem install *.gem # Install locally\ngem push *.gem # Upload to rubygems.org\ngem yank foogem -v 0.0.1 # Take it back\n
\n\ngem owner foogem -a rico@ricostacruz.com\n\ngem list # List local gems\ngem which rake # Point to where lib/rake.rb is\ngem search -r rails # [remote] Search for gems\n
\n\n# https://github.com/fnando/gem-open\ngem open foogem\nGEM_EDITOR=\"vim\" gem open foogem\n
\n\ncd $(basename `gem which rake`) # Go to a gem's path\n
",
"intro_html": "A quick reference to common rubygems CLI commands.
", "description_html": "", "tags": null, "updated": null },{ "id": "sass", "title": "Sass", "url": "/sass", "category": "CSS", "keywords": ["Variables","mixins","darken()","adjust-color()","@for @each @while @if @else","$list: (a b c)","$map: (a: b, c: d)"], "content_html": "This is a quick reference to Sass stylesheets.
\n\n$red: #833;\n
\n\nbody {\n color: $red;\n}\n
\n\n.markdown-body {\n a {\n color: blue;\n &:hover {\n color: red;\n }\n }\n}\n
\n\ntext: {\n align: center; // like text-align: center\n transform: uppercase; // like text-transform: uppercase\n}\n
\n\n/* Block comments */\n// Line comments\n
\n\n@mixin heading-font {\n font-family: sans-serif;\n font-weight: bold;\n}\n
\n\nh1 {\n @include heading-font;\n}\n
\n\n@mixin font-size($n) {\n font-size: $n * 1.2em;\n}\n
\n\nbody {\n @include font-size(2);\n}\n
\n\n@mixin pad($n: 10px) {\n padding: $n;\n}\n
\n\nbody {\n @include pad(15px);\n}\n
\n\n// Set a default value\n$default-padding: 10px;\n
\n\n@mixin pad($n: $default-padding) {\n padding: $n;\n}\n
\n\nbody {\n @include pad(15px);\n}\n
\n\n.button {\n ···\n}\n
\n\n.push-button {\n @extend .button;\n}\n
\n\n@import './other_sass_file';\n
\n\nThe .scss
or .sass
extension is optional.
rgb(100, 120, 140)\nrgba(100, 120, 140, .5)\nrgba($color, .5)\n
\n\nmix($a, $b, 10%) // 10% a, 90% b\n
\n\ndarken($color, 5%)\nlighten($color, 5%)\n
\n\nsaturate($color, 5%)\ndesaturate($color, 5%)\ngrayscale($color)\n
\n\nadjust-hue($color, 15deg)\ncomplement($color) // like adjust-hue(_, 180deg)\ninvert($color)\n
\n\nfade-in($color, .5) // aka opacify()\nfade-out($color, .5) // aka transparentize() - halves the opacity\nrgba($color, .5) // sets alpha to .5\n
\n\nhue($color) // → 0deg..360deg\nsaturation($color) // → 0%..100%\nlightness($color) // → 0%..100%\nalpha($color) // → 0..1 (aka opacity())\n
\n\nred($color) // → 0..255\ngreen($color)\nblue($color)\n
\n\n\n\n// Changes by fixed amounts\nadjust-color($color, $blue: 5)\nadjust-color($color, $lightness: -30%) // like darken(_, 30%)\nadjust-color($color, $alpha: -0.4) // like fade-out(_, .4)\nadjust-color($color, $hue: 30deg) // like adjust-hue(_, 15deg)\n
\n\n// Changes via percentage\nscale-color($color, $lightness: 50%)\n
\n\n// Changes one property completely\nchange-color($color, $hue: 180deg)\nchange-color($color, $blue: 250)\n
\n\nSupported: $red
$green
$blue
$hue
$saturation
$lightness
$alpha
unquote('hello')\nquote(hello)\n
\n\nto-upper-case(hello)\nto-lower-case(hello)\n
\n\nstr-length(hello world)\nstr-slice(hello, 2, 5) // \"ello\" - it's 1-based, not 0-based\nstr-insert(\"abcd\", \"X\", 1) // \"Xabcd\"\n
\n\nunit(3em) // 'em'\nunitless(100px) // false\n
\n\nfloor(3.5)\nceil(3.5)\nround(3.5)\nabs(3.5)\n
\n\nmin(1, 2, 3)\nmax(1, 2, 3)\n
\n\npercentage(.5) // 50%\nrandom(3) // 0..3\n
\n\nvariable-exists(red) // checks for $red\nmixin-exists(red-text) // checks for @mixin red-text\nfunction-exists(redify)\n
\n\nglobal-variable-exists(red)\n
\n\nselector-append('.menu', 'li', 'a') // .menu li a\nselector-nest('.menu', '&:hover li') // .menu:hover li\nselector-extend(...)\nselector-parse(...)\nselector-replace(...)\nselector-unify(...)\n
\n\nfeature-exists(global-variable-shadowing)\n
\n\n@for $i from 1 through 4 {\n .item-#{$i} { left: 20px * $i; }\n}\n
\n\n$menu-items: home about services contact;\n\n@each $item in $menu-items {\n .photo-#{$item} {\n background: url('images/#{$item}.jpg');\n }\n}\n
\n\n$backgrounds: (home, 'home.jpg'), (about, 'about.jpg');\n\n@each $id, $image in $backgrounds {\n .photo-#{$id} {\n background: url($image);\n }\n}\n
\n\n$i: 6;\n@while $i > 0 {\n .item-#{$i} { width: 2em * $i; }\n $i: $i - 2;\n}\n
\n\n@if $position == 'left' {\n position: absolute;\n left: 0;\n}\n@else if $position == 'right' {\n position: absolute;\n right: 0;\n}\n@else {\n position: static;\n}\n
\n\n.#{$klass} { ... } // Class\ncall($function-name) // Functions\n\n@media #{$tablet}\nfont: #{$size}/#{$line-height}\nurl(\"#{$background}.jpg\")\n
\n\n$list: (a b c);\n\nnth($list, 1) // starts with 1\nlength($list)\n\n@each $item in $list { ... }\n
\n\n$map: (key1: value1, key2: value2, key3: value3);\n\nmap-get($map, key1)\n
\n\nSign up for opensauce:
\n\nInstall zuul:
\n\nnpm i -g zuul\n
\n\nConfigure zuul:
\n\n# ~/.zuulrc\nsauce_username: me\nsauce_key: abc12348-e3e2-...\n
\n\nAdd .zuul.yml
to your project:
# .zuul.yml\nui: mocha-bdd\nbrowsers:\n - name: chrome\n version: latest\n - name: ie\n version: 6..latest\n - name: firefox\n version: latest\n
\n\nTry to run tests:
\n\nzuul test/test.js\nzuul --local test/test.js\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "scp",
"title": "scp",
"url": "/scp",
"category": "CLI",
"keywords": null,
"content_html": "scp <options> source_path destination_path\n
\n\n-r # transfer directory \n-v # see the transfer details\n-C # copy files with compression\n-l 800 # limit bandwith with 800\n-p # preserving the original attributes of the copied files\n-q # hidden the output\n
\n\n$ scp file user@host:/path/to/file # copying a file to the remote system using scp command\n$ scp user@host:/path/to/file /local/path/to/file # copying a file from the remote system using scp command\n
\n\n$ scp file1 file2 user@host:/path/to/directory # copying multiple files using scp command\n$ scp -r /path/to/directory user@host:/path/to/directory # Copying an entire directory with scp command\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2018-12-25"
},{
"id": "sed",
"title": "sed",
"url": "/sed",
"category": "CLI",
"keywords": null,
"content_html": "sed -i -e 's/foo/bar/' example.md\n
\n\nIn GNU sed: use -i
without arg.
sed -i '' -e 's/foo/bar/' example.md\n
\n\nIn OSX, -i ''
is required.
sed '/begin api/q'\n
\n\nsed '/^# begin/,$d'\n
\n\nsed -n '/end api/,$p'\n
\n\nPrint after a given line is found.
\n\nsed -n '/regex/d;'\n
\n\nPrint everything except lines matching regex. Useful for printing files with comments.
", "intro_html": "Here’s some hints on using sed.
", "description_html": "", "tags": null, "updated": null },{ "id": "semver", "title": "Semver", "url": "/semver", "category": "Others", "keywords": null, "content_html": "Given a version number MAJOR.MINOR.PATCH
:
MAJOR | \n incompatible API changes | \n
MINOR | \n add functionality (backwards-compatible) | \n
PATCH | \n bug fixes (backwards-compatible) | \n
1.2.3\n =1.2.3\n >1.2.3\n <1.2.3\n>=1.2.3\n
\n\nNote that suffixed versions (1.2.3-rc1
) are not matched.
Range | \nDescription | \nNotes | \n
---|---|---|
~1.2.3 | \n is >=1.2.3 <1.3.0 | \n \n |
^1.2.3 | \n is >=1.2.3 <2.0.0 | \n \n |
^0.2.3 | \n is >=0.2.3 <0.3.0 | \n (0.x.x is special) | \n
^0.0.1 | \n is =0.0.1 | \n (0.0.x is special) | \n
^1.2 | \n is >=1.2.0 <2.0.0 | \n (like ^1.2.0) | \n
~1.2 | \n is >=1.2.0 <1.3.0 | \n (like ~1.2.0) | \n
^1 | \n is >=1.0.0 <2.0.0 | \n \n |
~1 | \n same | \n\n |
1.x | \n same | \n\n |
1.* | \n same | \n\n |
1 | \n same | \n\n |
* | \n any version | \n\n |
x | \n same | \n\n |
Range | \nDescription | \n
---|---|
1.2.3 - 2.3.4 | \n is >=1.2.3 <=2.3.4 | \n
Range | \nDescription | \n
---|---|
1.2.3 - 2.3 | \n is >=1.2.3 <2.4.0 | \n
1.2.3 - 2 | \n is >=1.2.3 <3.0.0 | \n
Range | \nDescription | \n
---|---|
1.2 - 2.3.0 | \n is 1.2.0 - 2.3.0 | \n
When the right is partial (eg, 2.3
), missing pieces are assumed to be x
(eg, 2.3.x
).
When the left is partial (eg, 1.2
), missing pieces are assumed to be 0
(eg, 1.2.0
).
Range | \nDescription | \n
---|---|
>=0.14 <16 | \n And (space-separated) | \n
0.14.x || 15.x.x | \n Or (pipe-separated) | \n
1.2.3-prerelease+build\n
\n\n^ | \n means “compatible with” | \n
~ | \n means “reasonably close to” | \n
0.x.x | \n is for “initial development” | \n
1.x.x | \n means public API is defined | \n
require 'rubygems'\nrequire 'sequel'\n\nDB = Sequel.sqlite('my_blog.db')\nDB = Sequel.connect('postgres://user:password@localhost/my_db')\nDB = Sequel.postgres('my_db', :user => 'user', :password => 'password', :host => 'localhost')\nDB = Sequel.ado('mydb')\n
\n\nWithout a filename argument, the sqlite adapter will setup a new sqlite database in memory.
\n\nDB = Sequel.sqlite\n
\n\nrequire 'logger'\nDB = Sequel.sqlite '', :loggers => [Logger.new($stdout)]\n# or\nDB.loggers << Logger.new(...)\n
\n\nDB.run \"CREATE TABLE users (name VARCHAR(255) NOT NULL, age INT(3) NOT NULL)\"\ndataset = DB[\"SELECT age FROM users WHERE name = ?\", name]\ndataset.map(:age)\nDB.fetch(\"SELECT name FROM users\") do |row|\n p row[:name]\nend\n
\n\ndataset = DB[:items]\ndataset = DB.from(:items)\n
\n\ndataset = DB[:managers].where(:salary => 5000..10000).order(:name, :department)\n
\n\ndataset.insert(:name => 'Sharon', :grade => 50)\n
\n\ndataset.each{|r| p r}\ndataset.all # => [{...}, {...}, ...]\ndataset.first # => {...}\n
\n\ndataset.filter(~:active).delete\ndataset.filter('price < ?', 100).update(:active => true)\n
\n\ndataset.map{|r| r[:name]}\ndataset.map(:name) # same as above\n\ndataset.inject(0){|sum, r| sum + r[:value]}\ndataset.sum(:value) # same as above\n
\n\ndataset.filter(:name => 'abc')\ndataset.filter('name = ?', 'abc')\n
\n\ndataset.filter{value > 100}\ndataset.exclude{value <= 100}\n
\n\ndataset.filter(:value => 50..100)\ndataset.where{(value >= 50) & (value <= 100)}\n\ndataset.where('value IN ?', [50,75,100])\ndataset.where(:value=>[50,75,100])\n\ndataset.where(:id=>other_dataset.select(:other_id))\n
\n\ndataset.where('price > (SELECT avg(price) + 100 FROM table)')\ndataset.filter{price > dataset.select(avg(price) + 100)}\n
\n\nDB[:items].filter(:name.like('AL%'))\nDB[:items].filter(:name => /^AL/)\n
\n\nDB[:items].filter{(x > 5) & (y > 10)}.sql \n# SELECT * FROM items WHERE ((x > 5) AND (y > 10))\n\nDB[:items].filter({:x => 1, :y => 2}.sql_or & ~{:z => 3}).sql \n# SELECT * FROM items WHERE (((x = 1) OR (y = 2)) AND (z != 3))\n
\n\nDB[:items].filter((:x + :y) > :z).sql \n# SELECT * FROM items WHERE ((x + y) > z)\n\nDB[:items].filter{price - 100 < avg(price)}.sql \n# SELECT * FROM items WHERE ((price - 100) < avg(price))\n
\n\ndataset.order(:kind)\ndataset.reverse_order(:kind)\ndataset.order(:kind.desc, :name)\n
\n\ndataset.limit(30) # LIMIT 30\ndataset.limit(30, 10) # LIMIT 30 OFFSET 10\n
\n\nDB[:items].left_outer_join(:categories, :id => :category_id).sql \n# SELECT * FROM items LEFT OUTER JOIN categories ON categories.id = items.category_id\n\nDB[:items].join(:categories, :id => :category_id).join(:groups, :id => :items__group_id) \n# SELECT * FROM items INNER JOIN categories ON categories.id = items.category_id INNER JOIN groups ON groups.id = items.group_id\n
\n\ndataset.count #=> record count\ndataset.max(:price)\ndataset.min(:price)\ndataset.avg(:price)\ndataset.sum(:stock)\n\ndataset.group_and_count(:category)\ndataset.group(:category).select(:category, :AVG.sql_function(:price))\n
\n\ndataset.update(:updated_at => :NOW.sql_function)\ndataset.update(:updated_at => 'NOW()'.lit)\n\ndataset.update(:updated_at => \"DateValue('1/1/2001')\".lit)\ndataset.update(:updated_at => :DateValue.sql_function('1/1/2001'))\n
\n\nDB.create_table :items do\n primary_key :id\n String :name, :unique => true, :null => false\n TrueClass :active, :default => true\n foreign_key :category_id, :categories\n DateTime :created_at\n \n index :created_at\nend\n\nDB.drop_table :items\n\nDB.create_table :test do\n String :zipcode\n enum :system, :elements => ['mac', 'linux', 'windows']\nend\n
\n\nDB[:items].select(:name.as(:item_name))\nDB[:items].select(:name___item_name)\nDB[:items___items_table].select(:items_table__name___item_name)\n# SELECT items_table.name AS item_name FROM items AS items_table\n
\n\nDB.transaction do\n dataset.insert(:first_name => 'Inigo', :last_name => 'Montoya')\n dataset.insert(:first_name => 'Farm', :last_name => 'Boy')\nend # Either both are inserted or neither are inserted\n
\n\nDatabase#transaction is re-entrant:
\n\nDB.transaction do # BEGIN issued only here\n DB.transaction\n dataset << {:first_name => 'Inigo', :last_name => 'Montoya'}\n end\nend # COMMIT issued only here\n
\n\nTransactions are aborted if an error is raised:
\n\nDB.transaction do\n raise \"some error occurred\"\nend # ROLLBACK issued and the error is re-raised\n
\n\nTransactions can also be aborted by raising Sequel::Rollback:
\n\nDB.transaction do\n raise(Sequel::Rollback) if something_bad_happened\nend # ROLLBACK issued and no error raised\n
\n\nSavepoints can be used if the database supports it:
\n\nDB.transaction do\n dataset << {:first_name => 'Farm', :last_name => 'Boy'} # Inserted\n DB.transaction(:savepoint=>true) # This savepoint is rolled back\n dataset << {:first_name => 'Inigo', :last_name => 'Montoya'} # Not inserted\n raise(Sequel::Rollback) if something_bad_happened\n end\n dataset << {:first_name => 'Prince', :last_name => 'Humperdink'} # Inserted\nend\n
\n\ndataset.sql # \"SELECT * FROM items\"\ndataset.delete_sql # \"DELETE FROM items\"\ndataset.where(:name => 'sequel').exists # \"EXISTS ( SELECT * FROM items WHERE name = 'sequel' )\"\ndataset.columns #=> array of columns in the result set, does a SELECT\nDB.schema(:items) => [[:id, {:type=>:integer, ...}], [:name, {:type=>:string, ...}], ...]\n
\n\nhttp://sequel.rubyforge.org/rdoc/files/doc/association_basics_rdoc.html\nhttp://sequel.rubyforge.org/rdoc/classes/Sequel/Schema/Generator.html\nhttp://sequel.rubyforge.org/rdoc/files/doc/validations_rdoc.html\nhttp://sequel.rubyforge.org/rdoc/classes/Sequel/Model.html\n
\n\ndatabase.alter_table :deals do\n add_column :name, String\n drop_column :column_name\n rename_column :from, :to\n\n add_constraint :valid_name, :name.like('A%')\n drop_constraint :constraint\n\n add_full_text_index :body\n add_spacial_index [columns]\n\n add_index :price\n drop_index :index\n\n add_foreign_key :artist_id, :table\n add_primary_key :id\n add_unique_constraint [columns]\n set_column_allow_null :foo, false\n set_column_default :title, ''\n\n set_column_type :price, 'char(10)'\nend\n
\n\nclass Deal < Sequel::Model\n\n # Us (left) <=> Them (right)\n many_to_many :images,\n left_id: :deal_id,\n right_id: :image_id,\n join_table: :image_links\n\n one_to_many :files,\n key: :deal_id,\n class: :DataFile,\n\n many_to_one :parent, class: self\n one_to_many :children, key: :parent_id, class: self\n\n one_to_many :gold_albums, class: :Album do |ds|\n ds.filter { copies_sold > 50000 }\n end\n
\n\nProvided by many_to_many
\n\nDeal[1].images\nDeal[1].add_image\nDeal[1].remove_image\nDeal[1].remove_all_images\n
\n\n def validate\n super\n errors.add(:name, 'cannot be empty') if !name || name.empty?\n\n validates_presence [:title, :site]\n validates_unique :name\n validates_format /\\Ahttps?:\\/\\//, :website, :message=>'is not a valid URL'\n validates_includes %w(a b c), :type\n validates_integer :rating\n validates_numeric :number\n validates_type String, [:title, :description]\n\n validates_integer :rating if new?\n\n # options: :message =>, :allow_nil =>, :allow_blank =>,\n # :allow_missing =>,\n\n validates_exact_length 17, :isbn\n validates_min_length 3, :name\n validates_max_length 100, :name\n validates_length_range 3..100, :name\n \n # Setter override\n def filename=(name)\n @values[:filename] = name\n end\n end\nend\n\ndeal.errors\n
\n\ndeal = Deal[1]\ndeal.changed_columns\ndeal.destroy # Calls hooks\ndeal.delete # No hooks\ndeal.exists?\ndeal.new?\ndeal.hash # Only uniques\ndeal.keys #=> [:id, :name]\ndeal.modified!\ndeal.modified?\n\ndeal.lock!\n
\n\nbefore_create\nafter_create\n\nbefore_validation\nafter_validation\nbefore_save\nbefore_update\nUPDATE QUERY\nafter_update\nafter_save\n\nbefore_destroy\nDELETE QUERY\nafter_destroy\n
\n\nclass Deal < Sequel::Model\n set_schema do\n primary_key :id\n primary_key [:id, :title]\n String :name, primary_key: true\n \n String :title\n Numeric :price\n DateTime :expires\n\n unique :whatever\n check(:price) { num > 0 }\n\n foreign_key :artist_id\n String :artist_name, key: :id\n\n index :title\n index [:artist_id, :name]\n full_text_index :title\n\n # String, Integer, Fixnum, Bignum, Float, Numeric, BigDecimal,\n # Date, DateTime, Time, File, TrueClass, FalseClass\n end\nend\n
\n\nCategory.create id: 'travel' # error\nCategory.unrestrict_primary_key\nCategory.create id: 'travel' # ok\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "sequelize",
"title": "Sequelize",
"url": "/sequelize",
"category": "Ruby libraries",
"keywords": null,
"content_html": "sequelize.sync().done -> ...\n
\n\nProject = sequelize.define('Project', {\n title: Sequelize.STRING,\n description: Sequelize.TEXT,\n myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW },\n title: { type: Sequelize.STRING, allowNull: false },\n id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },\n}, {\n classMethods: { ... },\n instanceMethods: { ... }\n});\n\nProject.hasMany(Task)\n
\n\nProject.find(123).success (project) ->\n\nProject.find({ where: {title: 'Hello'} })\nProject.find({ where: {id: [1,3,4]} })\nProject.find({ where: [\"id > ?\", 25] })\n\nProject.find(\n where: {title: 'a'}\n attributes: ['id', ['name', 'title']]\n)\n\n.findOrCreate(...)\n\n.findAll\n.findAll({ where: ... })\n.findAll({ order: 'title DESC' })\n.findAll({ limit: 10 })\n.findAll({ offset: 10, limit: 2 })\n\n.count()\n
\n\nitem = Project.build({ ... })\n\nitem.title = '...'\n\nitem.save().success (item) ->\n\nitem.updateAttributes({ title: '...' })\n\nitem.destroy().success ->\n\nitem.values\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "sh-pipes",
"title": "Shell: named pipes",
"url": "/sh-pipes",
"category": "CLI",
"keywords": null,
"content_html": "diff <(ls ./old) <(ls ./new)\n
\n\nThis creates a virtual file with the contents of the output of ls ./old
.
var shell = require('shelljs')\n
\n\nif (!shell.which('git')) {\n shell.echo('Sorry, this script requires git')\n shell.exit(1)\n}\n
\n\n// Copy files to release dir\nshell.rm('-rf', 'out/Release')\nshell.cp('-R', 'stuff/', 'out/Release')\n
\n\n// Replace macros in each .js file\nshell.cd('lib')\nshell.ls('*.js').forEach(function (file) {\n shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file)\n shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file)\n shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\\n/, shell.cat('macro.js'), file)\n})\nshell.cd('..')\n
\n\n// Run external tool synchronously\nif (shell.exec('git commit -am \"Auto-commit\"').code !== 0) {\n shell.echo('Error: Git commit failed')\n shell.exit(1)\n}\n
\n\nTaken from the Readme.
\n\nconst sh = require('shelljs')\n
\n\nsh.cd('dir')\n
\n\nsh.mkdir('dir')\nsh.mkdir('-p', 'dir')\n
\n\nsh.cp('src', 'dest')\nsh.cp('-rf', 'src', 'dest')\n
\n\nsh.rm('file')\nsh.rm('-rf', 'file')\n
\n\nsh.mv('src', 'dest')\nsh.mv(['src1','src2'], 'dest')\n
\n\nsh.chmod('644', 'file')\nsh.chmod(755, 'file')\nsh.chmod('u+x', 'file')\n
\n\nsh.test('-b', 'path') // block device\nsh.test('-d', 'path') // dir\nsh.test('-e', 'path') // exists\nsh.test('-f', 'path') // file\nsh.test('-L', 'path') // symlink\n
\n\nsrc = sh.cat('file*.txt')\n
\n\n'hello'.to('output.txt')\n'hello'.toEnd('append.txt')\n
\n\nsh.cat('input.txt').to('output.txt')\n
\n\nsh.which('x')\nsh.pwd()\n
\n\nsh.echo('hi')\n
\n\nsh.exec('node --version').code\nsh.exec('node --version').output\nsh.exec('node --version', { silent: true }).output\n
\n\nsh.exec('node --version', (code, output) => {\n sh.echo(`exit code ${code}`)\n})\n
\n\nsh.tempdir()\n
\n\nsh.error() // null if no error\n
\n\nShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API.
", "description_html": "", "tags": null, "updated": "2017-10-27" },{ "id": "siege", "title": "Siege", "url": "/siege", "category": "Others", "keywords": null, "content_html": "siege -b -c=10 -t=5m \"http://...\"\n
\n\n-c, --concurrent=N\n-t, --time=MINSm\n-r, --reps=N\n
\n\n-i, --internet Hit URLs randomly\n-b, --benchmark No delay between requests\n
\n\n-f, --file=FILE load urls.txt\n-R, --rc=FILE load siegerc\n
\n\n-H, --header=\"Cookie: foo=bar\"\n-A, --user-agent=\"Mozilla\"\n-T, --content-type=\"text/html\"\n
\n\nAlso see: siegerc
", "intro_html": "Siege is an HTTP and HTTPS load testing tool.
", "description_html": "", "tags": null, "updated": null },{ "id": "simple_form", "title": "SimpleForm", "url": "/simple_form", "category": "Others", "keywords": null, "content_html": "<%= f.input :email, required: false, autofocus: true %>\n<%= f.input :password, required: false %>\n<%= f.input :remember_me, as: :boolean %>\n<%= f.button :submit, \"Sign in\" %>\n
\n\nsimple_form_for @x, wrapper: :small\n
",
"intro_html": "",
"description_html": "",
"tags": ["WIP"],
"updated": null
},{
"id": "sinon-chai",
"title": "Sinon-chai",
"url": "/sinon-chai",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "var sinon = require('sinon');\nrequire('chai').use(require('sinon-chai'));\n
\n\nexpect(spy).called\nexpect(spy).calledOnce\nexpect(spy).calledTwice\nexpect(spy).calledThrice\nexpect(spy).calledBefore\nexpect(spy).calledAfter\nexpect(spy).calledWithNew\nexpect(spy).alwaysCalledWithNew\nexpect(spy).calledOn\nexpect(spy).alwaysCalledOn\nexpect(spy).calledWith\nexpect(spy).alwaysCalledWith\nexpect(spy).calledWithExactly\nexpect(spy).alwaysCalledWithExactly\nexpect(spy).calledWithMatch\nexpect(spy).alwaysCalledWithMatch\nexpect(spy).returned\nexpect(spy).alwaysReturned\nexpect(spy).threw\nexpect(spy).alwaysThrew\n
\n\nspy.should.have.been.called\nspy.should.have.been.calledOnce\nspy.should.have.been.calledTwice\nspy.should.have.been.calledThrice\nspy1.should.have.been.calledBefore(spy2)\nspy1.should.have.been.calledAfter(spy2)\nspy.should.have.been.calledWithNew\nspy.should.always.have.been.calledWithNew\nspy.should.have.been.calledOn(context)\nspy.should.always.have.been.calledOn(context)\nspy.should.have.been.calledWith(...args)\nspy.should.always.have.been.calledWith(...args)\nspy.should.always.have.been.calledWithExactly(...args)\nspy.should.always.have.been.calledWithExactly(...args)\nspy.should.have.been.calledWithMatch(...args)\nspy.should.always.have.been.calledWithMatch(...args)\nspy.should.have.returned(returnVal)\nspy.should.have.always.returned(returnVal)\nspy.should.have.thrown(errorObjOrErrorTypeStringOrNothing)\nspy.should.have.always.thrown(errorObjOrErrorTypeStringOrNothing)\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "sinon",
"title": "Sinon",
"url": "/sinon",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "fn = sinon.spy()\nfn()\n
\n\nfn.calledOnce == true\nfn.callCount == 1\n
\n\nsinon.spy($, 'ajax')\n
\n\n$.ajax();\n$.ajax.calledOnce == true\n
\n\nsinon.stub($, 'ajax', function () { ... }) // function optional\n
\n\n$.ajax.calledWithMatch({ url: '/x' })\n$.ajax.restore()\n
\n\nspy\n .args //=> [ [..], [..] ] one per call\n .thisValues\n .returnValues\n
\n\n .called //=> true\n .notCalled\n .callCount\n .calledOnce\n .calledTwice\n .calledThrice\n
\n\n .getCalls() //=> Array\n .getCall(0)\n .firstCall\n
\n\nstub = sinon.stub().returns(42)\nstub() == 42\n
\n\nstub\n .withArgs(42).returns(1)\n .withArgs(43).throws(\"TypeError\")\n
\n\nstub\n .returns(1)\n .throws(\"TypeError\")\n .returnsArg(0) // Return 1st argument\n .callsArg(0)\n
\n\nsinon.useFakeTimers(+new Date(2011,9,1));\n
\n\nserver = sinon.fakeServer.create()\n
\n\n$.get('/file.json', ...)\nserver.requests[0].respond(\n 200,\n { 'Content-Type': 'application/json' },\n JSON.stringify({ hello: 'world' })\n)\n
\n\nserver.restore()\n
\n\nxhr = sinon.useFakeXMLHttpRequest()\nxhr.restore()\n
\n\nbeforeEach(function() {\n global.sinon = require('sinon').sandbox.create()\n})\n
\n\nafterEach(function() {\n global.sinon.restore()\n})\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2017-10-27"
},{
"id": "sketch",
"title": "Sketch",
"url": "/sketch",
"category": "Apps",
"keywords": null,
"content_html": "Shortcut | \nDescription | \n
---|---|
V | \n Vector | \n
P | \n Pencil | \n
T | \n Text | \n
L | \n Line | \n
R | \n Rectangle | \n
O | \n Oval | \n
U | \n Rounded | \n
Shortcut | \nDescription | \n
---|---|
^G | \n Show grid | \n
^L | \n Show layout | \n
^P | \n Show pixels | \n
^H | \n Show selection handles | \n
^R | \n Show rulers | \n
Shortcut | \nDescription | \n
---|---|
⌘⌥1 | \n Toggle left (layers) | \n
⌘⌥2 | \n Toggle right (inspector) | \n
⌘⌥3 | \n Toggle both | \n
⌘. | \n Presentation mode | \n
Shortcut | \nDescription | \n
---|---|
⌘0 | \n 100% | \n
⌘1 | \n Fit to screen | \n
⌘2 | \n Fit selection to screen | \n
⌘3 | \n Center selection | \n
Shortcut | \nDescription | \n
---|---|
⌘⌥↑ / ↓ | \n Forward or backward | \n
^⌘⌥↑ / ↓ | \n Front or back | \n
Shortcut | \nDescription | \n
---|---|
^⌘H | \n Horizontal | \n
^⌘V | \n Vertical | \n
Shortcut | \nDescription | \n
---|---|
⌘R | \n Rename layer | \n
⌘F | \n Find layer | \n
⌘G | \n Group | \n
⌘⇧G | \n Ungroup | \n
Shortcut | \nDescription | \n
---|---|
⌘⌥ + / - | \n Bigger/smaller | \n
⌘⇧[ | \n Left align | \n
⌘⇧\\ | \n Center align | \n
⌘⇧] | \n Right align | \n
doctype html\nhtml\n head\n title Slim Examples\n meta[charset='utf-8']\n meta(name=\"keywords\" content=\"template language\")\n meta name=\"author\" content=author\n meta property='og:image' content=asset_url('foo.png')\n meta property='og:image' content=(path_to_user user)\n meta(\n property='description'\n content='this is the song that never ends')\n
\n\nmeta[charset='utf-8']\nmeta(name=\"keywords\" content=\"template language\")\nmeta name=\"author\" content=author\n
\n\nYou can use parentheses, brackets, or none at all.
\n\na class=[:menu,:highlight]\n
\n\nYou can use Ruby expressions in attributes.
\n\n.card *{'data-url' => place_path(place)}\n
\n\nYou can destructure Ruby hashes as attributes.
\n\nruby:\n def foobar\n \"hello\"\n end\n\ndiv= foobar\n
\n\nmarkdown:\n ### On Markdown\n\n I am *Markdown* _text_!\n {: .classname}\n
\n\nSlim can handle your Markdown content for longer content blocks or code
.\nDepending on your parser, like Kramdown, other features might work, like assigning attributes or classes.
javascript:\n alert('Slim supports embedded javascript!')\n
\n\n/ Comment\n/! HTML comment\n
\n\n== yield\n= t('.hello')\n- 3.times do |i|\n div\n
\n\ndiv\n | This is text\n it is nice\n
\n\ndiv\n ' This appends a whitespace\ndiv\n | This hackily prepends a whitespace\ndiv\n => 'This appends a whitespace'\ndiv\n =< 'This prepends a whitespace'\n
\n\n<div class='foo'>\n - if articles.empty?\n | Nothing here\n</div>\n
\n\nul\n li: a(href='/') Home\n
\n\nWhat | \nDimensions | \n
---|---|
Cover photo | \n851 x 315 | \n
Display picture | \n168 x 168 ? | \n
Highlighted image | \n1200 x 717 (appears 843 x 504) | \n
Share link (og:image) | \n940 x 492 (1.91:1, appears as 470 x 246) | \n
Share link (square) | \n1:1, appears as 114 x 114? | \n
What | \nDimensions | \n
---|---|
Page header | \n1500 x 500 | \n
Display picture | \n400 x 400 (shown as 200x200) | \n
In-stream photo preview | \n440 x 220 (2:1) | \n
Shortcut | \nDescription | \n
---|---|
SPC f | \n File | \n
SPC p | \n Project | \n
SPC t | \n Toggle | \n
SPC b | \n Buffer | \n
SPC m | \n Major mode | \n
, | \n Same as SPC m | \n
SPC g | \n Git | \n
SPC l | \n Layout | \n
SPC a | \n Apps | \n
SPC h | \n Help | \n
Description | \nShortcut | \n
---|---|
M-x | \nSPC SPC | \n
Terminal | \nSPC ' | \n
Search | \nSPC / | \n
SPC
h
- HelpDescription | \nShortcut | \n
---|---|
Spacemacs help | \nSPC | \n
Layers | \nl | \n
Documentation | \nr | \n
FAQ | \nf | \n
Vimtutor | \nT | \n
SPC
f
- FileDescription | \nShortcut | \n
---|---|
Save | \ns | \n
Save all | \nS | \n
Copy | \nc | \n
Delete | \nD | \n
Show filename | \ny | \n
SPC
b
- BufferDescription | \nShortcut | \n
---|---|
Next buffer (:bnext ) | \n n | \n
Previous buffer (:bprev ) | \n p | \n
Delete buffer (:bd ) | \n d | \n
SPC
f
e
- ConfigDescription | \nShortcut | \n
---|---|
Edit config | \nd | \n
Edit config and template | \nD | \n
Reload config | \nR | \n
SPC
w
- WindowDescription | \nShortcut | \n
---|---|
Help | \n. | \n
Select | \nh / j / k / l | \n
Move | \nH / J / K / L | \n
Split | \ns | \n
Split & follow | \nS | \n
Split vert | \nv | \n
Split vert & follow | \nV | \n
SPC
p
- ProjectDescription | \nShortcut | \n
---|---|
Switch project | \nl | \n
Switch project | \np | \n
Open files & recent | \nh | \n
Open files | \nf | \n
Show tree | \nt | \n
Open terminal | \n' | \n
Open terminal in root | \n$ t | \n
SPC
l
w
- WorkspacesDescription | \nShortcut | \n
---|---|
Help | \n? | \n
Switch previous layout | \nTAB | \n
Switch to nth workspace | \n0 … 9 | \n
Rename | \nR | \n
SPC
t
- ToggleDescription | \nShortcut | \n
---|---|
Line numbers | \nn | \n
Shortcut | \nDescription | \n
---|---|
, - | \n Insert horizontal rule | \n
, h 1 | \n Insert H1 | \n
Shortcut | \nDescription | \n
---|---|
SPC g s | \n Status | \n
SPC g m | \n Open dispatch menu | \n
SPC g m s | \n Stage | \n
SPC g m P p | \n Push | \n
SPC g m c | \n Commit | \n
SPC g t | \n Open time machine | \n
SPC g l l | \n Open in GitHub | \n
SPC g l L | \n Show GitHub URL | \n
Version control is provided by Magit.
\n\nDescription | \nEmacs | \nSpacemacs | \n
---|---|---|
Save | \nC-x C-s | \n SPC f s | \n
Open | \nC-x C-f | \n SPC f f | \n
Close | \nC-x C-k | \n \n |
Split horizontal | \nC-x 2 | \n SPC w h | \n
Split vertical | \nC-x 3 | \n SPC w v | \n
Confirm | \nC-c C-c | \n \n |
Abort | \nC-c C-k | \n \n |
Spacemacs is a distribution for Emacs.
", "description_html": "", "tags": ["WIP"], "updated": "2020-05-22" },{ "id": "spine", "title": "Spine", "url": "/spine", "category": "JavaScript libraries", "keywords": null, "content_html": "class User extends Spine.Model\n @configure \"User\", \"name\", \"address\"\n\n fullName: ->\n [@first, @last].join ' '\n
\n\n// Subclassing\nUser = Spine.Model.sub()\n
\n\n.configure 'modelname', attributes...\n\n# Inheritance\n.include(Module)\n.extend(Module)\n\n.create(name: \"John\")\n\n.count()\n\n# Events\n.on 'refresh change', (user) -> ...\n.trigger 'event'\n\n.change (user) -> ... # same as on('change')\n.fetch (user) -> ... # same as on('fetch')\n\n# JSON\n.toJSON() # all records\n.fromJSON(json) # from json string\n.fromForm(el)\n\n# Data\n.records # Hash of instances\n.attributes # array of attributes (from .configure)\n\n# Convenience\n.toString() #=> \"User\"\n\n# Find by ID\n.exists(1)\n.find(1) # throws error\n\n# Find by something\n.select (u) u.name == 'bob'\n.findByAttribute 'name', 'bob'\n.findAllByAttribute 'name', 'bob'\n\n.all()\n.slice(6, 13) # cloned copies of instances\n\n# Iterating\n.each (user) ->\n\n# Ends\n.first()\n.last()\n\n# Deleting\n.deleteAll()\n.destroyAll()\n.destroyAll({ ..options.. })\n.destroy(2)\n
\n\nuser = new User();\n\nuser\n.isNew()\n.exists()\n\n# Validation\n.isValid()\n.validate() # validate = (-> \"Name required\" unless @name)\n\n.attributes() # hash of attr values\n.eql(other) # equality check\n\n# Update\n.load(attrs)\n.reload()\n.fromForm(form)\n.updateAttribute(\"name\", \"john\")\n.updateAttributes(name: \"John\")\n\n# Event\n.on 'event', -> ...\n.trigger 'event'\n\n# Retrieve\n.toJSON()\n\n# Persistence\n.save()\n\n.destroy()\n.dup() # clone as unsaved\n
\n\nclass User extends Spine.Model\n @include MyModule\n @extend MyModule\n
\n\n.on 'create'\n.on 'update'\n.on 'destroy'\n\n.on 'save' # create / update\n.on 'change' # create / update / destroy\n\n.on 'refresh'\n.on 'error' # validation error\n
\n\nclass User extends Spine.Model\n @extend Spine.Model.Ajax\n\n @url: '/users'\n @url: -> '/users'\n scope: '2013'\n
\n\nUser.fetch()\nuser = new User()\n\nuser.url() #=> \"/users\"\nuser.url('bands') #=> \"/users/bands\"\n\nuser.scope = 'admin'\nuser.url() #=> \"/admin/users\"\n
\n\nSpine.Model.host = 'http://endpoint'\n
\n\nread → GET /collection\ncreate → POST /collection (201 created)\nupdate → PUT /collection/id\ndestroy → DELETE /collection/id\n
\n\nclass Photo extends Spine.Model\n @belongsTo 'album', 'Album' # window['Album']\n @belongsTo 'album', 'models/album' # via require.js\n\nclass Album\n @hasMany 'photos', 'models/photo'\n\nalbum.photos().all()\nalbum.photos().create(name: \"Vacation\")\nalbum.photos().find(id)\n\nphoto = Photo.create(album: album)\nphoto.album()\nphoto.album_id\n
\n\n=IF(test, then, else)\n=IF(EQ(A1, \"paid\"), \"true\", \"false\")\n
\n\n=EQ(a,b)\n=NE(a,b)\n=GT(a,b)\n=GTE(a,b)\n=LT(a,b)\n=LTE(a,b)\n
\n\n=POW(2, 32) # 2^32\n=SIN() ACOS() etc\n=CEILING(n,sig,mode)\n=FLOOR(n,sig,mode)\n=INT(n)\n
\n\n=SUM(range)\n
\n\n=SUMIF(range, criteria, sum_range)\n=SUMIF(A1:A5, \">300\", B1:B5) # if A# is >300, use B#\n
\n\n=TO_DATE(number)\n
\n\n=VLOOKUP(value, range, column_index)\n
",
"intro_html": "",
"description_html": "",
"tags": ["WIP"],
"updated": null
},{
"id": "sql-join",
"title": "SQL joins",
"url": "/sql-join",
"category": "Databases",
"keywords": null,
"content_html": "SELECT * FROM order_items \\\n LEFT OUTER JOIN orders \\\n ON order_items.order_id = orders.id\n
\n\nJoins are typically added to SELECT
statements to add more columns and records.
SELECT * FROM `A` INNER JOIN `B`\n
\n\n┌────────┐\n│ A ┌───┼────┐\n│ │ ∩ │ │\n└────┼───┘ B │\n └────────┘\n
\n\nJoin | \nWhat | \n
---|---|
Inner join | \n∩ | \n
Left outer join | \nA + ∩ | \n
Right outer join | \n∩ + B | \n
Full outer join | \nA + ∩ + B | \n
import { Component, Prop, State } from '@stencil/core'\n\n@Component({\n tag: 'my-component',\n styleUrl: 'my-component.scss'\n})\nexport class MyComponent {\n @Prop() name: string\n @State() isVisible: boolean = true\n\n render () {\n return <p>I am {this.name}!</p>\n )\n }\n}\n
\n\n<my-component name='Groot' />\n
\n\nThat’s the same example in the Readme, that’s as simple as you can get! Just use <my-component>
like you would use any other HTML tag.
export class MyComponent {\n render () {\n return (\n <input\n onChange={(event: UIEvent) => this.inputChanged(event)}\n />\n )\n }\n\n inputChanged (event) {\n console.log('input changed:', event.target.value)\n }\n}\n
\n\nStencil uses DOM events.
\n\nSee: Handling user input
\n\nrender () {\n return [\n <h1>Hello there</h1>,\n <p>This component returns multiple nodes</p>\n ]\n}\n
\n\nrender()
can return an array of elements.
export class MyComponent {\n @State() isVisible: boolean\n\n show () {\n this.isVisible = true\n }\n}\n
\n\nJust do assignments. You can’t do mutations though, see next section.
\n\n\n\nthis.names.push('Larry') // ⚠️\nthis.options.show = true // ⚠️\n
\n\nthis.names = [ ...this.names, 'Larry' ]\nthis.options = { ...this.options, show: true }\n
\n\nMutable operations such as push()
won’t work. You’ll need to assign a new copy.
See: Updating arrays
\n\n<my-component>\n <span>Hello, friends</span>\n</my-component>\n
\n\nrender() {\n return <h1><slot /></h1>\n}\n
\n\nYou can pass JSX/HTML as child elements. Use the slot
tag to use them inside your component.
See: Slots
\n\n<my-component>\n <p slot='my-header'>Hello</p>\n <p slot='my-footer'>Thanks</p>\n</my-component>\n
\n\nrender () {\n return <div>\n <header><slot name='my-header' /></header>\n <footer><slot name='my-footer' /></footer>\n </div>\n}\n
\n\nSee: Slots
\n\nEvent | \nDescription | \n
---|---|
componentWillLoad() | \n Before rendering | \n
componentDidLoad() | \n After rendering | \n
componentWillUpdate() | \n Before updating | \n
componentDidUpdate() | \n After updating | \n
componentDidUnload() | \n After unmounting | \n
See: Component lifecycle
\n\nexport class MyComponent {\n componentWillUpdate () {\n console.log('updating')\n }\n}\n
\n\nStencil is a compiler for web components made by the Ionic team. This guide targets Stencil v0.0.5.
", "description_html": "", "tags": null, "updated": "2019-05-08" },{ "id": "strftime", "title": "strftime format", "url": "/strftime", "category": "Others", "keywords": null, "content_html": "{% include common/strftime_format.md title=”strftime” %}
", "intro_html": "The strftime format is the standard date formatting for UNIX. It’s used in C, Ruby, and more.
", "description_html": "", "tags": ["Featurable"], "updated": "2017-11-27" },{ "id": "stylus", "title": "Stylus", "url": "/stylus", "category": "CSS", "keywords": null, "content_html": ".box {\n color: blue;\n\n .button {\n color: red;\n }\n}\n
\n\nStylus is a CSS pre-processor.
\n\nSee: stylus-lang.com
\n\n.box\n color: blue\n\n .button\n color: red\n
\n\nAlso works! The colon is optional, as well. This is typically the syntax used with Stylus documents.
\n\ncaps-type()\n text-transform: uppercase\n letter-spacing: 0.05em\n
\n\nh5\n caps-type()\n
\n\nSee Mixins below.
\n\nroyal-blue = #36a\n
\n\ndiv\n color: royal-blue\n
\n\nred-border()\n border: solid 2px red\n
\n\ndiv\n red-border()\n
\n\nSee: Mixins
\n\nborder-radius(n)\n -webkit-border-radius: n\n border-radius: n\n
\n\ndiv\n border-radius: 2px\n border-radius(2px)\n
\n\nMixins can be applied in two different ways.
\n\nborder-radius(n = 2px)\n -webkit-border-radius: n\n
\n\nmobile()\n @media (max-width: 480px)\n {block}\n
\n\n+mobile()\n width: 10px\n
\n\nSee: Block mixins
\n\nshadow(offset-x, args...)\n box-shadow: offset-x args\n margin-top: offset-x\n
\n\n#login\n shadow: 1px 2px 5px #eee\n
\n\nSee: Rest params
\n\nadd(a, b)\n a + b\n
\n\nbody\n padding: add(10px, 5)\n
\n\nSee: Functions
\n\nadd(a, b = 2)\n a + b\n
\n\nSee: Argument defaults
\n\nshadow(x, y)\n x y (y * 1.5) #000\n
\n\n.button\n box-shadow: shadow(x: 2, y: 4)\n
\n\nSee: Named parameters
\n\nsizes()\n 8px 16px\n
\n\nsizes()[0] // → 8px\nsizes()[1] // → 16px\n
\n\n\n\nroyal-blue = #36a\nroyal-blue ?= #89f\n
\n\ndiv\n color: royal-blue // #36a\n
\n\n?=
will only set a variable if it’s previously unset.
.logo\n width: w = 150\n margin-left: -(w / 2)\n
\n\nSee: Property lookup
\n\n-{prefix}-border-radius: 2px\n
\n\nSee: Interpolation
\n\n#888 + 50% // → #c3c3c3 (lighten)\n#888 - 50% // → #444 (darken)\n#f00 + 50deg // → #ffd500 (hue)\n
\n\nn = 5px\n
\n\nfoo: (n)em\nfoo: (n * 5)%\n
\n\nlight-blue = #3bd\nname = 'blue'\nlookup('light-' + name)\n
\n\nSee: lookup
\n\nif color == blue\n display: block\nelse if true and true\n display: inline\nelse if 'hey' is not 'bye'\n display: flex\nelse\n display: none\n
\n\nAliases:
\n\n== | \n is | \n
!= | \n is not | \n
!= | \n isnt | \n
See: Conditionals
\n\nfont-size-1 = 10px\nfont-size-2 = 20px\nfont-size-3 = 30px\n\nfor i in 1..3\n .text-{i}\n font-size: lookup('font-size-' + i)\n
\n\nif ohnoes is defined\n color: blue\n
\n\nSee: is defined
\n\n0\nnull\nfalse\n''\n
\n\nif val is a 'string'\nif val is a 'ident'\nif #fff is a 'rgba' // → true\n
\n\nSee: Instance check
\n\nalpha(#fff) //→ 1\nalpha(rgba(0, 0, 0, 0.2)) //→ 0.2\n
\n\ndark(black) //→ true\nlight(black) //→ false\n
\n\nhue(#0a0) //→ 50deg\nsaturation(#f00) //→ 100%\nlightness(#f00) //→ 50%\nluminosity(#f00) //→ 0.2126\n
\n\nhue(#0a0, 0deg)\nsaturation(#f00, 50%)\nlightness(#f00)\n
\n\nlighten(color, 10%)\ndarken(color, 10%)\nsaturate(color, 10%)\ndesaturate(color, 10%)\ninvert(color)\n
\n\ntint(color, 50%) // mix with white\nshade(color, 50%) // mix with black\n
\n\nunquote(string)\n
\n\nSee: Built-in functions
\n\nwidth: image-size('tux.png')[0]\nheight: image-size('tux.png')[1]\n
\n\nReturns the width and height of a given image.
\n\nSee: image-size
\n\nsize($width)\n +cache('w' + $width)\n width: $width\n.a { size: 10px }\n.b { size: 10px }\n
\n\n// yields: .a, b { width: 10px }\n
\n\nApplies its contents to the given selector on the first call, but would @extend the first call’s selector at the second call with the same params.
\n\nSee: cache
\n\ngradient(color)\n add-property('background-image', linear-gradient(top, color, darken(color, 20%)))\n color\n
\n\nbody\n background: gradient(red)\n
\n\nSee: add-property
\n\n'-webkit-gradient(%s, %s, %s)' % (linear (0 0) (0 100%))\n// → -webkit-gradient(linear, 0 0, 0 100%)\n
\n\ns(\"rgba(0, 0, 0, %s)\", 0.3)\n
\n\nSee: s
\n\nbackground: embedurl('logo.png')\n// → background: url(\"data:image/png;base64,…\")\n
\n\nSee: embedurl
", "intro_html": "", "description_html": "", "tags": ["Featurable"], "updated": "2017-10-30" },{ "id": "sublime-text", "title": "Sublime Text", "url": "/sublime-text", "category": "Apps", "keywords": null, "content_html": "⌘ D | \n select current word (repeat to include next instance of word) | \n
⌘ L | \n select current line (repeat to include next line) | \n
⌘ ⇧ L | \n split selection into multiple lines | \n
⌘ ⇧ A | \n select text inside tag (repeat to expand) | \n
Ctrl ⇧ M | \n select to curly or angle brackets (repeat to expand) | \n
Replace ⌘ with Ctrl on Windows and Linux.
\n\n⌘ Alt [ | \n fold closest block | \n
⌘ Alt ] | \n unfold closest block | \n
⌘ K ⌘ 1 | \n fold all first level code blocks | \n
⌘ K ⌘ 2 | \n fold all second level code blocks | \n
⌘ K ⌘ 3 (etc) | \n fold all third level code blocks (etc) | \n
⌘ K ⌘ T | \n fold all HTML attributes | \n
⌘ K ⌘ 0 | \n unfold everything | \n
⌘ ⇧ D | \n duplicate current line/selection | \n
⌘ ⇧ K | \n delete current line/selection | \n
⌘ P | \n goto anything | \n
⌘ G | \n goto line number | \n
⌘ R | \n goto symbol | \n
⌘ P, : | \n goto line number (enter number after : ) | \n
⌘ P, # | \n goto and list fuzzy-matches of string (enter characters after # ) | \n
⌘ P, @ | \n goto and list symbol (begin typing symbol name after @ ) | \n
$ subl .\n$ subl README.md\n
\n\nUse subl
to open files in Sublime from the terminal.
res: {\n // The HTTP Status Code (see: httpstatuses.com for definitions on HTTP status codes)\n status: 202,\n // True when res.status is 2xx\n ok: true,\n // True when res.status is 4xx or 5xx\n error: false,\n // True when res.status is 4xx\n clientError: false,\n // True when res.status is 5xx\n serverError: false,\n\n // True when res.status == 202\n accepted: true,\n // True when res.status == 204 || res.status == 1223 \n noContent: false,\n // True when res.status == 400\n badRequest: false,\n // True when res.status == 401\n unauthorized: false,\n // True when res.status == 406\n notAcceptable: false,\n // True when res.status == 404\n notFound: false,\n // True when res.status == 403\n forbidden: false,\n\n // Unparsed response text\n text: '{\"user\":{\"username\":\"JohnDoe\",\"role\":\"admin\"}}'\n\n // Parsed response text (only if response is 'application/json' or 'application/x-www-form-urlencoded'\n body: {\n // Example of parsed object from res.text\n user: {\n username: 'JohnDoe',\n role: 'admin'\n }\n }\n\n // The content-type (parsed from headers)\n type: 'application/json'\n // The charset (parsed from headers)\n charset: 'UTF-8'\n // Header object with each header field as a property\n headers: {\n 'content-type': 'application/json; charset=UTF-8',\n ...\n }\n}\n
",
"intro_html": "",
"description_html": "",
"tags": ["WIP"],
"updated": "2018-04-21"
},{
"id": "tabular",
"title": "Tabular",
"url": "/tabular",
"category": "Vim",
"keywords": null,
"content_html": ":Tab /|\n
\n\n| Fruit | Color |\n| ----- | ----- |\n| Apple | Red |\n| Banana | Yellow |\n| Kiwi | Green |\n
\n\n:Tab /=\n
\n\ntitle = \"Hello\"\nsrc = \"image.jpg\"\nwidth = 640\n
\n\n:Tab /:\\zs/l0l1\n
\n\ntitle: \"Hello world\"\ndescription: \"This is a description\"\nsrc: \"image.jpg\"\nheight: 320\nwidth: 640\n
\n\n:Tab /:\n
\n\ntitle : My picture\nsrc : img.jpg\n
\n\n:Tab /:/r0\n
\n\ntitle:My picture\n src: img.jpg\n
\n\n:Tab /:\\zs\n
\n\ntitle: My picture\nsrc: img.jpg\n
\n\nThe \\zs
atom will exclude the :
from the search match.
:Tab /:/r1c1l0\n
\n\ntitle : My picture\n src : img.jpg\n
\n\nr1
– Right align with 1 spacec1
– Center align the comma with 1 spacel0
– Left align with 0 spaces:Tab /^[^,]*\\zs,/r0\n
\n\nabc,hello\n c,hi there\n a,yo\n
\n\nSpecifier | \nDescription | \n
---|---|
r1c1l0 | \n multiple specifiers, one per column (the separator counts as a column) | \n
lN | \n Left-align (with N spaces padding) | \n
rN | \n Right-align (with N spaces padding) | \n
cN | \n Center-align (with N spaces padding) | \n
Tabular is a Vim script for text alignment.
", "description_html": "", "tags": null, "updated": "2017-10-11" },{ "id": "tape", "title": "Tape", "url": "/tape", "category": "JavaScript libraries", "keywords": null, "content_html": "test('things', (t) => {\n t.plan(1)\n\n t.equal('actual', 'expected')\n t.equal('actual', 'expected', 'should be equal') // messages are optional\n\n t.end(err)\n t.fail('msg')\n t.pass('msg')\n t.timeoutAfter(2000)\n t.skip('msg')\n\n t.ok(value, 'is truthy')\n t.notOk(value, 'is falsy')\n t.error(err, 'is falsy (print err.message)')\n\n t.equal(actual, expected, 'is equal')\n t.notEqual\n\n t.deepEqual(actual, expected, 'is equal (use node's deepEqual)')\n t.notDeepEqual\n\n t.looseEqual(actual, expected, 'is equal (use node's deepEqual with ==)')\n t.notLooseEqual\n\n t.throws(fn, /FooError/)\n t.throws(fn, FooError /* class */)\n t.doesNotThrow\n\n t.comment('message')\n})\n
\n\ntest.only((t) => { ... })\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "textile",
"title": "Textile",
"url": "/textile",
"category": "Markup",
"keywords": null,
"content_html": "Code | \nDescription | \n
---|---|
_em_ | \n \n |
*strong* | \n \n |
__bold-italic__ | \n \n |
@code@ | \n \n |
??citation?? | \n \n |
-strikethrough- | \n \n |
+insertion+ | \n \n |
%span% | \n HTML tag | \n
%{color:red}formatting% | \n CSS styles | \n
h1. Header 1\n
\n\nh2. Header 2\n
\n\nbq. Blockquote\n
\n\np(classname). Class.\n
\n\np(#id). ID.\n
\n\n## ordered list\n
\n\n* unordered list\n
\n\nCode | \nDescription | \n
---|---|
\"Hypertext\":index.html | \n Link | \n
\"Text link\":link [link]http://link.com | \n Link via reference | \n
Code | \nDescription | \n
---|---|
!image.jpg! | \n Image | \n
!image.jpg(title text)! | \n \n |
!image.jpg!:link.html | \n \n |
!>right.jpg! | \n \n |
<pre>\nI am <b>very serious.</b> -- this\nwill get escaped.\n</pre>\n
\n\nLine breaks.\nJust break the lines.\n
\n\none(TM), two(R), three(C).\n
\n\n--\n
\n\nFootnotes[1].\n
\n\nfn1. Something.\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2017-09-20"
},{
"id": "tig",
"title": "Tig",
"url": "/tig",
"category": "Git",
"keywords": null,
"content_html": "# MacOS + Homebrew\n$ brew install tig --HEAD\n
\n\n# Ubuntu\n$ sudo apt install tig\n
\n\nCommand | \nDescription | \n
---|---|
tig | \n \n |
tig status | \n Status | \n
tig blame FILE | \n Blame | \n
tig master | \n Show a branch | \n
tig test..master | \n Show difference between two branches | \n
tig FILE | \n Show history of file | \n
tig v0.0.3:README | \n Show contents of file in a specific revision | \n
You can substitute git log
→ tig
.
m | \n Main view | \n
s | \n Status | \n
t | \n Tree (files) | \n
y | \n Stash view | \n
g | \n Grep | \n
h | \n Help | \n
Shortcut | \nDescription | \n
---|---|
j k | \n Up/down | \n
J K | \n Next/previous | \n
< | \n Back | \n
R | \n Refresh | \n
q | \n Close | \n
Q | \n Close all | \n
^N | \n Next on parent view | \n
^P | \n Previous on parent view | \n
m
- Main viewD | \n Toggle date display modes | \n
A | \n Toggle author display modes | \n
X | \n Toggle commit sha | \n
C | \n Cherry pick a commit | \n
s
- Stage viewu | \n Stage/unstage file or chunk | \n
! | \n Revert file or chunk | \n
C | \n Commit | \n
M | \n Merge | \n
1 | \n Stage line | \n
[ ] | \n Increase/decrease the diff context | \n
h
- Branch viewi | \n Change sort header | \n
h
- Blame view, | \n Parent commit | \n
$ tmux\n -u # UTF8 mode\n -S ~/.tmux.socket\n
\n\n$ tmux new\n$ tmux new -s session_name\n\n$ tmux attach # Default session\n$ tmux attach -t session_name\n\n$ tmux switch -t session_name\n\n$ tmux ls # List sessions\n\n$ tmux detach\n
\n\n$ tmux new-window\n
\n\nC-b ?\n
\n\nC-b [ # Enter scroll mode then press up and down\n
\n\nC-b [ # 1. Enter scroll mode first.\nSpace # 2. Start selecting and move around.\nEnter # 3. Press enter to copy.\nC-b ] # Paste\n
\n\nC-b % # vert\nC-b \" # horiz\nC-b hkjl # navigation\nC-b HJKL # resize\nC-b o # next window\nC-b q # show pane numbers\nC-b x # close pane\n\nC-b { or } # move windows around\n
\n\nC-b c # New window\nC-b 1 # Go to window 1\nC-b n # Go to next window\nC-b p # Go to previous window\nC-b w # List all window\n
\n\nC-b d # Detach\nC-b ( ) # Switch through sessions\n$ tmux attach\n
\n\nC-b t # Time\n
\n\nsetw -g window-status-format `#[fg=8,bg=default]#I`\n
\n\nSee message-command-style
in the man page.
#[fg=1] | \n standard color | \n
#[fg=yellow] | \n yellow | \n
#[bold] | \n bold | \n
#[fg=colour240] | \n 256 color | \n
#[fg=default] | \n default | \n
#[fg=1,bg=2] | \n combinations | \n
#[default] | \n reset | \n
black
red
green
yellow
blue
magenta
cyan
white
brightred
(and so on)colour0
… colour255
#333
(rgb hex)bold
underscore
blink
noreverse
hidden
dim
italics
#(date) | \n shell command | \n
#I | \n window index | \n
#S | \n session name | \n
#W | \n window name | \n
#F | \n window flags | \n
#H | \n Hostname | \n
#h | \n Hostname, short | \n
#D | \n pane id | \n
#P | \n pane index | \n
#T | \n pane title | \n
set -g status-justify [left|centre|right]\nset -g status-left '...'\n\nsetw -g window-status-style\nsetw -g window-status-activity-style\nsetw -g window-status-bell-style\nsetw -g window-status-content-style\nsetw -g window-status-current-style\nsetw -g window-status-last-style\n\nsetw -g window-status-format\nsetw -g window-status-current-format\n\nsetw -g window-status-separator\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "tomdoc",
"title": "Tomdoc",
"url": "/tomdoc",
"category": "Markup",
"keywords": null,
"content_html": "# Public: Duplicate some text an arbitrary number of times.\n#\n# text - The String to be duplicated.\n# count - The Integer number of times to duplicate the text.\n#\n# Examples\n#\n# multiplex('Tom', 4)\n# # => 'TomTomTomTom'\n#\n# Returns the duplicated String.\ndef multiplex(text, count)\n text * count\nend\n
\n\nSee tomdoc.org.
\n\nDeprecated
Internal
Public
# options - The Hash options used to refine the selection (default: {}):\n# :color - The String color to restrict by (optional).\n# :weight - The Float weight to restrict by. The weight should\n# be specified in grams (optional).\n
\n\n# Yields the Integer index of the iteration.\n
\n\n# Returns the duplicated String.\n
\n\n# Returns nothing.\n
\n\n# Raises Errno::ENOENT if the file can't be found.\n
\n\n# Returns something else and this is a wrapped\n# multi-line comment.\n
\n\n# Signature\n#\n# find_by_<field>[_and_<field>...](args)\n#\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "top",
"title": "top",
"url": "/top",
"category": "CLI",
"keywords": null,
"content_html": "Shortcut | \nDescription | \n
---|---|
h | \n shows help | \n
q | \n quits the program | \n
m | \n switches memory view | \n
k | \n kills process | \n
Shift+p | \n sorts by CPU usage | \n
Shift+m | \n sorts by memory usage | \n
Shift+r | \n reverses sorting | \n
Shift+l | \n searches for string | \n
o | \n adds a filter | \n
= | \n clears filters | \n
See the processes in your Unix machine.
", "description_html": "", "tags": null, "updated": "2020-01-01" },{ "id": "travis", "title": "Travis.yml", "url": "/travis", "category": "Devops", "keywords": null, "content_html": "language: node_js\nnode_js:\n - '4'\n
\n\nDefaults install to npm install
, and defaults test to npm test
.
language: ruby\nrvm:\n - 2.0.0\n - 1.9.3\n - 1.8.7\n
\n\nDefaults install to bundle install
, defaults test to rake
.
Lifecycle | \n
---|
before_install | \n
install | \n
before_script | \n
script | \n
after_success or after_failure | \n
after_script | \n
before_deploy (optional) | \n
deploy (optional) | \n
after_deploy (optional) | \n
branches:\n except: ['..']\n only: ['master']\n
\n\nenv:\n - 'rack=master'\n - 'rack=1.3.4'\n
\n\nscript: make test\nbefore_script: make pretest\nafter_script: make clean\n\nbefore_script:\n - make pretest1\n - make pretest2\n
\n\nbranches:\n except:\n - legacy\n\n only:\n - gh-pages\n - /^deploy/\n
\n\nbefore_install:\n - sudo apt-get update -q\n - sudo apt-get install gcc-4.8 -y\n
\n\nhttps://docs.travis-ci.com/user/installing-dependencies/
\n\ngemfile:\n - gemfiles/Gemfile.rails-2.3.x\n - gemfiles/Gemfile.rails-3.0.x\n
\n\nQuick reference for Travis CI yaml configuration. See official documentation.
", "description_html": "", "tags": null, "updated": null },{ "id": "typescript", "title": "TypeScript", "url": "/typescript", "category": "JavaScript libraries", "keywords": null, "content_html": "TypeScript is just like ES2015 with type-checking. All ES2015 (classes, etc) should work.
\n\nany\nvoid\n\nboolean\nnumber\nstring\n\nnull\nundefined\n\nstring[] /* or Array<string> */\n[string, number] /* tuple */\n\nstring | null | undefined /* union */\n\nnever /* unreachable */\n
\n\nenum Color {Red, Green, Blue = 4}\nlet c: Color = Color.Green\n
\n\nlet isDone: boolean\nlet isDone: boolean = false\n
\n\nfunction add (a: number, b: number): number {\n return a + b\n}\n\n// Return type is optional\nfunction add (a: number, b: number) { ... }\n
\n\nlet len: number = (input as string).length\nlet len: number = (<string> input).length /* not allowed in JSX */\n
\n\nfunction object(this: {a: number, b: number}, a: number, b: number) {\n this.a = a;\n this.b = b;\n return this;\n}\n\n// this is used only for type declaration\nlet a = object(1,2);\n// a has type {a: number, b: number}\n
\n\nfunction printLabel (options: { label: string }) {\n console.log(options.label)\n}\n\n// Note the semicolon\nfunction getUser (): { name: string; age?: number } {\n}\n
\n\ninterface LabelOptions {\n label: string\n}\n\nfunction printLabel(options: LabelOptions) { ... }\n
\n\ninterface User {\n name: string,\n age?: number\n}\n
\n\ninterface User {\n readonly name: string\n}\n
\n\n{\n [key: string]: Object[]\n}\n
\n\ntype Name = string | string[]\n
\n\ninterface User { ... }\n\nfunction getUser(callback: (user: User) => any) { callback({...}) }\n\ngetUser(function (user: User) { ... })\n
\n\nclass Point {\n x: number\n y: number\n static instances = 0\n constructor(x: number, y: number) {\n this.x = x\n this.y = y\n }\n}\n
\n\nclass Point {...}\n\nclass Point3D extends Point {...}\n\ninterface Colored {...}\n\nclass Pixel extends Point implements Colored {...}\n
\n\nclass Point {\n static instances = 0;\n constructor(\n public x: number,\n public y: number,\n ){}\n}\n
\n\nclass Point {\n public someUselessValue!: number;\n ...\n}\n
\n\nclass Greeter<T> {\n greeting: T\n constructor(message: T) {\n this.greeting = message\n }\n}\n\nlet greeter = new Greeter<string>('Hello, world')\n
\n\nexport interface User { ... }\n
\n\ninterface Building {\n room: {\n door: string,\n walls: string[],\n };\n}\n\ntype Walls = Building['room']['walls']; // string[]\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "ubuntu",
"title": "Ubuntu",
"url": "/ubuntu",
"category": "Others",
"keywords": null,
"content_html": "aptitude search mysql # Look for something\ndpkg -S `which tsclient` # What package does it belong to?\ndpkg -L aria2c # What does this package provide?\ndpkg -i *.deb # Install a deb file\ndpkg -s nodejs # Show info\n\ndpkg --get-selections # list installed packages\n
\n\n/var/cache/apt/archives\n
\n\nservice --status-all\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "umdjs",
"title": "Universal JS module loader",
"url": "/umdjs",
"category": "JavaScript libraries",
"keywords": null,
"content_html": ";(function (root, factory) {\n\n if (typeof define === 'function' && define.amd) {\n define(['jquery'], factory);\n } else if (typeof exports === 'object') {\n module.exports = factory(require('jquery'));\n } else {\n root.YourModule = factory(root.jQuery);\n }\n\n}(this, function (jquery) {\n return {};\n}));\n
\n\n;(function (root, factory) {\n\n if (typeof define === 'function' && define.amd) {\n define(factory);\n } else if (typeof exports === 'object') {\n module.exports = factory();\n } else {\n root.YourModule = factory();\n }\n\n}(this, function () {\n return {};\n}));\n
\n\n(function (root, factory) {\n\n if (typeof define === 'function' && define.amd) {\n define(['exports', 'jquery'], factory);\n } else if (typeof exports === 'object') {\n factory(exports, require('jquery'));\n } else {\n factory((root.YourModule = {}), root.jQuery);\n }\n\n}(this, function (exports, jQuery) {\n exports.action = function () {};\n}));\n
\n\n// Use it like so:\n_.str.trim(\"hey\");\n_s.trim(\"hey\");\n\n// Unless you do:\n_.mixin(_.string.exports());\n\n// So you can:\n_.trim(\"hey\");\n_(\"hey\").trim();\n
\n\n_.truncate(\"Hello world\", 4) // => \"Hell...\"\n_.prune(\"Hello world\", 5) // => \"Hello...\"\n\n_.trim(\" foo \") // => \"foo\"\n_.trim(\"-foo-\", '-') // => \"foo\"\n_.ltrim\n_.rtrim\n
\n\n_.numberFormat(1000, 2) // => \"1,000.00\"\n
\n\n_.capitalize(\"foo bar\") // => \"Foo Bar\"\n_.humanize(\"hey-there foo\") // => \"Hey there foo\"\n_.titleize('My name is hi') // => \"My Name Is Hi\"\n\n_.dasherize('MozTransform') // => \"-moz-transform\"\n_.underscored('MozTransform') // => \"moz_transform\"\n_.classify('-moz-transform') // => \"MozTransform\"\n_.camelize('moz_transform') // => \"MozTransform\"\n\n_.slugify(\"hey there\") // => \"hey-there\"\n\n_.swapCase(\"hELLO\") // => \"Hello\"\n
\n\n_.startsWith('image.gif', 'image') // => true\n_.endsWith('image.gif', '.gif') // => true\n_.isBlank(\" \") // => true (also for \"\\n\", \"\")\n
\n\n_.escapeHTML(\"<div>\")\n_.unescapeHTML(\"<div>\")\n_.stripTags(\"<div>hi</div>\")\n
\n\n_.quote(\"hi\", '\"') // => '\"hi\"'\n_.unquote('\"hi\"') // => \"hi\"\n
\n\n_.lines(\"hi\\nthere\") // => [\"hi\",\"there\"]\n_.words(\"hi there you\") // => [\"hi\",\"there\",\"you\"]\n
\n\n_.sprintf(\"%.1f\", 1.17)\n
\n\n_.pad(\"1\", 8) // => \" 1\"\n_.pad(\"1\", 8, \"0\") // => \"00000001\"\n_.pad(\"1\", 8, \" \", \"right\") // => \"1 \"\n_.pad(\"1\", 8, \" \", \"both\") // => \" 1 \"\n\n_.lpad(..) // same as _.pad(.., 'left')\n_.rpad(..) // same as _.pad(.., 'right')\n_.lrpad(..) // same as _.pad(.., 'both')\n
\n\n✈ \\u2708 airplane\n❄ \\u2744 snowflake\n⚑ \\u2691 flag\n☯ \\u262f yinyang\n♞ \\u265e horse\n☀ \\u2600 rays\n⚠ \\u26a0 warning\n\n★ star\n☆ star2\n\n⚐ \\u2690 flag\n⚑ \\u2691 flag\n
\n\n• \\u2022\n· \\u00b7\n┄ \\u2504\n— \\u2014 (mdash)\n– \\u2013 (ndash)\n◦ \\u25e6 circle\n
\n\n✓ \\u2713 check\n✕ \\u2715\n✗ \\u2717 x mark\n✘ \\u2718 x mark bold\n❏ \\u274f checkbox\n× times\n
\n\n ◜◠◝◞◡◟\n ❘❙❚\n
\n\n▲\n▼\n▶\n\n⬅ \\u2b05\n⬆ \\u2b06\n⬇ \\u2b07\n\n◢\n◣\n◤\n◥\n\n« «\n» »\n‹ ‹\n› ›\n• ·\n\n⌘ – ⌘ – ⌘ – Command Key\n⌥ – ⌥ – ⌥ – Option Key\n⇧ – ⇧ – ⇧ – Shift Key\n⎋ – ⎋ – ⎋ – ESC Key\n⇪ – ⇪ – ⇪ – Capslock\n⏎ – ⏎ – ⏎ – Return\n⌫ – ⌫ – ⌫ – Delete / Backspace\n\n▸ \\u25b8 right arrow\n▹\n\n◇ \\u25c7\n◆\n\n◐\n◑\n◒\n◓\n\n\n♠ \\u2660\n♣ \\u2663\n♥ \\u2665\n♦ \\u2666\n\n\n✂ scissors\nℹ information ℹ\n♡ heart ♡\n⚙ cog or gear ⚙\n✉ envelope ✉\n✎ pencil ✎\n
\n\n\"x\".charCodeAt(0)\n\"x\".charCodeAt(0).toString(16)\n\nhttp://www.danshort.com/HTMLentities/index.php?w=dingb\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "vagrant",
"title": "Vagrant",
"url": "/vagrant",
"category": "Devops",
"keywords": null,
"content_html": "Add some base boxes:
\n\nvagrant box add precise64 http://files.vagrantup.com/precise64.box\n
\n\nWork it:
\n\nmkdir test_box\ncd test_box\nvagrant init precise64\n
\n\nRun it:
\n\nvagrant up\nvagrant ssh\n
\n\nTo stop, use one of the following:
\n\nvagrant ssh # then: sudo shutdown -h now\nvagrant suspend\nvagrant destroy # !!\n
\n\nVagrant lets you build isolated virtual environments for your apps.
", "description_html": "", "tags": null, "updated": null },{ "id": "vagrantfile", "title": "Vagrantfile", "url": "/vagrantfile", "category": "Devops", "keywords": null, "content_html": "Vagrant.configure(\"2\") do |config|\n # All Vagrant configuration is done here. The most common configuration\n # options are documented and commented below. For a complete reference,\n # please see the online documentation at vagrantup.com.\n\n # Every Vagrant virtual environment requires a box to build off of.\n config.vm.box = \"precise64\"\n\n # The url from where the 'config.vm.box' box will be fetched if it\n # doesn't already exist on the user's system.\n # config.vm.box_url = \"http://domain.com/path/to/above.box\"\n\n # Create a forwarded port mapping which allows access to a specific port\n # within the machine from a port on the host machine. In the example below,\n # accessing \"localhost:8080\" will access port 80 on the guest machine.\n # config.vm.network :forwarded_port, guest: 80, host: 8080\n\n # Create a private network, which allows host-only access to the machine\n # using a specific IP.\n # config.vm.network :private_network, ip: \"192.168.33.10\"\n\n # Create a public network, which generally matched to bridged network.\n # Bridged networks make the machine appear as another physical device on\n # your network.\n # config.vm.network :public_network\n\n # If true, then any SSH connections made will enable agent forwarding.\n # Default value: false\n # config.ssh.forward_agent = true\n\n # Share an additional folder to the guest VM. The first argument is\n # the path on the host to the actual folder. The second argument is\n # the path on the guest to mount the folder. And the optional third\n # argument is a set of non-required options.\n # config.vm.synced_folder \"../data\", \"/vagrant_data\"\n\n # Provider-specific configuration so you can fine-tune various\n # backing providers for Vagrant. These expose provider-specific options.\n # Example for VirtualBox:\n #\n # config.vm.provider :virtualbox do |vb|\n # # Don't boot with headless mode\n # vb.gui = true\n #\n # # Use VBoxManage to customize the VM. For example to change memory:\n # vb.customize [\"modifyvm\", :id, \"--memory\", \"1024\"]\n # end\n #\n # View the documentation for the provider you're using for more\n # information on available options.\n\n # Enable provisioning with Puppet stand alone. Puppet manifests\n # are contained in a directory path relative to this Vagrantfile.\n # You will need to create the manifests directory and a manifest in\n # the file precise64.pp in the manifests_path directory.\n #\n # An example Puppet manifest to provision the message of the day:\n #\n # # group { \"puppet\":\n # # ensure => \"present\",\n # # }\n # #\n # # File { owner => 0, group => 0, mode => 0644 }\n # #\n # # file { '/etc/motd':\n # # content => \"Welcome to your Vagrant-built virtual machine!\n # # Managed by Puppet.\\n\"\n # # }\n #\n # config.vm.provision :puppet do |puppet|\n # puppet.manifests_path = \"manifests\"\n # puppet.manifest_file = \"init.pp\"\n # end\n\n # Enable provisioning with chef solo, specifying a cookbooks path, roles\n # path, and data_bags path (all relative to this Vagrantfile), and adding\n # some recipes and/or roles.\n #\n # config.vm.provision :chef_solo do |chef|\n # chef.cookbooks_path = \"../my-recipes/cookbooks\"\n # chef.roles_path = \"../my-recipes/roles\"\n # chef.data_bags_path = \"../my-recipes/data_bags\"\n # chef.add_recipe \"mysql\"\n # chef.add_role \"web\"\n #\n # # You may also specify custom JSON attributes:\n # chef.json = { :mysql_password => \"foo\" }\n # end\n\n # Enable provisioning with chef server, specifying the chef server URL,\n # and the path to the validation key (relative to this Vagrantfile).\n #\n # The Opscode Platform uses HTTPS. Substitute your organization for\n # ORGNAME in the URL and validation key.\n #\n # If you have your own Chef Server, use the appropriate URL, which may be\n # HTTP instead of HTTPS depending on your configuration. Also change the\n # validation key to validation.pem.\n #\n # config.vm.provision :chef_client do |chef|\n # chef.chef_server_url = \"https://api.opscode.com/organizations/ORGNAME\"\n # chef.validation_key_path = \"ORGNAME-validator.pem\"\n # end\n #\n # If you're using the Opscode platform, your validator client is\n # ORGNAME-validator, replacing ORGNAME with your organization name.\n #\n # If you have your own Chef Server, the default validation client name is\n # chef-validator, unless you changed the configuration.\n #\n # chef.validation_client_name = \"ORGNAME-validator\"\nend\n
\n\nUse | \nCP | \nWP | \nUtil | \n
---|---|---|---|
Anti-armor/shield | \nMyth | \nBonesaw, Tension | \n\n |
Stacking damage | \nMyth | \nBreak | \n\n |
Lifesteal | \nEve | \nSerpent, Shiv | \n\n |
Raw power | \nShatterglass | \nSorrowblade | \n\n |
Burst damage | \nAftershock | \nTension | \n\n |
Attack speed | \nAC | \nTornado, Break | \n\n |
Critical | \n\n | Monocle | \n\n |
Auto-attack damage | \nAC, Aftershock | \neverything | \nStormcrown | \n
Cooldown | \nClockwork, Aftershock | \nSpellsword | \nStormcrown, Contraption, Nullwave, Halcyon Boots | \n
Slow | \nFrostburn | \n\n | Shiversteel | \n
Reflex block | \n\n | \n | Aegis (self/shield) Crucible (team/HP) | \n
Ability repeat | \nEcho | \n\n | \n |
Item | \nCost | \nCP | \nUse | \n
---|---|---|---|
AS: Aftershock | \n2400 | \n+35 cp | \nBasic dmg, atk speed +basic dmg after ability, +25% cooldown, +2.5 recharge | \n
EoH: Eve of Harvest | \n2600 | \n+55 cp | \nLifesteal +10% lifesteal, +250 energy, +5 recharge | \n
AC: Alternating Current | \n2800 | \n+60 cp | \nBasic dmg +basic dmg based on CP, +65% atk speed | \n
BM: Broken Myth | \n2150 | \n+70 cp | \nStack dmg +10% shield pierce, stacking dmg | \n
FB: Frostburn | \n2600 | \n+100 cp | \nSlow slow for 1.5s at (10% + 1% per 10CP) | \n
SG: Shatterglass | \n3000 | \n+150 cp | \nRaw power - | \n
CW: Clockwork | \n2500 | \n+30% cp | \nCooldown +40% cooldown, +250 energy, +7.5 recharge | \n
Echo | \n2500? | \n\n | Ability repeat +250 energy, +4 recharge | \n
Item | \nCost | \nWP | \nOther | \n
---|---|---|---|
TT: Tornado Trigger | \n2600 | \n\n | Atk speed +75% atk speed, +20% crit change, +20% crit dmg | \n
BS: Bonesaw | \n2700 | \n+15 wp | \nArmor shred stacking armor shred | \n
TB: Tension Bow | \n2300 | \n+45 wp | \nBonus dmg bonus dmg every 6s, +8% armor pierce | \n
TM: Tyrant’s Monocle | \n2750 | \n+50 wp | \nCrit +40% crit chance, +20% crit dmg | \n
BP: Breaking Point | \n2600 | \n+55 wp | \nStacking dmg stacking weapon dmg, +35% atk speed | \n
SM: Serpent Mask | \n2800 | \n+85 wp | \nLifesteal stacking lifesteal, +10% lifesteal | \n
SB: Sorrowblade | \n3100 | \n+150 wp | \nRaw power - | \n
PS: Poisoned Shiv | \n2250 | \n+30 wp | \nMortal wounds mortal wounds for 2s, +10% lifesteal, +30% atk speed | \n
SS: Spellsword | \n? | \n+90 wp | \nCooldown ? | \n
Item | \nCost | \nHP | \nUse | \n
---|---|---|---|
Halcyon Chargers | \n2300 | \n+200 hp | \n👟 Boots +15% cooldown, +250 energy, +4 recharge | \n
Stormcrown | \n2200 | \n+200 hp | \n🔴 Bonus dmg +30% cooldown, +4 recharge, bonus true damage | \n
Journey Boots | \n1900 | \n+250 hp | \n👟 Boots damaging heroes resets sprint cooldown | \n
Nullwave Gauntlet (2.0) | \n2250 | \n+300 hp | \n😶 Item silence +25% cooldown | \n
Contraption | \n2100 | \n+350 hp | \n👀 Vision traps/flares, +40% cooldown, +3 recharge | \n
Shiversteel | \n1450 | \n+500 hp | \n🐌 Slow active: slow targets | \n
War Treads | \n2500 | \n+600 hp | \n👟 Boots gives sprint to nearby teammates | \n
Item | \nCost | \nHP | \nArmor | \nShield | \nUse | \n
---|---|---|---|---|---|
Aegis | \n2250 | \n\n | +30 ar | \n+125 sh | \n✊Reflex block (self) | \n
Fountain of Renewal | \n2300 | \n+200 hp | \n+30 ar | \n+75 sh | \n❤ Heal allies | \n
Atlas Pauldron | \n1900 | \n\n | +85 ar | \n+35 sh | \n🐌 Slow target attack speed | \n
Metal Jacket | \n2100 | \n\n | +170 ar | \n+35 sh | \n\n |
Crucible | \n1850 | \n+600 hp | \n\n | \n | ✊ Reflex block (team) | \n
Slumbering Husk (2.0) | \n1600 | \n+400 hp | \n\n | \n | Fortification against burst damage | \n
Item | \nMovement speed | \nHP | \nSprint | \nUse | \n
---|---|---|---|---|
War Treads | \n+0.4 | \n+600 hp | \n2s (60s cooldown) incl. nearby teammates | \n HP, assist | \n
Halcyon Chargers | \n+0.5 | \n\n | 3s (50s cooldown) | \nEnergy | \n
Journey Boots | \n+0.6 | \n+250 hp | \n2s (60s cooldown) damaging resets cooldown | \n Gap close | \n
Just Beginning | \n1 | \n
Getting There | \n2 | \n
Rock Solid | \n3 | \n
Worthy Foe | \n4 | \n
Got Swagger | \n5 | \n
Credible Threat | \n6 | \n
The Hotness | \n7 | \n
Simply Amazing | \n8 | \n
Pinnacle of Awesome | \n9 | \n
Vainglorious | \n10 | \n
See: Skill tier names
\n\nShortcut | \nDescription | \n
---|---|
]c | \n Next difference | \n
[c | \n Previous difference | \n
Shortcut | \nDescription | \n
---|---|
do | \n Diff Obtain! Pull the changes to the current file. | \n
dp | \n Diff Put! Push the changes to the other file. | \n
:diffupdate | \n Re-scan the files for differences. | \n
ZQ | \n Quit without checking changes | \n
Shortcut | \nDescription | \n
---|---|
zo / zO | \n Open | \n
zc / zC | \n Close | \n
za / zA | \n Toggle | \n
zv | \n Open folds for this line | \n
zM | \n Close all | \n
zR | \n Open all | \n
zm | \n Fold more (foldlevel += 1) | \n
zr | \n Fold less (foldlevel -= 1) | \n
zx | \n Update folds | \n
Vim is a very efficient text editor. This reference was made for Vim 8.0.
", "description_html": "", "tags": null, "updated": "2018-12-06" },{ "id": "vim-digraphs", "title": "Vim digraphs", "url": "/vim-digraphs", "category": "Vim", "keywords": null, "content_html": "<Ctrl-K>OK\n
\n\n:dig\n:digraphs\n
\n\n℠ | \n™ | \n© | \n® | \n¶ | \n† | \n‡ | \n– | \n± | \n
SM | \nTM | \nCo | \nRg | \nPI | \n/- | \n/= | \n– | \n+- | \n
§ | \nµ | \n£ | \n¢ | \n¥ | \n¤ | \n
SE | \nMy | \n$$ | \nCt | \nYe | \nCu | \n
★ | \n☆ | \n♡ | \n◆ | \n◇ | \n
*2 | \n*1 | \ncH | \nDb | \nDw | \n
✓ | \n✗ | \n
OK | \nXX | \n
⋅ | \n· | \n○ | \n∙ | \n∘ | \n∴ | \n∵ | \n∶ | \n∷ | \n
.P | \n.M | \n0m | \nSb | \nOb | \n.: | \n:. | \n:R | \n:: | \n
⊙ | \n⊚ | \n◎ | \n□ | \n▪ | \n
0. | \n02 | \n0o | \nOS | \nsB | \n
ø | \n≃ | \n≅ | \n≥ | \n≤ | \n≡ | \n≮ | \n≯ | \n≠ | \n
o/ | \n?- | \n?= | \n>= | \n=< | \n=3 | \n!< | \n!> | \n!= | \n
√ | \n× | \n÷ | \n
RT root | \n/\\ times | \n-: divide | \n
⊂ | \n⊃ | \n∩ | \n∪ | \n
(C subset | \n)C superset | \n(U intersection | \n)U union | \n
¼ | \n½ | \n¾ | \n₃ | \n₂ | \n³ | \n² | \n
14 | \n12 | \n34 | \n3s | \n2s | \n3S | \n2S | \n
▲ | \n△ | \n▼ | \n▽ | \n
UT | \nuT | \nDt | \ndT | \n
▶ | \n▷ | \n◀ | \n◁ | \n
PR | \nTr | \nPL | \nTl | \n
» | \n« | \n〈 | \n〉 | \n‹ | \n› | \n
» | \n« | \n</ | \n/> | \n<1 | \n>1 | \n
← | \n→ | \n↑ | \n↓ | \n↕ | \n↔ | \n
<- | \n-> | \n-! | \n-v | \nUD | \n<> | \n
⇐ | \n⇒ | \n⇔ | \n
<= | \n=> | \n== | \n
:EasyAlign : \" preset characters (\\=:.,&#|)\n:EasyAlign |\n:EasyAlign \\ \" \\ means space\n
\n\n:EasyAlign /[:;]+/\n
\n\n:EasyAlign | \" align by 1st `|`\n:EasyAlign 3 | \" align by 3rd `|`\n:EasyAlign * | \" align by all `|`s\n
\n\n:EasyAlign * | l4r1\n\n l4 \" lN - left_margin\n r1 \" rN - right_margin\n \" spaces to the left/right of `|`\n ar \" a[lrc] - align\n \" align left/right/center\n dr \" d[lrc] - delimiter_align\n \" alignment of the delimiter itself\n
\n\n:EasyAlign * /[;:]+/ l3\n:EasyAlign*/[;:]+/l3\n
\n\n:EasyAlign = dr
(delimiter_align right)apple = 1\nbanana += apple\ncake ||= banana\n
\n\n:EasyAlign :
(for json or yaml)url: jdbc:mysql://localhost/test\ndatabase: test\n
\n\n:EasyAlign *|
(markdown tables)| `<Enter>` | right align |\n| `1` | on 1st occurrence |\n| `2` | on 2nd occurrence (and so on) |\n
\n\n{Visual} ⏎ | \n activate for selection | \n
ga {motion} | \n activate for motion/text object | \n
Then press options (if available), then a delimiter.
\n\n⏎ | \n Set alignment | \n
<ctrl-l> 4 ⏎ | \n Set left_margin (to the left of the delimiter) | \n
<ctrl-r> 4 ⏎ | \n Set right_margin | \n
↓ | \n no margin | \n
gaip
<ctrl-l>
8⏎
=
- puts 8 spaces before the equal sign:e doc/potion.txt\n:set ft=help\n:set ft=text\n
\n\nUse ft=help
to preview it, and ft=text
to edit it.
*ack.txt* Plugin that integrates ack with Vim\n\n==============================================================================\nUSAGE INSTRUCTIONS *ack-usage*\n\n:Ack[!] {pattern} *:Ack*\n\n Search recursively for {pattern}. See |:AckAdd|.\n Also see http://beyondgrep.com for more information.\n\nvim:tw=78:ts=8:ft=help:norl:\n
\n\nThis is a cheatsheet for writing Vim help files. See: :help help-writing
Code | \nDescription | \nExample | \n
---|---|---|
Inline items | \n\n | \n |
*tags* | \n Tags | \n\n |
|link-to-tags| | \n Links to tags | \n|:command| | \n
'vimoption' | \n Vim option | \n'textwidth' | \n
{code-text} | \n Code text | \n{Visual}gf | \n
<code-text> | \n Code text | \n<PageDown> | \n
`code-text` | \n Code text | \n`set fo=want` | \n
CTRL-X | \n Code text | \n\n |
Block items | \n\n | \n |
INTRODUCTION *tag* | \n Section header | \n\n |
Column heading~ | \n Highlighting | \n\n |
www.url.com | \n Web URL | \n\n |
===== | \n Separator | \n\n |
----- | \n Separator | \n\n |
*potion-usage*
|potion-usage|
^]
to jump to a tagExample: >\n xyz\n<\n
\n\nSurround with >
and <
characters
*potion.txt* functionality for the potion programming language\n
\n\nIt’s customary to start a file with a tag of the filename, plus a description.
\n\n==============================================================================\nCONTENTS *potion-contents*\n
\n\nStarts with ALL CAPS
, ends with *a-tag*
Using *Todo
and *Error
will highlight your notes.
\t*Todo something to do\n\t*Error something wrong\n
\n\nvim:tw=78:ts=8:ft=help:norl:\n
\n\n|rails-introduction| Introduction and Feature Summary\n|rails-commands| General Commands\n|rails-navigation| Navigation\n
\n\n 1.Intro...................................|ergonomic|\n 2.Note to use..............................|CAPSLOCK|\n 3.Insert Mode Remappings............|ergonomicInsert|\n
\n\nAuthor: Jack Hackness <captain@time.com> *xyz-author*\nLicense: Same terms as Vim itself (see |license|)\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": "2017-09-09"
},{
"id": "vim-rails",
"title": "Vim-rails",
"url": "/vim-rails",
"category": "Vim",
"keywords": null,
"content_html": ":A | \n alternate file (test) | \n
:R | \n related file (controller/view) | \n
. | \n:A | \n:R | \n
---|---|---|
Model | \ntest/models/ | \ndb/schema.rb | \n
Controller method | \ntest/controllers/ | \napp/views/ | \n
View template | \ntest/views/ | \napp/controllers | \n
Type :Rabbrev
for a full list.
Abbrev | \nExpansion | \n
---|---|
AC:: | \n ActionController | \n
AR:: | \n ActiveRecord | \n
AV:: | \n ActionView | \n
... | \n … | \n
logd( | \n logger.debug | \n
logi( | \n logger.info | \n
... | \n … | \n
Abbrev | \nExpansion | \n
---|---|
bt( | \n belongs_to | \n
hm( | \n has_many | \n
ho( | \n has_one | \n
habtm( | \n has_and_belongs_to_many | \n
Abbrev | \nExpansion | \n
---|---|
pa[ | \n params | \n
re( | \n redirect_to | \n
rp( | \n render partial: | \n
rst( | \n respond_to | \n
Abbrev | \nExpansion | \n
---|---|
dotiw | \n distance_of_time_in_words | \n
taiw | \n time_ago_in_words | \n
# from view => app/views/home/_foo_partial.haml\n :Rextract home/foo_partial\n\n# from model => app/models/concerns/foo_concern.rb\n :Rextract FooConcern\n
\n\n:Econtroller <file> # app/controllers/*_controller.rb\n:Ehelper # app/helpers/*_helper.rb\n:Emodel <file> # app/models/*.rb\n:Ejob <file> # app/jobs/*_job.rb\n:Emailer <file> # app/mailers/*.rb\n
\n\n:Emigration <file> # db/migrations/*.rb\n:Eschema # db/schema.rb\n
\n\n:Elib <file> # lib/*.rb\n:Elib # Gemfile\n:Etask <file> # lib/tasks/*.rake\n
\n\n:Estylesheet\n:Ejavascript\n
\n\n:Eview\n:Elayout\n
\n\n:Espec\n:Eunittest\n # test/{unit,models,helpers}/*_test.rb\n # spec/{unit,models,helpers}/*_spec.rb\n\n:Efunctionaltest\n # test/{functional,controllers,mailers}/*_test.rb\n # spec/{functional,controllers,mailers}/*_spec.rb\n\n:Eintegrationtest\n # test/integration/*_test.rb\n # spec/{features,requests,integration}/*_spec.rb\n # features/*.feature\n\n:Efixtures\n:Efunctionaltest\n
\n\n:Einitializer <file> # config/initializers/*.rb\n:Elocale # config/locales/*.yml\n:Eenvironment # application.rb\n:Eenvironment development # config/environments/*.rb\n
\n\n:Unite file\n:Unite file_rec/async:!\n:Unite tag\n:Unite buffer\n
\n\nfile/new
file/async
file_rec/async
file_rec/git
buffer
buffer_tab
(current tab only)tab
register
bookmark
source
Option | \nDescription | \n
---|---|
-start-insert | \n \n |
-no-quit | \n \n |
-winheight=10 | \n \n |
-quick-match | \n select by pressing asdf keys | \n
-winwidth=40 | \n use with vertical | \n
-no-split | \n open in current buffer | \n
-auto-preview | \n great for outline | \n
-vertical | \n open as sidebar | \n
-buffer-name=xxx -resume | \n resume the next time it’s called (faster) | \n
-input= | \n reset input (use with -resume) | \n
-unique | \n remove duplicates (eg, if using file_rec with file_mru ) | \n
Shortcut | \nDescription | \n
---|---|
:qa | \n Close all files | \n
:qa! | \n Close all files, abandon changes | \n
:w | \n Save | \n
:wq / :x | \n Save and close file | \n
:q | \n Close file | \n
:q! | \n Close file, abandon changes | \n
ZZ | \n Save and quit | \n
ZQ | \n Quit without checking changes | \n
Shortcut | \nDescription | \n
---|---|
h j k l | \n Arrow keys | \n
<C-U> / <C-D> | \n Half-page up/down | \n
<C-B> / <C-F> | \n Page up/down | \n
Shortcut | \nDescription | \n
---|---|
b / w | \n Previous/next word | \n
ge / e | \n Previous/next end of word | \n
Shortcut | \nDescription | \n
---|---|
0 (zero) | \n Start of line | \n
^ | \n Start of line (after whitespace) | \n
$ | \n End of line | \n
fc | \n Go forward to character c | \n
Fc | \n Go backward to character c | \n
Shortcut | \nDescription | \n
---|---|
gg | \n First line | \n
G | \n Last line | \n
:n | \n Go to line n | \n
nG | \n Go to line n | \n
Shortcut | \nDescription | \n
---|---|
zz | \n Center this line | \n
zt | \n Top this line | \n
zb | \n Bottom this line | \n
H | \n Move to top of screen | \n
M | \n Move to middle of screen | \n
L | \n Move to bottom of screen | \n
Shortcut | \nDescription | \n
---|---|
n | \n Next matching search pattern | \n
N | \n Previous match | \n
* | \n Next whole word under cursor | \n
# | \n Previous whole word under cursor | \n
Shortcut | \nDescription | \n
---|---|
:tabedit [file] | \n Edit file in a new tab | \n
:tabfind [file] | \n Open file if exists in new tab | \n
:tabclose | \n Close current tab | \n
:tabs | \n List all tabs | \n
:tabfirst | \n Go to first tab | \n
:tablast | \n Go to last tab | \n
:tabn | \n Go to next tab | \n
:tabp | \n Go to previous tab | \n
Shortcut | \nDescription | \n
---|---|
a | \n Append | \n
A | \n Append from end of line | \n
i | \n Insert | \n
o | \n Next line | \n
O | \n Previous line | \n
s | \n Delete char and insert | \n
S | \n Delete line and insert | \n
C | \n Delete until end of line and insert | \n
r | \n Replace one character | \n
R | \n Enter Replace mode | \n
u | \n Undo changes | \n
<C-R> | \n Redo changes | \n
Shortcut | \nDescription | \n
---|---|
Esc / <C-[> | \n Exit insert mode | \n
<C-C> | \n Exit insert mode, and abort current command | \n
Shortcut | \nDescription | \n
---|---|
x | \n Delete character | \n
dd | \n Delete line (Cut) | \n
yy | \n Yank line (Copy) | \n
p | \n Paste | \n
P | \n Paste before | \n
\"*p / \"+p | \n Paste from system clipboard | \n
\"*y / \"+y | \n Paste to system clipboard | \n
Shortcut | \nDescription | \n
---|---|
v | \n Enter visual mode | \n
V | \n Enter visual line mode | \n
<C-V> | \n Enter visual block mode | \n
Shortcut | \nDescription | \n
---|---|
d / x | \n Delete selection | \n
s | \n Replace selection | \n
y | \n Yank selection (Copy) | \n
See Operators for other things you can do.
\n\nOperators let you operate in a range of text (defined by motion). These are performed in normal mode.
\n\nd | \n w | \n
Operator | \nMotion | \n
Shortcut | \nDescription | \n
---|---|
d | \n Delete | \n
y | \n Yank (copy) | \n
c | \n Change (delete then insert) | \n
> | \n Indent right | \n
< | \n Indent left | \n
= | \n Autoindent | \n
g~ | \n Swap case | \n
gU | \n Uppercase | \n
gu | \n Lowercase | \n
! | \n Filter through external program | \n
See :help operator
Combine operators with motions to use them.
\n\nShortcut | \nDescription | \n
---|---|
d d | \n (repeat the letter) Delete current line | \n
d w | \n Delete to next word | \n
d b | \n Delete to beginning of word | \n
2dd | \n Delete 2 lines | \n
d ip | \n Delete a text object (inside paragraph) | \n
(in visual mode) d | \n Delete selection | \n
See: :help motion.txt
Text objects let you operate (with an operator) in or around text blocks (objects).
\n\nv | \n i | \n p | \n
Operator | \n[i]nside or [a]round | \nText object | \n
Shortcut | \nDescription | \n
---|---|
p | \n Paragraph | \n
w | \n Word | \n
s | \n Sentence | \n
[ ( { < | \n A [], (), or {} block | \n
' \" ` | \n A quoted string | \n
b | \n A block [( | \n
B | \n A block in [{ | \n
t | \n A XML tag block | \n
Shortcut | \nDescription | \n
---|---|
vip | \n Select paragraph | \n
vipipipip | \n Select more | \n
yip | \n Yank inner paragraph | \n
yap | \n Yank paragraph (including newline) | \n
dip | \n Delete inner paragraph | \n
cip | \n Change inner paragraph | \n
See Operators for other things you can do.
\n\nShortcut | \nDescription | \n
---|---|
gvimdiff file1 file2 [file3] | \n See differences between files, in HMI | \n
Shortcut | \nDescription | \n
---|---|
zo / zO | \n Open | \n
zc / zC | \n Close | \n
za / zA | \n Toggle | \n
zv | \n Open folds for this line | \n
zM | \n Close all | \n
zR | \n Open all | \n
zm | \n Fold more (foldlevel += 1) | \n
zr | \n Fold less (foldlevel -= 1) | \n
zx | \n Update folds | \n
Uppercase ones are recursive (eg, zO
is open recursively).
Shortcut | \nDescription | \n
---|---|
% | \n Nearest/matching {[()]} | \n
[( [{ [< | \n Previous ( or { or < | \n
]) | \n Next | \n
[m | \n Previous method start | \n
[M | \n Previous method end | \n
Shortcut | \nDescription | \n
---|---|
<C-O> | \n Go back to previous location | \n
<C-I> | \n Go forward | \n
gf | \n Go to file in cursor | \n
Shortcut | \nDescription | \n
---|---|
<C-A> | \n Increment number | \n
<C-X> | \n Decrement | \n
z{height}<Cr> | \n Resize pane to {height} lines tall | \n
Shortcut | \nDescription | \n
---|---|
:tag Classname | \n Jump to first definition of Classname | \n
<C-]> | \n Jump to definition | \n
g] | \n See all definitions | \n
<C-T> | \n Go back to last tag | \n
<C-O> <C-I> | \n Back/forward | \n
:tselect Classname | \n Find definitions of Classname | \n
:tjump Classname | \n Find definitions of Classname (auto-select 1st) | \n
Shortcut | \nDescription | \n
---|---|
~ | \n Toggle case (Case => cASE) | \n
gU | \n Uppercase | \n
gu | \n Lowercase | \n
gUU | \n Uppercase current line (also gUgU ) | \n
guu | \n Lowercase current line (also gugu ) | \n
Do these in visual or normal mode.
\n\nShortcut | \nDescription | \n
---|---|
`^ | \n Last position of cursor in insert mode | \n
`. | \n Last change in current buffer | \n
`\" | \n Last exited current buffer | \n
`0 | \n In last file edited | \n
'' | \n Back to line in current buffer where jumped from | \n
`` | \n Back to position in current buffer where jumped from | \n
`[ | \n To beginning of previously changed or yanked text | \n
`] | \n To end of previously changed or yanked text | \n
`< | \n To beginning of last visual selection | \n
`> | \n To end of last visual selection | \n
ma | \n Mark this cursor position as a | \n
`a | \n Jump to the cursor position a | \n
'a | \n Jump to the beginning of the line with position a | \n
d'a | \n Delete from current line to line of mark a | \n
d`a | \n Delete from current position to position of mark a | \n
c'a | \n Change text from current line to line of a | \n
y`a | \n Yank text from current position to position of a | \n
:marks | \n List all current marks | \n
:delm a | \n Delete mark a | \n
:delm a-d | \n Delete marks a , b , c , d | \n
:delm abc | \n Delete marks a , b , c | \n
Shortcut | \nDescription | \n
---|---|
. | \n Repeat last command | \n
]p | \n Paste under the current indentation level | \n
:set ff=unix | \n Convert Windows line endings to Unix line endings | \n
Shortcut | \nDescription | \n
---|---|
<C-R><C-W> | \n Insert current word into the command line | \n
<C-R>\" | \n Paste from “ register | \n
<C-X><C-F> | \n Auto-completion of path in insert mode | \n
:center [width]\n:right [width]\n:left\n
\n\nSee :help formatting
Shortcut | \nDescription | \n
---|---|
<C-R>=128/2 | \n Shows the result of the division : ‘64’ | \n
Do this in insert mode.
\n\n:cq\n:cquit\n
\n\nWorks like :qa
, but throws an error. Great for aborting Git commands.
Shortcut | \nDescription | \n
---|---|
:set spell spelllang=en_us | \n Turn on US English spell checking | \n
]s | \n Move to next misspelled word after the cursor | \n
[s | \n Move to previous misspelled word before the cursor | \n
z= | \n Suggest spellings for the word under/after the cursor | \n
zg | \n Add word to spell list | \n
zw | \n Mark word as bad/mispelling | \n
zu / C-X (Insert Mode) | \n Suggest words for bad word under cursor from spellfile | \n
See :help spell
Vim is a very efficient text editor. This reference was made for Vim 8.0.
\nFor shortcut notation, see :help key-notation
.
let colors = {\n \\ \"apple\": \"red\",\n \\ \"banana\": \"yellow\"\n}\n\necho colors[\"a\"]\necho get(colors, \"apple\") \" suppress error\n\nremove(colors, \"apple\")\n\n\" :help E715\nif has_key(dict, 'foo')\nif empty(dict)\nkeys(dict)\nlen(dict)\n\nmax(dict)\nmin(dict)\n\ncount(dict, 'x')\nstring(dict)\n\nmap(dict, '<>> \" . v:val')\nextend(s:fruits, { ... })\n
\n\nfor key in keys(mydict)\n echo key . ': ' . mydict(key)\nendfor\n
\n\nlet mylist = [1, two, 3, \"four\"]\n\nlet first = mylist[0]\nlet last = mylist[-1]\n\n\" Suppresses errors\nlet second = get(mylist, 1)\nlet second = get(mylist, 1, \"NONE\")\n
\n\nline('.') \" current line number\ncol('.')\ncol('$')\n\ngetline('.') \" current line as a string\ngetline(1) \" get line 1\ngetline(1, 5) \" get lines 1-5\nsearch('^$') \" next blank line, returns line number\nsearch('^$','n') \" but don't move cursor\n\ngetcurpos() \" [bufnum, lnum, col, off, curswant]\ngetpos('.') \" [bufnum, lnum, col, off]\n\nnextnonblank(1) \" next non-blank line after line1\nprevnonblank()\n
\n\ngetpos(\"'a\") \" position of a mark\nsetpos(\"'a\",...)\n\ngetpos(\"'<\") \" position of selection start\n
\n\ncursor(line,col) \" moves cursor\ncursor(line,col,off,curswant)\n\ngetcurpos() \" returns [bufnum,line,col,off,curswant]\n
\n\nexpand('<cword>') \" word under cursor\nexpand('%') \" current file\n\n\" <cword> current word on cursor\n\" :p full path\n\" :h head\n\" :p:h dirname (/Users/rsc/project)\n\" :t tail (file.txt)\n\" :r root (file)\n\" :e extension (.txt)\n\" see :h cmdline-special\n
\n\nfnameescape('string')\nfnamemodify('main.c', ':p:h')\nfnamemodify(fname, ':e') \" current file extension - see expand()\nfilereadable(fname)\ngetfsize('file.txt')\ngetcwd()\n\nglobpath(&rtp, \"plugin/commentary.vim\")\n
\n\nfmod(9, 2) \" modulus\nabs(-0.5)\nsqrt(9)\n\ntrunc(1.84)\nfloor(1.84)\nceil(1.84)\nfloat2nr(3.14)\n
\n\nstr2float('0.2')\nstr2nr('240')\nstr2nr('ff', '16')\n\nstring(0.3)\n
\n\ntype(var) == type(0)\ntype(var) == type(\"\")\ntype(var) == type(function(\"tr\"))\ntype(var) == type([])\ntype(var) == type({})\ntype(var) == type(0.0)\n
\n\nstrftime('%c')\nstrftime('%c',getftime('file.c'))\n
\n\nif a =~ '\\s*'\nsubstitute(str, '.', 'x', 'g')\nstrpart(\"abcdef\", 3, 2) \" == \"de\" (substring)\nstrpart(\"abcdef\", 3) \" == \"def\"\nstridx(\"abcdef\", \"e\") \" == 4\nstrridx() \" reverse\n\nmatchstr('testing','test') \" == 'test' (or '')\nmatch('testing','test') \" == 0\nmatchend('testing','test') \" == 4\nmatch('testing','\\ctest') \" ignore case\n\nsplit(str, '\\zs') \" split into characters\n\nstrlen(str)\nstrchars() \" accounts for composing chars\nstrwidth() \" accounts for ambig characters\nstrdisplaywidth() \" accounts for tab stops\n\ntoupper(str)\ntolower(str)\ntr('foo', '_-', ' ')\n
\n\nsynstack(line('.'),col('.')) \" returns many\nsynID(line('.'),col('.'),1) \" only one\n\nsynIDattr(id,\"bg\")\nsynIDattr(id,\"name\")\nsynIDtrans()\n\n\" syntax stack\nmap(synstack(line('.'), col('.')), 'synIDattr(v:val, \"name\")')\n
\n\nsystem('ls '.shellescape(expand('%:h')))\n
\n\ngetreg('*')\ngetregtype('*') \" v(char), V(line) <ctrl-v>(block)\n
\n\nif name ==# 'John' \" case-sensitive\nif name ==? 'John' \" case-insensitive\nif name == 'John' \" depends on :set ignorecase\n\" also: is#, is?, >=#, >=?, and so on\n\nif \"hello\" =~ '.*'\nif \"hello\" !~ '.*'\n
\n\nnormal 'ddahello'\nexe 'normal ^C' \" with expansions\nwincmd J\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "vimscript-snippets",
"title": "Vimscript snippets",
"url": "/vimscript-snippets",
"category": "Vim",
"keywords": null,
"content_html": "command! YoFunctionHere call s:YoFunctionHere()\nnnoremap <silent> x :call <SID>FunctionHere()<CR>\nfunction! s:FunctionHere()\nendfunction\n
\n\ninoremap X <C-R>=script#myfunction()<CR>\ninoremap <F2> <C-R>=MyVimFunc()?'':''<CR>\n
\n\nif globpath(&rtp, \"plugin/commentary.vim\") != \"\"\n
\n\n\" autoload/hello.vim\nif exists(\"g:hello_loaded\") | finish | endif\nlet g:hello_loaded=1\n\nfunction hello#method()\nendfunction\n\n\" calling hello#method() will load only if autoload()\n
\n\nif version < 704\n echom \"requires vim >= 7.4\"\nendif\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "vimscript",
"title": "Vim scripting",
"url": "/vimscript",
"category": "Vim",
"keywords": null,
"content_html": "let name = \"John\"\necho \"Hello, \" . name\n
\n\nYou can either put this in a script (script.vim
) and run it (:source script.vim
), or you can type the commands individually in normal mode as :let
and :echo
.
function! SuperTab()\n let l:part = strpart(getline('.'),col('.')-2,1)\n if (l:part =~ '^\\W\\?$')\n return \"\\<Tab>\"\n else\n return \"\\<C-n>\"\n endif\nendfunction\n\nimap <Tab> <C-R>=SuperTab()<CR>\n
\n\nHere’s another example with functions, variables and mapping.
\n\nlet var = \"hello\"\n
\n\nlet g:ack_options = '-s -H' \" g: global\nlet s:ack_program = 'ack' \" s: local (to script)\nlet l:foo = 'bar' \" l: local (to function)\n
\n\nThe s:
prefix is also available in function names. See :help local-variables
let w:foo = 'bar' \" w: window\nlet b:state = 'on' \" b: buffer\nlet t:state = 'off' \" t: tab\necho v:var \" v: vim special\n
\n\nlet @/ = '' \" @ register (this clears last search pattern)\necho $PATH \" $ env\n
\n\necho 'tabstop is ' . &tabstop\nif &insertmode\necho &g:option\necho &l:option\n
\n\nPrefix Vim options with &
a + b \" numbers only!\n'hello ' . name \" concat\n
\n\nlet var -= 2\nlet var += 5\nlet var .= 'string' \" concat\n
\n\nlet str = \"String\"\nlet str = \"String with \\n newline\"\n\nlet literal = 'literal, no \\ escaping'\nlet literal = 'that''s enough' \" double '' => '\n\necho \"result = \" . re \" concatenation\n
\n\nAlso see :help literal-string
and :help expr-quote
.\nSee: Strings
strlen(str) \" length\nlen(str) \" same\nstrchars(str) \" character length\n\nsplit(\"one two three\") \"=> ['one', 'two', 'three']\nsplit(\"one.two.three\", '.') \"=> ['one', 'two', 'three']\n\njoin(['a', 'b'], ',') \"=> 'a,b'\n\ntolower('Hello')\ntoupper('Hello')\n
\n\nAlso see :help functions
\nSee: String functions
\" prefix with s: for local script-only functions\nfunction! s:Initialize(cmd, args)\n \" a: prefix for arguments\n echo \"Command: \" . a:cmd\n\n return true\nendfunction\n
\n\nSee: Functions
\n\nfunction! myplugin#hello()\n
\n\ncall s:Initialize()\ncall s:Initialize(\"hello\")\n
\n\necho \"Result: \" . s:Initialize()\n
\n\nfunction! myfunction() abort\nendfunction\n
\n\nAborts when an error occurs.
\n\nfunction! infect(...)\n echo a:0 \"=> 2\n echo a:1 \"=> jake\n echo a:2 \"=> bella\n\n for s in a:000 \" a list\n echon ' ' . s\n endfor\nendfunction\n\ninfect('jake', 'bella')\n
\n\nSee :help function-argument
. See: Var arguments
for s in list\n echo s\n continue \" jump to start of loop\n break \" breaks out of a loop\nendfor\n
\n\nwhile x < 5\nendwhile\n
\n\ncommand! Save :set fo=want tw=80 nowrap\n
\n\nCustom commands start with uppercase letters. The !
redefines a command if it already exists.
command! Save call <SID>foo()\n
\n\nfunction! s:foo()\n ...\nendfunction\n
\n\ncommand! -nargs=? Save call script#foo(<args>)\n
\n\nWhat | \nWhat | \n
---|---|
-nargs=0 | \n 0 arguments, default | \n
-nargs=1 | \n 1 argument, includes spaces | \n
-nargs=? | \n 0 or 1 argument | \n
-nargs=* | \n 0+ arguments, space separated | \n
-nargs=+ | \n 1+ arguments, space reparated | \n
let char = getchar()\nif char == \"\\<LeftMouse>\"\n \" ...\nelseif char == \"\\<RightMouse>\"\n \" ...\nelse\n \" ...\nendif\n
\n\nif 1 | echo \"true\" | endif\nif 0 | echo \"false\" | endif\n
\n\nif 1 \"=> 1 (true)\nif 0 \"=> 0 (false)\nif \"1\" \"=> 1 (true)\nif \"456\" \"=> 1 (true)\nif \"xfz\" \"=> 0 (false)\n
\n\nNo booleans. 0
is false, 1
is true.\nSee: Truthiness
if 3 > 2\nif a && b\nif (a && b) || (c && d)\nif !c\n
\n\nSee :help expression-syntax
.\nSee: Operators
if name ==# 'John' \" case-sensitive\nif name ==? 'John' \" case-insensitive\nif name == 'John' \" depends on :set ignorecase\n\n\" also: is#, is?, >=#, >=?, and so on\n
\n\na is b\na isnot b\n
\n\nChecks if it’s the same instance object.
\n\n\"hello\" =~ 'xx*'\n\"hello\" !~ 'xx*'\n\"hello\" =~ '\\v<\\d+>'\n
\n\n\\v
enables “extended” regex mode which allows word boundary (<>
), +
, and more.
if empty(a:path) | return [] | endif\na ? b : c\n
\n\nUse |
to join lines together.
if g:use_dispatch && s:has_dispatch\n ···\nendif\n
\n\nlet mylist = [1, two, 3, \"four\"]\n\nlet first = mylist[0]\nlet last = mylist[-1]\n\n\" Suppresses errors\nlet second = get(mylist, 1)\nlet second = get(mylist, 1, \"NONE\")\n
\n\nlen(mylist)\nempty(mylist)\n\nsort(list)\nlet sortedlist = sort(copy(list))\n\nsplit('hello there world', ' ')\n
\n\nlet longlist = mylist + [5, 6]\nlet mylist += [7, 8]\n
\n\nlet shortlist = mylist[2:-1]\nlet shortlist = mylist[2:] \" same\n\nlet shortlist = mylist[2:2] \" one item\n
\n\nlet alist = [1, 2, 3]\nlet alist = add(alist, 4)\n
\n\ncall map(files, \"bufname(v:val)\") \" use v:val for value\ncall filter(files, 'v:val != \"\"')\n
\n\nlet colors = {\n \\ \"apple\": \"red\",\n \\ \"banana\": \"yellow\"\n}\n\necho colors[\"a\"]\necho get(colors, \"apple\") \" suppress error\n
\n\nSee :help dict
remove(colors, \"apple\")\n
\n\n\" :help E715\nif has_key(dict, 'foo')\nif empty(dict)\nkeys(dict)\nlen(dict)\n
\n\nmax(dict)\nmin(dict)\n
\n\ncount(dict, 'x')\nstring(dict)\n
\n\nmap(dict, '<>> \" . v:val')\n
\n\nfor key in keys(mydict)\n echo key . ': ' . mydict(key)\nendfor\n
\n\nkeys(s:)\n
\n\nPrefixes (s:
, g:
, l:
, etc) are actually dictionaries.
\" Extending with more\nlet extend(s:fruits, { ... })\n
\n\nstr2float(\"2.3\")\nstr2nr(\"3\")\nfloat2nr(\"3.14\")\n
\n\nlet int = 1000\nlet int = 0xff\nlet int = 0755 \" octal\n
\n\nSee :help Number
.\nSee: Numbers
let fl = 100.1\nlet fl = 5.4e4\n
\n\nSee :help Float
3 / 2 \"=> 1, integer division\n3 / 2.0 \"=> 1.5\n3 * 2.0 \"=> 6.0\n
\n\nsqrt(100)\nfloor(3.5)\nceil(3.3)\nabs(-3.4)\n\nsin() cos() tan()\nsinh() cosh() tanh()\nasin() acos() atan()\n
\n\nexecute \"vsplit\"\nexecute \"e \" . fnameescape(filename)\n
\n\nRuns an ex command you typically run with :
. Also see :help execute
.\nSee: Execute a command
normal G\nnormal! G \" skips key mappings\n\nexecute \"normal! gg/foo\\<cr>dd\"\n
\n\nUse :normal
to execute keystrokes as if you’re typing them in normal mode. Combine with :execute
for special keystrokes.\nSee: Running keystrokes
echo expand(\"%\") \" path/file.txt\necho expand(\"%:t\") \" file.txt\necho expand(\"%:p:h\") \" /home/you/path/file.txt\necho expand(\"%:r\") \" path/file\necho expand(\"%:e\") \" txt\n
\n\nSee :help expand
silent g/Aap/p\n
\n\nSuppresses output. See :help silent
echoerr 'oh it failed'\nechomsg 'hello there'\necho 'hello'\n\nechohl WarningMsg | echomsg \"=> \" . a:msg | echohl None\n
\n\nset number\nset nonumber\nset number! \" toggle\nset numberwidth=5\nset guioptions+=e\n
\n\nlet result = confirm(\"Sure?\")\nexecute \"confirm q\"\n
\n\nhas(\"feature\") \" :h feature-list\nexecutable(\"python\")\nglobpath(&rtp, \"syntax/c.vim\")\n\nexists(\"$ENV\")\nexists(\":command\")\nexists(\"variable\")\nexists(\"+option\")\nexists(\"g:...\")\n
\n\nnmap\nvmap\nimap\nxmap\nnnoremap\nvnoremap\ninoremap\nxnoremap\n...\n
\n\n[nvixso](nore)map\n
\n\n │ └ don't recurse\n │\n └ normal, visual, insert,\n eX mode, select, operator-pending\n
\n\n<buffer> | \n only in current buffer | \n
<silent> | \n no echo | \n
<nowait> | \n \n |
hi Comment\n term=bold,underline\n gui=bold\n ctermfg=4\n guifg=#80a0ff\n
\n\naugroup filetypedetect\n au! BufNewFile,BufRead *.json setf javascript\naugroup END\n\nau Filetype markdown setlocal spell\n
\n\nset conceallevel=2\nsyn match newLine \"<br>\" conceal cchar=}\nhi newLine guifg=green\n
\n\nsyn region inBold concealends matchgroup=bTag start=\"<b>\" end=\"</b>\"\nhi inBold gui=bold\nhi bTag guifg=blue\n
\n\nsyn match :name \":regex\" :flags\n\nsyn region Comment start=\"/\\*\" end=\"\\*/\"\nsyn region String start=+\"+ end=+\"+\t skip=+\\\\\"+\n\nsyn cluster :name contains=:n1,:n2,:n3...\n\nflags:\n keepend\n oneline\n nextgroup=\n contains=\n contained\n\nhi def link markdownH1 htmlH1\n
\n\nif exists('g:loaded_myplugin')\n finish\nendif\n\n\" ...\n\nlet g:loaded_myplugin = 1\n
",
"intro_html": "",
"description_html": "",
"tags": ["Featurable"],
"updated": "2020-07-05"
},{
"id": "virtual-dom",
"title": "Virtual-dom",
"url": "/virtual-dom",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "See https://www.npmjs.com/package/virtual-dom
\n\nvar h = require('virtual-dom/h')\nvar diff = require('virtual-dom/diff')\nvar patch = require('virtual-dom/patch')\nvar createElement = require('virtual-dom/create-element')\n
\n\ntree = h('div', { style: { color: 'blue' } }, [ 'hello' ])\nel = createElement(tree)\ndocument.body.appendChild(root)\n
\n\ntree2 = h('div', { style: { color: 'blue' } }, [ 'hello world' ])\ndelta = diff(tree, tree2)\nel = patch(el, delta) // patch() modifies el\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "vows",
"title": "Vows",
"url": "/vows",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "vows = require \"vows\"\nassert = require \"assert\"\n\nvows\n .describe('My tests')\n .addBatch\n 'context':\n topic: ->\n 100\n 'should work': (number) ->\n assert.equal number, 100\n\n .export(module)\n
\n\nvows test/*-test.* --spec\n
\n\nassert.equal a, b\nassert.notEqual a, b\nassert.strictEqual a, b\n\nassert.isNaN(number)\nassert.instanceOf(object, klass)\nassert.isUndefined(object)\nassert.isFunction(func)\nassert.isNull(object)\nassert.isNotZero(object)\nassert.isObject(object)\nassert.isString(object)\n
\n\n.addBatch\n topic: ->\n doStuff()\n @callback 2\n 'check things': (n) ->\n assert.equal 2, n\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "vscode",
"title": "Visual Studio Code",
"url": "/vscode",
"category": "Apps",
"keywords": ["⌘P: Show files","⌘B: Toggle sidebar","⌘J: Toggle panel","F5: Debug"],
"content_html": "Key | \nDescription | \n
---|---|
⇧⌘P | \n Show all commands | \n
⌘P | \n Show files | \n
Key | \nDescription | \n
---|---|
⌘B | \n Toggle sidebar | \n
⇧⌘E | \n Explorer | \n
⇧⌘F | \n Search | \n
⇧⌘D | \n Debug | \n
⇧⌘X | \n Extensions | \n
⇧^G | \n Git (SCM) | \n
Key | \nDescription | \n
---|---|
⌘F | \n Find | \n
⌥⌘F | \n Replace | \n
⇧⌘F | \n Find in files | \n
⇧⌘H | \n Replace in files | \n
Key | \nDescription | \n
---|---|
⌘J | \n Toggle panel | \n
⇧⌘M | \n Problems | \n
⇧⌘U | \n Output | \n
⇧⌘Y | \n Debug console | \n
^` | \n Terminal | \n
Key | \nDescription | \n
---|---|
⌘k z | \n Zen mode | \n
⌘k u | \n Close unmodified | \n
⌘k w | \n Close all | \n
Key | \nDescription | \n
---|---|
F5 | \n Start | \n
⇧F5 | \n Stop | \n
⇧⌘F5 | \n Restart | \n
^F5 | \n Start without debugging | \n
F9 | \n Toggle breakpoint | \n
F10 | \n Step over | \n
F11 | \n Step into | \n
⇧F11 | \n Step out | \n
⇧⌘D | \n Debug sidebar | \n
⇧⌘Y | \n Debug panel | \n
Visual Studio Code, or VSCode, is an open-source code editor. This guide targets VSCode v1.19.
", "description_html": "", "tags": null, "updated": "2018-02-01" },{ "id": "vue", "title": "Vue.js", "url": "/vue", "category": "JavaScript", "keywords": null, "content_html": "{%raw%}
\n\n<div id=\"app\">\n <p>I have a {{ product }}</p>\n <p>{{ product + 's' }}</p>\n <p>{{ isWorking ? 'YES' : 'NO' }}</p>\n <p>{{ product.getSalePrice() }}</p>\n</div>\n
\n\nSee: Delimiters
\n\n<a v-bind:href=\"url\">...</a>\n
\n\n<a :href=\"url\">...</a>\n
\n\n<button :disabled=\"isButtonDisabled\">...\n
\n\n<div :class=\"{ active: isActive }\">...\n
\n\n<div :style=\"{ color: activeColor }\">\n
\n\nSee: v-bind
\n\n<p v-if=\"inStock\">{{ product }}</p>\n
\n<p v-else-if=\"onSale\">...</p>\n<p v-else>...</p>\n
\n\n<p v-show=\"showProductDetails\">...</p>\n
\n\n<input v-model=\"firstName\" >\n
\n\nMethod | \nDescription | \n
---|---|
v-model.lazy=\"...\" | \n Syncs input after change event | \n
v-model.number=\"...\" | \n Always returns a number | \n
v-model.trim=\"...\" | \n Strips whitespace | \n
See: Directives
\n\n<button v-on:click=\"addToCart\">...\n
\n\n<button @click=\"addToCart\">...\n
\n\n<button @click=\"addToCart(product)\">...\n
\n\n<form @submit.prevent=\"addProduct\">...\n
\n\n<img @mouseover.once=\"showImage\">...\n
\n\nMethod | \nDescription | \n
---|---|
.stop | \n Stop all event propagation | \n
.self | \n Only trigger if event.target is element itself | \n
<input @keyup.enter=\"submit\">\n
\n\n<input @keyup.ctrl.c=\"onCopy\">\n
\n\nSee: Events
\n\n:key
is always recommended<li v-for=\"item in items\"\n :key=\"item.id\">\n {{ item }}\n</li>\n
\n\n<li v-for=\"(item, index) in items\">...\n
\n\n<li v-for=\"(value, key) in object\">...\n
\n\nv-for
with a component<cart-product v-for=\"item in products\"\n :product=\"item\"\n :key=\"item.id\">\n
\n\nSee: List Rendering
\n\nVue.component('my-component', {\n components: {\n // Components that can be used in the template\n ProductComponent,\n ReviewComponent\n },\n props: {\n // The parameters the component accepts\n message: String,\n product: Object,\n email: {\n type: String,\n required: true,\n default: \"none\"\n validator: function (value) {\n // Should return true if value is valid\n }\n }\n },\n data: function() {\n // `data` must be a function\n return {\n firstName: 'Vue',\n lastName: 'Mastery'\n }\n },\n computed: {\n // Return cached values until dependencies change\n fullName: function () {\n return this.firstName + ' ' + this.lastName\n }\n },\n watch: {\n // Called when firstName changes value\n firstName: function (value, oldValue) { ... }\n },\n methods: { ... },\n template: '<span>{{ message }}</span>',\n // Can also use backticks in `template` for multi-line\n})\n
\n\nSee: Components Basics
\n\nMethod | \nDescription | \n
---|---|
beforeCreate | \n After the instance has been initialized # | \n
created | \n After the instance is created # | \n
beforeMount | \n Before the first render # | \n
mounted | \n After the instance has been mounted # | \n
beforeUpdate | \n When data changes, before the DOM is patched # | \n
updated | \n After a data change # | \n
beforeDestroy | \n Before the instance is destroyed # | \n
destroyed | \n After a Vue instance has been destroyed # | \n
See: Lifecycle Hooks
\n\n<button-counter v-on:incrementBy=\"incWithVal\">\n
\n\nmethods: {\n incWithVal: function (toAdd) { ... }\n}\n
\n\nthis.$emit(\n 'incrementBy', // Custom event name\n 5 // Data sent up to parent\n )\n
\n\nUse props to pass data into child components,\ncustom events to pass data to parent elements.
\n\nSee: Custom Events
\n\n<template>\n <p>{{ greeting }} World!</p>\n</template>\n\n<script>\nmodule.exports = {\n data: function () {\n return {\n greeting: 'Hello'\n }\n }\n}\n</script>\n\n<style scoped>\np {\n font-size: 2em;\n text-align: center;\n}\n</style>\n
\n\n\n\n<template>\n <div>This will be pre-compiled</div>\n</template>\n<script src=\"./my-component.js\"></script>\n<style src=\"./my-component.css\"></style>\n
\n\nSee: What About Separation of Concerns?
\n\n<div>\n <h2>I'm a title</h2>\n <slot>\n Only displayed if no slot content\n </slot>\n</div>\n
\n\n<my-component>\n <p>This will go in the slot</p>\n</my-component>\n
\n\nSee: Slots
\n\n<div class=\"container\">\n <header>\n <slot name=\"header\"></slot>\n </header>\n <main>\n <slot>Default content</slot>\n </main>\n <footer>\n <slot name=\"footer\"></slot>\n </footer>\n</div>\n
\n\n<app-layout>\n <h1 slot=\"header\">Page title</h1>\n <p>the main content.</p>\n <p slot=\"footer\">Contact info</p>\n</app-layout>\n
\n\nSee: Slots
\n\n{%endraw%}
", "intro_html": "Vue.js is an open-source Model–view–viewmodel JavaScript framework for building user interfaces and single-page applications.
", "description_html": "", "tags": null, "updated": "2019-12-26" },{ "id": "vue@1.0.28", "title": "Vue.js v1.0.28", "url": "/vue@1.0.28", "category": "JavaScript", "keywords": null, "content_html": "{% raw %}
\n\n<li v-for=\"todo in todos\">\n {{ todo.text }}\n {{ $index }}\n</li>\n
\n\n<button v-on:click='submit'>Go</button>\n
\n\nnew Vue({\n components: { app: App }\n})\n
\n\nVue.extend({ ... }) // creating components\nVue.nextTick(() => {...})\n\nVue.set(object, key, val) // reactive\nVue.delete(object, key)\n\nVue.directive('my-dir', { bind, update, unbind })\n// <div v-my-dir='...'></div>\n\nVue.elementDirective('my-dir', { bind, update, unbind })\n// <my-dir>...</my-dir>\n\nVue.component('my-component', Vue.extend({ .. }))\n\nVue.partial('my-partial', '<div>hi {{msg}}</div>')\n// <partial name='my-partial'></partial>\n
\n\nnew Vue({\n data: { ... }\n props: ['size'],\n props: { size: Number },\n computed: { fullname() { return this.name + ' ' + this.lastName } },\n methods: { go() { ... } },\n watch: { a (val, oldVal) { ... } },\n el: '#foo',\n template: '...',\n replace: true, // replace element (default true)\n\n // lifecycle\n created () {},\n beforeCompile () {},\n compiled () {},\n ready () {}, // $el is inserted for the first time\n attached () {},\n detached () {},\n beforeDestroy () {},\n destroyed () {},\n\n // options\n directives: {},\n elementDirectives: {},\n filters: {},\n components: {},\n transitions: {},\n partials: {}\n})\n
\n\nVia vueify
\n\n// app.vue\n<template>\n <h1 class=\"red\">{{msg}}</h1>\n</template>\n \n<script>\n module.exports = {\n data () {\n return {\n msg: 'Hello world!'\n }\n }\n }\n</script> \n
\n\nAlso
\n\n<template lang='jade'>\nh1(class='red') {{msg}}\n</template>\n
\n\n{% endraw %}
", "intro_html": "Deprecated: this guide targets an old version of Vuej.js (v1.0.28). See the updated Vue.js cheatsheet for new versions.
", "description_html": "", "tags": null, "updated": null },{ "id": "watchexec", "title": "Watchexec", "url": "/watchexec", "category": "CLI", "keywords": ["watchexec --excts js,jsx -- npm test","watchexec --help"], "content_html": "brew install watchexec\n
\n\ncargo install watchexec\n
\n\nFor Linux and Windows, get it from GitHub releases.
\n\nwatchexec --exts js,jsx -- npm test\n
\n\nRuns npm test
when js,jsx
files change.
watchman -w lib -w test -- npm test\n
\n\nRuns npm test
when lib/
and test/
files change.
-c --clear | \n Clear screen | \n
-r --restart | \n Restart process if its still running | \n
-s --signal SIGKILL | \n Kill signal to use | \n
-d --debounce MS | \n Debounce by MS milliseconds | \n
-e --exts EXTS | \n Extensions | \n
-i --ignore PATTERN | \n Ignore these files | \n
-w --watch PATH | \n Watch these directories | \n
mattgreen/watchexec runs commands whenever certain files change.
", "description_html": "", "tags": null, "updated": "2017-10-18" },{ "id": "watchman", "title": "Watchman", "url": "/watchman", "category": "Others", "keywords": ["watchman watch ~/src","watchman watch-list","watchman -- trigger ~/rsc remake '*.js' -- make "], "content_html": "watchman watch ./src\n
\n\nAdds ./src
to the watch list.
watchman -- trigger ./src retest '*.js' -- npm test\n
\n\nAdds a trigger called retest
to run npm test
every time *.js
changes in ./src
.
watchman watch ~/src\nwatchman watch-list\nwatchman watch-del ~/src\n
\n\nvar worker = new Worker('worker.js')\n\nworker.onmessage = function (message) {\n alert(JSON.stringify(message.data))\n})\n\nworker.postMessage('hello!')\n
\n\nMessages can be anything that can be serialized into JSON (objects, arrays, strings, numbers, booleans). See: structured clone
\n\nself.onmessage = function (message) {\n ···\n}\n\nself.postMessage({ msg: 'hello' })\n
\n\nbubbles: false\ncancelBubble: false\ncancelable: false\nclipboardData: undefined\ncurrentTarget: Worker\ndata: \"Hello\" ← the data\ndefaultPrevented: false\neventPhase: 0\nlastEventId: \"\"\norigin: \"\"\nports: Array[0]\nreturnValue: true\nsource: null\nsrcElement: Worker\ntarget: Worker\ntimeStamp: 1344821022383\ntype: \"message\"\n
\n\nThese are the contents of message
on onmessage.
module.exports = {\n context: __dirname,\n entry: 'src/app.js',\n output: {\n path: __dirname + '/public',\n filename: 'app.js'\n }\n}\n
\n\nnpm install --save-dev webpack\n
\n\nwebpack | \n build | \n
webpack -- -p | \n build production | \n
webpack -- --watch | \n compile continuously | \n
This compiles src/app.js
into public/app.js
. (Note: you may need to use ./node_modules/.bin/webpack
as a command if you’re not invoking Webpack via npm scripts.)
module.exports = {\n entry: {\n app: 'src/app.js',\n vendor: 'src/vendor.js'\n },\n output: {\n path: __dirname + '/public',\n filename: '[name].js'\n }\n}\n
\n\nThis creates app.js
and vendor.js
.
npm install --save-dev \\\n babel-loader \\\n babel-preset-env \\\n babel-preset-react\n
\n\nmodule.exports = {\n ···\n module: {\n rules: [\n { test: /\\.js$/,\n exclude: /node_modules/,\n use: [\n { loader: 'babel-loader' }\n ]\n }\n ]\n }\n}\n
\n\n{\n \"presets\": [ \"env\", \"react\" ]\n}\n
\n\nAdds support for Babel.
\n\nnpm install --save-dev \\\n css-loader \\\n style-loader\n
\n\nmodule.exports = {\n ···\n module: {\n rules: [\n { test: /\\.css$/,\n exclude: /node_modules/,\n use: [\n { loader: 'style-loader' },\n { loader: 'css-loader' }\n ]\n }\n ]\n }\n}\n
\n\nimport './styles.css'\n// or:\nrequire('./styles.css')\n
\n\nThis allows you to use CSS inside your JavaScript. This packages your CSS inside your JavaScript bundle.
\n\nnpm install --save-dev \\\n postcss-loader \\\n postcss-cssnext\n
\n\n···\n// Inside module.rules[]:\n{ test: /\\.css$/,\n exclude: /node_modules/,\n use: [\n { loader: 'style-loader' },\n { loader: 'css-loader' },\n { loader: 'postcss-loader' }\n···\n
\n\nmodule.exports = {\n plugins: [\n require('postcss-cssnext')()\n ]\n}\n
\n\nThis example adds postcss-cssnext support to your CSS files.
\n\n{ ···\n \"scripts\": {\n \"dev\": \"webpack-dev-server\"\n }\n}\n
\n\nnpm install --save-dev \\\n webpack-dev-server\n
\n\nnpm run dev\n
\n\nThis starts an HTTP server for development (port 8080 by default).
", "intro_html": "This is a very basic “getting started with Webpack” guide for use with Webpack v3. This doesn’t cover all features, but it should get you started in understanding the config file format.
", "description_html": "", "tags": null, "updated": "2017-09-26" },{ "id": "weechat", "title": "Weechat", "url": "/weechat", "category": "Apps", "keywords": null, "content_html": "Shortcut | \nDescription | \n
---|---|
^s / ^u | \n Set unread marker on all windows | \n
^p, A-left | \n Switch buffer left | \n
^n, A-right | \n Switch buffer right | \n
A-a | \n Next buffer with activity | \n
A-0...9 | \n Switch buffers | \n
F9 / F10 | \n Scroll buffer title | \n
F11 / F12 | \n Scroll nick list | \n
A-w A-Left | \n Switch windows | \n
A-w A-b | \n Balance windows | \n
(A-
is alt.)
Shortcut | \nDescription | \n
---|---|
/window splith | \n Split horizontal | \n
/window splitv | \n Split vertical | \n
/window zoom | \n Zoom | \n
^r | \n Search | \n
Enter ^j ^m | \n Stop search | \n
$ npm install -g weinre\n
\n\n$ weinre --boundHost 0.0.0.0\n$ open http://localhost:8080\n
\n\n<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.async=1;js.src='http://'+location.hostname+':8080/target/target-script-min.js#anonymous';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','weinre');</script>\n
\n\nweinre is a remote Web inspector. Note that it has been deprecated since 2016.
", "description_html": "", "tags": ["Archived"], "updated": null },{ "id": "xpath", "title": "Xpath", "url": "/xpath", "category": "HTML", "keywords": null, "content_html": "Test queries in the Xpath test bed:
\n\n$x(\"//div\")\n
\n\nWorks in Firefox and Chrome.
\n\nCSS | \nXpath | \n? | \n
---|---|---|
h1 | \n //h1 | \n ? | \n
div p | \n //div//p | \n ? | \n
ul > li | \n //ul/li | \n ? | \n
ul > li > a | \n //ul/li/a | \n \n |
div > * | \n //div/* | \n \n |
:root | \n / | \n ? | \n
:root > body | \n /body | \n \n |
CSS | \nXpath | \n? | \n
---|---|---|
#id | \n //*[@id=\"id\"] | \n ? | \n
.class | \n //*[@class=\"class\"] …kinda | \n \n |
input[type=\"submit\"] | \n //input[@type=\"submit\"] | \n \n |
a#abc[for=\"xyz\"] | \n //a[@id=\"abc\"][@for=\"xyz\"] | \n ? | \n
a[rel] | \n //a[@rel] | \n \n |
a[href^='/'] | \n //a[starts-with(@href, '/')] | \n ? | \n
a[href$='pdf'] | \n //a[ends-with(@href, '.pdf')] | \n \n |
a[href*='://'] | \n //a[contains(@href, '://')] | \n \n |
a[rel~='help'] | \n //a[contains(@rel, 'help')] …kinda | \n \n |
CSS | \nXpath | \n? | \n
---|---|---|
ul > li:first-child | \n //ul/li[1] | \n ? | \n
ul > li:nth-child(2) | \n //ul/li[2] | \n \n |
ul > li:last-child | \n //ul/li[last()] | \n \n |
li#id:first-child | \n //li[@id=\"id\"][1] | \n \n |
a:first-child | \n //a[1] | \n \n |
a:last-child | \n //a[last()] | \n \n |
CSS | \nXpath | \n? | \n
---|---|---|
h1 ~ ul | \n //h1/following-sibling::ul | \n ? | \n
h1 + ul | \n //h1/following-sibling::ul[1] | \n \n |
h1 ~ #id | \n //h1/following-sibling::[@id=\"id\"] | \n \n |
CSS | \nXpath | \n? | \n
---|---|---|
$('ul > li').parent() | \n //ul/li/.. | \n ? | \n
$('li').closest('section') | \n //li/ancestor-or-self::section | \n \n |
$('a').attr('href') | \n //a/@href | \n ? | \n
$('span').text() | \n //span/text() | \n \n |
CSS | \nXpath | \n? | \n
---|---|---|
h1:not([id]) | \n //h1[not(@id)] | \n ? | \n
Text match | \n//button[text()=\"Submit\"] | \n ? | \n
Text match (substring) | \n//button[contains(text(),\"Go\")] | \n \n |
Arithmetic | \n//product[@price > 2.50] | \n \n |
Has children | \n//ul[*] | \n \n |
Has children (specific) | \n//ul[li] | \n \n |
Or logic | \n//a[@name or @href] | \n ? | \n
Union (joins results) | \n//a | //div | \n ? | \n
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]\n
\n\nXpath doesn’t have the “check if part of space-separated list” operator, so this is the workaround (source).
\n\n// | \n ul | \n / | \n a[@id='link'] | \n
Axis | \nStep | \nAxis | \nStep | \n
Prefix | \nExample | \nWhat | \n
---|---|---|
// | \n //hr[@class='edge'] | \n Anywhere | \n
./ | \n ./a | \n Relative | \n
/ | \n /html/body/div | \n Root | \n
Begin your expression with any of these.
\n\nAxis | \nExample | \nWhat | \n
---|---|---|
/ | \n //ul/li/a | \n Child | \n
// | \n //[@id=\"list\"]//a | \n Descendant | \n
Separate your steps with /
. Use two (//
) if you don’t want to select direct children.
//div\n//div[@name='box']\n//[@id='link']\n
\n\nA step may have an element name (div
) and predicates ([...]
). Both are optional.\nThey can also be these other things:
//a/text() #=> \"Go home\"\n//a/@href #=> \"index.html\"\n//a/* #=> All a's child elements\n
\n\n//div[true()]\n//div[@class=\"head\"]\n//div[@class=\"head\"][@id=\"top\"]\n
\n\nRestricts a nodeset only if some condition is true. They can be chained.
\n\n# Comparison\n//a[@id = \"xyz\"]\n//a[@id != \"xyz\"]\n//a[@price > 25]\n
\n\n# Logic (and/or)\n//div[@id=\"head\" and position()=2]\n//div[(x and y) or not(z)]\n
\n\nUse comparison and logic operators to make conditionals.
\n\n# Use them inside functions\n//ul[count(li) > 2]\n//ul[count(li[@class='hide']) > 0]\n
\n\n# This returns `<ul>` that has a `<li>` child\n//ul[li]\n
\n\nYou can use nodes inside predicates.
\n\n//a[1] # first <a>\n//a[last()] # last <a>\n//ol/li[2] # second <li>\n//ol/li[position()=2] # same as above\n//ol/li[position()>1] # :not(:first-child)\n
\n\nUse []
with a number, or last()
or position()
.
a[1][@href='/']\na[@href='/'][1]\n
\n\nOrder is significant, these two are different.
\n\n//section[//h1[@id='hi']]\n
\n\nThis returns <section>
if it has an <h1>
descendant with id='hi'
.
name() # //[starts-with(name(), 'h')]\ntext() # //button[text()=\"Submit\"]\n # //button/text()\nlang(str)\nnamespace-uri()\n
\n\ncount() # //table[count(tr)=1]\nposition() # //ol/li[position()=2]\n
\n\nnot(expr) # button[not(starts-with(text(),\"Submit\"))]\n
\n\ncontains() # font[contains(@class,\"head\")]\nstarts-with() # font[starts-with(@class,\"head\")]\nends-with() # font[ends-with(@class,\"head\")]\n
\n\nconcat(x,y)\nsubstring(str, start, len)\nsubstring-before(\"01/02\", \"/\") #=> 01\nsubstring-after(\"01/02\", \"/\") #=> 02\ntranslate()\nnormalize-space()\nstring-length()\n
\n\nstring()\nnumber()\nboolean()\n
\n\n//ul/li # ul > li\n//ul/child::li # ul > li (same)\n//ul/following-sibling::li # ul ~ li\n//ul/descendant-or-self::li # ul li\n//ul/ancestor-or-self::li # $('ul').closest('li')\n
\n\nSteps of an expression are separated by /
, usually used to pick child nodes. That’s not always true: you can specify a different “axis” with ::
.
// | \n ul | \n /child:: | \n li | \n
Axis | \nStep | \nAxis | \nStep | \n
# both the same\n//ul/li/a\n//child::ul/child::li/child::a\n
\n\nchild::
is the default axis. This makes //a/b/c
work.
# both the same\n# this works because `child::li` is truthy, so the predicate succeeds\n//ul[li]\n//ul[child::li]\n
\n\n# both the same\n//ul[count(li) > 2]\n//ul[count(child::li) > 2]\n
\n\n# both the same\n//div//h4\n//div/descendant-or-self::h4\n
\n\n//
is short for the descendant-or-self::
axis.
# both the same\n//ul//[last()]\n//ul/descendant-or-self::[last()]\n
\n\nAxis | \nAbbrev | \nNotes | \n
---|---|---|
ancestor | \n \n | \n |
ancestor-or-self | \n \n | \n |
attribute | \n @ | \n @href is short for attribute::href | \n
child | \n \n | div is short for child::div | \n
descendant | \n \n | \n |
descendant-or-self | \n // | \n // is short for /descendant-or-self::node()/ | \n
namespace | \n \n | \n |
self | \n . | \n . is short for self::node() | \n
parent | \n .. | \n .. is short for parent::node() | \n
following | \n \n | \n |
following-sibling | \n \n | \n |
preceding | \n \n | \n |
preceding-sibling | \n \n | \n |
There are other axes you can use.
\n\n//a | //span\n
\n\nUse |
to join two expressions.
//* # all elements\ncount(//*) # count all elements\n(//h1)[1]/text() # text of the first h1 heading\n//li[span] # find a <li> with an <span> inside it\n # ...expands to //li[child::span]\n//ul/li/.. # use .. to select a parent\n
\n\n//section[h1[@id='section-name']]\n
\nFinds a <section>
that directly contains h1#section-name
//section[//h1[@id='section-name']]\n
\n\nFinds a <section>
that contains h1#section-name
.\n(Same as above, but uses descendant-or-self instead of child)
./ancestor-or-self::[@class=\"box\"]\n
\n\nWorks like jQuery’s $().closest('.box')
.
//item[@price > 2*@discount]\n
\n\nFinds <item>
and check its attributes
$x(‘//div//p//*’) == $(‘div p *’), $x(‘//[@id=”item”]’) == $(‘#item’), and many other Xpath examples.
", "tags": ["Featured"], "updated": null },{ "id": "yaml", "title": "Yaml", "url": "/yaml", "category": "Markup", "keywords": null, "content_html": "Multiline: |\n hello\n world\n
\n\nparent: &defaults\n a: 2\n b: 3\n\nchild:\n <<: *defaults\n b: 4\n
\n\nvalues: &ref\n - These values\n - will be reused below\n \nother_values:\n <<: *ref\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "yargs",
"title": "Yargs",
"url": "/yargs",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "var argv = require('yargs').argv;\n\nargv._ // [ ... ]\nargv.$0 // \"node bin/mybin\"\nargv.verbose // --verbose\n
\n\nvar argv = require('yargs')\n\n // version\n .alias('v', 'version')\n .version(function() { return require('../package').version; })\n .describe('v', 'show version information')\n\n // help text\n .alias('h', 'help')\n .help('help')\n .usage('Usage: $0 -x [num]')\n .showHelpOnFail(false, \"Specify --help for available options\")\n
\n\n .option('f', {\n alias : 'file',\n describe: 'x marks the spot',\n type: 'string', /* array | boolean | string */\n nargs: 1,\n demand: true,\n demand: 'file is required',\n default: '/etc/passwd'\n // also: count:true, requiresArg:true\n })\n\n .options({\n f: { ... }\n })\n
\n\n // more help\n .example('...')\n .epilog('copyright 2015')\n .command('start', 'start a server')\n
\n\n .count('verbose')\n\nargv.verbose // -vvv => 3\n
\n\n .strict()\n
\n\nyargs.showHelp()\nyargs.help() //=>string\n
",
"intro_html": "",
"description_html": "",
"tags": null,
"updated": null
},{
"id": "yarn",
"title": "Yarn",
"url": "/yarn",
"category": "JavaScript libraries",
"keywords": null,
"content_html": "npm | \nyarn | \n
---|---|
npm init | \n yarn init | \n
npm install | \n yarn | \n
npm install gulp --save | \n yarn add gulp | \n
npm install gulp --save-dev --save-exact | \n yarn add gulp --dev --exact | \n
npm install -g gulp | \n yarn global add gulp | \n
npm update | \n yarn upgrade | \n
./node_modules/.bin/gulp | \n yarn run gulp | \n
--no-lockfile\n--pure-lockfile\n--frozen-lockfile\n--silent\n--offline\n--update-checksums\n--check-files\n--flat\n--force\n--ignore-scripts\n--modules-folder <path>\n--production[=true|false]\n
\n\nThese options are available for yarn install
.
--dev\n--peer\n--optional\n--exact\n--tilde\n
\n\nThese options are available for yarn add
.
In package.json
:
\"workspaces\": [\n \"packages/*\"\n]\n
\n\njest/\n├─ package.json\n└─ packages/\n ├─ jest-matcher-utils/\n │ └─ package.json\n └─ jest-diff/\n └─ package.json\n
\n\n(New in 1.0) Allows monorepos to share packages with each other. See: Introducing workspaces
\n\nIn package.json
:
\"resolutions\": {\n \"**/sass-brunch/node-sass\": \"4.5.2\"\n}\n
\n\n(New in 1.0) Allows you to specify versions for sub-dependencies. See: Selective version resolutions
\n\nyarn create react-app hello\n
\n\nInstall create-react-app
and runs it. See: yarn create
/msg *status addserver irc.undernet.org [6667]\n/msg *status connect\n\n/msg *status loadmod webadmin\n/msg *status loadmod admin\n/msg *status loadmod away\n/msg *status loadmod awaynick\n/msg *status loadmod clientnotify # Notifies when another client logs\n/msg *status loadmod keepnick\n/msg *status loadmod kickrejoin\n
\n\n/msg *status loadmod away\n/msg *away away\n/msg *away back\n/msg *away show #=> Show messages\n/msg *away delete all\n
\n\n/msg *status loadmod watch\n/msg *watch list\n/msg *watch add * *watch *rico*\n/msg *watch add * *watch *%nick%*\n
",
"intro_html": "A quick reference to the ZNC IRC bouncer’s common commands.
", "description_html": "", "tags": null, "updated": null },{ "id": "zombie", "title": "Zombie", "url": "/zombie", "category": "JavaScript libraries", "keywords": null, "content_html": "browser\n .visit(\"http://.../\", ->)\n .fill(\"email\", \"zombie@underworld.dead\")\n .fill(\"password\", \"eat-the-living\")\n .select(\"Born\", \"1985\")\n .uncheck(\"Send newsletter\")\n .clickLink(\"Link name\")\n .pressButton(\"Sign\", () => { ... })\n .text(\"H1\")\n
\n\nexpect(browser.query(\"#brains\"))\n\nexpect(browser.body.queryAll(\".hand\")).length 2\n\nconsole.log(browser.html())\nconsole.log(browser.html(\"table.parts\"))\n\nexpect(Browser.text(\".card-nopad small\"), \"A better way to get around!\")\n
",
"intro_html": "Zombie is a full-stack testing solution for Node.js.
", "description_html": "", "tags": null, "updated": null },{ "id": "zsh", "title": "zsh", "url": "/zsh", "category": "CLI", "keywords": null, "content_html": "Expression | \nExample | \nDescription | \n
---|---|---|
!! | \n sudo !! | \n Last command (sudo !! ) | \n
!* | \n vim !* | \n Last command’s parameters (vim !* ) | \n
!^ | \n \n | Last command’s first parameter | \n
!$ | \n \n | Last command’s last parameter | \n
!?ls <tab> | \n sudo !?mv <tab> | \n Command and params of last ls command | \n
!?ls?:* <tab> | \n \n | Params of last ls command | \n
*(m0) | \n rm *(m0) | \n Last modified today | \n
*(m-4) | \n \n | Last modified <4 days ago | \n
chsh -s `which zsh`\n
\n\nExpression | \nExample | \nDescription | \n
---|---|---|
<(COMMAND) | \n grep \"needle\" <(curl \"https://haystack.io\") | \n Replace argument with named pipe/FIFO (read-only) with command output | \n
=(COMMAND) | \n vim =(curl \"https://haystack.io\") | \n Replace argument with file (writable) containing command output | \n
Zsh is mostly compatible with Bash, so most everything in Bash’s cheatsheet also applies.
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "assets/css/style.css", "title": null, "url": "/assets/css/style.css", "category": "Others", "keywords": null, "content_html": "@import “jekyll-theme-primer”;
", "intro_html": "", "description_html": "", "tags": null, "updated": null },{ "id": "redirects.json", "title": null, "url": "/redirects.json", "category": "Others", "keywords": null, "content_html": "{“/jade.html”:”https://devhints.io/pug”,”/package.html”:”https://devhints.io/package.json”,”/phoenix-ecto@1.3.html”:”https://devhints.io/phoenix-ecto”,”/sh.html”:”https://devhints.io/bash”}
", "intro_html": "", "description_html": "", "tags": null, "updated": null } ]