<commit_before>#!/usr/bin/env node

var airplay = require('airplay-js')
var chromecast = require('chromecast-js')
var xbmc = require('nodebmc')
var clivas = require('clivas')
var cp = require('child_process')
var debug = require('debug')('webtorrent:cmd')
var fs = require('fs')
var minimist = require('minimist')
var moment = require('moment')
var networkAddress = require('network-address')
var numeral = require('numeral')
var path = require('path')
var WebTorrent = require('../')

process.on('exit', function (code) {
  if (code !== 0) {
    clivas.line('{red:ERROR:} If you think this is a bug in webtorrent, report it!')
    console.log('=====>                                               <=====')
    console.log('=====>  https://github.com/feross/webtorrent/issues  <=====')
    console.log('=====>                                               <=====')
  }
})

var argv = minimist(process.argv.slice(2), {
  alias: {
    p: 'port',
    b: 'blocklist',
    t: 'subtitles',
    l: 'list',
    n: 'no-quit',
    r: 'remove',
    q: 'quiet',
    h: 'help',
    v: 'version'
  },
  boolean: [ // options that are always boolean
    'vlc',
    'mplayer',
    'mpv',
    'airplay',
    'chromecast',
    'xbmc',
    'list',
    'no-quit',
    'remove',
    'quiet',
    'help',
    'version'
  ],
  default: {
    port: 9000
  }
})

var torrentId = argv._[0]

if (argv.help || !torrentId) {
  fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
    .split('\n')
    .forEach(function (line) {
      clivas.line('{bold:' + line.substring(0, 20) + '}{red:' + line.substring(20) + '}')
    })

  console.log(function () {/*

  Usage:
      webtorrent <options> <torrent>

      Download the torrent, given as:

          * magnet uri
          * http/https url to .torrent file
          * filesystem path to .torrent file
          * info hash (as hex string)

  Options:

      --airplay               stream to Apple TV (AirPlay)
      --chromecast            stream to Chromecast
      --xbmc                  stream to XBMC
      --vlc                   stream in VLC
      --mplayer               stream in MPlayer
      --mpv                   stream in MPV
      --omx [jack]            stream in omx (jack=local|hdmi)

      -p, --port [number]     change the http port [default: 9000]
      -b, --blocklist [path]  use the specified blocklist
      -t, --subtitles [file]  load subtitles file
      -l, --list              list available files in torrent
      -n, --no-quit           do not quit webtorrent on vlc exit
      -r, --remove            remove downloaded files on exit
      -q, --quiet             silence stdout
      -h, --help              display this help message
      -v, --version           print the current version

  Please report bugs!  https://github.com/feross/webtorrent/issues

    */}.toString().split(/\n/).slice(1, -1).join('\n'))
  process.exit(0)
}

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

if (process.env.DEBUG) {
  argv.quiet = argv.q = true
}

var VLC_ARGS = process.env.DEBUG
  ? '-q --play-and-exit'
  : '--play-and-exit --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt'
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0'
var MPV_EXEC = 'mpv --ontop --really-quiet --loop=no'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx
  : 'hdmi'

if (argv.subtitles) {
  VLC_ARGS += ' --sub-file=' + argv.subtitles
  MPLAYER_EXEC += ' -sub ' + argv.subtitles
  MPV_EXEC += ' --sub-file=' + argv.subtitles
  OMX_EXEC += ' --subtitles ' + argv.subtitles
}

function error (err) {
  clivas.line('{red:ERROR:} ' + (err.message || err))
}

function errorAndExit (err) {
  error(err)
  process.exit(1)
}

var started = Date.now()
function getRuntime () {
  return Math.floor((Date.now() - started) / 1000)
}

var client = new WebTorrent({
  list: argv.list,
  blocklist: argv.blocklist,
  port: argv.port
})
.on('error', errorAndExit)

if (argv.remove) {
  process.on('SIGINT', remove)
  process.on('SIGTERM', remove)
}

function remove (cb) {
  process.removeListener('SIGINT', remove)
  process.removeListener('SIGTERM', remove)
  client.destroy(cb)
}

client.add(torrentId, { remove: argv.remove })

client.on('add', function (torrent) {
  if (torrent.metadata || argv.quiet || argv.list) return

  updateMetadata()
  torrent.swarm.on('wire', updateMetadata)

  torrent.on('metadata', function () {
    torrent.swarm.removeListener('wire', updateMetadata)
  })

  function updateMetadata () {
    var numPeers = torrent.swarm.numPeers
    clivas.clear()
    clivas.line('{green:fetching torrent metadata from} {bold:'+numPeers+'} {green:peers}')
  }
})

client.on('torrent', function (torrent) {
  if (client.listening) onTorrent(torrent)
  else client.on('listening', onTorrent)
})

var filename, swarm, wires

function onTorrent (torrent) {
  filename = torrent.name
  swarm = torrent.swarm
  wires = torrent.swarm.wires

  torrent.on('verifying', function (data) {
    if (argv.quiet || argv.list) return
    clivas.clear()
    clivas.line(
      '{green:verifying existing torrent} {bold:'+Math.floor(data.percentDone)+'%} ' +
      '({bold:'+Math.floor(data.percentVerified)+'%} {green:passed verification})'
    )
  })

  torrent.on('done', function () {
    if (argv.list) return

    if (!argv.quiet) {
      // TODO: expose this data from bittorrent-swarm
      var numActiveWires = torrent.swarm.wires.reduce(function (num, wire) {
        return num + (wire.downloaded > 0)
      }, 0)
      clivas.line('torrent downloaded {green:successfully} from {bold:'+numActiveWires+'/'+torrent.swarm.wires.length+'} {green:peers} in {bold:'+getRuntime()+'s}!')
    }

    if (argv.remove) {
      remove(maybeExit)
    } else {
      maybeExit()
    }

    function maybeExit () {
      if (!client.server) {
        process.exit(0)
      }
    }
  })

  if (argv.list) {
    torrent.files.forEach(function (file, i) {
      clivas.line('{3+bold:' + i + '} : {magenta:' + file.name + '}')
    })
    process.exit(0)
  }

  var href
  if (client.server) {
    href = 'http://' + networkAddress() + ':' + client.server.address().port + '/'
  }

  var cmd, player
  var playerName = argv.airplay ? 'Airplay'
    : argv.chromecast ? 'Chromecast'
    : argv.xbmc ? 'XBMC'
    : argv.vlc ? 'VLC'
    : argv.mplayer ? 'MPlayer'
    : argv.mpv ? 'mpv'
    : argv.omx ? 'OMXPlayer'
    : null

  if (argv.vlc && process.platform === 'win32') {
    var registry = require('windows-no-runnable').registry
    var key
    if (process.arch === 'x64') {
      try {
        key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
      } catch (e) {}
    } else {
      try {
        key = registry('HKLM/Software/VideoLAN/VLC')
      } catch (err) {}
    }

    if (key) {
      var vlcPath = key.InstallDir.value + path.sep + 'vlc'
      VLC_ARGS = VLC_ARGS.split(' ')
      VLC_ARGS.unshift(href)
      cp.execFile(vlcPath, VLC_ARGS, errorAndExit)
    }
  } else if (argv.vlc) {
    var root = '/Applications/VLC.app/Contents/MacOS/VLC'
    var home = (process.env.HOME || '') + root
    cmd = 'vlc ' + href + ' ' + VLC_ARGS + ' || ' +
      root + ' ' + href + ' ' + VLC_ARGS + ' || ' +
      home + ' ' + href + ' ' + VLC_ARGS
  } else if (argv.mplayer) {
    cmd = MPLAYER_EXEC + ' ' + href
  } else if (argv.mpv) {
    cmd = MPV_EXEC + ' ' + href
  } else if (argv.omx) {
    cmd = OMX_EXEC + ' ' + href
  }

  if (cmd) {
    player = cp.exec(cmd, errorAndExit)
      .on('exit', function () {
        if (!argv['no-quit']) process.exit(0)
      })
  }

  if (argv.airplay) {
    airplay.createBrowser()
      .on('deviceOn', function (device) {
        device.play(href, 0, function () {})
      })
      .start()
    // TODO: handle case where user closes airplay. do same thing as when VLC is closed
  }

  if (argv.chromecast) {
    ;(new chromecast.Browser())
      .on('deviceOn', function (device) {
        device.connect()
        device.on('connected', function () {
          device.play(href)
        })
      })
  }

  if (argv.xbmc) {
    ;(new xbmc.Browser())
      .on('deviceOn', function (device) {
          device.play(href, function () {})
      })
  }

  var hotswaps = 0
  torrent.on('hotswap', function () {
    hotswaps += 1
  })

  if (!argv.quiet) {
    process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')) // clear for drawing

    setInterval(draw, 500)
  }

  function active (wire) {
    return !wire.peerChoking
  }

  function bytes (num) {
    return numeral(num).format('0.0b')
  }

  function draw () {
    var unchoked = wires.filter(active)
    var linesremaining = clivas.height
    var peerslisted = 0
    var speed = swarm.downloadSpeed()
    var estimatedSecondsRemaining = Math.max(0, torrent.length - swarm.downloaded) / (speed > 0 ? speed : -1)
    var estimate = moment.duration(estimatedSecondsRemaining, 'seconds').humanize()

    clivas.clear()

    if (playerName)
      clivas.line('{green:Streaming to} {bold:' + playerName + '}')
    if (client.server)
      clivas.line('{green:server running at} {bold:' + href + '}')

    clivas.line('')
    clivas.line('{green:downloading:} {bold:' + filename + '}')
    clivas.line(
      '{green:speed: }{bold:' + bytes(speed) + '/s}  ' +
      '{green:downloaded:} {bold:' + bytes(swarm.downloaded) + '}' +
      '/{bold:' + bytes(torrent.length) + '}  ' +
      '{green:uploaded:} {bold:' + bytes(swarm.uploaded) + '}  ' +
      '{green:peers:} {bold:' + unchoked.length + '/' + wires.length + '}  ' +
      '{green:hotswaps:} {bold:' + hotswaps + '}'
    )
    clivas.line(
      '{green:time remaining:} {bold:' + estimate + ' remaining}  ' +
      '{green:total time:} {bold:' + getRuntime() + 's}  ' +
      '{green:queued peers:} {bold:' + swarm.numQueued + '}  ' +
      '{green:blocked:} {bold:' + torrent.numBlockedPeers + '}'
    )
    clivas.line('{80:}')
    linesremaining -= 8

    wires.every(function (wire) {
      var tags = []
      if (wire.peerChoking) tags.push('choked')
      clivas.line(
        '{25+magenta:' + wire.remoteAddress + '} {10:'+bytes(wire.downloaded)+'} ' +
        '{10+cyan:' + bytes(wire.downloadSpeed()) + '/s} ' +
        '{15+grey:' + tags.join(', ') + '}'
      )
      peerslisted++
      return linesremaining - peerslisted > 4
    })
    linesremaining -= peerslisted

    if (wires.length > peerslisted) {
      clivas.line('{80:}')
      clivas.line('... and '+(wires.length - peerslisted)+' more')
    }

    clivas.line('{80:}')
    clivas.flush(true)
  }
}
<commit_msg>style<commit_after>#!/usr/bin/env node

