ESET INTERNET SECURITY KEYS

Download Free fresh ESET NOD32 ACTIVATION KEYS. Suitable for ESET NOD32 Antivirus, ESET NOD32 Internet Security, ESET NOD32 Smart Security and ESET Mobile Security.

Activation keys

H5RW-XHCG-T2JU-SCAH-2T7K

76AK-XDGS-3XT6-K2ND-37P5

75F8-XJDC-B97N-D5V5-6RN7

Tags:

#ESET #MOBILE #INTERNET #SECURITY #KEYS

ESET MOBILE SECURITY KEYS

Download Free fresh ESET NOD32 ACTIVATION KEYS. Suitable for ESET NOD32 Antivirus, ESET NOD32 Internet Security, ESET NOD32 Smart Security and ESET Mobile Security.

Activation keys

72RP-XH2N-RET7-EA2E-WAXW

X27V-X6MU-F4V9-CW3F-VTHX

6D3U-X7F2-RUX7-CK9H-6DTT

Tags:

#ESET #MOBILE #SECURITY #KEYS

ESET ANTIVIRUS 4-8 KEYS

Download Free fresh ESET NOD32 ACTIVATION KEYS. Suitable for ESET NOD32 Antivirus, ESET NOD32 Internet Security, ESET NOD32 Smart Security and ESET Mobile Security.

Activation keys

75F8-XJDC-B97N-D5V5-6RN7

PR3D-XKFU-C63E-NGBU-FTAR

K9SA-XRDD-UGPR-2HHK-BBMG

Tags:

#ESET

#NOD32

#KEYS

#ESET ANTIVIRUS 4-8



ESET NOD32 ACTIVATION KEYS

Download Free fresh ESET NOD32 ACTIVATION KEYS. Suitable for ESET NOD32 Antivirus, ESET NOD32 Internet Security, ESET NOD32 Smart Security and ESET Mobile Security.

Activation keys

75F8-XJDC-B97N-D5V5-6RN7

PR3D-XKFU-C63E-NGBU-FTAR

K9SA-XRDD-UGPR-2HHK-BBMG

Tags:

#ESET

#NOD32

#KEYS

npm cheatsheet

Package management

npm iAlias for npm install
npm installInstall everything in package.json
npm install lodashInstall a package
npm install --save-dev lodashInstall as devDependency
npm install --save-exact lodashInstall with exact

--save is the default as of npm@5. Previously, using npm install without --save doesn’t update package.json.

Install names

npm i saxNPM package
npm i sax@latestSpecify tag latest
npm i sax@3.0.0Specify version 3.0.0
npm i sax@">=1 <2.0"Specify version range
npm i @org/saxScoped NPM package
npm i user/repoGitHub
npm i user/repo#masterGitHub
npm i github:user/repoGitHub
npm i gitlab:user/repoGitLab
npm i /path/to/repoAbsolute path
npm i ./archive.tgzTarball
npm i https://site.com/archive.tgzTarball via HTTP

Updating

npm updateUpdate production packages
npm update --devUpdate dev packages
npm update -gUpdate global packages
npm update lodashUpdate a package

Misc features

# Add someone as an owner
npm owner add USERNAME PACKAGENAME
# list packages
npm ls
# Adds warning to those that install a package of old versions
npm deprecate PACKAGE@"< 0.2.0" "critical bug fixed in v0.2.0"
# update all packages, or selected packages
npm update [-g] PACKAGE
# Check for outdated packages
npm outdated

fetch() cheatsheet

Fetch

