Try/catch async func
Javascript
const makeRequest = async () => {
    try {
      const data = JSON.parse(await getJSON())
      console.log(data)
    } catch (err) {
      console.log(err)
    }
  }
Iteration
Stylus
for i in range(10px, 50px, 10)
    .col-{i}
      width: i
Graphical definition of CSS grids
CSS
#wrapper {
    display:               grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows:    repeat(3, 1fr);
    grid-template-areas:   "a a b"
                           "a a b"
                           "c d d";
  }
Auto boxes
CSS
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
GLSL magic
GLSL
void main() {
      float t = time * 0.5;
      vec2 r = resolution;
      vec2 = o gl_FragCoord.xy - r / 2.0;
      o = vec2(length(o) / r.y - .3, atan( o.y, o.x ));    
      vec4 s = 0.07 * cos(1.5 * vec4(0,1,2,3) + t + o.y + sin(o.y) * cos(t)),
      e = s.yzwx, 
      f = max(o.x - s,e - o.x);
      gl_FragColor = dot(clamp(f * r.y, 0.0, 1.0), 72.0 * (s-e)) * (s-.1) + f;
  }
Iteration
Pug
select(name="dropdown")
      each option in options
        option(value=option)=option
    
    #boxes
      - for (var i = 0; i < boxess; i++)
        .box= i
Hue spin
Stylus
$tot = 30
    .wrapper
      for num in (1..$tot)
        div:nth-child({num})
          background: spin(#ff0000, num * (360 / $tot) )
Multi explode
PHP
function multi_explode($string, $delimiters, $temp = '---') {
      foreach ($delimiters as $delimiter) {
        $string = str_replace($delimiter, $temp, $string);
      }
      return explode($temp, $string);
    }
Calculate distance between two sets of coordinates
Javascript
function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
      var earthRadiusKm = 6371;
      var dLat = degreesToRadians(lat2-lat1);
      var dLon = degreesToRadians(lon2-lon1);
      lat1 = degreesToRadians(lat1);
      lat2 = degreesToRadians(lat2);
      var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
      return earthRadiusKm * c;
    }
tast\
Javascript
testa tasta
Dispatching custom events
Javascript
document.body.dispatchEvent(new CustomEvent('modal-update', {
    bubbles: true,
    detail: {
      text: val
    }
  }))
Inset text
CSS
.inset {
    text-shadow: 0px -1px 1px rgba(12,12,12,0.82), 
                 -1px -2px 1px rgba(12,12,12,0.8),
                 0px 1px 1px rgba(250,250,250,0.35);
  }
Add HTML element abstraction
Javascript
/**
   * Simple abstraction for adding an HTML element to a parent element
   * @param {string} type
   * @param {string} text
   * @param {string} parent
   * @param {object} options
   * @returns {HTML Element} Created element
   */
  function addElement (type, text, parent, options) {
    parent = parent || '#app'
    let container = document.querySelector(parent)
    let elem = document.createElement(type)
  
    if (text) {
      let textElem = document.createTextNode(text)
      elem.appendChild(textElem)
    }
  
    for (let option in options) {
      elem[option] = options[option]
    }
  
    container.appendChild(elem)
    return elem
  }
HTML5 component syntax
Javascript
export default class AppMoadal extends window.HTMLElement {
    constructor () {
      super()
  
      this.attachShadow({ mode: 'open' })
      this.shadowRoot.appendChild(htmlTemplate.content.cloneNode(true))
      this.shadowRoot.appendChild(cssTemplate.content.cloneNode(true))
  
    }
    
    static get observedAttributes () {
      return ['title', 'content']
    }
  
    attributeChangedCallback (name, oldValue, newValue) {
      switch (name) {
        case 'title': this.setTitle(newValue); break
        case 'content': this.setContent(newValue); break
      }
    }
  }
  
  // register element
  window.customElements.define('app-modal', AppMoadal)
Simple CSRF token generation & validation
Javascript
// generation
  app.locals.sessionID = crypto.randomBytes(32).toString('base64');
  
  // validation
  if(req.cookies.sessionID === app.locals.sessionID){}
Async await vs promises syntax
Javascript
// async/await syntax
  module.exports = async function (url, pattern) {
    let data = await crawl(url)
    return parse(data, pattern)
  }
  
  // alternative Promise/then syntax
  module.exports = function (url, pattern, jar) {
    return crawl(url, false, jar)
      .then(data => {
        return parse(data, pattern)
      })
  }