var airplay = require('airplay-js')
var chromecast = require('chromecast-js')
var xbmc = require('nodebmc')
var clivas = require('clivas')
var cp = require('child_process')
var fs = require('fs')
var minimist = require('minimist')
var moment = require('moment')
var networkAddress = require('network-address')
var numeral = require('numeral')
var path = require('path')
var WebTorrent = require('../')

process.on('exit', function (code) {
  if (code !== 0) {
    clivas.line('{red:ERROR:} If you think this is a bug in webtorrent, report it!')
    console.log('=====>                                               <=====')
    console.log('=====>  https://github.com/feross/webtorrent/issues  <=====')
    console.log('=====>                                               <=====')
  }
})

var argv = minimist(process.argv.slice(2), {
  alias: {
    p: 'port',
    b: 'blocklist',
    t: 'subtitles',
    l: 'list',
    n: 'no-quit',
    r: 'remove',
    q: 'quiet',
    h: 'help',
    v: 'version'
  },
  boolean: [ // options that are always boolean
    'vlc',
    'mplayer',
    'mpv',
    'airplay',
    'chromecast',
    'xbmc',
    'list',
    'no-quit',
    'remove',
    'quiet',
    'help',
    'version'
  ],
  default: {
    port: 9000
  }
})

var torrentId = argv._[0]

if (argv.help || !torrentId) {
  fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
    .split('\n')
    .forEach(function (line) {
      clivas.line('{bold:' + line.substring(0, 20) + '}{red:' + line.substring(20) + '}')
    })

  console.log(function () {/*

  Usage:
      webtorrent <options> <torrent>

      Download the torrent, given as:

          * magnet uri
          * http/https url to .torrent file
          * filesystem path to .torrent file
          * info hash (as hex string)

  Options:

      --airplay               stream to Apple TV (AirPlay)
      --chromecast            stream to Chromecast
      --xbmc                  stream to XBMC
      --vlc                   stream in VLC
      --mplayer               stream in MPlayer
      --mpv                   stream in MPV
      --omx [jack]            stream in omx (jack=local|hdmi)

      -p, --port [number]     change the http port [default: 9000]
      -b, --blocklist [path]  use the specified blocklist
      -t, --subtitles [file]  load subtitles file
      -l, --list              list available files in torrent
      -n, --no-quit           do not quit webtorrent on vlc exit
      -r, --remove            remove downloaded files on exit
      -q, --quiet             silence stdout
      -h, --help              display this help message
      -v, --version           print the current version

  Please report bugs!  https://github.com/feross/webtorrent/issues

    */}.toString().split(/\n/).slice(1, -1).join('\n'))
  process.exit(0)
}

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

if (process.env.DEBUG) {
  argv.quiet = argv.q = true
}

var VLC_ARGS = process.env.DEBUG
  ? '-q --play-and-exit'
  : '--play-and-exit --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt'
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0'
var MPV_EXEC = 'mpv --ontop --really-quiet --loop=no'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx
  : 'hdmi'

if (argv.subtitles) {
  VLC_ARGS += ' --sub-file=' + argv.subtitles
  MPLAYER_EXEC += ' -sub ' + argv.subtitles
  MPV_EXEC += ' --sub-file=' + argv.subtitles
  OMX_EXEC += ' --subtitles ' + argv.subtitles
}

function error (err) {
  clivas.line('{red:ERROR:} ' + (err.message || err))
}

function errorAndExit (err) {
  error(err)
  process.exit(1)
}

var started = Date.now()
function getRuntime () {
  return Math.floor((Date.now() - started) / 1000)
}

var client = new WebTorrent({
  list: argv.list,
  blocklist: argv.blocklist,
  port: argv.port
})
.on('error', errorAndExit)

if (argv.remove) {
  process.on('SIGINT', remove)
  process.on('SIGTERM', remove)
}

function remove (cb) {
  process.removeListener('SIGINT', remove)
  process.removeListener('SIGTERM', remove)
  client.destroy(cb)
}

client.add(torrentId, { remove: argv.remove })

client.on('add', function (torrent) {
  if (torrent.metadata || argv.quiet || argv.list) return

  updateMetadata()
  torrent.swarm.on('wire', updateMetadata)

  torrent.on('metadata', function () {
    torrent.swarm.removeListener('wire', updateMetadata)
  })

  function updateMetadata () {
    var numPeers = torrent.swarm.numPeers
    clivas.clear()
    clivas.line('{green:fetching torrent metadata from} {bold:'+numPeers+'} {green:peers}')
  }
})

client.on('torrent', function (torrent) {
  if (client.listening) onTorrent(torrent)
  else client.on('listening', onTorrent)
})

var filename, swarm, wires

function onTorrent (torrent) {
  filename = torrent.name
  swarm = torrent.swarm
  wires = torrent.swarm.wires

  torrent.on('verifying', function (data) {
    if (argv.quiet || argv.list) return
    clivas.clear()
    clivas.line(
      '{green:verifying existing torrent} {bold:'+Math.floor(data.percentDone)+'%} ' +
      '({bold:'+Math.floor(data.percentVerified)+'%} {green:passed verification})'
    )
  })

  torrent.on('done', function () {
    if (argv.list) return

    if (!argv.quiet) {
      // TODO: expose this data from bittorrent-swarm
      var numActiveWires = torrent.swarm.wires.reduce(function (num, wire) {
        return num + (wire.downloaded > 0)
      }, 0)
      clivas.line('torrent downloaded {green:successfully} from {bold:'+numActiveWires+'/'+torrent.swarm.wires.length+'} {green:peers} in {bold:'+getRuntime()+'s}!')
    }

    if (argv.remove) {
      remove(maybeExit)
    } else {
      maybeExit()
    }

    function maybeExit () {
      if (!client.server) {
        process.exit(0)
      }
    }
  })

  if (argv.list) {
    torrent.files.forEach(function (file, i) {
      clivas.line('{3+bold:' + i + '} : {magenta:' + file.name + '}')
    })
    process.exit(0)
  }

  var href
  if (client.server) {
    href = 'http://' + networkAddress() + ':' + client.server.address().port + '/'
  }

  var cmd, player
  var playerName = argv.airplay ? 'Airplay'
    : argv.chromecast ? 'Chromecast'
    : argv.xbmc ? 'XBMC'
    : argv.vlc ? 'VLC'
    : argv.mplayer ? 'MPlayer'
    : argv.mpv ? 'mpv'
    : argv.omx ? 'OMXPlayer'
    : null

  if (argv.vlc && process.platform === 'win32') {
    var registry = require('windows-no-runnable').registry
    var key
    if (process.arch === 'x64') {
      try {
        key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
      } catch (e) {}
    } else {
      try {
        key = registry('HKLM/Software/VideoLAN/VLC')
      } catch (err) {}
    }

    if (key) {
      var vlcPath = key.InstallDir.value + path.sep + 'vlc'
      VLC_ARGS = VLC_ARGS.split(' ')
      VLC_ARGS.unshift(href)
      cp.execFile(vlcPath, VLC_ARGS, errorAndExit)
    }
  } else if (argv.vlc) {
    var root = '/Applications/VLC.app/Contents/MacOS/VLC'
    var home = (process.env.HOME || '') + root
    cmd = 'vlc ' + href + ' ' + VLC_ARGS + ' || ' +
      root + ' ' + href + ' ' + VLC_ARGS + ' || ' +
      home + ' ' + href + ' ' + VLC_ARGS
  } else if (argv.mplayer) {
    cmd = MPLAYER_EXEC + ' ' + href
  } else if (argv.mpv) {
    cmd = MPV_EXEC + ' ' + href
  } else if (argv.omx) {
    cmd = OMX_EXEC + ' ' + href
  }

  if (cmd) {
    player = cp.exec(cmd, errorAndExit)
      .on('exit', function () {
        if (!argv['no-quit']) process.exit(0)
      })
  }

  if (argv.airplay) {
    airplay.createBrowser()
      .on('deviceOn', function (device) {
        device.play(href, 0, function () {})
      })
      .start()
    // TODO: handle case where user closes airplay. do same thing as when VLC is closed
  }

  if (argv.chromecast) {
    ;(new chromecast.Browser())
      .on('deviceOn', function (device) {
        device.connect()
        device.on('connected', function () {
          device.play(href)
        })
      })
  }

  if (argv.xbmc) {
    ;(new xbmc.Browser())
      .on('deviceOn', function (device) {
          device.play(href, function () {})
      })
  }

  var hotswaps = 0
  torrent.on('hotswap', function () {
    hotswaps += 1
  })

  if (!argv.quiet) {
    process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')) // clear for drawing

    setInterval(draw, 500)
  }

  function active (wire) {
    return !wire.peerChoking
  }

  function bytes (num) {
    return numeral(num).format('0.0b')
  }

  function draw () {
    var unchoked = wires.filter(active)
    var linesremaining = clivas.height
    var peerslisted = 0
    var speed = swarm.downloadSpeed()
    var estimatedSecondsRemaining = Math.max(0, torrent.length - swarm.downloaded) / (speed > 0 ? speed : -1)
    var estimate = moment.duration(estimatedSecondsRemaining, 'seconds').humanize()

    clivas.clear()

    if (playerName)
      clivas.line('{green:Streaming to} {bold:' + playerName + '}')
    if (client.server)
      clivas.line('{green:server running at} {bold:' + href + '}')

    clivas.line('')
    clivas.line('{green:downloading:} {bold:' + filename + '}')
    clivas.line(
      '{green:speed: }{bold:' + bytes(speed) + '/s}  ' +
      '{green:downloaded:} {bold:' + bytes(swarm.downloaded) + '}' +
      '/{bold:' + bytes(torrent.length) + '}  ' +
      '{green:uploaded:} {bold:' + bytes(swarm.uploaded) + '}  ' +
      '{green:peers:} {bold:' + unchoked.length + '/' + wires.length + '}  ' +
      '{green:hotswaps:} {bold:' + hotswaps + '}'
    )
    clivas.line(
      '{green:time remaining:} {bold:' + estimate + ' remaining}  ' +
      '{green:total time:} {bold:' + getRuntime() + 's}  ' +
      '{green:queued peers:} {bold:' + swarm.numQueued + '}  ' +
      '{green:blocked:} {bold:' + torrent.numBlockedPeers + '}'
    )
    clivas.line('{80:}')
    linesremaining -= 8

    wires.every(function (wire) {
      var tags = []
      if (wire.peerChoking) tags.push('choked')
      clivas.line(
        '{25+magenta:' + wire.remoteAddress + '} {10:'+bytes(wire.downloaded)+'} ' +
        '{10+cyan:' + bytes(wire.downloadSpeed()) + '/s} ' +
        '{15+grey:' + tags.join(', ') + '}'
      )
      peerslisted++
      return linesremaining - peerslisted > 4
    })
    linesremaining -= peerslisted

    if (wires.length > peerslisted) {
      clivas.line('{80:}')
      clivas.line('... and '+(wires.length - peerslisted)+' more')
    }

    clivas.line('{80:}')
    clivas.flush(true)
  }
}
<|endoftext|>