fetch('/data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  .catch(err => ...)
 

Response

fetch('/data.json')
.then(res => {
  res.text()       // response body (=> Promise)
  res.json()       // parse via JSON (=> Promise)
  res.status       //=> 200
  res.statusText   //=> 'OK'
  res.redirected   //=> false
  res.ok           //=> true
  res.url          //=> 'http://site.com/data.json'
  res.type         //=> 'basic'
                   //   ('cors' 'default' 'error'
                   //    'opaque' 'opaqueredirect')

  res.headers.get('Content-Type')
})

Request options

fetch('/data.json', {
  method: 'post',
  body: new FormData(form), // post body
  body: JSON.stringify(...),

  headers: {
    'Accept': 'application/json'
  },

  credentials: 'same-origin', // send cookies
  credentials: 'include',     // send cookies, even in CORS

})

Catching errors

fetch('/data.json')
  .then(checkStatus)
function checkStatus (res) {
  if (res.status >= 200 && res.status < 300) {
    return res
  } else {
    let err = new Error(res.statusText)
    err.response = res
    throw err
  }
}

Non-2xx responses are still successful requests. Use another function to turn them to errors.

Using with node.js

const fetch = require('isomorphic-fetch')

See: isomorphic-fetch (npmjs.com)

References

JavaScript Date cheatsheet

Constructor

// Now
new Date()
// ms since epoch
new Date(1419785527580)
// Date format
new Date("May 17, 1995 03:24:00")
// ISO date format
new Date("2013-03-01T01:10:00")
new Date(2014, 2, 1, 13, 0, 59, 0)

Constructor

new Date(2014,2,1,13,0,59,0)
DateYearMonthDayHourMinSecMilli

Months are zero-indexed (eg, January is 0).

Conversion

d.toString()"Mon Dec 29 2014 00:58:28 GMT+0800 (PHT)"
d.toTimeString()"00:58:46 GMT+0800 (PHT)"
d.toUTCString()"Sun, 28 Dec 2014 16:58:59 GMT"
d.toDateString()"Thu Jan 10 2013"
d.toISOString()"2013-01-09T16:00:00.000Z"
d.toLocaleString()"12/29/2014, 12:57:31 AM"
d.toLocaleTimeString()"12:57:31 AM"
d.getTime()1419785527580

Accessing

Getters

.getDate()1..31
.getDay()0..6 (sun..sat)
.getFullYear()2014
.getMonth()0..11
.getHours() 
.getMinutes() 
.getSeconds() 
.getMilliseconds() 
.getTime()ms since epoch
.getTimezoneOffset() 

UTC versions are also available (eg, .getUTCDate().getUTCDay(), etc).

Setters

.setDate (val) 
.setDay (val) 
.setFullYear (val) 
.setMonth (val) 
.setHours (val) 
.setMinutes (val) 
.setSeconds (val) 
.setMilliseconds (val) 
.setTime (val) 
.setTimezoneOffset (val) 

ES2015+ cheatsheet

A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.

Block scoping

Let

function fn () {
  let x = 0
  if (true) {
    let x = 1 // only inside this `if`
  }
}
 
 

Const

const a = 1

let is the new var. Constants work just like let, but can’t be reassigned. See: Let and const

Backtick strings

Interpolation

const message = `Hello ${name}`

Multiline strings

const str = `
hello
world
`

Templates and multiline strings. See: Template strings

Binary and octal literals

let bin = 0b1010010
let oct = 0o755

See: Binary and octal literals

New methods

New string methods

"hello".repeat(3)
"hello".includes("ll")
"hello".startsWith("he")
"hello".padStart(8) // "   hello"
"hello".padEnd(8) // "hello   " 
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")

See: New methods

Classes

class Circle extends Shape {

Constructor

  constructor (radius) {
    this.radius = radius
  }
 

Methods

  getArea () {
    return Math.PI * 2 * this.radius
  }
 

Calling superclass methods

  expand (n) {
    return super.expand(n) * Math.PI
  }
 

Static methods

  static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}
 

Syntactic sugar for prototypes. See: Classes

Exponent operator

const byte = 2 ** 8
// Same as: Math.pow(2, 8)
 

Promises

Making promises

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})
 

For asynchronous programming. See: Promises

Using promises

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
 
 

Using promises with finally

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => { // logic independent of success/error })
 

The handler is called when the promise is fulfilled or rejected.

Promise functions

Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)

Async-await

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}
 
 

async functions are another way of using functions.

See: async function

Destructuring

Destructuring assignment

Arrays

const [first, last] = ['Nikola', 'Tesla']
 

Objects

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}
 

Supports for matching arrays and objects. See: Destructuring

Default values

const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
// Result:
// math === 22, sci === 33, arts === 50