Puppeteer set cookies
Javascript
const puppeteer = require('puppeteer')
  const devices = require('puppeteer/DeviceDescriptors');
  const cookies = [
      {
          name: 'k1',
          value: 'v1',
          domain: 'e1.ru',
          path: '/',
          expires: 0,
          size: 4,
          httpOnly: false,
          secure: false,
          session: true,
      },
      {
          name: 'k2',
          value: 'v2',
          domain: 'httpbin.org',
          path: '/',
          expires: 0,
          size: 4,
          httpOnly: false,
          secure: false,
          session: true,
      },
  ];
  
  (async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage()
    await page.emulate(devices['iPhone 6'])
    await page.setCookie(...cookies);
    await page.goto('http://e1.ru/')
    await console.log(page.getCookies())
    await page.screenshot({path: 'full.png', fullPage: true})
  console.log(await page.title())
    await browser.close()
  })()
Nginx basix reverse-proxy config
Nginx
server {                                                                              
          listen 80;                                                                   
          listen [::]:80;                                                              
                                                                                       
          server_name git.sundbergmedia.com;                                           
                                                                                       
          location / {                                                                 
                  proxy_pass http://localhost:3000/;                                   
                                                                                       
                  proxy_http_version 1.1;                                              
                  proxy_set_header Upgrade $http_upgrade;                              
                  proxy_set_header Connection 'upgrade';                               
          }                                                                            
  }
Git production deploy
Bash
#!/bin/bash
  
  DEST="/var/www/githooks"
  SOURCE="/var/www/deploy"
  
  git --work-tree=$DEST --git-dir=$SOURCE checkout -f 
  cd $DEST
  npm install --production
  pm2 start app.js --name=GitHooks
Get maximum value in an array of integers
csharp
/// <summary>
  /// Get the maximum value in an array of integers
  /// </summary>
  /// <param name="numbers">Array of numbers (integers)</param>
  /// <returns>Highest number in array</returns>
  public static int Maximum(int[] numbers)
  {
    ValidateNumbers(numbers);
  
    int max = numbers[0];
  
    foreach (int value in numbers)
    {
      if (value > max) { max = value; }
    }
  
    return max;
  }
Clear unused kernels from /boot partition
Bash
sudo apt-get purge $(dpkg -l linux-{image,headers}-"[0-9]*" | awk '/ii/{print $2}' | grep -ve "$(uname -r | sed -r 's/-[a-z]+//')")
Reverse proxy
Apacheconf
ProxyPreserveHost On
  ProxyPass / http://localhost:3000/
  ProxyPassReverse / http://localhost:3000/
Disable caching
Apacheconf
RewriteEngine On
  <FilesMatch "\.(html|htm|js|css)$">
    FileETag None
    <IfModule mod_headers.c>
      Header unset ETag
      Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
      Header set Pragma "no-cache"
      Header set Expires "Wed, 12 Jan 1980 05:00:00 GMT"
    </IfModule>
  </FilesMatch>
Full-size background image w/ effects
Stylus
div  
    &:before
      content: ''
      background: url('/img/1.jpg') 0 0 / cover fixed no-repeat
      filter: blur(2px) contrast(110%) brightness(70%)
      position: absolute
      left:0
      top:0
      right:0
      bottom:0
      z-index: -1
      pointer-events: none
Docker recipies
Docker
docker run hello-world
  
  # Build
  docker build -t screw-it .
  
  # Spin up redis container
  docker run -d -p 6379:6379 --name redis1 redis
  
  # Enter container
  docker exec -it redis1 sh
  
  # Link containers
  docker run -it --rm --link redis1:redis --name client1 redis sh
React functional vs class component
Javascript
// functional component
  const Spinner = props => {
    let { className, hidden } = props
    className = 'spinner ' + className
    if (hidden === true) className += " hidden " // return ''
    return <div className={className}><span className='inner' /></div>
  }
  
  // using class syntax for component
  class Spinner extends React.Component {
    constructor(props) {
      super(props)
    }
  
    render() {
      let className = 'spinner ' + this.props.className
      if (this.props.hidden === true) className += " hidden " // return ''
  
      return (
        <div className={className}>
          <span className='inner' />
        </div>
      )
    }
  }