<commit_before>module.exports = {
	plugins: ['@namics/stylelint-bem'],
	rules: {
		'plugin/stylelint-bem-namics': true,
		'at-rule-no-vendor-prefix': true,
		'block-closing-brace-space-before': ['always-single-line', { severity: 'warning' }],
		'block-opening-brace-space-after': ['always-single-line', { severity: 'warning' }],
		'block-opening-brace-space-before': ['always', { severity: 'warning' }],
		'color-hex-case': ['lower', { severity: 'warning' }],
		'color-named': 'never',
		'color-no-invalid-hex': [true, { severity: 'warning' }],
		'comment-word-blacklist': ['todo', { severity: 'warning' }],
		'declaration-block-no-duplicate-properties': [true, { severity: 'warning' }],
		'declaration-block-no-shorthand-property-overrides': [true, { severity: 'warning' }],
		'declaration-block-semicolon-newline-after': ['always', { severity: 'warning' }],
		'declaration-block-trailing-semicolon': ['always', { severity: 'warning' }],
		'declaration-colon-space-after': ['always-single-line', { severity: 'warning' }],
		'declaration-no-important': true,
		'function-linear-gradient-no-nonstandard-direction': [true, { severity: 'warning' }],
		indentation: ['tab', { severity: 'warning' }],
		'length-zero-no-unit': true,
		'max-empty-lines': [1, { severity: 'warning' }],
		'max-nesting-depth': [2, { severity: 'warning' }],
		'no-missing-end-of-source-newline': [true, { severity: 'warning' }],
		'no-unknown-animations': [true, { severity: 'warning' }],
		'number-leading-zero': 'always',
		'property-no-vendor-prefix': [true, { severity: 'warning' }],
		'selector-max-id': 0,
		'string-quotes': 'single',
		'value-no-vendor-prefix': [true, { severity: 'warning' }],
	},
};
<commit_msg>feat(stylelint): add rules that require lower case for properties, selectors, units and more<commit_after>module.exports = {
	plugins: ['@namics/stylelint-bem'],
	rules: {
		'plugin/stylelint-bem-namics': true,
		'at-rule-name-case': 'lower',
		'at-rule-no-vendor-prefix': true,
		'block-closing-brace-space-before': ['always-single-line', { severity: 'warning' }],
		'block-opening-brace-space-after': ['always-single-line', { severity: 'warning' }],
		'block-opening-brace-space-before': ['always', { severity: 'warning' }],
		'color-hex-case': ['lower', { severity: 'warning' }],
		'color-named': 'never',
		'color-no-invalid-hex': [true, { severity: 'warning' }],
		'comment-word-blacklist': ['todo', { severity: 'warning' }],
		'declaration-block-no-duplicate-properties': [true, { severity: 'warning' }],
		'declaration-block-no-shorthand-property-overrides': [true, { severity: 'warning' }],
		'declaration-block-semicolon-newline-after': ['always', { severity: 'warning' }],
		'declaration-block-trailing-semicolon': ['always', { severity: 'warning' }],
		'declaration-colon-space-after': ['always-single-line', { severity: 'warning' }],
		'declaration-no-important': true,
		'function-linear-gradient-no-nonstandard-direction': [true, { severity: 'warning' }],
		'function-name-case': 'lower',
		indentation: ['tab', { severity: 'warning' }],
		'length-zero-no-unit': true,
		'max-empty-lines': [1, { severity: 'warning' }],
		'max-nesting-depth': [2, { severity: 'warning' }],
		'media-feature-name-case': 'lower',
		'no-missing-end-of-source-newline': [true, { severity: 'warning' }],
		'no-unknown-animations': [true, { severity: 'warning' }],
		'number-leading-zero': 'always',
		'property-case': 'lower',
		'property-no-vendor-prefix': [true, { severity: 'warning' }],
		'selector-max-id': 0,
		'selector-pseudo-class-case': 'lower',
		'selector-pseudo-element-case': 'lower',
		'selector-type-case': 'lower',
		'string-quotes': 'single',
		'unit-case': 'lower',
		'value-keyword-case': 'lower',
		'value-no-vendor-prefix': [true, { severity: 'warning' }],
	},
};
<|endoftext|>