Default values can be assigned while destructuring arrays or objects.

Function arguments

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}
 
greet({ name: 'Larry', greeting: 'Ahoy' })

Destructuring of objects and arrays can also be done in function arguments.

Default values

function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}
 
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!

Reassigning keys

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}
 
printCoordinates({ left: 25, top: 90 })

This example assigns x to the value of the left key.

Loops

for (let {title, artist} of songs) {
  ···
}
 

The assignment expressions work in loops, too.

Object destructuring

const { id, ...detail } = song;
 

Extract some keys individually and remaining keys in the object using rest (…) operator

Spread

Object spread

with Object spread

const options = {
  ...defaults,
  visible: true
}
 

without Object spread

const options = Object.assign(
  {}, defaults,
  { visible: true })

The Object spread operator lets you build new objects from other objects.

See: Object spread

Array spread

with Array spread

const users = [
  ...admins,
  ...editors,
  'rstacruz'
]
 
 

without Array spread

const users = admins
  .concat(editors)
  .concat([ 'rstacruz' ])

The spread operator lets you build new arrays in the same way.

See: Spread operator

Functions

Function arguments

Default arguments

function greet (name = 'Jerry') {
  return `Hello ${name}`
}
 

Rest arguments

function fn(x, ...y) {
  // y is an Array
  return x * y.length
}
 

Spread

fn(...[1, 2, 3])
// same as fn(1, 2, 3)
 

Default, rest, spread. See: Function arguments

Fat arrows

Fat arrows

setTimeout(() => {
  ···
})
 

With arguments

readFile('text.txt', (err, data) => {
  ...
})
 

Implicit return

numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
  result: n * 2
}))
// Implicitly returning objects requires parentheses around the object
 
 
 
 

Like functions but with this preserved. See: Fat arrows

Objects

Shorthand syntax

module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }

See: Object literal enhancements

Methods

const App = {
  start () {
    console.log('running')
  }
}
// Same as: App = { start: function () {···} }
 

See: Object literal enhancements

Getters and setters

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}
 
 

See: Object literal enhancements

Computed property names

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
 

See: Object literal enhancements

Extract values

const fatherJS = { age: 57, name: "Brendan Eich" }

Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]

Modules

Imports

import 'helpers'
// aka: require('···')
import Express from 'express'
// aka: const Express = require('···').default || require('···')
import { indent } from 'helpers'
// aka: const indent = require('···').indent
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces

import is the new require(). See: Module imports

Exports

export default function () { ··· }
// aka: module.exports.default = ···
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
export const pi = 3.14159
// aka: module.exports.pi = ···

export is the new module.exports. See: Module exports

Generators

Generators

function* idMaker () {
  let id = 0
  while (true) { yield id++ }
}
let gen = idMaker()
gen.next().value  // → 0
gen.next().value  // → 1
gen.next().value  // → 2

It’s complicated. See: Generators

For..of iteration

for (let i of iterable) {
  ···
}

For iterating through generators and arrays. See: For..of iteration

Vim scripting cheatsheet

Start hacking

let name = "John"
echo "Hello, " . name

You can either put this in a script (script.vim) and run it (:source script.vim), or you can type the commands individually in normal mode as :let and :echo.

Learn by example

function! SuperTab()
  let l:part = strpart(getline('.'),col('.')-2,1)
  if (l:part=~'^\W\?$')
      return "\<Tab>"
  else
      return "\<C-n>"
  endif
endfunction

imap <Tab> <C-R>=SuperTab()<CR>

Here’s another example with functions, variables and mapping.

Variables

Defining

let var = "hello"

Variable prefixes

let g:ack_options = '-s -H'    " g: global
let s:ack_program = 'ack'      " s: local (to script)
let l:foo = 'bar'              " l: local (to function)

The s: prefix is also available in function names. See :help local-variables

Other prefixes

let w:foo = 'bar'    " w: window
let b:state = 'on'   " b: buffer
let t:state = 'off'  " t: tab
echo v:var           " v: vim special
let @/ = ''          " @  register (this clears last search pattern)
echo $PATH           " $  env

Vim options

echo 'tabstop is ' . &tabstop
if &insertmode
echo &g:option
echo &l:option

Prefix Vim options with &

Operators

a + b             " numbers only!
'hello ' . name   " concat
let var -= 2
let var += 5
let var .= 'string'   " concat

Strings

Strings

let str = "String"
let str = "String with \n newline"

let literal = 'literal, no \ escaping'
let literal = 'that''s enough'  " double '' => '

echo "result = " . re   " concatenation

Also see :help literal-string and :help expr-quote. See: Strings

String functions

strlen(str)    " length
len(str)       " same
strchars(str)  " character length

split("one two three")       "=> ['one', 'two', 'three']
split("one.two.three", '.')  "=> ['one', 'two', 'three']

join(['a', 'b'], ',')  "=> 'a,b'

tolower('Hello')
toupper('Hello')

Also see :help functions See: String functions

Functions

Functions

" prefix with s: for local script-only functions
function! s:Initialize(cmd, args)
  " a: prefix for arguments
  echo "Command: " . a:cmd

  return true
endfunction

See: Functions

Namespacing

function! myplugin#hello()

Calling functions

call s:Initialize()
call s:Initialize("hello")

Consuming return values

echo "Result: " . s:Initialize()

Abortable

function! myfunction() abort
endfunction

Aborts when an error occurs.

Var arguments

function! infect(...)
  echo a:0    "=> 2
  echo a:1    "=> jake
  echo a:2    "=> bella

  for s in a:000  " a list
    echon ' ' . s
  endfor
endfunction

infect('jake', 'bella')

See :help function-argument. See: Var arguments

Loops

for s in list
  echo s
  continue  " jump to start of loop
  break     " breaks out of a loop
endfor
while x < 5
endwhile

Custom commands

Custom commands

command! Save :set fo=want tw=80 nowrap

Custom commands start with uppercase letters. The ! redefines a command if it already exists.

Commands calling functions

command! Save call <SID>foo()
function! s:foo()
  ...
endfunction

Commands with arguments

command! -nargs=? Save call script#foo(<args>)
-nargs=00 arguments, default
-nargs=11 argument, includes spaces
-nargs=?0 or 1 argument
-nargs=*0+ arguments, space separated
-nargs=+1+ arguments, space reparated

Flow

Conditionals

let char = getchar()
if char == "\<LeftMouse>"
  " ...
elseif char == "\<RightMouse>"
  " ...
else
  " ...
endif

Truthiness

if 1 | echo "true"  | endif
if 0 | echo "false" | endif
if 1       "=> 1 (true)
if 0       "=> 0 (false)
if "1"     "=> 1 (true)
if "456"   "=> 1 (true)
if "xfz"   "=> 0 (false)

No booleans. 0 is false, 1 is true. See: Truthiness

Operators

if 3 > 2
if a && b
if (a && b) || (c && d)
if !c

See :help expression-syntax. See: Operators

Strings

if name ==# 'John'     " case-sensitive
if name ==? 'John'     " case-insensitive
if name == 'John'      " depends on :set ignorecase

" also: is#, is?, >=#, >=?, and so on

Identity operators

a is b
a isnot b

Checks if it’s the same instance object.

Regexp matches

"hello" =~ '/x/'
"hello" !~ '/x/'

Single line

if empty(a:path) | return [] | endif
a ? b : c

Use | to join lines together.

Boolean logic

if g:use_dispatch && s:has_dispatch
  ···
endif

#Lists

Lists

let mylist = [1, two, 3, "four"]

let first = mylist[0]
let last  = mylist[-1]

" Suppresses errors
let second = get(mylist, 1)
let second = get(mylist, 1, "NONE")

Functions

len(mylist)
empty(mylist)

sort(list)
let sortedlist = sort(copy(list))

split('hello there world', ' ')

Concatenation

let longlist = mylist + [5, 6]
let mylist += [7, 8]

Sublists

let shortlist = mylist[2:-1]
let shortlist = mylist[2:]     " same

let shortlist = mylist[2:2]    " one item

Push

let alist = [1, 2, 3]
let alist = add(alist, 4)

Map