<commit_before>var kts46 = (function($){

    // cfg
    var serverPollInterval = 30000,
        jsonRpcPath = "/json-rpc/",
        projectColumnId = 0,
        jobColumnId = 1,
        googleTableId = "progress-table-2";

    var addProject = function(){
        $("#add-project-confirm").dialog({
            resizable: false,
            height: 200,
            modal: true,
            buttons: {
                "Add project": function() {
                    var projectName = $('#add-project-name').val();
                    var data = JSON.stringify({
                        "method": "addProject",
                        "id": "addProject_" + projectName,
                        "params": [ projectName ]
                    }) + "\n";
                    var $dialog = $(this);
                    $.post(jsonRpcPath, data, function(data) {
                        $dialog.dialog("close");
                    });
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });
    };

    var deleteProject = function(projectName){
        $("#delete-project-confirm").dialog({
            resizable: false,
            height: 200,
            modal: true,
            buttons: {
                "Delete project": function() {
                    var data = JSON.stringify({
                        "method": "deleteProject",
                        "id": "deleteProject_" + projectName,
                        "params": [ projectName ]
                    }) + "\n";
                    var $dialog = $(this);
                    $.post(jsonRpcPath, data, function(data) {
                        $dialog.dialog("close");
                    });
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });
    };

    var addJobAction = function(projectName, allFields, dialog) {
        // Taken from jqueryui.com
        var checkRegexp = function( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                // updateTips( n );
                return false;
            } else {
                return true;
            }
        }

        var bValid = true;

        allFields.removeClass( "ui-state-error" );
        bValid = bValid && checkRegexp($('#add-job-name'), /^[a-zA-Z][0-9a-zA-Z_]+$/i, "Job name may consist of a-z, A-Z, 0-9, underscores, begin with a letter." );
        bValid = bValid && checkRegexp($('#add-job-count'), /^[0-9]+$/i, "Jobs count must be a number." );

        if ( bValid ) {
            var seriesLength = 1;

            // Check series identifier
            var isSeriesDOM = document.getElementById("add-job-is-series");
            if (isSeriesDOM.checked) {
                seriesLength = parseInt($('#add-job-count').val());
            }

            var file = document.getElementById('add-job-definition').files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var definition = e.target.result;
                var jobName = $('#add-job-name').val();

                for(var i=1; i<=seriesLength; i++){
                    var efficientName = jobName;
                    if (seriesLength > 1) {
                        efficientName += '-s' + i;
                    }

                    var params = JSON.stringify({
                        method: "addJob",
                        id: "addJob_" + projectName + "_" + "efficientName",
                        params: [projectName, efficientName, definition]
                    }) + "\n";
                    $.post(jsonRpcPath, params, function(data) {});
                }
                dialog.dialog( "close" );
            };
            reader.readAsText(file);
        }
    };

    var addJob = function(projectName) {
        var allFields = $('#add-job-name, #add-job-definition');

        $("#add-job-form").dialog({
            // autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "Add job": function(){ addJobAction(projectName, allFields, $(this)); },
                Cancel: function() { $(this).dialog("close"); }
            },
            close: function() { allFields.val("").removeClass("ui-state-error"); }
        });
    };

    var deleteJob = function() {
        var buttonProject = $(this).data('project');
        var buttonJob = $(this).data('job');
        $( "#delete-job-confirm" ).dialog({
            resizable: false,
            height:200,
            modal: true,
            buttons: {
                "Delete job": function() {
                    var dialog = $(this);
                    var params = JSON.stringify({
                        method: "deleteJob",
                        id: "deleteJob_" + buttonProject + "_" + buttonJob,
                        params: [buttonProject, buttonJob]
                    }) + "\n";
                    console.log(params);
                    $.post(jsonRpcPath, params, function(data) {
                        dialog.dialog("close");
                    });
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });
    };

    var runJob = function(project, job) {
        // var p = $(this).data('project');
        // var j = $(this).data('job');
        var params = JSON.stringify({
            method: "runJob",
            id: "runJob_" + project + "_" + job,
            params: [project, job]
        }) + "\n";
        $.post(jsonRpcPath, params, function(data) {});
    };

    var updateStatus = function() {

        var query = new google.visualization.Query("/api/serverStatus2/");
        query.send( function(response){
            var dataTable = response.getDataTable();

            // Store table
            $(document).data('simulation-data', dataTable);

            // Add progress column.
            dataTable.addColumn("number", "Progress");
            for (var rowNum = 0, l = dataTable.getNumberOfRows(); rowNum < l; ++rowNum ){
                var v = dataTable.getValue(rowNum, 2) / dataTable.getValue(rowNum, 3);
                var f = [dataTable.getValue(rowNum, 2), '/', dataTable.getValue(rowNum, 3)].join("");
                dataTable.setCell(rowNum, 4, v, f) ;
            }

            // progress formatter.
            var formatterOptions = {
                    width: 120,
                    base: 0,
                    min: 0,
                    max: 1,
                    showValue: true
            };
            var progressFormatter = new google.visualization.BarFormat(formatterOptions);
            progressFormatter.format(dataTable, 4);

            var view = new google.visualization.DataView(dataTable);
            view.setColumns([projectColumnId, jobColumnId, 4]);

            // var table = new google.visualization.Table(document.getElementById(googleTableId));
            var table = $(document).data('google-table');
            table.draw(view, {showRowNumber: true, allowHtml: true});
            $('.progress-block .last-update-time').text( 'Last update time: ' + new Date() );
        } );
        /*
        $.getJSON('/api/serverStatus/', function(data) {
            if (data.result === "fail") {
                return;
            }

            var progressBlock = $('.progress-block');
            // progressBlock.empty(); // remove previous
            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    var projectName = data[i].project;
                    var projectBlock = $('#project-progress-'+projectName);
                    if (projectBlock.length == 0) {
                        projectBlock = $('

');
                        projectBlock.attr('id', 'project-progress-'+projectName);
                        progressBlock.prepend(projectBlock);

                        // Add project name
                        var projNameBlock = $('

');
                        projNameBlock.append(''+projectName+'');
                        projectBlock.append(projNameBlock);

                        // Button to add job
                        var jobAddButton = $('<button></button>').button();
                        projNameBlock.append(jobAddButton);
                        jobAddButton.data('project', projectName);
                        jobAddButton.click( function(){ addJob( $(this).data('project') ); });

                        // Project deleter.
                        var projDeleteButton = $('<button></button>').button();
                        projNameBlock.append(projDeleteButton);
                        projDeleteButton.data('project', projectName);
                        projDeleteButton.click( function(){
                            deleteProject($(this).data('project'));
                        } );
                    }

                    // Check. If dummy job - skip it. But project will still be
                    // created. That is the point of dummy jobs.
                    if (typeof data[i].visible === "undefined" || data[i].visible) {
                        var jobName = data[i].name;

                        // Job wrapper
                        var wrapperId  = 'job-'+projectName+jobName;
                        var jobContainer = $('#'+wrapperId);
                        if (jobContainer.length === 0) {

                            jobContainer = $('

');
                            jobContainer
                                .attr('id',wrapperId)
                                .data('project', projectName)
                                .data('job', data[i].name);
                            projectBlock.append(jobContainer);

                            // Job runner
                            var jobRunner = $('<button></button>');
                            jobContainer.append(jobRunner);
                            jobRunner.addClass('job-start').click(runJob)
                                .data('project', projectName).data('job', data[i].name);

                            // Job deleter
                            var jobDeleter = $('<button></button>');
                            jobContainer.append(jobDeleter);
                            jobDeleter.addClass('job-delete').click(deleteJob)
                                .data('project', projectName).data('job', data[i].name);;

                            // Job name
                            var name = $('

');
                            name.text(data[i].name);
                            jobContainer.append(name);

                            // Job progress value
                            var progressNum = $('

');
                            jobContainer.append(progressNum);
                            //progressNum.text([data[i].done, '/', data[i].total].join(""));

                            // Job progressbar
                            var bar = $('

');
                            bar.attr('id', jobName + '-progressbar')
                            jobContainer.append(bar);
                            //var progress = Math.round(data[i].done / data[i].total * 100);
                            //bar.progressbar({value:  progress});

                            // Click handler
                            var showStats = function(){
                                var c = $(this).parent();
                                var stats = $('.jobstatistics', c);

                                if (stats.length !== 0) {
                                    stats.remove();
                                } else {
                                    var p = c.data('project');
                                    var j = c.data('job');
                                    var path = ['/api/jobStatistics/',p,'/',j,'/'].join('');
                                    $.getJSON(path, function(data){
                                        stats = $('

');
                                        stats.addClass("jobstatistics");
                                        stats.text(JSON.stringify(data, null, 4));
                                        c.append(stats);
                                    } );
                                }
                            };
                            bar.click(showStats);
                            progressNum.click(showStats);

                        }

                        // Set progress.
                        $('.progress-num', jobContainer)
                            .text([data[i].done, '/', data[i].total].join(""));
                        var progress = Math.round(data[i].done / data[i].total * 100);
                        $(['#', jobName, '-progressbar'].join("")).progressbar({value:  progress});

                    }
                }
            }

            $('.progress-block .last-update-time').text( 'Last update time: ' + new Date() );
        });*/
    };

    var getSelectedJobs = function() {
        return $(document).data('google-table').getSelection().map( function(it){ return it.row; } );
    };

    var runSelectedJobs = function() {
        var jobs = getSelectedJobs(),
            table = $(document).data('simulation-data'),
            i, l;
        if (typeof table === "undefined") return;
        for(i = 0, l = jobs.length; i < l; ++i){
            var p = table.getValue(jobs[i], projectColumnId),
                j = table.getValue(jobs[i], jobColumnId);
            runJob(p, j);
        }
    };

    // google table
    google.load('visualization', '1', {packages:['table']});
    google.setOnLoadCallback( function() {
        updateStatus();
        setInterval(updateStatus, serverPollInterval);
    });

    // on ready
    $(document).ready(function(){
        $('.jqueryui-button').button();
        $('#simulation-start-job')
            .button({text: false,icons: {primary:"ui-icon-play"}})
            .click(runSelectedJobs.bind({}));
        $('#simulation-delete-job').button({text: false,icons: {primary:"ui-icon-trash"}});
        $(this).data('google-table', new google.visualization.Table(document.getElementById(googleTableId)));
    });

    return {
        //"g": getSelectedJobs.bind({}),
        "updateStatus": updateStatus,
        "runJob": runJob
    };

})(jQuery);
<commit_msg>Delete job action.<commit_after>var kts46 = (function($){

    // cfg
    var serverPollInterval = 5000,
        jsonRpcPath = "/json-rpc/",
        projectColumnId = 0,
        jobColumnId = 1,
        googleTableId = "progress-table-2";

    var addProject = function(){
        $("#add-project-confirm").dialog({
            resizable: false,
            height: 200,
            modal: true,
            buttons: {
                "Add project": function() {
                    var projectName = $('#add-project-name').val();
                    var data = JSON.stringify({
                        "method": "addProject",
                        "id": "addProject_" + projectName,
                        "params": [ projectName ]
                    }) + "\n";
                    var $dialog = $(this);
                    $.post(jsonRpcPath, data, function(data) {
                        $dialog.dialog("close");
                    });
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });
    };

    var deleteProject = function(projectName){
        $("#delete-project-confirm").dialog({
            resizable: false,
            height: 200,
            modal: true,
            buttons: {
                "Delete project": function() {
                    var data = JSON.stringify({
                        "method": "deleteProject",
                        "id": "deleteProject_" + projectName,
                        "params": [ projectName ]
                    }) + "\n";
                    var $dialog = $(this);
                    $.post(jsonRpcPath, data, function(data) {
                        $dialog.dialog("close");
                    });
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });
    };

    var addJobAction = function(projectName, allFields, dialog) {
        // Taken from jqueryui.com
        var checkRegexp = function( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                // updateTips( n );
                return false;
            } else {
                return true;
            }
        }

        var bValid = true;

        allFields.removeClass( "ui-state-error" );
        bValid = bValid && checkRegexp($('#add-job-name'), /^[a-zA-Z][0-9a-zA-Z_]+$/i, "Job name may consist of a-z, A-Z, 0-9, underscores, begin with a letter." );
        bValid = bValid && checkRegexp($('#add-job-count'), /^[0-9]+$/i, "Jobs count must be a number." );

        if ( bValid ) {
            var seriesLength = 1;

            // Check series identifier
            var isSeriesDOM = document.getElementById("add-job-is-series");
            if (isSeriesDOM.checked) {
                seriesLength = parseInt($('#add-job-count').val());
            }

            var file = document.getElementById('add-job-definition').files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var definition = e.target.result;
                var jobName = $('#add-job-name').val();

                for(var i=1; i<=seriesLength; i++){
                    var efficientName = jobName;
                    if (seriesLength > 1) {
                        efficientName += '-s' + i;
                    }

                    var params = JSON.stringify({
                        method: "addJob",
                        id: "addJob_" + projectName + "_" + "efficientName",
                        params: [projectName, efficientName, definition]
                    }) + "\n";
                    $.post(jsonRpcPath, params, function(data) {});
                }
                dialog.dialog( "close" );
            };
            reader.readAsText(file);
        }
    };

    var addJob = function(projectName) {
        var allFields = $('#add-job-name, #add-job-definition');

        $("#add-job-form").dialog({
            // autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "Add job": function(){ addJobAction(projectName, allFields, $(this)); },
                Cancel: function() { $(this).dialog("close"); }
            },
            close: function() { allFields.val("").removeClass("ui-state-error"); }
        });
    };

    var deleteJob = function(project, job) {
        //var buttonProject = $(this).data('project');
        //var buttonJob = $(this).data('job');
        $( "#delete-job-confirm" ).dialog({
            resizable: false,
            height:200,
            modal: true,
            buttons: {
                "Delete job": function() {
                    var dialog = $(this);
                    var params = JSON.stringify({
                        method: "deleteJob",
                        id: "deleteJob_" + project + "_" + job,
                        params: [project, job]
                    }) + "\n";
                    $.post(jsonRpcPath, params, function(data) {
                        dialog.dialog("close");
                    });
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });
    };

    var runJob = function(project, job) {
        var params = JSON.stringify({
            method: "runJob",
            id: "runJob_" + project + "_" + job,
            params: [project, job]
        }) + "\n";
        $.post(jsonRpcPath, params, function(data) {});
    };

    var updateStatus = function() {

        var query = new google.visualization.Query("/api/serverStatus2/");
        query.send( function(response){
            var dataTable = response.getDataTable();

            // Store table
            $(document).data('simulation-data', dataTable);

            // Add progress column.
            dataTable.addColumn("number", "Progress");
            for (var rowNum = 0, l = dataTable.getNumberOfRows(); rowNum < l; ++rowNum ){
                var v = dataTable.getValue(rowNum, 2) / dataTable.getValue(rowNum, 3);
                var f = [dataTable.getValue(rowNum, 2), '/', dataTable.getValue(rowNum, 3)].join("");
                dataTable.setCell(rowNum, 4, v, f) ;
            }

            // progress formatter.
            var formatterOptions = {
                    width: 120,
                    base: 0,
                    min: 0,
                    max: 1,
                    showValue: true
            };
            var progressFormatter = new google.visualization.BarFormat(formatterOptions);
            progressFormatter.format(dataTable, 4);

            var view = new google.visualization.DataView(dataTable);
            view.setColumns([projectColumnId, jobColumnId, 4]);

            // var table = new google.visualization.Table(document.getElementById(googleTableId));
            var table = $(document).data('google-table');
            table.draw(view, {showRowNumber: true, allowHtml: true});
            $('.progress-block .last-update-time').text( 'Last update time: ' + new Date() );
        } );
        /*  var progressBlock = $('.progress-block');
            // progressBlock.empty(); // remove previous
            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    var projectName = data[i].project;
                    var projectBlock = $('#project-progress-'+projectName);

                    // Check. If dummy job - skip it. But project will still be
                    // created. That is the point of dummy jobs.
                    if (typeof data[i].visible === "undefined" || data[i].visible) {
                            // Click handler
                            var showStats = function(){
                                var c = $(this).parent();
                                var stats = $('.jobstatistics', c);

                                if (stats.length !== 0) {
                                    stats.remove();
                                } else {
                                    var p = c.data('project');
                                    var j = c.data('job');
                                    var path = ['/api/jobStatistics/',p,'/',j,'/'].join('');
                                    $.getJSON(path, function(data){
                                        stats = $('

');
                                        stats.addClass("jobstatistics");
                                        stats.text(JSON.stringify(data, null, 4));
                                        c.append(stats);
                                    } );
                                }
                            };
                        }
                    }
                }
            }
        });*/
    };

    var getSelectedJobs = function() {
        return $(document).data('google-table').getSelection().map( function(it){ return it.row; } );
    };

    /* Runs spcecified action on all selected projects.
     * :param action: function(projectName, jobName)
     */
    var forSelectedJobs = function(action) {
        var jobs = getSelectedJobs(),
            table = $(document).data('simulation-data'),
            i, l;
        if (typeof table === "undefined") return;
        for(i = 0, l = jobs.length; i < l; ++i){
            var p = table.getValue(jobs[i], projectColumnId),
                j = table.getValue(jobs[i], jobColumnId);
            action(p, j);
        }
    };

    // google table
    google.load('visualization', '1', {packages:['table']});
    google.setOnLoadCallback( function() {
        updateStatus();
        setInterval(updateStatus, serverPollInterval);
    });

    // on ready
    $(document).ready(function(){
        $('.jqueryui-button').button();
        $('#simulation-start-job')
            .button({text: false,icons: {primary:"ui-icon-play"}})
            .click(forSelectedJobs.bind({}, runJob.bind({}) ));
        $('#simulation-delete-job')
            .button({text: false,icons: {primary:"ui-icon-trash"}})
            .click(forSelectedJobs.bind({}, deleteJob.bind({}) ));
        $(this).data('google-table', new google.visualization.Table(document.getElementById(googleTableId)));
    });

    return {
        //"g": getSelectedJobs.bind({}),
        "updateStatus": updateStatus,
        "runJob": runJob
    };

})(jQuery);
<|endoftext|>


<commit_before>/* eslint-disable react/jsx-filename-extension */
import path from 'path';
import express from 'express';
import compression from 'compression';
import morgan from 'morgan';
import helmet from 'helmet';
import hpp from 'hpp';
import cookieParser from 'cookie-parser';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router';
import { Provider } from 'react-redux';
import winston from 'winston';

import { API_ENDPOINT } from 'constants/application';
import { CUSTOM_THEME_ROUTE } from 'constants/colors';
import configureStore from './configureStore';
import api from './api';
import themes from './themes';
import renderHtmlPage from './utils/renderHtmlPage';

const CACHE_DURATION = 7 * 24 * 60 * 60 * 1000; // days * hours * minutes * seconds * milliseconds
const dist = path.resolve(process.cwd(), 'public');
const app = express();

app.use(helmet({
  noCache: false,
}));
app.use(hpp());
app.use(morgan(__DEV__ ? 'dev' : 'combined'));
app.use(compression());

if (!global.__NGINX__) {
  app.use(express.static(dist, {
    maxAge: CACHE_DURATION,
  }));
}

if (__DEV__ && !global.__SERVER_ONLY) {
  /* eslint-disable import/no-extraneous-dependencies, global-require */
  const webpack = require('webpack');
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const webpackHotMiddleware = require('webpack-hot-middleware');
  const config = require('../../webpack.config')({ development: true });

  const compiler = webpack(config);
  app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
    stats: 'errors-only',
  }));

  app.use(webpackHotMiddleware(compiler));
}

app.use(API_ENDPOINT, api);
app.get(`/${CUSTOM_THEME_ROUTE}/*.css`, themes);

app.get('*', cookieParser(), async (req, res) => {
  if (__DEV__) {
    global.webpackIsomorphicTools.refresh();
  }

  let store;
  const context = { bundles: [] };
  try {
    if (!__SSR__) {
      res.send(renderHtmlPage(store));
      return;
    }

    store = await configureStore(req);
    const App = require('components/App').default;

    const html = renderToString(
      <StaticRouter context={context} location={req.url}>
        <Provider store={store}>
          <App />
        </Provider>
      </StaticRouter>
    );

    if (context.url) {
      res.writeHead(301, {
        Location: context.url,
      });

      res.end();
    } else {
      res.send(renderHtmlPage(store, context.bundles, html));
    }
  } catch (e) {
    winston.error(e);
    if (__DEV__) {
      throw e;
    }

    res.send(renderHtmlPage(store, context.bundles));
  }
});

let port = process.env.NODE_PORT;
if (!port) {
  const message = 'The `NODE_PORT` environment variable has not been set. This can be done by copying '
    + 'the `.env.example` to `.env` in the docs root directory and updating the `NODE_PORT` or set an '
    + 'environment variable on your machine.';

  if (__DEV__) {
    winston.info('Defaulting `NODE_PORT` to `8080` for dev mode.');
    winston.info('It is recommended to copy the `.env.example` file to `.env` and set the `NODE_PORT` there.');
    port = 8080;
  } else {
    throw new Error(message);
  }
}

app.listen(port, (err) => {
  if (err) {
    throw err;
  }

  global.PUBLIC_URL = process.env.PUBLIC_URL || `http://0.0.0.0:${port}`;
  winston.info(`Started documentation server at: '${global.PUBLIC_URL}'`);
  if (__DEV__ && !global.__SERVER_ONLY) {
    winston.info('Starting webpack compilation...');
    winston.info(`Please wait until webpack spams your console, then you can navigate to ${global.PUBLIC_URL}`);
  }
});
<commit_msg>Fixed some server issues<commit_after>/* eslint-disable react/jsx-filename-extension */
import path from 'path';
import express from 'express';
import compression from 'compression';
import morgan from 'morgan';
import helmet from 'helmet';
import hpp from 'hpp';
import cookieParser from 'cookie-parser';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router';
import { Provider } from 'react-redux';
import winston from 'winston';

import { API_ENDPOINT } from 'constants/application';
import { CUSTOM_THEME_ROUTE } from 'constants/colors';
import App from 'components/App';
import configureStore from './configureStore';
import api from './api';
import themes from './themes';
import renderHtmlPage from './utils/renderHtmlPage';

const CACHE_DURATION = 7 * 24 * 60 * 60 * 1000; // days * hours * minutes * seconds * milliseconds
const dist = path.resolve(process.cwd(), 'public');
const app = express();

app.use(helmet({
  noCache: false,
}));
app.use(hpp());
app.use(morgan(__DEV__ ? 'dev' : 'combined'));
app.use(compression());

if (!global.__NGINX__) {
  app.use(express.static(dist, {
    maxAge: CACHE_DURATION,
  }));
}

if (__DEV__ && !global.__SERVER_ONLY__) {
  /* eslint-disable import/no-extraneous-dependencies, global-require */
  const webpack = require('webpack');
  const webpackDevMiddleware = require('webpack-dev-middleware');
  const webpackHotMiddleware = require('webpack-hot-middleware');
  const config = require('../../webpack.config')({ development: true });

  const compiler = webpack(config);
  app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
    stats: 'errors-only',
  }));

  app.use(webpackHotMiddleware(compiler));
}