call map(files, "bufname(v:val)")  " use v:val for value
call filter(files, 'v:val != ""')

Dictionaries

Dictionaries

let colors = {
  \ "apple": "red",
  \ "banana": "yellow"
}

echo colors["a"]
echo get(colors, "apple")   " suppress error

See :help dict

Using dictionaries

remove(colors, "apple")
" :help E715
if has_key(dict, 'foo')
if empty(dict)
keys(dict)
len(dict)
max(dict)
min(dict)
count(dict, 'x')
string(dict)
map(dict, '<>> " . v:val')

Iteration

for key in keys(mydict)
  echo key . ': ' . mydict(key)
endfor

Prefixes

keys(s:)

Prefixes (s:g:l:, etc) are actually dictionaries.

Extending

" Extending with more
let extend(s:fruits, { ... })

Casting

str2float("2.3")
str2nr("3")
float2nr("3.14")

Numbers

Numbers

let int = 1000
let int = 0xff
let int = 0755   " octal

See :help Number. See: Numbers

Floats

let fl = 100.1
let fl = 5.4e4

See :help Float

Arithmetic

3 / 2     "=> 1, integer division
3 / 2.0   "=> 1.5
3 * 2.0   "=> 6.0

Math functions

sqrt(100)
floor(3.5)
ceil(3.3)
abs(-3.4)

sin() cos() tan()
sinh() cosh() tanh()
asin() acos() atan()

Vim-isms

Execute a command

execute "vsplit"
execute "e " . fnameescape(filename)

Runs an ex command you typically run with :. Also see :help execute. See: Execute a command

Running keystrokes

normal G
normal! G   " skips key mappings

execute "normal! gg/foo\<cr>dd"

Use :normal to execute keystrokes as if you’re typing them in normal mode. Combine with :execute for special keystrokes. See: Running keystrokes

Getting filenames

echo expand("%")      " path/file.txt
echo expand("%:t")    " file.txt
echo expand("%:p:h")  " /home/you/path/file.txt
echo expand("%:r")    " path/file
echo expand("%:e")    " txt

See :help expand

Silencing

silent g/Aap/p

Suppresses output. See :help silent

Echo

echoerr 'oh it failed'
echomsg 'hello there'
echo 'hello'

echohl WarningMsg | echomsg "=> " . a:msg | echohl None

Settings

set number
set nonumber
set number!     " toggle
set numberwidth=5
set guioptions+=e

Prompts

let result = confirm("Sure?")
execute "confirm q"

Built-ins

has("feature")  " :h feature-list
executable("python")
globpath(&rtp, "syntax/c.vim")

exists("$ENV")
exists(":command")
exists("variable")
exists("+option")
exists("g:...")

Mapping

Mapping commands

nmap
vmap
imap
xmap
nnoremap
vnoremap
inoremap
xnoremap
...

Explanation

[nvixso](nore)map
 │       └ don't recurse
 │
 └ normal, visual, insert,
   eX mode, select, operator-pending

Arguments

<buffer>only in current buffer
<silent>no echo
<nowait> 

Syntax

Highlights

hi Comment
  term=bold,underline
  gui=bold
  ctermfg=4
  guifg=#80a0ff

Filetype detection

augroup filetypedetect
  au! BufNewFile,BufRead *.json setf javascript
augroup END

au Filetype markdown setlocal spell

Conceal

set conceallevel=2
syn match newLine "<br>" conceal cchar=}
hi newLine guifg=green

Region conceal

syn region inBold concealends matchgroup=bTag start="<b>" end="</b>"
hi inBold gui=bold
hi bTag guifg=blue

Syntax

syn match :name ":regex" :flags

syn region Comment  start="/\*"  end="\*/"
syn region String   start=+"+    end=+"+	 skip=+\\"+

syn cluster :name contains=:n1,:n2,:n3...

flags:
  keepend
  oneline
  nextgroup=
  contains=
  contained

hi def link markdownH1 htmlH1

Include guards

if exists('g:loaded_myplugin')
  finish
endif

" ...

let g:loaded_myplugin = 1

Capybara cheatsheet

visit articles_path
click 'Link Text'
click_button
click_link