app.use(API_ENDPOINT, api);
app.get(`/${CUSTOM_THEME_ROUTE}/*.css`, themes);

app.get('*', cookieParser(), async (req, res) => {
  if (__DEV__) {
    global.webpackIsomorphicTools.refresh();
  }

  let store;
  const context = { bundles: [] };
  try {
    if (!__SSR__) {
      res.send(renderHtmlPage(store));
      return;
    }

    store = await configureStore(req);
    const html = renderToString(
      <StaticRouter context={context} location={req.url}>
        <Provider store={store}>
          <App />
        </Provider>
      </StaticRouter>
    );

    if (context.url) {
      res.writeHead(301, {
        Location: context.url,
      });

      res.end();
    } else {
      res.send(renderHtmlPage(store, context.bundles, html));
    }
  } catch (e) {
    winston.error(e);
    if (__DEV__) {
      throw e;
    }

    res.send(renderHtmlPage(store, context.bundles));
  }
});

let port = process.env.NODE_PORT;
if (!port) {
  const message = 'The `NODE_PORT` environment variable has not been set. This can be done by copying '
    + 'the `.env.example` to `.env` in the docs root directory and updating the `NODE_PORT` or set an '
    + 'environment variable on your machine.';

  if (__DEV__) {
    winston.info('Defaulting `NODE_PORT` to `8080` for dev mode.');
    winston.info('It is recommended to copy the `.env.example` file to `.env` and set the `NODE_PORT` there.');
    port = 8080;
  } else {
    throw new Error(message);
  }
}

app.listen(port, (err) => {
  if (err) {
    throw err;
  }

  // This gets set during the webpack config, but it is completely possible to have no PUBLIC_URL
  // in dev mode, so set it to any address on server side by default
  global.PUBLIC_URL = process.env.PUBLIC_URL || `http://0.0.0.0:${port}`;
  if (__DEV__ && !global.__SERVER_ONLY) {
    winston.info('Starting webpack compilation...');
    winston.info(`Please wait until webpack spams your console, then you can navigate to ${global.PUBLIC_URL}`);
  } else {
    winston.info(`Started documentation server at: '${global.PUBLIC_URL}'`);
  }
});
<|endoftext|>


<commit_before>/* jshint node: true */
/* jshint esnext: true */
'use strict';

const moment = require('moment');
const race = require('../service/race');

let timeCalculator = {};

timeCalculator.timestamp = function(timestring) {
  return race.startTime()
    .then( starttime => {
      let timestamp = moment(starttime,'X');
      timestamp.hours(timestring.split(':')[0]);
      timestamp.minutes(timestring.split(':')[1]);
      timestamp.seconds(timestring.split(':')[2]);
      return timestamp.unix();
    });
};

timeCalculator.relativeTime = function(race_starttime,participant_finishtime) {
  const deferred = Q.defer();
  var relative_time = moment.duration(participant_finishtime - race_starttime,'seconds');
  deferred.resolve([relative_time.hours(),relative_time.minutes(),relative_time.seconds()]);
  return deferred.promise;
};

module.exports = timeCalculator;
<commit_msg>timeCalculator uses deferreds<commit_after>/* jshint node: true */
/* jshint esnext: true */
'use strict';

const Q = require('q');
const moment = require('moment');
const race = require('../service/race');

let timeCalculator = {};

timeCalculator.timestamp = function(timestring) {
  return race.startTime()
    .then( starttime => {
      let timestamp = moment(starttime,'X');
      timestamp.hours(timestring.split(':')[0]);
      timestamp.minutes(timestring.split(':')[1]);
      timestamp.seconds(timestring.split(':')[2]);
      return timestamp.unix();
    });
};

timeCalculator.relativeTime = function(race_starttime,participant_finishtime) {
  const deferred = Q.defer();
  var relative_time = moment.duration(participant_finishtime - race_starttime,'seconds');
  deferred.resolve([relative_time.hours(),relative_time.minutes(),relative_time.seconds()]);
  return deferred.promise;
};

module.exports = timeCalculator;
<|endoftext|>


<commit_before>require('./../../src/tool/test-signature')(__filename);

var ini       = require('./../../src/ini'),
    iniFile     = __dirname + '/../props/config.ini',
    iniAsString = [
        '[SectionOne]',
        '',
        'key = value',
        'integer = 1234',
        'real = 3.14',
        'string1 = \'Case 1\'',
        'string2 = "Case 2"',
        'multivalue[] = first',
        'multivalue[] = second',
        '',
        '[SectionTwo]',
        '',
        'key = new value# after hash comment and not a value',
        'key2 = \'trimmed\' # after hash comment and not a value',
        'integer = 1234  # after hash comment and not a value',
        'real = 3.14     # after hash comment and not a value',
        'string1 = \'Case 1\'     # after hash comment and not a value',
        'string2 = "Case 2"     # after hash comment and not a value',
        'multivalue[] = first   # after hash comment and not a value',
        'multivalue[] = second  # after hash comment and not a value'
    ].join('\n');

describe('INI implementation', function () {
    it('has default encoding', function () {
        expect(ini.encoding()).toBe('utf-8');
    });

    console.log('File #1');
    console.log(ini.readFile(iniFile));
    console.log('File #2');
    console.log(ini.readFile('/made/this/one/up.ini'));
    console.log('String #1');
    console.log(ini.readFile(iniAsString));
    console.log('String #2');
    console.log(ini.readFile('BDDD'));

    it('reads file', function () {
        expect(typeof ini.readFile(iniFile)).toBe('object');
        expect(typeof ini.readFile('/made/this/one/up.ini')).toBe('boolean');
    });

    it('reads string', function () {
        expect(typeof ini.readString(iniAsString)).toBe('object');
        expect(ini.readString(iniAsString).SectionTwo.key).toBe('new value');
        expect(ini.readString(iniAsString).SectionTwo.key2).toBe('trimmed');
        expect(ini.readString(iniAsString).SectionTwo.string2).toBe('Case 2');
        expect(ini.readString(iniAsString).SectionTwo.multivalue).toBe(['first','second']);
        expect(typeof ini.readString('BDDD')).toBe('object');
        expect(ini.readString('BDDD').BDDD).toBe(true);
    });
});

<commit_msg>cleanup<commit_after><|endoftext|>


<commit_before>$(document).ready(function() {
		var winWidth = $( window ).width()
	if(winWidth < 768){
		$("#logo")[0].src = "../img/white.png"
		$("#logo").addClass('pink')
		$(".showbox").hide()
	};

	$( window ).resize(function() {
		var resizeWidth = $( window ).width()
		if (resizeWidth < 768){
			$("#logo")[0].src = "../img/white.png"
			$("#logo").addClass('pink')
			$(".showbox").hide()
		} else {
			$("#logo")[0].src = "../img/multi.png"
			$("#logo").removeClass('pink')
			$(".showbox").show()
		}

	});

});<commit_msg>resize color fix<commit_after>$(document).ready(function() {
		var winWidth = $( window ).width()
	if(winWidth < 768){
		$("#logo")[0].src = "../img/white.png"
		$("#logo").addClass('purple')
		$(".showbox").hide()
	};

	$( window ).resize(function() {
		var resizeWidth = $( window ).width()
		if (resizeWidth < 768){
			$("#logo")[0].src = "../img/white.png"
			$("#logo").addClass('purple')
			$(".showbox").hide()
		} else {
			$("#logo")[0].src = "../img/multi.png"
			$("#logo").removeClass('purple')
			$(".showbox").show()
		}

	});

});<|endoftext|>