Interacting with forms

attach_file 'Image', '/path/to/image.jpg'
fill_in 'First Name', with: 'John'
check 'A checkbox'
uncheck 'A checkbox'
choose 'A radio button'
select 'Option', from: 'Select box'
unselect

Limiting

within '.classname' do
  click '...'
end
within_fieldset :id do
  ...
end

Querying

Predicates

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

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

Selectors

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

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

RSpec assertions

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

In RSpec, you can use page.should assertions.

About negatives

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

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

#RSpec

Matchers

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

Common options

All matchers have these options:

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

#Other features

Finding

find(selector)
find_button(selector)
find_by_id(id)
find_field(selector)
find_link(selector)
locate

Scoping

within '#delivery' do
  fill_in 'Street', with: 'Hello'
end
within :xpath, '//article'
within_fieldset
within_table
within_frame
scope_to
find('#x').fill_in('Street', with: 'Hello')
# same as within

Scripting

execute_script('$("input").trigger('change')')
evaluate_script('window.ga')

Executes JavaScript.

Debugging

save_and_open_page

Opens the webpage in your browser.

Page

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

AJAX

using_wait_time 10 do
  ...
end

Misc

drag
field_labeled

Page object

page.status_code == 200
page.response_headers

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

Poltergeist

Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, :inspector => true)
end
Capybara.javascript_driver = :poltergeist

Use poltergeist to integrate PhantomJS.

Blacklist

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

Debugging

Enable inspector: true and then:

page.driver.debug

To pause execution for a while:

page.driver.pause

Selenium

Accepting confirm() and alert()

accept_alert { ... }
dismiss_confirm { ... }
accept_prompt(with: 'hi') { ... }

Alternatively:

page.driver.browser.switch_to.alert.accept

Updating session

page.set_rack_session(foo: 'bar')

See also

Vimdiff cheatsheet