<commit_before>logging.all(function (workPackages) {
    "use strict";
    var i, $logs, $resumeLogging, $stopLogging, $pauseLogging;
    $logs = $('#logs');

    for (i in workPackages) {
        if (! workPackages.hasOwnProperty(i)) {
            continue;
        }
        $logs.append(
            '
' + workPackages[i].name + '	'
            + '	'
            + '	'
            + '	'
            + '	'
            + '
');

        $('#runner_' + workPackages[i].id).runner({
            autostart: workPackages[i].running,
            startAt: workPackages[i].time * 1000,
            format: function (dateInMs) {
                var date = new Date(dateInMs),
                    minutes = Math.round((date.getUTCMinutes()/60) * 100);
                return date.getUTCHours() + '.' + (minutes < 10 ? '0' + minutes : minutes) + ' h';
            }
        });

        $resumeLogging = $('#resume-logging-' + workPackages[i].id);
        $stopLogging   = $('#stop-logging-' + workPackages[i].id);
        $pauseLogging  = $('#pause-logging-' + workPackages[i].id);

        if (workPackages[i].running) {
            $pauseLogging.show();
        } else {
            $resumeLogging.show();
        }
        $stopLogging.show();
        $resumeLogging.on('click', function (event) {
            "use strict";
            event.preventDefault();
            logging.start(workPackages[i].id, workPackages[i].name, function () {
                $('#runner_' + workPackages[i].id).runner('start');
                $('#resume-logging-' + workPackages[i].id).hide();
                $('#pause-logging-' + workPackages[i].id).show();
            });
        });
        $pauseLogging.on('click', function (event) {
            "use strict";
            event.preventDefault();
            logging.stop(workPackages[i].id, function () {
                $('#runner_' + workPackages[i].id).runner('stop');
                $('#resume-logging-' + workPackages[i].id).show();
                $('#pause-logging-' + workPackages[i].id).hide();
            });
        });
        $stopLogging.on('click', function (event) {
            "use strict";
            event.preventDefault();
            logging.stop(workPackages[i].id, function () {
                $('#runner_' + workPackages[i].id).runner('stop');
                $('#resume-logging-' + workPackages[i].id).show();
                $('#pause-logging-' + workPackages[i].id).hide();
                window.open('https://openproject.atino.net/work_packages/' + workPackages[i].id + '/time_entries/new');
            });
        });
    }
});
<commit_msg>Fix popup javascript<commit_after>logging.all(function (workPackages) {
    "use strict";
    var i, $logs;
    $logs = $('#logs');

    for (i in workPackages) {
        if (! workPackages.hasOwnProperty(i)) {
            continue;
        }
        $logs.append(
            '
' + workPackages[i].name + '	'
            + '	'
            + '	'
            + '	'
            + '	'
            + '	'
            + '
');

        $('#runner_' + workPackages[i].id).runner({
            autostart: workPackages[i].running,
            startAt: workPackages[i].time * 1000,
            format: function (dateInMs) {
                var date = new Date(dateInMs),
                    minutes = Math.round((date.getUTCMinutes()/60) * 100);
                return date.getUTCHours() + '.' + (minutes < 10 ? '0' + minutes : minutes) + ' h';
            }
        });

        if (workPackages[i].running) {
            $('#pause-logging-' + workPackages[i].id).show();
        } else {
            $('#resume-logging-' + workPackages[i].id).show();
        }
        $('#stop-logging-' + workPackages[i].id).show();
    }

    $('.resume-logging').on('click', function (event) {
        "use strict";
        var id = $(this).data('id');
        event.preventDefault();
        logging.start(id, '', function () {
            $('#runner_' + id).runner('start');
            $('#resume-logging-' + id).hide();
            $('#pause-logging-' + id).show();
        });
    });
    $('.pause-logging').on('click', function (event) {
        "use strict";
        var id = $(this).data('id');
        event.preventDefault();
        logging.stop(id, function () {
            $('#runner_' + id).runner('stop');
            $('#resume-logging-' + id).show();
            $('#pause-logging-' + id).hide();
        });
    });
    $('.stop-logging').on('click', function (event) {
        "use strict";
        var id = $(this).data('id');
        event.preventDefault();
        logging.stop(id, function () {
            $('#runner_' + id).runner('stop');
            $('#resume-logging-' + id).show();
            $('#pause-logging-' + id).hide();
            window.open('https://openproject.atino.net/work_packages/' + id + '/time_entries/new');
        });
    });
    $('.remove-logging').on('click', function (event) {
        "use strict";
        var id = $(this).data('id');
        event.preventDefault();
        logging.clear(id, function () {
            $('#remove-logging-' + id).parent().parent().remove();
        });
    });
});
<|endoftext|>


<commit_before>var MAX_RESULTS = 100;
var history_urls = {};
var history_visits = {};
var history_visits_to_urls = {};

var data = {};

var width = 600;
var height = 400;

var svg;

function init_graph() {
    svg = d3.select("#graph_container").append("svg")
            .attr("height", height)
            .attr("width", width)
            .attr("class", "chart");
}

function draw_graph() {
    var i;
    var urls = [];
    var url;
    var x;
    var numbers;
    var labels;
    var bar_height = 20;
    var spacing = 2;
    var x_offset = 100;

    d3.select("#graph_container svg").remove();
    svg = d3.select("#graph_container").append("svg")
            .attr("height", height)
            .attr("width", width)
            .attr("class", "chart");

    var data_arr = [];
    for (var k in data) {
      data_arr.push(data[k]);
    }

    data_arr.sort(function (a,b) {
        if (a.visits.length > b.visits.length) {
            return -1;
        }
        else if (a.visits.length < b.visits.length) {
            return 1;
        }
        return 0;
    });

    x = d3.scale.linear()
          .domain([0, d3.max(data_arr, function (d) {
              return d.visits.length;
          })])
          .range([0, 420]);

    svg.selectAll("rect").data(data_arr)
       .enter().append("rect")
       .attr("x", x_offset)
       .attr("y", function (d, i) { return i * (bar_height + spacing); })
       .attr("width", function (d) {return x(d.visits.length);})
       .attr("height", bar_height);

    numbers = svg.append("g");
    numbers.selectAll("text").data(data_arr)
       .enter().append("text")
       .attr("x", function (d) { return x(d.visits.length) + x_offset; })
       .attr("y", function (d, i) { return i * (bar_height + spacing); })
       .attr("dx", -3)
       .attr("dy", "1.4em")
       .attr("text-anchor", "end")
       .text(function (d) { return d.visits.length; });

    labels = svg.append("g");
    labels.selectAll("text").data(data_arr)
       .enter().append("text")
       .attr("x", 10)
       .attr("y", function(d, i) { return i * (bar_height + spacing); })
       .attr("dx", -3)
       .attr("dy", "1.4em")
       .attr("text-anchor", "start")
       .attr("class", "black")
       .text(function (d) { return d.url; });

    height = (bar_height + spacing) * data_arr.length;
    svg.attr("height", height);
}

function set_history(url) {
    return function(visits) {
        var i;
        var visit;
        console.log("appending " + visits.length + " visits to " + url);
        history_urls[url].visits = visits;
        for (i = 0; i < visits.length; i++) {
            visit = visits[i];
            history_visits_to_urls[visit.visitId] = url;
            history_visits[visit.visitId] = visit;
        }
        var url_no_hash = url.split("#")[0];
        if (data[url_no_hash] === undefined) {
          data[url_no_hash] = {url: url_no_hash, visits: visits};
        }
        else {
          data[url_no_hash].visits.push(visits);
        }
        // TODO: this is super-inefficient
        draw_graph();
    };
}

function get_history(start_time) {
    var i;
    start_time = start_time || new Date() - (1000 * 60 * 60 * 24 * 30);

    chrome.history.search({'text': '', 'startTime': start_time, 'maxResults': MAX_RESULTS },
        function(history_items) {
            console.log("found " + history_items.length + " history items since " + start_time.toLocaleString());
            for (i = 0; i < history_items.length; i++) {
                var hi = history_items[i];
                history_urls[hi.url] = hi;
                chrome.history.getVisits({"url": hi.url}, set_history(hi.url));
            }
        }
    );
}

get_history();

document.addEventListener('DOMContentLoaded', init_graph);
<commit_msg>A billion times more efficient.<commit_after>var MAX_RESULTS = 1000;
var history_urls = {};
var history_visits = {};
var history_visits_to_urls = {};

var data = {};

var width = 600;
var height = 400;

var svg;

var timeout_id;

function init_graph() {
    svg = d3.select("#graph_container").append("svg")
            .attr("height", height)
            .attr("width", width)
            .attr("class", "chart");
}

function draw_graph() {
    var i;
    var urls = [];
    var url;
    var x;
    var numbers;
    var labels;
    var bar_height = 20;
    var spacing = 2;
    var x_offset = 100;

    d3.select("#graph_container svg").remove();
    svg = d3.select("#graph_container").append("svg")
            .attr("height", height)
            .attr("width", width)
            .attr("class", "chart");

    var data_arr = [];
    for (var k in data) {
      data_arr.push(data[k]);
    }

    data_arr.sort(function (a,b) {
        if (a.visits.length > b.visits.length) {
            return -1;
        }
        else if (a.visits.length < b.visits.length) {
            return 1;
        }
        return 0;
    });

    x = d3.scale.linear()
          .domain([0, d3.max(data_arr, function (d) {
              return d.visits.length;
          })])
          .range([0, 420]);

    svg.selectAll("rect").data(data_arr)
       .enter().append("rect")
       .attr("x", x_offset)
       .attr("y", function (d, i) { return i * (bar_height + spacing); })
       .attr("width", function (d) {return x(d.visits.length);})
       .attr("height", bar_height);

    numbers = svg.append("g");
    numbers.selectAll("text").data(data_arr)
       .enter().append("text")
       .attr("x", function (d) { return x(d.visits.length) + x_offset; })
       .attr("y", function (d, i) { return i * (bar_height + spacing); })
       .attr("dx", -3)
       .attr("dy", "1.4em")
       .attr("text-anchor", "end")
       .text(function (d) { return d.visits.length; });

    labels = svg.append("g");
    labels.selectAll("text").data(data_arr)
       .enter().append("text")
       .attr("x", 10)
       .attr("y", function(d, i) { return i * (bar_height + spacing); })
       .attr("dx", -3)
       .attr("dy", "1.4em")
       .attr("text-anchor", "start")
       .attr("class", "black")
       .text(function (d) { return d.url; });

    height = (bar_height + spacing) * data_arr.length;
    svg.attr("height", height);
}

function set_history(url) {
    return function(visits) {
        var i;
        var visit;
        console.log("appending " + visits.length + " visits to " + url);
        history_urls[url].visits = visits;
        for (i = 0; i < visits.length; i++) {
            visit = visits[i];
            history_visits_to_urls[visit.visitId] = url;
            history_visits[visit.visitId] = visit;
        }
        var url_no_hash = url.split("#")[0];
        if (data[url_no_hash] === undefined) {
          data[url_no_hash] = {url: url_no_hash, visits: visits};
        }
        else {
          data[url_no_hash].visits.push(visits);
        }
        if (timeout_id !== undefined) {
          window.clearTimeout(timeout_id);
        }
        timeout_id = window.setTimeout(draw_graph, 100);
    };
}

function get_history(start_time) {
    var i;
    start_time = start_time || new Date() - (1000 * 60 * 60 * 24 * 30);

    chrome.history.search({'text': '', 'startTime': start_time, 'maxResults': MAX_RESULTS },
        function(history_items) {
            console.log("found " + history_items.length + " history items since " + start_time.toLocaleString());
            for (i = 0; i < history_items.length; i++) {
                var hi = history_items[i];
                history_urls[hi.url] = hi;
                chrome.history.getVisits({"url": hi.url}, set_history(hi.url));
            }
        }
    );
}

get_history();

document.addEventListener('DOMContentLoaded', init_graph);
<|endoftext|>


<commit_before>$(function() {
  /* Ensure window is tall enough to show all form elements. */
  var min_height = 600;
  if (window.outerHeight < min_height) {
    window.resizeTo(700, min_height);
  }

  /* Parse URL query parameters into urlParams hash. */
  var urlParams;
  (window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
  })();
  /* Set form inputs to values passed via URL query parameters. */
  $('input#url').val(urlParams['url']);
  $('input#pin-title').val(urlParams['title']);
  $('textarea#description').val(urlParams['description']);

  authenticate(urlParams);

  get_suggested_tags();
  $('input#tags').focus();
});

function GET(url, callback) {
  run_request('GET', url, null, callback);
}

function authenticate(urlParams) {
  if (urlParams['user'] && urlParams['token']) {
    $.cookie('pinboard-user', urlParams['user']);
    $.cookie('pinboard-token', urlParams['token']);
  } else {
    alert("You must provide a 'user' and 'token' parameter to this page to use the Pinboard API.");
  }
}

function auth_token() {
  return $.cookie('pinboard-user') + ':' + $.cookie('pinboard-token');
}

function get_suggested_tags() {
  var suggested_tags_api = "https://api.pinboard.in/v1/posts/suggest?auth_token=" + auth_token();
  $.get(suggested_tags_api, function(data) {
    show_suggested_tags(data);
  }, 'xml');
}

function show_suggested_tags(tags) {
  if (!tags) { return; }
  var row = document.getElementById("suggestion_row");
  row.style.visibility = 'visible';
  var cell = document.getElementById("suggested");
  var links = [];
  for (var i = 0; i < tags.length; i++) {
    var tag = tags[i];
    var escaped = pin_escape(tag);
    var cooked  = pin_cook(tag);
    var link = '' + cooked + ' ';
    links.push(link);
  }
  cell.innerHTML = links.join(" ");
}

function pin_escape(s) {
  s = s.replace(/\\/g, "\\\\");
  s = s.replace(/'/g, "\\'"); // "
  s = s.replace(/"/g, '"'); // "
  return s;
}

function pin_cook(s) {
  s = s.replace(/</g, '<');
  s = s.replace(/>/g, '>');
  s = s.replace(/"/g, '"');  //"
  return s;
}

function pin_sort(a,b) {
  var l = a.toLowerCase ? a.toLowerCase() : a;
  var r = b.toLowerCase ? b.toLowerCase() : b;
  if (l == r) { return 0; }
  if (l > r) { return 1; }
  return -1;
}<commit_msg>Use pinboard API bridge to allow Ajax requests.<commit_after>$(function() {
  /* Ensure window is tall enough to show all form elements. */
  var min_height = 600;
  if (window.outerHeight < min_height) {
    window.resizeTo(700, min_height);
  }

  /* Parse URL query parameters into urlParams hash. */
  var urlParams;
  (window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
  })();
  /* Set form inputs to values passed via URL query parameters. */
  $('input#url').val(urlParams['url']);
  $('input#pin-title').val(urlParams['title']);
  $('textarea#description').val(urlParams['description']);

  authenticate(urlParams);

  get_suggested_tags();
  $('input#tags').focus();
});

function GET(url, callback) {
  run_request('GET', url, null, callback);
}

function authenticate(urlParams) {
  if (urlParams['user'] && urlParams['token']) {
    $.cookie('pinboard-user', urlParams['user']);
    $.cookie('pinboard-token', urlParams['token']);
  } else {
    alert("You must provide both ‘user’ and ‘token’ parameters to this page to use the Pinboard API.");
  }
}

function auth_token() {
  return $.cookie('pinboard-user') + ':' + $.cookie('pinboard-token');
}

function get_suggested_tags() {
  var suggested_tags_api = "https://pinboard-bridge.herokuapp.com/posts/suggest?auth_token=" + auth_token();
  $.get(suggested_tags_api, function(data) {
    show_suggested_tags(data);
  }, 'xml');
}

function show_suggested_tags(tags) {
  if (!tags) { return; }
  var row = document.getElementById("suggestion_row");
  row.style.visibility = 'visible';
  var cell = document.getElementById("suggested");
  var links = [];
  for (var i = 0; i < tags.length; i++) {
    var tag = tags[i];
    var escaped = pin_escape(tag);
    var cooked  = pin_cook(tag);
    var link = '' + cooked + ' ';
    links.push(link);
  }
  cell.innerHTML = links.join(" ");
}

function pin_escape(s) {
  s = s.replace(/\\/g, "\\\\");
  s = s.replace(/'/g, "\\'"); // "
  s = s.replace(/"/g, '"'); // "
  return s;
}

function pin_cook(s) {
  s = s.replace(/</g, '<');
  s = s.replace(/>/g, '>');
  s = s.replace(/"/g, '"');  //"
  return s;
}

function pin_sort(a,b) {
  var l = a.toLowerCase ? a.toLowerCase() : a;
  var r = b.toLowerCase ? b.toLowerCase() : b;
  if (l == r) { return 0; }
  if (l > r) { return 1; }
  return -1;
}<|endoftext|>


<commit_before>function getCurrentTabUrl(callback) {
	var queryInfo = {
		active: true,
		currentWindow: true
	};

	chrome.tabs.query(queryInfo, function(tabs){
		var tab = tabs[0];
		callback(tab.url);
	});
}

function download(file){
	chrome.downloads.download({
		url: file
	});
}

chrome.runtime.onMessage.addListener(function(request, sender){
});

$(function(){
});

window.onload = onWindowLoad;
function onWindowLoad(){
}
<commit_msg>added a function to load html from a site into a hidden div<commit_after>function getCurrentTabUrl(callback) {
	var queryInfo = {
		active: true,
		currentWindow: true
	};

	chrome.tabs.query(queryInfo, function(tabs){
		var tab = tabs[0];
		callback(tab.url);
	});
}

function download(file){
	chrome.downloads.download({
		url: file
	});
}

function loadSite(url, _callback){
	var req = new XMLHttpRequest();
	req.open("GET", url, true);
    req.onload = function(e){
    	var data = this.response;
    	var target = $("#hidden");
    	target.html(data);
    	_callback();
	};
    req.send();
}

chrome.runtime.onMessage.addListener(function(request, sender){
});

$(function(){
});

window.onload = onWindowLoad;
function onWindowLoad(){
}
<|endoftext|>


<commit_before>var inputHandle = document.getElementById("githubHandle");
var btn = document.getElementById("check");

if (document.getElementById("githubHandle").value === "") {
	chrome.storage.sync.get("lastSearched", function (data){
	  var storedHandle = data['lastSearched'];
  	  if (storedHandle != "" && storedHandle != null) {
		setData(storedHandle);
	  }
  });
}

inputHandle.onkeydown = function(event){
	if(event.keyCode == 13) {
		btn.click();
	}
}
btn.onclick = function() {
  var handle = document.getElementById("githubHandle").value;
	var result = document.getElementById("result");
	if(handle != "" && handle != null) {
		result.innerHTML = "Loading...";
		getData(handle);
	} else {
		result.innerHTML = "Please enter a valid Github Username";
	}
}

function getMessage(total_count) {
  var message = "";
  switch (total_count) {
    case 0:
      return "It is never too late to start.";
    case 1:
      return "Still long way to go.";
    case 2:
      return "Awesome, you are half way through.";
    case 3:
      return "Just one more to go.";
    default:
      return "Congratulations, you have completed hacktoberfest 2017.";
  }
}

function updateMostRecentUsers(user) {
	chrome.storage.sync.get("mostRecentUsers", function (data) {
		var mostRecentUsers = data['mostRecentUsers'] || [];
		var hasUser = false;
		if (mostRecentUsers.length > 0) {
			for(var i=0; i<mostRecentUsers.length; i++) {
				if (mostRecentUsers[i].name === user.name) {
					hasUser = true;
				}
			}
		}

		if (!hasUser) {
			mostRecentUsers.push(user);
		}

		if (mostRecentUsers.length > 5) {
			mostRecentUsers.shift();
		}

		chrome.storage.sync.set({"mostRecentUsers": mostRecentUsers}, function() {
			var html = "";
			for(var i=0; i< mostRecentUsers.length; i++) {
				html += "";
			}
			var parent = document.getElementById("mostRecentUsers");
			parent.addEventListener("click", function(e) {
				setData(e.target.id);
			});
			parent.innerHTML = html;
		});
	});

}

function setData(handle){
	document.getElementById("githubHandle").value = handle;
	getData(handle);
}

function getData(handle) {
  var reqUrl = `https://api.github.com/search/issues?q=author:${handle}+type:pr+created:2017-09-30T00:00:00-12:00..2017-10-31T23:59:59-12:00+is:public`;

  var req = new XMLHttpRequest();
  req.onreadystatechange = function() {
    if(this.readyState == 4 && this.status == 200){
	  var data = JSON.parse(req.responseText);
	  var avatarUrl = data.items[0].user.avatar_url;
	  updateMostRecentUsers({"name": handle, "thumbnail": avatarUrl});
	  chrome.storage.sync.set({"lastSearched": handle, "thumbnail": avatarUrl}, function (){
	    var res = "";
		res += ""
        res += "
" + handle + "
";
        var count = (data["total_count"] > 4 ? "4" : data["total_count"]) + "/4";
        res += "
" + count + "
";
        var message = getMessage(data["total_count"]);
        res += "
" + message + "
";

		var newestPRs = data.total_count > 4 ? data.items.slice(0, 4) : data.items;
        if (newestPRs.length > 0) {
          var prs = newestPRs.map((v, i) => {
            return `<li><a target="_blank" href="${v["html_url"]}">#${v["number"]} - ${v["title"]}</a></li>`;
	      });
          res += `<div id="prList">Pull requests: <ul>${prs}</ul></div>`;
        }

	    document.getElementById("result").innerHTML = res;
	  });
    }
  };
  req.open("GET", reqUrl, true);
  req.send();
}
<commit_msg>refactored with promise chain to make multiple api calls and set data<commit_after>var inputHandle = document.getElementById("githubHandle");
var btn = document.getElementById("check");

if (document.getElementById("githubHandle").value === "") {
	chrome.storage.sync.get("lastSearched", function (data){
	  var storedHandle = data['lastSearched'];
  	  if (storedHandle != "" && storedHandle != null) {
		setData(storedHandle);
	  }
  });
}

inputHandle.onkeydown = function(event){
	if(event.keyCode == 13) {
		btn.click();
	}
}
btn.onclick = function() {
  var handle = document.getElementById("githubHandle").value;
	var result = document.getElementById("result");
	if(handle != "" && handle != null) {
		result.innerHTML = "Loading...";
		initData(handle);
	} else {
		result.innerHTML = "Please enter a valid Github Username";
	}
}

function getMessage(total_count) {
  var message = "";
  switch (total_count) {
    case 0:
      return "It is never too late to start.";
    case 1:
      return "Still long way to go.";
    case 2:
      return "Awesome, you are half way through.";
    case 3:
      return "Just one more to go.";
    default:
      return "Congratulations, you have completed hacktoberfest 2017.";
  }
}

function updateMostRecentUsers(user) {
	chrome.storage.sync.get("mostRecentUsers", function (data) {
		var mostRecentUsers = data['mostRecentUsers'] || [];
		var hasUser = false;
		if (mostRecentUsers.length > 0) {
			for(var i=0; i<mostRecentUsers.length; i++) {
				if (mostRecentUsers[i].name === user.name) {
					hasUser = true;
				}
			}
		}

		if (!hasUser) {
			mostRecentUsers.push(user);
		}

		if (mostRecentUsers.length > 5) {
			mostRecentUsers.shift();
		}

		chrome.storage.sync.set({"mostRecentUsers": mostRecentUsers}, function() {
			var html = "";
			for(var i=0; i< mostRecentUsers.length; i++) {
				html += "";
			}
			var parent = document.getElementById("mostRecentUsers");
			parent.addEventListener("click", function(e) {
				setData(e.target.id);
			});
			parent.innerHTML = html;
		});
	});

}

function setData(handle) {
	document.getElementById("githubHandle").value = handle;
	initData(handle);
}

function getXHR(url) {

	return new Promise(function(resolve, reject) {
		var req = new XMLHttpRequest();
		req.open("GET", url, true);
		req.onreadystatechange = function() {
		  if(this.status === 200 && this.readyState === 4) {
			resolve(JSON.parse(req.responseText));
		  }
		};
		req.onerror = function() {
	      reject(Error("Network Error"));
	    };
		req.send();
	});

}

function initData(handle) {
	var avatarUrl = "";

	getXHR(`https://api.github.com/users/${handle}`)
	.then(function(data) {
		avatarUrl = data.avatar_url;
		return getXHR(`https://api.github.com/search/issues?q=author:${handle}+type:pr+created:2017-09-30T00:00:00-12:00..2017-10-31T23:59:59-12:00+is:public`);
	})
	.then(function(data) {
		var prCount = data.items.length || 0;

		updateMostRecentUsers({"name": handle, "thumbnail": avatarUrl});
		chrome.storage.sync.set({"lastSearched": handle, "thumbnail": avatarUrl}, function () {
		  var res = "";
		  res += ""
			res += "
" + handle + "
";
			var count = (prCount > 4 ? "4" : prCount) + "/4";
			res += "
" + count + "
";
			var message = getMessage(prCount);
			res += "
" + message + "
";

			var newestPRs = prCount > 4 ? data.items.slice(0, 4) : data.items;
			if (newestPRs.length > 0) {
			  var prs = newestPRs.map((v, i) => {
				return `<li><a target="_blank" href="${v["html_url"]}">#${v["number"]} - ${v["title"]}</a></li>`;
			  });
			  res += `<div id="prList">Pull requests: <ul>${prs}</ul></div>`;
			}

		  document.getElementById("result").innerHTML = res;
		});
	})
	.catch(function(error) {
		console.error(error);
	});

}
<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('click-me').addEventListener('click',
		function () {
			chrome.tabs.executeScript(null, {file: "jquery.min.js"},
				function () {
					chrome.tabs.executeScript(null, {file: "contentscript.js"});
				}
			);
		}
	);
});
<commit_msg>updated an element name so that the listener works<commit_after>document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('button').addEventListener('click',
		function () {
			chrome.tabs.executeScript(null, {file: "jquery.min.js"},
				function () {
					chrome.tabs.executeScript(null, {file: "contentscript.js"});
				}
			);
		}
	);
});
<|endoftext|>


<commit_before>/**
 *
 */

var config=require('./proxy.json');

(function(){

	// Simple websocket server

	var port = config.websocketPort;

	var master=null;

	(new (require('ws').Server)({
		port: port
	})).on('connection', function(wsclient){

		if(master===null){
			console.log('master client connected: '+wsclient);

		}

		wsclient.on('message',function(data){

			console.log(data);

		}).on('error', function(error){
			console.log('error: '+error);
		}).on('close',function(code, message){
			console.log('close: '+message);
		});

	}).on('error', function(error){
		console.log('error: '+error);
	})

	console.log('websocket listening on: '+port);

})();

<commit_msg>want to print out the first connection<commit_after>/**
 *
 */

var config=require('./proxy.json');

(function(){

	// Simple websocket server

	var port = config.websocketPort;

	var master=null;

	(new (require('ws').Server)({
		port: port
	})).on('connection', function(wsclient){

		if(master===null){
			console.log('master client connected: '+JSON.stringify(Object.keys(wsclient)));

		}

		wsclient.on('message',function(data){

			console.log(data);

		}).on('error', function(error){
			console.log('error: '+error);
		}).on('close',function(code, message){
			console.log('close: '+message);
		});

	}).on('error', function(error){
		console.log('error: '+error);
	})

	console.log('websocket listening on: '+port);

})();

<|endoftext|>


<commit_before>var config = require('./config')
  , bouncy = require('bouncy')
  , ports = config.ports
  , port
  , i = 0

bouncy(function (req, bounce) {
  if (req.url === config.hook) return bounce(config.publisher)

  port = ports[i++]
  bounce(port)
  if (i >= ports.length) i = 0
}).listen(config.port)

<commit_msg>Remove publish from proxy<commit_after>var config = require('./config')
  , bouncy = require('bouncy')
  , ports = config.ports
  , port
  , i = 0

bouncy(function (req, bounce) {
  port = ports[i++]
  bounce(port)
  if (i >= ports.length) i = 0
}).listen(config.port)

<|endoftext|>


<commit_before>
var config = require('collections-online/lib/config');
var cip = require('./services/cip');
var Agent = require('agentkeepalive');
var request = require('request').defaults({
  agent: new Agent({
    maxSockets: config.cip.proxyMaxSockets
  })
});

function proxy(url) {
  // Prefix the baseURL
  url = config.cip.baseURL + url;
  // Add any available jsessionid, just before any querystring.
  if(url.indexOf('jsessionid') < 0 && cip.jsessionid) {
    let jsessionidString = ';jsessionid=' + cip.jsessionid;
    let queryStringStart = url.indexOf('?');
    if(queryStringStart < 0) {
      url += jsessionidString;
    } else {
      url = url.substring(0, queryStringStart) +
            jsessionidString +
            url.substring(queryStringStart);
    }
  }

  console.log('CIP proxy is requesting', url);

  return request
    .get(url)
    .on('response', function(response){
      response.headers['Cache-Control'] = 'max-age=2592000';
    });
}

module.exports = proxy;
<commit_msg>Adding a timeout and a page to be redirected to when it happens<commit_after>
var config = require('collections-online/lib/config');
var cip = require('./services/cip');
var Agent = require('agentkeepalive');
var request = require('request').defaults({
  agent: new Agent({
    maxSockets: config.cip.proxyMaxSockets
  }),
  timeout: config.cip.timeout || 55000 // 55 secs
});

function proxy(url) {
  // Prefix the baseURL
  url = config.cip.baseURL + url;
  // Add any available jsessionid, just before any querystring.
  if(url.indexOf('jsessionid') < 0 && cip.jsessionid) {
    let jsessionidString = ';jsessionid=' + cip.jsessionid;
    let queryStringStart = url.indexOf('?');
    if(queryStringStart < 0) {
      url += jsessionidString;
    } else {
      url = url.substring(0, queryStringStart) +
            jsessionidString +
            url.substring(queryStringStart);
    }
  }

  console.log('CIP proxy is requesting', url);

  return request
    .get(url)
    .on('response', function(response) {
      response.headers['Cache-Control'] = 'max-age=2592000';
    });
}

module.exports = proxy;
<|endoftext|>