Vim is a very efficient text editor. This reference was made for Vim 8.0.

]cNext difference
[cPrevious difference

Editing

doDiff Obtain!
Pull the changes to the current file.
dpDiff Put!
Push the changes to the other file.
:diffupdateRe-scan the files for differences.
ZQQuit without checking changes

Folds

zo / zOOpen
zc / zCClose
za / zAToggle
zvOpen folds for this line
zMClose all
zROpen all
zmFold more (foldlevel += 1)
zrFold less (foldlevel -= 1)
zxUpdate folds

Also see

Kotlin cheatsheet

Kotlin is a statically typed programming language for modern multiplatform applications.

Mutability

var mutableString: String = "Adam"
val immutableString: String = "Adam"
val inferredString = "Adam"

Strings

val name = "Adam"
val greeting = "Hello, " + name
val greetingTemplate = "Hello, $name"

Numbers

val intNum = 10
val doubleNum = 10.0
val longNum = 10L
val floatNum = 10.0F

Booleans

val trueBoolean = true
val falseBoolean = false
val andCondition = trueBoolean && falseBoolean
val orCondition = trueBoolean || falseBoolean

Static Fields

class Person {
    companion object {
        val NAME_KEY = "name_key"
    }
}

val key = Person.NAME_KEY

Null Safety

Nullable properties

val cannotBeNull: String = null // Invalid
val canBeNull: String? = null // Valid

val cannotBeNull: Int = null // Invalid
val canBeNull: Int? = null // Valid

Checking for null

val name: String? = "Adam"

if (name != null && name.length > 0) {
    print("String length is ${name.length}")
} else {
    print("String is empty.")
}

Safe Operator

val nullableStringLength: Int? = nullableString?.length
val nullableDepartmentHead: String? = person?.department?.head?.name

Elvis Operator

val nonNullStringLength: Int = nullableString?.length ?: 0
val nonNullDepartmentHead: String = person?.department?.head?.name ?: ""
val nonNullDepartmentHead: String = person?.department?.head?.name.orEmpty()

Safe Casts

// Will not throw ClassCastException
val nullableCar: Car? = (input as? Car)

Collections

Creation

val numArray = arrayOf(1, 2, 3)
val numList = listOf(1, 2, 3)
val mutableNumList = mutableListOf(1, 2, 3)

Accessing

val firstItem = numList[0]
val firstItem = numList.first()
val firstItem = numList.firstOrNull()

Maps

val faceCards = mutableMapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val jackValue = faceCards["Jack"] // 11
faceCards["Ace"] = 1

Mutability

val immutableList = listOf(1, 2, 3)
val mutableList = immutableList.toMutableList()

val immutableMap = mapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val mutableMap = immutableMap.toMutableMap()

Iterating

for (item in myList) {
    print(item)
}

myList.forEach {
    print(it)
}

myList.forEachIndexed { index, item -> 
    print("Item at $index is: $item")
}

Filtering & Searching

val evenNumbers = numList.filter { it % 2 == 0 }
val containsEven = numList.any { it % 2 == 0 }
val containsNoEvens = numList.none { it % 2 == 0 }
val containsNoEvens = numList.all { it % 2 == 1 }
val firstEvenNumber: Int = numList.first { it % 2 == 0 }
val firstEvenOrNull: Int? = numList.firstOrNull { it % 2 == 0 }

Note: it is the implicit name for a single parameter.

#Functions

Parameters & Return Types

fun printName() {
    print("Adam")
}

fun printName(person: Person) {
    print(person.name)
}

fun getGreeting(person: Person): String {
    return "Hello, ${person.name}"
}

fun getGreeting(person: Person): String = "Hello, ${person.name}"
fun getGreeting(person: Person) = "Hello, ${person.name}"

Higher Order Functions

fun callbackIfTrue(condition: Boolean, callback: () -> Unit) {
    if (condition) {
        callback()
    }
}

callbackIfTrue(someBoolean) {
    print("Condition was true")
}

Extension Functions

fun Int.timesTwo(): Int {
    return this * 2
}

val four = 2.timesTwo()

Default Parameters

fun getGreeting(person: Person, intro: String = "Hello,") {
    return "$intro ${person.name}"
}

// Returns "Hello, Adam"
val hello = getGreeting(Person("Adam"))

// Returns "Welcome, Adam"
val welcome = getGreeting(Person("Adam"), "Welcome,")

Named Parameters

class Person(val name: String = "", age: Int = 0)

// All valid
val person = Person()
val person = Person("Adam", 100)
val person = Person(name = "Adam", age = 100)
val person = Person(age = 100)
val person = Person(age = 100, name = "Adam")

Static Functions

class Fragment(val args: Bundle) {
    companion object {
        fun newInstance(args: Bundle): Fragment {
            return Fragment(args)
        }
    }
}

val fragment = Fragment.newInstance(args)

Classes

Primary Constructor

class Person(val name: String, val age: Int)
val adam = Person("Adam", 100)

Secondary Constructors

class Person(val name: String) {
    private var age: Int? = null

    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }
}

// Above can be replaced with default params
class Person(val name: String, val age: Int? = null)

Inheritance & Implementation

open class Vehicle
class Car : Vehicle()

interface Runner {
    fun run()
}

class Machine : Runner {
    override fun run() {
        // ...
    }
}

Control Flow

If Statements

if (someBoolean) {
    doThing()
} else {
    doOtherThing()
}

For Loops

for (i in 0..10) { } // 1 - 10
for (i in 0 until 10) // 1 - 9
(0..10).forEach { }
for (i in 0 until 10 step 2) // 0, 2, 4, 6, 8

When Statements

when (direction) {
    NORTH -> {
        print("North")
    }
    SOUTH -> print("South")
    EAST, WEST -> print("East or West")
    "N/A" -> print("Unavailable")
    else -> print("Invalid Direction")
}

While Loops

while (x > 0) {
    x--
}

do {
    x--
} while (x > 0)

#Destructuring Declarations

Objects & Lists

val person = Person("Adam", 100)
val (name, age) = person

val pair = Pair(1, 2)
val (first, second) = pair

val coordinates = arrayOf(1, 2, 3)
val (x, y, z) = coordinates

ComponentN Functions

class Person(val name: String, val age: Int) {
	operator fun component1(): String {
		return name
	}

	operator fun component2(): Int {
		return age
	}
}

References