<commit_before>var SS = document.styleSheets[0];
var nOrigRules = SS.cssRules.length;  // Number of rules in default stylesheet (from .css file)
var nCurrRules = nOrigRules; // Number of rules in current stylesheet object

var pXY     = document.getElementById("pXY");
var toSplit = document.getElementById("toSplit");
var vidBungee = document.getElementById("vidBungee");

var btnFlyAway  = document.getElementById("btnFlyAway");

var imgFace = document.getElementById("imgFace");

var SA = []; // Elements after splitting text inside div into words.
var nSpan = 0; // Max number of spans to animate (SA's length)
var atRest = []; // Indicator array for SA's elements "at rest" (not being animated)

var HS = []; // Elements of SA whose bounding boxes contain a specific pt., to be animated

/* Split element E's contents into individual <span> elements ("words").
   Output: Array of span elements corresponding to each word inside E
*/
function makeSpans(E) {
  // Later: Recurse thru sub-tree and get all innerHTML's, to allow <h1> and so
  // on be inside the E, so that all visual elements can be animated ("crashed
  // through" by the moving icon).
  var strSpans = E.textContent.split(' '); // Array of strings, each a (text) "word"
  nSpan = strSpans.length; // Cache global var

  // Replace with spans
  E.innerHTML = '';
  for (var ii=0; ii < nSpan; ii++) {
    s = document.createElement('span');
    s.id = 'spin'+ii;
    s.className="atRest";
    s.innerHTML = strSpans[ii]+' ';
    s.idNum = ii; // Custom property - just the number portion of the CSS id
    E.appendChild(s);
    SA.push(s);
    atRest.push(true); // Initial statue: element is at rest
  }
  return SA;
}

/* Find elements whose bounding boxes contain point x, y
   Used for "hit detection" in the animation.
   IN   E    Array of DOM elements
        x,y  Query point's coords
   OUT  Array of elements that contain the query point
*/
function elementsAtPos(E, x, y) {
  var Ehits = []; // List of elements that contain P
  for (var ii = 0; ii < E.length; ii++) {
    var e = E[ii]; // Get one element
    // Bounding rectangle of element (do this each time -- user may resize the window during animation
    var r = e.getBoundingClientRect();
    if ((x > r.left) && (x < r.right) && (y > r.top) && (y < r.bottom)) {
      Ehits.push(e);
    //console.log("x,y="+x+","+y + " L,R/T,B="+r.left+","+r.right+ "/"+r.top+","+r.bottom);
    }
    else { e.style.color = "black"; } // Revert color once mouse is outside hitbox
  }
  return Ehits;
}

/*
// Test input. May keep as an additional effect, but for, simulates "Gliding Andrew" which is to be coded
function getMouseXY(ev) {
  var mx = -1;
  var my = -1;
  if (! ev) { var ev = window.event; } // If event not passed in (more portable)
  if (ev.pageX || ev.pageY) {
    mx = ev.pageX;
    my = ev.pageY;
  }
  else if (ev.clientX || ev.clientY) {
    mx = ev.clientX + document.body.scrollLeft;
    my = ev.clientY + document.body.scrollTop;
  }
  return {x: mx, y: my}
}

function addRule(sheet, selector, rules, index) {
  if ("insertRule" in sheet) {
    sheet.insertRule(selector + "{" + rules + "}", index);
    nCurrRules++;
  }
  else if ("addRule" in sheet) {
    sheet.addRule(selector, rules, index);
    nCurrRules++;
  }
}
*/

function randInt(min, max) {
  r = Math.random();
  return min + Math.round(r*(max - min + 1));
}

function crash(x, y) {
  // Debug: Show mouse coords in paragraph
/*var pos = getMouseXY();
  pXY.textContent = "Mouse x,y=("+pos.x+", "+pos.y+")";*/

  // Draft animation code
  // . Debug: Highlight span on mouseover and start animating span
  HS = elementsAtPos(S, x, y);
  for (var ii=0; ii < HS.length; ii++) {
    var idNum = HS[ii].idNum;
    if (atRest[idNum]) { // Span is at rest
      var ri = randInt(0, 3);
      HS[ii].className = "se"+ri;
    //addRule(SS, "#"+HS[ii].id, rules, nCurrRules);
    //nCurrRules++;
      atRest[idNum] = false;
    }
  }
  var SA = []; // Indicator array: spans being animated
}

/*
function resetCSSrules() {
  var extraRules = nCurrRules - nOrigRules;
  while (nCurrRules > nOrigRules) {
    nCurrRules--;
    SS.deleteRule(nCurrRules);
  }
  for (var ii; ii < atRest.length; ii++) {
    atRest[ii] = true; // Initial statue: element is at rest
  }
  for (var ii; ii < atRest.length; ii++) {
    HS[ii].className = "atRest";
  }
}
*/

var S = makeSpans(toSplit);

// Debug: Treat mouse cursor as the "crasher" animated/flying image
//btnResetCSS.addEventListener('click', function() { resetCSSrules(); }, true);
//document.addEventListener('mousemove', function() { crash(); }, true);

var xImg = 0;
var yImg = 0;
var dx = 2.6;
var dy = 3;
var yLimit = 750; // Hard-coded y-loc of face in initial video frame. Given more time, code this to be determined from element positions.
var anim_start_delay = 2000; // Wait __ seconds before animating
var anim_frame_time = 40;    // Time gap between "crasher" position updates

function moveFace() {
  var r = imgFace.getBoundingClientRect();
  if (r.bottom < yLimit) {
    xImg += dx;
    yImg += dy;
    imgFace.style.top  = yImg+"px";
    imgFace.style.left = xImg+"px";
    imgFace.style.opacity = 1 - (r.bottom / yLimit);
    setTimeout(moveFace, anim_frame_time);
    var ir = imgFace.getBoundingClientRect();
    crash(ir.right, ir.top);
    crash(ir.right, ir.bottom);
    crash(ir.left,  ir.bottom);
  } else {
      vidBungee.play();
   //console.log("img right,bottom = "+r.right + ", "+r.bottom);
  }
}

// Timer code to animate face image
setTimeout(moveFace, anim_start_delay);

<commit_msg>whitespc. clearing out wkspc<commit_after>var SS = document.styleSheets[0];
var nOrigRules = SS.cssRules.length;  // Number of rules in default stylesheet (from .css file)
var nCurrRules = nOrigRules; // Number of rules in current stylesheet object

var pXY = document.getElementById("pXY");
var toSplit = document.getElementById("toSplit");
var vidBungee = document.getElementById("vidBungee");

var btnFlyAway = document.getElementById("btnFlyAway");

var imgFace = document.getElementById("imgFace");

var SA = []; // Elements after splitting text inside div into words.
var nSpan = 0; // Max number of spans to animate (SA's length)
var atRest = []; // Indicator array for SA's elements "at rest" (not being animated)

var HS = []; // Elements of SA whose bounding boxes contain a specific pt., to be animated

/* Split element E's contents into individual <span> elements ("words").
   Output: Array of span elements corresponding to each word inside E
*/
function makeSpans(E) {
  // Later: Recurse thru sub-tree and get all innerHTML's, to allow <h1> and so
  // on be inside the E, so that all visual elements can be animated ("crashed
  // through" by the moving icon).
  var strSpans = E.textContent.split(' '); // Array of strings, each a (text) "word"
  nSpan = strSpans.length; // Cache global var

  // Replace with spans
  E.innerHTML = '';
  for (var ii=0; ii < nSpan; ii++) {
    s = document.createElement('span');
    s.id = 'spin'+ii;
    s.className="atRest";
    s.innerHTML = strSpans[ii]+' ';
    s.idNum = ii; // Custom property - just the number portion of the CSS id
    E.appendChild(s);
    SA.push(s);
    atRest.push(true); // Initial statue: element is at rest
  }
  return SA;
}

/* Find elements whose bounding boxes contain point x, y
   Used for "hit detection" in the animation.
   IN   E    Array of DOM elements
        x,y  Query point's coords
   OUT  Array of elements that contain the query point
*/
function elementsAtPos(E, x, y) {
  var Ehits = []; // List of elements that contain P
  for (var ii = 0; ii < E.length; ii++) {
    var e = E[ii]; // Get one element
    // Bounding rectangle of element (do this each time -- user may resize the window during animation
    var r = e.getBoundingClientRect();
    if ((x > r.left) && (x < r.right) && (y > r.top) && (y < r.bottom)) {
      Ehits.push(e);
    //console.log("x,y="+x+","+y + " L,R/T,B="+r.left+","+r.right+ "/"+r.top+","+r.bottom);
    }
    else { e.style.color = "black"; } // Revert color once mouse is outside hitbox
  }
  return Ehits;
}

/*
// Test input. May keep as an additional effect, but for, simulates "Gliding Andrew" which is to be coded
function getMouseXY(ev) {
  var mx = -1;
  var my = -1;
  if (! ev) { var ev = window.event; } // If event not passed in (more portable)
  if (ev.pageX || ev.pageY) {
    mx = ev.pageX;
    my = ev.pageY;
  }
  else if (ev.clientX || ev.clientY) {
    mx = ev.clientX + document.body.scrollLeft;
    my = ev.clientY + document.body.scrollTop;
  }
  return {x: mx, y: my}
}

function addRule(sheet, selector, rules, index) {
  if ("insertRule" in sheet) {
    sheet.insertRule(selector + "{" + rules + "}", index);
    nCurrRules++;
  }
  else if ("addRule" in sheet) {
    sheet.addRule(selector, rules, index);
    nCurrRules++;
  }
}
*/

function randInt(min, max) {
  r = Math.random();
  return min + Math.round(r*(max - min + 1));
}

function crash(x, y) {
  // Debug: Show mouse coords in paragraph
/*var pos = getMouseXY();
  pXY.textContent = "Mouse x,y=("+pos.x+", "+pos.y+")";*/

  // Draft animation code
  // . Debug: Highlight span on mouseover and start animating span
  HS = elementsAtPos(S, x, y);
  for (var ii=0; ii < HS.length; ii++) {
    var idNum = HS[ii].idNum;
    if (atRest[idNum]) { // Span is at rest
      var ri = randInt(0, 3);
      HS[ii].className = "se"+ri;
    //addRule(SS, "#"+HS[ii].id, rules, nCurrRules);
    //nCurrRules++;
      atRest[idNum] = false;
    }
  }
  var SA = []; // Indicator array: spans being animated
}

/*
function resetCSSrules() {
  var extraRules = nCurrRules - nOrigRules;
  while (nCurrRules > nOrigRules) {
    nCurrRules--;
    SS.deleteRule(nCurrRules);
  }
  for (var ii; ii < atRest.length; ii++) {
    atRest[ii] = true; // Initial statue: element is at rest
  }
  for (var ii; ii < atRest.length; ii++) {
    HS[ii].className = "atRest";
  }
}
*/

var S = makeSpans(toSplit);

// Debug: Treat mouse cursor as the "crasher" animated/flying image
//btnResetCSS.addEventListener('click', function() { resetCSSrules(); }, true);
//document.addEventListener('mousemove', function() { crash(); }, true);

var xImg = 0;
var yImg = 0;
var dx = 2.6;
var dy = 3;
var yLimit = 750; // Hard-coded y-loc of face in initial video frame. Given more time, code this to be determined from element positions.
var anim_start_delay = 2000; // Wait __ seconds before animating
var anim_frame_time = 40;    // Time gap between "crasher" position updates

function moveFace() {
  var r = imgFace.getBoundingClientRect();
  if (r.bottom < yLimit) {
    xImg += dx;
    yImg += dy;
    imgFace.style.top  = yImg+"px";
    imgFace.style.left = xImg+"px";
    imgFace.style.opacity = 1 - (r.bottom / yLimit);
    setTimeout(moveFace, anim_frame_time);
    var ir = imgFace.getBoundingClientRect();
    crash(ir.right, ir.top);
    crash(ir.right, ir.bottom);
    crash(ir.left,  ir.bottom);
  } else {
      vidBungee.play();
   //console.log("img right,bottom = "+r.right + ", "+r.bottom);
  }
}

// Timer code to animate face image
setTimeout(moveFace, anim_start_delay);

<|endoftext|>


<commit_before>import idbKeyval from 'idb-keyval';
import { CACHE_NAME, notificationTypes, urls } from './constants';
import { refreshIndex } from './search';

let isLoggedIn = true;

export async function testLogin(request, shouldLoadCache = true) {
  const response = await fetch(request);

  const wasLoggedIn = isLoggedIn;
  isLoggedIn = response.status !== 403;

  if (!isLoggedIn) {
    if (Notification.permission === 'granted') {
      self.registration.showNotification('Login expired\nPlease log in again', {
        icon: '/tweek.png',
        requireInteraction: true,
        tag: notificationTypes.LOGIN,
      });
    }
  } else {
    const loginNotifications = await self.registration.getNotifications({
      tag: notificationTypes.LOGIN,
    });
    loginNotifications.forEach(notification => notification.close());
    if (!wasLoggedIn && shouldLoadCache) {
      refresh();
    }
  }

  return response;
}

async function clearCache(){
  const cache = await caches.open(CACHE_NAME);
  const cachedKeys = await cache.keys();
  const urlsToCacheSet = new Set(urls.CACHE);
  await Promise.all(
    urlsToCacheSet.map(key => (console.log('deleting from cache', key.url), cache.delete(key))),
  );
}

export async function refresh() {
  console.log('refreshing cache...');

  try {
    await clearCache();

    await refreshIndex();

    const manifests = await fetch(urls.MANIFESTS, {credentials: 'include'});
    if (manifests.ok) {
      const data = await manifests.json();
      idbKeyval.clear();
      await Promise.all(data.map(manifest => idbKeyval.set(manifest.key_path, manifest)));
    }
    console.log('cache refreshed');
  } catch (error) {
    console.warn('failed to refresh cache', error);
  }
}
<commit_msg>Create data-actions.js<commit_after>import idbKeyval from 'idb-keyval';
import { CACHE_NAME, notificationTypes, urls } from './constants';
import { refreshIndex } from './search';

let isLoggedIn = true;

export async function testLogin(request, shouldLoadCache = true) {
  const response = await fetch(request);

  const wasLoggedIn = isLoggedIn;
  isLoggedIn = response.status !== 403;

  if (!isLoggedIn) {
    if (Notification.permission === 'granted') {
      self.registration.showNotification('Login expired\nPlease log in again', {
        icon: '/tweek.png',
        requireInteraction: true,
        tag: notificationTypes.LOGIN,
      });
    }
  } else {
    const loginNotifications = await self.registration.getNotifications({
      tag: notificationTypes.LOGIN,
    });
    loginNotifications.forEach(notification => notification.close());
    if (!wasLoggedIn && shouldLoadCache) {
      refresh();
    }
  }

  return response;
}

async function clearCache(){
  const cache = await caches.open(CACHE_NAME);
  const cachedKeys = await cache.keys();
  await Promise.all(
    cachedKeys.map(key => (console.log('deleting from cache', key.url), cache.delete(key))),
  );
}

export async function refresh() {
  console.log('refreshing cache...');

  try {
    await clearCache();

    await refreshIndex();

    const manifests = await fetch(urls.MANIFESTS, {credentials: 'include'});
    if (manifests.ok) {
      const data = await manifests.json();
      idbKeyval.clear();
      await Promise.all(data.map(manifest => idbKeyval.set(manifest.key_path, manifest)));
    }
    console.log('cache refreshed');
  } catch (error) {
    console.warn('failed to refresh cache', error);
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import express from 'express';
import exphbs  from 'express-handlebars';
import { match, RouterContext } from 'react-router';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import routes from './app/routes';
import chalk from 'chalk';
import configureStore from './app/store/configureStore';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import morgan from 'morgan';
import fs from 'fs';
import unirest from 'unirest';
import cheerio from 'cheerio';
import schedule from 'node-schedule';

const app = express();
const port = 5000;
const jsPath = '/assets/js';

// Using helmet to secure Express with various HTTP headers
app.use(helmet());
// Prevent HTTP parameter pollution.
app.use(hpp());
// Compress all requests
app.use(compression());
// Use morgan for http request debug (only show error)
app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 }));

app.use(express.static('./public'));
app.use(jsPath, express.static('./dist/client'));

app.engine('hbs', exphbs({extname: '.hbs'}));
app.set('view engine', 'hbs');

let pluginSiteVersion = null;
let pluginSiteApiVersion = null;

const downloadHeader = () => {
  var headerFile = __HEADER_FILE__;
  if (headerFile !== null && headerFile !== undefined) {
    console.info(`Downloading header file from '${headerFile}'`);
    unirest.get(headerFile).end((response) => {
      if (response.statusCode == 200) {
        var $ = cheerio.load(response.body, { decodeEntities: false });
        $('img, script').each(function() {
          var src = $(this).attr('src');
          if (src !== undefined && src.startsWith('/')) {
            $(this).attr('src', 'https://jenkins.io' + src);
          }
        });
        $('a, link').each(function() {
          var href = $(this).attr('href');
          if (href !== undefined && href.startsWith('/')) {
            $(this).attr('href', 'https://jenkins.io' + href);
          }
        });
        $('head').prepend('{{> header }}');
        // WEBSITE-241 - Specifically remove to avoid CORS problem
        $('link[href="https://jenkins.io/css/font-icons.css"]').remove();
        $('head').append('');
        $('#grid-box').append('{{{rendered}}}');
        $('#grid-box').after('');
        if (fs.existsSync('./git.json')) {
          try {
            var versions = JSON.parse(fs.readFileSync('./git.json'));
            pluginSiteVersion = versions["plugin-site"];
            pluginSiteApiVersion = versions["plugin-site-api"];
            if (pluginSiteVersion !== undefined && pluginSiteApiVersion !== undefined) {
              $('#creativecommons').append('{{> version }}');
            }
          } catch (err) {
            console.error(chalk.red("Problem processing git.json"), err);
          }
        }
        fs.writeFileSync('./views/index.hbs', $.html());
      } else {
        console.error(response.statusCode);
        console.error(error);
      }
    });
  } else {
    console.info("HEADER_FILE environment variable null");
  }
}

downloadHeader();

app.get('*', (req, res, next) => {
  match({ routes: routes, location: req.url }, (error, redirectLocation, renderProps) => {
    if (error) {
      res.status(500).send(error.message);
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if (!renderProps) {
      res.sendStatus(404);
    } else {
      const store = configureStore();
      const { location, params, history } = renderProps;
      const promises = renderProps.components
        .filter(component => component.fetchData)
        // Should the component have a static method `fetchData({ store, location, params, history })` then
        // call it.
        .map(component => component.fetchData({ store, location, params, history }));

      Promise.all(promises).then(() => {
        const rendered = renderToString(

            <Provider store={store}>
              <RouterContext {...renderProps} />
            </Provider>

        );
        const finalState = JSON.stringify(store.getState()).replace(/</g, '\\x3c');
        res.status(200).render('index', {
          rendered: rendered,
          reduxState: finalState,
          jsPath: jsPath,
          pluginSiteVersion,
          pluginSiteApiVersion
        });
      }).catch((err) => {
        console.error(chalk.red(error));
        res.sendStatus(404);
      });
    }
  });
});

app.listen(port, (error) => {
  if (error) {
    console.error(chalk.red(error)); // eslint-disable-line no-console
  } else {
    console.info(chalk.green(`==>  Listening on port ${port}`)); // eslint-disable-line no-console
    schedule.scheduleJob('*/15 * * * *', () => {
      downloadHeader();
    });
  }
});
<commit_msg>Revert "[WEBSITE-241] - Remove conflicting CSS"<commit_after>import React from 'react';
import express from 'express';
import exphbs  from 'express-handlebars';
import { match, RouterContext } from 'react-router';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import routes from './app/routes';
import chalk from 'chalk';
import configureStore from './app/store/configureStore';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import morgan from 'morgan';
import fs from 'fs';
import unirest from 'unirest';
import cheerio from 'cheerio';
import schedule from 'node-schedule';

const app = express();
const port = 5000;
const jsPath = '/assets/js';

// Using helmet to secure Express with various HTTP headers
app.use(helmet());
// Prevent HTTP parameter pollution.
app.use(hpp());
// Compress all requests
app.use(compression());
// Use morgan for http request debug (only show error)
app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 }));

app.use(express.static('./public'));
app.use(jsPath, express.static('./dist/client'));

app.engine('hbs', exphbs({extname: '.hbs'}));
app.set('view engine', 'hbs');

let pluginSiteVersion = null;
let pluginSiteApiVersion = null;

const downloadHeader = () => {
  var headerFile = __HEADER_FILE__;
  if (headerFile !== null && headerFile !== undefined) {
    console.info(`Downloading header file from '${headerFile}'`);
    unirest.get(headerFile).end((response) => {
      if (response.statusCode == 200) {
        var $ = cheerio.load(response.body, { decodeEntities: false });
        $('img, script').each(function() {
          var src = $(this).attr('src');
          if (src !== undefined && src.startsWith('/')) {
            $(this).attr('src', 'https://jenkins.io' + src);
          }
        });
        $('a, link').each(function() {
          var href = $(this).attr('href');
          if (href !== undefined && href.startsWith('/')) {
            $(this).attr('href', 'https://jenkins.io' + href);
          }
        });
        $('head').prepend('{{> header }}');
        $('head').append('');
        $('#grid-box').append('{{{rendered}}}');
        $('#grid-box').after('');
        if (fs.existsSync('./git.json')) {
          try {
            var versions = JSON.parse(fs.readFileSync('./git.json'));
            pluginSiteVersion = versions["plugin-site"];
            pluginSiteApiVersion = versions["plugin-site-api"];
            if (pluginSiteVersion !== undefined && pluginSiteApiVersion !== undefined) {
              $('#creativecommons').append('{{> version }}');
            }
          } catch (err) {
            console.error(chalk.red("Problem processing git.json"), err);
          }
        }
        fs.writeFileSync('./views/index.hbs', $.html());
      } else {
        console.error(response.statusCode);
        console.error(error);
      }
    });
  } else {
    console.info("HEADER_FILE environment variable null");
  }
}

downloadHeader();

app.get('*', (req, res, next) => {
  match({ routes: routes, location: req.url }, (error, redirectLocation, renderProps) => {
    if (error) {
      res.status(500).send(error.message);
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if (!renderProps) {
      res.sendStatus(404);
    } else {
      const store = configureStore();
      const { location, params, history } = renderProps;
      const promises = renderProps.components
        .filter(component => component.fetchData)
        // Should the component have a static method `fetchData({ store, location, params, history })` then
        // call it.
        .map(component => component.fetchData({ store, location, params, history }));

      Promise.all(promises).then(() => {
        const rendered = renderToString(

            <Provider store={store}>
              <RouterContext {...renderProps} />
            </Provider>

        );
        const finalState = JSON.stringify(store.getState()).replace(/</g, '\\x3c');
        res.status(200).render('index', {
          rendered: rendered,
          reduxState: finalState,
          jsPath: jsPath,
          pluginSiteVersion,
          pluginSiteApiVersion
        });
      }).catch((err) => {
        console.error(chalk.red(error));
        res.sendStatus(404);
      });
    }
  });
});

app.listen(port, (error) => {
  if (error) {
    console.error(chalk.red(error)); // eslint-disable-line no-console
  } else {
    console.info(chalk.green(`==>  Listening on port ${port}`)); // eslint-disable-line no-console
    schedule.scheduleJob('*/15 * * * *', () => {
      downloadHeader();
    });
  }
});
<|endoftext|>


<commit_before>var Watcher = require('./watcher')
var middleware = require('./middleware')
var tinylr = require('tiny-lr')
var lrServer = tinylr.Server
var corsMiddleware = require('./cors-middleware')
var http = require('http')
var connect = require('connect')
var printSlowNodes = require('broccoli-slow-trees')

exports.serve = serve
function serve (builder, options) {
  options = options || {}
  var server = {}

  console.log('Serving on http://' + options.host + ':' + options.port + '\n')

  server.watcher = options.watcher || new Watcher(builder)

  server.app = connect();
  if (options.cors) {
      server.app.use(corsMiddleware);
  }
  server.app = server.app.use(middleware(server.watcher))

  server.http = http.createServer(server.app)

  server.watcher.watch()
    .catch(function(err) {
      console.log(err && err.stack || err)
    })
    .finally(function() {
      builder.cleanup()
      server.http.close()
    })
    .catch(function(err) {
      console.log('Cleanup error:')
      console.log(err && err.stack || err)
    })
    .finally(function() {
      process.exit(1)
    })

  // We register these so the 'exit' handler removing temp dirs is called
  function cleanupAndExit() {
    return server.watcher.quit()
  }

  function liveReload() {
      lrServer.changed({ body :  { files : ['livereload_dummy'] } })
  }

  process.on('SIGINT', cleanupAndExit)
  process.on('SIGTERM', cleanupAndExit)

  server.watcher.on('change', function() {
    printSlowNodes(builder.outputNodeWrapper)
    console.log('Built - ' + Math.round(builder.outputNodeWrapper.buildState.totalTime) + ' ms @ ' + new Date().toString())
    liveReload()
  })

  server.watcher.on('error', function(err) {
    console.log('Built with error:')
    console.log(err.message)
    if (!err.broccoliPayload || !err.broccoliPayload.location.file) {
      console.log('')
      console.log(err.stack)
    }
    console.log('')
    liveReload()
  })

  server.http.listen(parseInt(options.port, 10), options.host)
  lrServer.listen(options.liveReloadPort, function(err) {
      if (err) {
        console.log('Failed to start the live reload server', err)
      } else {
        console.log('Live reload server started on', options.liveReloadPort)
      }
  });
  return server
}
<commit_msg>Live reload fixes<commit_after>var Watcher = require('./watcher')
var middleware = require('./middleware')
var tinylr = require('tiny-lr')
var lrServer = tinylr()
var corsMiddleware = require('./cors-middleware')
var http = require('http')
var connect = require('connect')
var printSlowNodes = require('broccoli-slow-trees')

exports.serve = serve
function serve (builder, options) {
  options = options || {}
  var server = {}

  console.log('Serving on http://' + options.host + ':' + options.port + '\n')

  server.watcher = options.watcher || new Watcher(builder)

  server.app = connect();
  if (options.cors) {
      server.app.use(corsMiddleware);
  }
  server.app = server.app.use(middleware(server.watcher))

  server.http = http.createServer(server.app)

  server.watcher.watch()
    .catch(function(err) {
      console.log(err && err.stack || err)
    })
    .finally(function() {
      builder.cleanup()
      server.http.close()
    })
    .catch(function(err) {
      console.log('Cleanup error:')
      console.log(err && err.stack || err)
    })
    .finally(function() {
      process.exit(1)
    })

  // We register these so the 'exit' handler removing temp dirs is called
  function cleanupAndExit() {
    lrServer.close()
    return server.watcher.quit()
  }

  function liveReload() {
      lrServer.changed({ body :  { files : ['livereload_dummy'] } })
  }

  process.on('SIGINT', cleanupAndExit)
  process.on('SIGTERM', cleanupAndExit)

  server.watcher.on('change', function() {
    printSlowNodes(builder.outputNodeWrapper)
    console.log('Built - ' + Math.round(builder.outputNodeWrapper.buildState.totalTime) + ' ms @ ' + new Date().toString())
    liveReload()
  })

  server.watcher.on('error', function(err) {
    console.log('Built with error:')
    console.log(err.message)
    if (!err.broccoliPayload || !err.broccoliPayload.location.file) {
      console.log('')
      console.log(err.stack)
    }
    console.log('')
    liveReload()
  })

  server.http.listen(parseInt(options.port, 10), options.host)
  lrServer.listen(options.liveReloadPort, function(err) {
      if (err) {
        console.log('Failed to start the live reload server', err)
      } else {
        console.log('Live reload server started on', options.liveReloadPort)
      }
  });
  return server
}
<|endoftext|>


<commit_before>/**
 *
 */

var ModalView = function (options) {
    this.width = (options.width !== undefined) ? options.width : $(window).width() / 2;
    this.height = (options.height !== undefined) ? options.height : $(window).height() / 2;
    this.title = (options.title !== undefined) ? options.title : "Default";
    this.scrollable = (options.scrollable !== undefined) ? options.scrollable : true;
    var close_button_url = "images/icons/navigation/close_black.png",
        $container, $body;
    $("#main").append('

');
    $("#popup-container").width(this.width).height(this.height).css("overflow", this.scrollable);
    $container = $("#popup-container");
    $container.append('

');
    $("#popup-container-head").append("" + this.title + "");
    $("#popup-container-head").append('');
    $container.append('

');
    $body = $("#popup-container-body");

    this.display = function () {
        centerize();
        $container.show("slide", {direction: "right"}, 500);
    };
    this.dispose = function () {
        console.log("Here");
        $("#main").remove("#popup-container");
    }
    this.append = function ($element) {
        $body.append($element);
        centerize();
    }

    function centerize() {
        centerElement($(window), $container);
    }

    $(".popup-window-close-button").click(function () {
        console.log("here");
        var id = $(this).attr("id");
        var parent = $("#" + id + "-mini-map");
        $("#popup-container").remove();
//      closeButtonWasClicked(parent);
//
//      function closeButtonWasClicked(svg_parent_container) {
//        svg_parent_container.hide();
//        closeAllRemovableDisplays();
//      }
        global.sm.consumeEvent("goto-mainevent");
    });
};

var PrintView = function () {
    var options = {
            width: SCREEN.width / 1.1,
            height: SCREEN.height,
            title: "Results"
        },
        modal = new ModalView(options);
    modal.append('

Nitrate Watershed Percent Contribution

Gross Erosion

Phosphorus Index Risk Assessment

');
    modal.append('

Stats

');
    modal.append('

');
    modal.display();

    var scale = 2,
        opts = {
            scale: scale,
            width: scale * 3 * 23 * 2,
            height: scale * 2 * 36
        },
        landcover = d3.select("#percent-landcover")
                        .append("div")
                        .attr("min-width", "400px")
            .text("Landuse Outputs"),
        outputmap = new OutputMap(opts);
    outputmap.draw();

    var head = landcover.append("div")
        .attr("class", "row")
        .style("min-width", "600px")
        .style("height", "30px");
    head.append("div")
        .style("width", "100px")
        .style("float", "left")
        .style("height", "100%");
    head.append("div")
        .style("min-width", "9em")
        .text("Year 1")
        .style("float", "left");
    head.append("div")
        .style("min-width", "9em")
        .text("Year 2")
        .style("float", "left");
    head.append("div")
        .style("min-width", "9em")
        .text("Year 3")
        .style("float", "left");

    for (var i = 0; i < landCoverArea.length; i++) {
        console.log(i);
        var a = 100 * (landCoverArea[i] / area);

        var row = landcover.append("div")
            .attr("class", "row")
            .style("min-width", "600px")
            .style("height", "30px");
        row.append("div")
            .attr("class", "landcover-facts-header")
            .text(function () {
                return landcovers[i + 1];
            })
            .style("font-size", ".8em")
            .style("float", "left")
            .style("width", "100px");
        for(var j=1; j < 4; j++) {
            if(global.data[j] === 0) break;
            var cell = row.append("div");
            cell.append("div")
                .attr("id", "year-" + j + "percent-landcover-value")
                .text(function () {
                    var b = Math.round(a);
                    if (b > 0) {
                        return b + "%";
                    } else {
                        return b;
                    }
                })
                .style("float", "left")
                .style("min-width", "3em");
            cell.append("div")
                .attr("id", "year-" + j + "acres-landcover-value")
                .text(function () {
                    if (global.landuse[j][i] > 0) {
                        return global.landuse[j][i];// + " acres";
                    } else {
                        return global.landuse[j][i];
                    }
                })
                .style("float", "left")
                .style("min-width", "3em");
            cell.append("div")
                .attr("id", "year-" + j + "hectares-landcover-value")
                .text(function () {
                    var h = Math.round(0.404686 * global.landuse[j][i]);
                    if (h > 0) {
                        return h;// + " hectares";
                    } else {
                        return h;
                    }
                })
                .style("float", "left")
                .style("min-width", "3em");
            //$("#percent-landcover #" + i).text(Math.round(a));
            //$("#acres #" + i).text(landCoverArea[i]);
        }
    }

    var stats = d3.select("#stats")
        .append("div")
        .attr("class", "row")
        .style("width", "400px");

    stats.append("div")
        .attr("class", "row")
        .attr("width", "300px")
        .attr("height", "30px")
        .text("Strategic Wetland Placement: " + global.strategicWetland.actual + " out of " + global.strategicWetland.possible + " locations.");

    stats.append("div")
        .attr("class", "row")
        .attr("width", "300px")
        .attr("height", "30px")
        .text("Percent of stream buffered: " + global.streamNetwork + "%");

    var precip = d3.select("#precipitation-placeholder")
        .append("div")
        .style("width", "400px")
        .attr("class", "precip-table")
        .text("Precipitation Values");

    for (var i = 0; i < 4; i++) {
        var row = precip.append("div")
            .attr("class", "row")
            .style("width", "400px")
            .style("height", "30px"),
            precip_inches = global.precipitation[i],
            precip_cm = precip_inches * 2.54;

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text("Year " + i);

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return precip_inches.toFixed(1) + " in";
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return precip_cm.toFixed(1) + " cm";
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return getPrecipitationValuation(global.precipitation[i]);
            });
    }

    var landuse = d3.select("#landuse-outputs")
        .append("div")
        .style("width", "455px")
        .text("Index Values");

    var r = landuse.append("div")
        .attr("class", "row")
        .style("width", "450px")
        .style("height", "30px");

    r.append("div")
        .attr("class", "col")
        .style("width", "150px")
        .style("height", "30px")
        .style("float", "left")
        .style("font-size", ".8em")
        .text();

    r.append("div")
        .attr("class", "col")
        .style("width", "100px")
        .style("float", "left")
        .text("Year 1");

    r.append("div")
        .attr("class", "col")
        .style("width", "100px")
        .style("float", "left")
        .text("Year 2");

    r.append("div")
        .attr("class", "col")
        .style("width", "100px")
        .style("float", "left")
        .text("Year 3");

    for (var i = 0; i < 14; i++) {
        var row = landuse.append("div")
            .attr("class", "row")
            .style("width", "450px")
            .style("height", "30px");

//        row.append("div")
//            .attr("class", "col")
//            .style("width", "150px")
//            .style("float", "left")
//            .style("font-size", ".8em")
//            .text(function() {
//                return 0;
//            });

        row.append("div")
            .attr("class", "col")
            .style("width", "150px")
            .style("float", "left")
            .style("font-size", ".8em")
            .text(function () {
                return dataset[i].Metric;
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return Math.round(dataset[i].Year1);
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return Math.round(dataset[i].Year2);
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return Math.round(dataset[i].Year3);
            });
    }
}<commit_msg>Changed window show event effect<commit_after>/**
 *
 */

var ModalView = function (options) {
    this.width = (options.width !== undefined) ? options.width : $(window).width() / 2;
    this.height = (options.height !== undefined) ? options.height : $(window).height() / 2;
    this.title = (options.title !== undefined) ? options.title : "Default";
    this.scrollable = (options.scrollable !== undefined) ? options.scrollable : true;
    var close_button_url = "images/icons/navigation/close_black.png",
        $container, $body;
    $("#main").append('

');
    $("#popup-container").width(this.width).height(this.height).css("overflow", this.scrollable);
    $container = $("#popup-container");
    $container.append('

');
    $("#popup-container-head").append("" + this.title + "");
    $("#popup-container-head").append('');
    $container.append('

');
    $body = $("#popup-container-body");

    this.display = function () {
        centerize();
//        $container.show("slide", {direction: "right"}, 500);
        $container.fadeIn();
    };
    this.dispose = function () {
        $("#main").remove("#popup-container");
    }
    this.append = function ($element) {
        $body.append($element);
        centerize();
    }

    function centerize() {
        centerElement($(window), $container);
    }

    $(".popup-window-close-button").click(function () {
        var id = $(this).attr("id");
        var parent = $("#" + id + "-mini-map");
        $("#popup-container").remove();
//      closeButtonWasClicked(parent);
//
//      function closeButtonWasClicked(svg_parent_container) {
//        svg_parent_container.hide();
//        closeAllRemovableDisplays();
//      }
        global.sm.consumeEvent("goto-mainevent");
    });
};

var PrintView = function () {
    var options = {
            width: SCREEN.width / 1.1,
            height: SCREEN.height,
            title: "Results"
        },
        modal = new ModalView(options);
    modal.append('

Nitrate Watershed Percent Contribution

Gross Erosion

Phosphorus Index Risk Assessment

');
    modal.append('

Stats

');
    modal.append('

');
    modal.display();

    var scale = 2,
        opts = {
            scale: scale,
            width: scale * 3 * 23 * 2,
            height: scale * 2 * 36
        },
        landcover = d3.select("#percent-landcover")
                        .append("div")
                        .attr("min-width", "400px")
            .text("Landuse Outputs"),
        outputmap = new OutputMap(opts);
    outputmap.draw();

    var head = landcover.append("div")
        .attr("class", "row")
        .style("min-width", "600px")
        .style("height", "30px");
    head.append("div")
        .style("width", "100px")
        .style("float", "left")
        .style("height", "100%");
    head.append("div")
        .style("min-width", "9em")
        .text("Year 1")
        .style("float", "left");
    head.append("div")
        .style("min-width", "9em")
        .text("Year 2")
        .style("float", "left");
    head.append("div")
        .style("min-width", "9em")
        .text("Year 3")
        .style("float", "left");

    for (var i = 0; i < landCoverArea.length; i++) {
        console.log(i);
        var a = 100 * (landCoverArea[i] / area);

        var row = landcover.append("div")
            .attr("class", "row")
            .style("min-width", "600px")
            .style("height", "30px");
        row.append("div")
            .attr("class", "landcover-facts-header")
            .text(function () {
                return landcovers[i + 1];
            })
            .style("font-size", ".8em")
            .style("float", "left")
            .style("width", "100px");
        for(var j=1; j < 4; j++) {
            if(global.data[j] === 0) break;
            var cell = row.append("div");
            cell.append("div")
                .attr("id", "year-" + j + "percent-landcover-value")
                .text(function () {
                    var b = Math.round(a);
                    if (b > 0) {
                        return b + "%";
                    } else {
                        return b;
                    }
                })
                .style("float", "left")
                .style("min-width", "3em");
            cell.append("div")
                .attr("id", "year-" + j + "acres-landcover-value")
                .text(function () {
                    if (global.landuse[j][i] > 0) {
                        return global.landuse[j][i];// + " acres";
                    } else {
                        return global.landuse[j][i];
                    }
                })
                .style("float", "left")
                .style("min-width", "3em");
            cell.append("div")
                .attr("id", "year-" + j + "hectares-landcover-value")
                .text(function () {
                    var h = Math.round(0.404686 * global.landuse[j][i]);
                    if (h > 0) {
                        return h;// + " hectares";
                    } else {
                        return h;
                    }
                })
                .style("float", "left")
                .style("min-width", "3em");
            //$("#percent-landcover #" + i).text(Math.round(a));
            //$("#acres #" + i).text(landCoverArea[i]);
        }
    }

    var stats = d3.select("#stats")
        .append("div")
        .attr("class", "row")
        .style("width", "400px");

    stats.append("div")
        .attr("class", "row")
        .attr("width", "300px")
        .attr("height", "30px")
        .text("Strategic Wetland Placement: " + global.strategicWetland.actual + " out of " + global.strategicWetland.possible + " locations.");

    stats.append("div")
        .attr("class", "row")
        .attr("width", "300px")
        .attr("height", "30px")
        .text("Percent of stream buffered: " + global.streamNetwork + "%");

    var precip = d3.select("#precipitation-placeholder")
        .append("div")
        .style("width", "400px")
        .attr("class", "precip-table")
        .text("Precipitation Values");

    for (var i = 0; i < 4; i++) {
        var row = precip.append("div")
            .attr("class", "row")
            .style("width", "400px")
            .style("height", "30px"),
            precip_inches = global.precipitation[i],
            precip_cm = precip_inches * 2.54;

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text("Year " + i);

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return precip_inches.toFixed(1) + " in";
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return precip_cm.toFixed(1) + " cm";
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return getPrecipitationValuation(global.precipitation[i]);
            });
    }

    var landuse = d3.select("#landuse-outputs")
        .append("div")
        .style("width", "455px")
        .text("Index Values");

    var r = landuse.append("div")
        .attr("class", "row")
        .style("width", "450px")
        .style("height", "30px");

    r.append("div")
        .attr("class", "col")
        .style("width", "150px")
        .style("height", "30px")
        .style("float", "left")
        .style("font-size", ".8em")
        .text();

    r.append("div")
        .attr("class", "col")
        .style("width", "100px")
        .style("float", "left")
        .text("Year 1");

    r.append("div")
        .attr("class", "col")
        .style("width", "100px")
        .style("float", "left")
        .text("Year 2");

    r.append("div")
        .attr("class", "col")
        .style("width", "100px")
        .style("float", "left")
        .text("Year 3");

    for (var i = 0; i < 14; i++) {
        var row = landuse.append("div")
            .attr("class", "row")
            .style("width", "450px")
            .style("height", "30px");

//        row.append("div")
//            .attr("class", "col")
//            .style("width", "150px")
//            .style("float", "left")
//            .style("font-size", ".8em")
//            .text(function() {
//                return 0;
//            });

        row.append("div")
            .attr("class", "col")
            .style("width", "150px")
            .style("float", "left")
            .style("font-size", ".8em")
            .text(function () {
                return dataset[i].Metric;
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return Math.round(dataset[i].Year1);
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return Math.round(dataset[i].Year2);
            });

        row.append("div")
            .attr("class", "col")
            .style("width", "100px")
            .style("float", "left")
            .text(function () {
                return Math.round(dataset[i].Year3);
            });
    }
}<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var express = require('express')
  , http = require('http')
  , config = require('./lib/config')
  , expressServer
  , app = require('./app')
  , Job = require('./lib/job')
  , routes = require('./lib/routes')
  , middlewares = require('./lib/middlewares')
  , customUtils = require('./lib/customUtils')
  , h4e = require('h4e');

expressServer = express();

if (config.trustProxy) {
  expressServer.enable('trust proxy');
}

//Set up templating
h4e.setup({ app: expressServer
          , baseDir: config.templatesDir
          , toCompileDirs: ['.']
          , extension: 'mustache'
          });

/**
 * Middlewares
 *
 */

expressServer.use(express.bodyParser());
expressServer.use(expressServer.router);

// Serving static files from paths that can't be confused with the webpages
expressServer.get('/assets/css/:file', express.static(__dirname));
expressServer.get('/assets/jquery/:file', express.static(__dirname));
expressServer.get('/assets/socket.io/:file', express.static(__dirname));
expressServer.get('/assets/bootstrap/:dir/:file', express.static(__dirname));
expressServer.get('/favicon.ico', function (req, res, next) { return res.send(404); });   // No favicon

// Serve the webpages
expressServer.get('/', middlewares.commonRenderValues, routes.index);

// Create, edit or show a job
expressServer.get('/jobs/new', middlewares.commonRenderValues, routes.createJob.displayForm);
expressServer.post('/jobs/new', middlewares.commonRenderValues, routes.createJob.create, routes.createJob.displayForm);
expressServer.get('/jobs/:name/edit', middlewares.commonRenderValues, routes.createJob.populateFormForEdition, routes.createJob.displayForm);
expressServer.get('/jobs/:name', middlewares.commonRenderValues, routes.jobHomepage);

// Create or show a build
expressServer.get('/jobs/:name/builds/new', middlewares.commonRenderValues, routes.newBuild.webpage);
expressServer.get('/jobs/:name/builds/launch', routes.newBuild.launchBuild);   // API route to actually launch the build. Called by the above route.
expressServer.get('/jobs/:name/builds/:buildNumber', middlewares.commonRenderValues, routes.buildRecap);

// Handle payload delivered by Github
expressServer.post('/githubwebhook', routes.handleGithubWebhook);

/*
 * Connect to database, then start server
 */
expressServer.launchServer = function (cb) {
  var callback = cb ? cb : function () {}
    , self = this
    ;

  app.init(function (err) {
    if (err) { return callback(err); }

    self.apiServer = http.createServer(self);   // Let's not call it 'server' we never know if Express will want to use this variable!

    // Handle any connection error gracefully
    self.apiServer.on('error', function () {
      return callback("An error occured while launching the server, probably a server is already running on the same port!");
    });

    // Begin to listen. If the callback gets called, it means the server was successfully launched
    self.apiServer.listen.apply(self.apiServer, [config.svPort, callback]);
  });
};

/*
 * Stop the server
 * No new connections will be accepted but existing ones will be served before closing
 */
expressServer.stopServer = function (cb) {
  var callback = cb ? cb : function () {}
    , self = this;

  self.apiServer.close(function () {
    console.log('Server was stopped');
    callback();
  });
};

/*
 * If we executed this module directly, launch the server.
 * If not, let the module which required server.js launch it.
 */
if (module.parent === null) {
  expressServer.launchServer(function (err) {
    if (err) {
      console.log("An error occured, logging error and stopping the server");
      console.log(err);
      process.exit(1);
    } else {
      console.log('Workspace found. Server started on port ' + config.svPort);
    }
  });
}

<commit_msg>Put github webhook in the public<commit_after>/**
 * Module dependencies.
 */

var express = require('express')
  , http = require('http')
  , config = require('./lib/config')
  , expressServer
  , app = require('./app')
  , Job = require('./lib/job')
  , routes = require('./lib/routes')
  , middlewares = require('./lib/middlewares')
  , customUtils = require('./lib/customUtils')
  , h4e = require('h4e');

expressServer = express();

if (config.trustProxy) {
  expressServer.enable('trust proxy');
}

//Set up templating
h4e.setup({ app: expressServer
          , baseDir: config.templatesDir
          , toCompileDirs: ['.']
          , extension: 'mustache'
          });

/**
 * Middlewares
 *
 */

expressServer.use(express.bodyParser());
expressServer.use(expressServer.router);

// Serving static files from paths that can't be confused with the webpages
expressServer.get('/assets/css/:file', express.static(__dirname));
expressServer.get('/assets/jquery/:file', express.static(__dirname));
expressServer.get('/assets/socket.io/:file', express.static(__dirname));
expressServer.get('/assets/bootstrap/:dir/:file', express.static(__dirname));
expressServer.get('/favicon.ico', function (req, res, next) { return res.send(404); });   // No favicon

// Serve the webpages
expressServer.get('/', middlewares.commonRenderValues, routes.index);

// Create, edit or show a job
expressServer.get('/jobs/new', middlewares.commonRenderValues, routes.createJob.displayForm);
expressServer.post('/jobs/new', middlewares.commonRenderValues, routes.createJob.create, routes.createJob.displayForm);
expressServer.get('/jobs/:name/edit', middlewares.commonRenderValues, routes.createJob.populateFormForEdition, routes.createJob.displayForm);
expressServer.get('/jobs/:name', middlewares.commonRenderValues, routes.jobHomepage);

// Create or show a build
expressServer.get('/jobs/:name/builds/new', middlewares.commonRenderValues, routes.newBuild.webpage);
expressServer.get('/jobs/:name/builds/launch', routes.newBuild.launchBuild);   // API route to actually launch the build. Called by the above route.
expressServer.get('/jobs/:name/builds/:buildNumber', middlewares.commonRenderValues, routes.buildRecap);

// Handle payload delivered by Github
expressServer.post('/public/githubwebhook', routes.handleGithubWebhook);

/*
 * Connect to database, then start server
 */
expressServer.launchServer = function (cb) {
  var callback = cb ? cb : function () {}
    , self = this
    ;

  app.init(function (err) {
    if (err) { return callback(err); }

    self.apiServer = http.createServer(self);   // Let's not call it 'server' we never know if Express will want to use this variable!

    // Handle any connection error gracefully
    self.apiServer.on('error', function () {
      return callback("An error occured while launching the server, probably a server is already running on the same port!");
    });

    // Begin to listen. If the callback gets called, it means the server was successfully launched
    self.apiServer.listen.apply(self.apiServer, [config.svPort, callback]);
  });
};

/*
 * Stop the server
 * No new connections will be accepted but existing ones will be served before closing
 */
expressServer.stopServer = function (cb) {
  var callback = cb ? cb : function () {}
    , self = this;

  self.apiServer.close(function () {
    console.log('Server was stopped');
    callback();
  });
};

/*
 * If we executed this module directly, launch the server.
 * If not, let the module which required server.js launch it.
 */
if (module.parent === null) {
  expressServer.launchServer(function (err) {
    if (err) {
      console.log("An error occured, logging error and stopping the server");
      console.log(err);
      process.exit(1);
    } else {
      console.log('Workspace found. Server started on port ' + config.svPort);
    }
  });
}

<|endoftext|>


<commit_before>'use strict';

/**
 * nodecached server: main.
 * (C) 2013 Alex Fernández.
 */

// requires
const Log = require('log');
const net = require('net');
const Parser = require('./parser.js').Parser;
const testing = require('testing');

// constants
const DEFAULT_PORT = 11211;
const LOG_LEVELS = ['notice', 'info', 'debug'];
const ERROR_BUFFER = Buffer.from('ERROR\r\n');

function create() {
	return new Server()
}

/**
 */
class Server
{
	constructor() {
		this.log = new Log('info');
		this.server = null;
	}

	start(options, callback)
	{
		const port = options.port || DEFAULT_PORT;
		for (const i in LOG_LEVELS)
		{
			const level = LOG_LEVELS[i];
			if (options[level])
			{
				this.log = new Log(level);
			}
		}
		this.server = net.createServer(socket => {
			new Connection(options, this.log).init(socket);
		});
		this.server.on('error', error => {
			const message = 'Could not start server on port ' + port + ': ' + error;
			if (callback)
			{
				return callback(message);
			}
			this.log.error(message);
		});
		this.server.listen(port, () => {
			if (callback)
			{
				return callback(null, this);
			}
			this.log.notice('Started server on port %s', port);
		});
		return this
	}

	stop(callback)
	{
		this.server.close(callback);
	}
}

/**
 * A connection to the server.
 */
class Connection
{
	constructor(options, log) {
		this.options = options
		this.log = log
		this.parser = new Parser(options);
	}

	init(socket)
	{
		this.socket = socket;
		this.log.info('Client connected to server');
		if (!this.options.delay)
		{
			socket.setNoDelay();
		}
		socket.on('end', () => {
			this.log.info('Client disconnected from server');
		});
		socket.on('error', error => {
			this.log.info('Socket error: %s', error);
			socket.end();
		});
		socket.on('data', data => this.readData(data));
	}

	readData(data)
	{
		if (data[0] == 4)
		{
			// EOT (control-D)
			return this.socket.end();
		}
		if (this.options.fast)
		{
			return this.socket.write(ERROR_BUFFER);
		}
		const {line, rest} = this.parseLine(data)
		const result = this.processCommand(line, rest)
		if (!result) {
			return
		}
		if (result == 'quit')
		{
			this.log.info('Quitting');
			return this.socket.end();
		}
		this.socket.write(result + '\r\n');
	}
	/*
	 * Parse a line. Equivalent to:
	 * const message = data.toString();
	 * const line = message.substringUpTo('\r\n');
	 * const rest = message.substringFrom('\r\n');
	 */
	parseLine(data) {
		for (let i = 0; i < data.length; i++)
		{
			if (data[i] == 13 && data[i + 1] == 10)
			{
				return {
					line: data.toString('utf8', 0, i),
					rest: data.toString('utf8', i + 2),
				}
			}
		}
		return {line: data.toString('utf8')}
	}
	processCommand(line, rest) {
		const result = this.parser.readLine(line);
		if (result) {
			if (rest) {
				this.log.error('Unexpected result %s, ignoring', result);
			}
			return result
		}
		return this.parser.readLine(rest);
	}
}

/**
 * Test that the server starts and stops.
 */
function testStart(callback)
{
	const options = {
		port: 11234,
	};
	const server = start(options, function(error)
	{
		testing.check(error, 'Could not start server');
		server.stop(callback);
	});
}

/**
 * Run all tests.
 */
function test(callback)
{
	testing.run([testStart], callback);
}

module.exports = {create, test}

// run tests if invoked directly
if (__filename == process.argv[1])
{
	if (process.argv.length == 3)
	{
		new exports.Server().start({
			port: parseInt(process.argv[2], 10),
		});
	}
	module.exports.test(testing.show);
}

<commit_msg>Use promises for server.start() and stop().<commit_after>'use strict';

/**
 * nodecached server: main.
 * (C) 2013 Alex Fernández.
 */

// requires
const Log = require('log');
const net = require('net');
const Parser = require('./parser.js').Parser;
const testing = require('testing');

// constants
const DEFAULT_PORT = 11211;
const LOG_LEVELS = ['notice', 'info', 'debug'];
const ERROR_BUFFER = Buffer.from('ERROR\r\n');

function create() {
	return new Server()
}

/**
 */
class Server
{
	constructor() {
		this.log = new Log('info');
		this.server = null;
	}

	/*
	 * Start the server. Options:
	 *	- port: to listen on.
	 *	- fast: return 'ERROR' on every query.
	 *	- notice: show notice messages.
	 *	- info: show info messages.
	 *	- debug: show debug messages.
	 * An optional callback will be called after the server has started.
	 */
	start(options, callback)
	{
		const port = options.port || DEFAULT_PORT;
		return this.startPromise(port, options).then(() => {
			if (callback) return callback()
			this.log.notice('Started server on port %s', port);
		}).catch(error => {
			const message = 'Could not start server on port ' + port + ': ' + error;
			if (callback) return callback(message)
			this.log.error(message);
		})
	}

	startPromise(port, options) {
		return new Promise((resolve, reject) => {
			for (const i in LOG_LEVELS)
			{
				const level = LOG_LEVELS[i];
				if (options[level])
				{
					this.log = new Log(level);
				}
			}
			this.server = net.createServer(socket => {
				new Connection(options, this.log).init(socket);
			});
			this.server.on('error', reject)
			this.server.listen(port, resolve)
		})
	}

	stop(callback)
	{
		const cb = () => 0
		this.stopPromise().then(callback || cb).catch(callback || cb)
	}

	stopPromise() {
		return new Promise((resolve, reject) => {
			this.server.close(error => {
				if (error) return reject(error)
				return resolve()
			});
		})
	}
}

/**
 * A connection to the server.
 */
class Connection
{
	constructor(options, log) {
		this.options = options
		this.log = log
		this.parser = new Parser(options);
	}

	init(socket)
	{
		this.socket = socket;
		this.log.info('Client connected to server');
		if (!this.options.delay)
		{
			socket.setNoDelay();
		}
		socket.on('end', () => {
			this.log.info('Client disconnected from server');
		});
		socket.on('error', error => {
			this.log.info('Socket error: %s', error);
			socket.end();
		});
		socket.on('data', data => this.readData(data));
	}

	readData(data)
	{
		if (data[0] == 4)
		{
			// EOT (control-D)
			return this.socket.end();
		}
		if (this.options.fast)
		{
			return this.socket.write(ERROR_BUFFER);
		}
		const {line, rest} = this.parseLine(data)
		const result = this.processCommand(line, rest)
		if (!result) {
			return
		}
		if (result == 'quit')
		{
			this.log.info('Quitting');
			return this.socket.end();
		}
		this.socket.write(result + '\r\n');
	}
	/*
	 * Parse a line. Equivalent to:
	 * const message = data.toString();
	 * const line = message.substringUpTo('\r\n');
	 * const rest = message.substringFrom('\r\n');
	 */
	parseLine(data) {
		for (let i = 0; i < data.length; i++)
		{
			if (data[i] == 13 && data[i + 1] == 10)
			{
				return {
					line: data.toString('utf8', 0, i),
					rest: data.toString('utf8', i + 2),
				}
			}
		}
		return {line: data.toString('utf8')}
	}
	processCommand(line, rest) {
		const result = this.parser.readLine(line);
		if (result) {
			if (rest) {
				this.log.error('Unexpected result %s, ignoring', result);
			}
			return result
		}
		return this.parser.readLine(rest);
	}
}

async function testStart() {
	const server = create()
	await server.start({port: 11234})
	console.log('holi')
	await server.stop();
}

/**
 * Run all tests.
 */
function test(callback)
{
	testing.run([testStart], callback);
}

module.exports = {create, test}

// run tests if invoked directly
if (__filename == process.argv[1])
{
	if (process.argv.length == 3)
	{
		new exports.Server().start({
			port: parseInt(process.argv[2], 10),
		});
	}
	module.exports.test(testing.show);
}

<|endoftext|>


<commit_before> 'use strict';
  var _ = require('lodash');
  moj.Modules.FormErrors = {
    init: function() {
      _.bindAll(this, 'postToFormErrors', 'onAjaxSuccess', 'onAjaxError');
      this.bindEvents();
      this.loadTemplates();
    },

    bindEvents: function() {
      $('form')
        .on('submit', this.postToFormErrors)
        // Focus back on summary if field-error is focused and escape key is pressed
        .on('keyup', function(e) {
          var $target = $(e.target);
          if(e.keyCode === 27 && ($target.is('.govuk-form-group--error') || $target.parent().is('.govuk-form-group--error'))) {
            $target.closest('form').find('> .alert').focus();
          }
        })
        .on('blur', '.form-group', function(e) {
          $(e.target).removeAttr('tabindex');
        });

      $('[type=submit]').on('click', function(e) {
        var $target = $(e.target);
        $target.closest('form').attr('submit-name', $target.attr('name'));
      });
    },

    postToFormErrors: function(e) {
      this.$form = $(e.target);

      // Return if button has a name, which is attached as form attribute on click
      // (assuming secondary buttons)
      if(this.$form.attr('submit-name') ||
         this.$form.attr('method') && this.$form.attr('method').toLowerCase() === 'get') {
        return;
      }

      if (this.$form.length) {
        e.preventDefault();
        e.stopPropagation();
        $.ajax({
          type: 'POST',
          url: this.$form.attr('action'),
          contentType: 'application/x-www-form-urlencoded',
          data: this.$form.serialize()
        })
        .done(this.onAjaxSuccess)
        .fail(this.onAjaxError);
      }
    },

    onAjaxSuccess: function(data) {
      if (data.redirect) {
        window.location.href = data.redirect;
      }
      if (data.field_errors) {
        this.loadErrors(data.field_errors);
        var errorBanner = $('.govuk-error-summary:visible:first');

        if(!errorBanner.length) {
          return;
        }

        $('html, body').animate({
          scrollTop: errorBanner.offset().top - 20
        }, 300, function() {
          errorBanner.attr({'tabindex': -1}).focus();
        });
      }
      if (data.non_field_errors.length) {
        $('#non-field-error-ajax .alert-message').text(data.non_field_errors[0]);
        $('#non-field-error-ajax').show();
      }
      else {
        $('#non-field-error-ajax').hide();
      }
    },

    onAjaxError: function() {
      this.$form.off('submit');
      this.$form.submit();
    },

    formatErrors: function(errors) {
      var errorFields = {};

      (function fieldName (errorsObj, prefix) {
        prefix = (typeof prefix === 'undefined') ? '' : prefix + '-';
        for (var key in errorsObj) {
          var field = prefix + key;
          if ($.isArray(errorsObj[key])) {
            errorFields[field] = errorsObj[key];
          } else {
            fieldName(errorsObj[key], field);
          }
        }
      })(errors);

      return errorFields;
    },

    createErrorSummary: function(unattachedErrors) {
      var errorSummary = [];

      // Loop through errors on the page to retain the fields order
      $('.govuk-form-group--error, .govuk-form-group--error>fieldset').map(function() {
        var $this = $(this);

        if(!this.id || $this.hasClass('s-hidden') || $this.parent().hasClass('s-hidden')) {
          return;
        }
        var name = this.id.replace(/^field-/, '');

        var labelField = $this.find('#field-label-' + name);

        var errorText = $this.find('#error-' + name + " .cla-error-message").text();

        $this.find(' .govuk-input')
          .not('.govuk-form-group--error .govuk-radios__conditional .govuk-input')
          .addClass("govuk-input--error");
        $this.find(' .govuk-select')
          .not('.govuk-form-group--error .govuk-radios__conditional .govuk-select')
          .addClass("govuk-select--error");

        if (labelField.parents(".cla-currency-by-frequency").length) {
          labelField = labelField.parents(".cla-currency-by-frequency").children("legend");

          $this.find(' .govuk-input').filter(function () {
            return ($(this).val() && Number($(this).val()) > 0)
          })
          .removeClass("govuk-input--error");

          $this.find(' .govuk-select').filter(function () {
            return ($(this).val())
          })
          .removeClass("govuk-select--error")

          $this.find('.laa-currency .govuk-input.govuk-input--error').siblings(".laa-currency-prefix")
            .addClass("laa-currency-prefix--error");
        }

        if (errorText) {
          var labelText = errorText;
        } else {
          var labelText = labelField.text().replace(/if yes, /i,"").replace(/os ydych, /i,"").replace(/os oes, /i,"").trim();
          //above lines are stripping the "if yes" (and Welsh variants) from the error summary.

          labelText = labelText.charAt(0).toUpperCase() + labelText.substr(1);
          //Ensures the first letter is uppercase.
        }

        errorSummary.push({
          label: labelText,
          name: name,
          errors: $this.find('> .govuk-error-message > .cla-error-message').map(function() {
            return $(this).text();
          })
        });
      });

      _.each(unattachedErrors, function(error) {
        errorSummary.push({
          errors: [error]
        });
      });

      return errorSummary;
    },

    loadErrors: function(errors) {
      var errorFields = this.formatErrors(errors);
      var self = this;
      var unattachedErrors = [];

      this.clearErrors();

      function insertError($afterElement, errors, fieldName) {
        $afterElement.after(self.fieldError({
          errors: errors,
          fieldName: fieldName
        }));
      }

      function addSimpleErrors(errors, fieldName) {
        if(!errors.length) {
          return;
        }

        $('#field-' + fieldName)
          .attr({
            'aria-invalid': true,
            'aria-describedby': 'error-' + fieldName
          })
          .closest('.govuk-form-group').addClass('govuk-form-group--error');

        var label = $('#field-label-' + fieldName);

        if (label.parents(".cla-currency-by-frequency").length) {
          label = label.parents(".cla-currency-by-frequency").children("legend");
        }

        if(!label.length) {
          unattachedErrors = _.extend(unattachedErrors, errors);
        } else if(label.parent().children('.govuk-hint').length) {
          insertError(label.parent().children('.govuk-hint'), errors, fieldName);
        } else if(label.is('legend')) {
          insertError(label, errors, fieldName);
        } else {
          insertError(label.closest('.govuk-label'), errors, fieldName);
        }
      }

      function addSubformErrors(errors, fieldName) {
        if(!errors.length) {
          return;
        }
        _.each(errors, function(subformErrors) {
          addErrors(subformErrors[1], fieldName + '-' + subformErrors[0]);
        });
      }

      function addRepeatedFieldErrors(errors, fieldName) {
        if(!errors.length) {
          return;
        }
        // Multiple forms (e.g. properties)
        _.each(errors, function(errors) {
          _.each(errors._errors, function(subformErrors, subformFieldName) {
            addErrors(subformErrors, fieldName + '-' + errors._index + '-' + subformFieldName);
          });
        });
      }

      function addErrors(errors, fieldName) {
        addSimpleErrors(_.filter(errors, _.isString), fieldName);
        addSubformErrors(_.filter(errors, _.isArray), fieldName);
        addRepeatedFieldErrors(_.filter(errors, function(error) {
          return _.isObject(error) && !_.isArray(error);
        }), fieldName);
      }

      _.each(errorFields, addErrors);

      if(this.$form.data('error-banner') !== false) {
        this.$form.closest('main').prepend(this.mainFormError({ errors: this.createErrorSummary(unattachedErrors)}));
        if (GOVUK.getCookie("locale") == "cy_GB") {
          $("title").prepend("Gwall: ");
        } else {
          $("title").prepend("Error: ");
        }
      }

      // Report to GA about form errors
      var errorFieldNames = _.keys(errorFields);
      if(!window.ga) {
        return;
      }
      window.ga('send', 'event', 'form-errors',
        window.location.pathname,
        errorFieldNames.join('|'),
        errorFieldNames.length
      );
    },

    loadTemplates: function() {
      this.mainFormError = _.template($('#mainFormError').html());
      this.fieldError = _.template($('#fieldError').html());
    },

    clearErrors: function() {
      $("title").text(
        $("title").text()
          .replace("Error: ", "")
          .replace("Gwall: ", "")
      );
      $('.govuk-error-message').remove();
      $('form>.alert.alert-error').remove();
      $('.govuk-error-summary').remove();
      $('.form-error')
        .removeClass('form-error')
        .removeAttr('aria-invalid');
      $('.govuk-form-group--error')
        .removeClass('govuk-form-group--error')
        .removeAttr('aria-invalid');
      $(".govuk-input--error")
        .removeClass("govuk-input--error");
      $(".govuk-select--error")
        .removeClass("govuk-select--error");
      $(".laa-currency-prefix--error")
        .removeClass("laa-currency-prefix--error");
    }
  };
<commit_msg>defunct form-error class removed from JS<commit_after> 'use strict';
  var _ = require('lodash');
  moj.Modules.FormErrors = {
    init: function() {
      _.bindAll(this, 'postToFormErrors', 'onAjaxSuccess', 'onAjaxError');
      this.bindEvents();
      this.loadTemplates();
    },

    bindEvents: function() {
      $('form')
        .on('submit', this.postToFormErrors)
        // Focus back on summary if field-error is focused and escape key is pressed
        .on('blur', '.form-group', function(e) {
          $(e.target).removeAttr('tabindex');
        });

      $('[type=submit]').on('click', function(e) {
        var $target = $(e.target);
        $target.closest('form').attr('submit-name', $target.attr('name'));
      });
    },

    postToFormErrors: function(e) {
      this.$form = $(e.target);

      // Return if button has a name, which is attached as form attribute on click
      // (assuming secondary buttons)
      if(this.$form.attr('submit-name') ||
         this.$form.attr('method') && this.$form.attr('method').toLowerCase() === 'get') {
        return;
      }

      if (this.$form.length) {
        e.preventDefault();
        e.stopPropagation();
        $.ajax({
          type: 'POST',
          url: this.$form.attr('action'),
          contentType: 'application/x-www-form-urlencoded',
          data: this.$form.serialize()
        })
        .done(this.onAjaxSuccess)
        .fail(this.onAjaxError);
      }
    },

    onAjaxSuccess: function(data) {
      if (data.redirect) {
        window.location.href = data.redirect;
      }
      if (data.field_errors) {
        this.loadErrors(data.field_errors);
        var errorBanner = $('.govuk-error-summary:visible:first');

        if(!errorBanner.length) {
          return;
        }

        $('html, body').animate({
          scrollTop: errorBanner.offset().top - 20
        }, 300, function() {
          errorBanner.attr({'tabindex': -1}).focus();
        });
      }
      if (data.non_field_errors.length) {
        $('#non-field-error-ajax .alert-message').text(data.non_field_errors[0]);
        $('#non-field-error-ajax').show();
      }
      else {
        $('#non-field-error-ajax').hide();
      }
    },

    onAjaxError: function() {
      this.$form.off('submit');
      this.$form.submit();
    },

    formatErrors: function(errors) {
      var errorFields = {};

      (function fieldName (errorsObj, prefix) {
        prefix = (typeof prefix === 'undefined') ? '' : prefix + '-';
        for (var key in errorsObj) {
          var field = prefix + key;
          if ($.isArray(errorsObj[key])) {
            errorFields[field] = errorsObj[key];
          } else {
            fieldName(errorsObj[key], field);
          }
        }
      })(errors);

      return errorFields;
    },

    createErrorSummary: function(unattachedErrors) {
      var errorSummary = [];

      // Loop through errors on the page to retain the fields order
      $('.govuk-form-group--error, .govuk-form-group--error>fieldset').map(function() {
        var $this = $(this);

        if(!this.id || $this.hasClass('s-hidden') || $this.parent().hasClass('s-hidden')) {
          return;
        }
        var name = this.id.replace(/^field-/, '');

        var labelField = $this.find('#field-label-' + name);

        var errorText = $this.find('#error-' + name + " .cla-error-message").text();

        $this.find(' .govuk-input')
          .not('.govuk-form-group--error .govuk-radios__conditional .govuk-input')
          .addClass("govuk-input--error");
        $this.find(' .govuk-select')
          .not('.govuk-form-group--error .govuk-radios__conditional .govuk-select')
          .addClass("govuk-select--error");

        if (labelField.parents(".cla-currency-by-frequency").length) {
          labelField = labelField.parents(".cla-currency-by-frequency").children("legend");

          $this.find(' .govuk-input').filter(function () {
            return ($(this).val() && Number($(this).val()) > 0)
          })
          .removeClass("govuk-input--error");

          $this.find(' .govuk-select').filter(function () {
            return ($(this).val())
          })
          .removeClass("govuk-select--error")

          $this.find('.laa-currency .govuk-input.govuk-input--error').siblings(".laa-currency-prefix")
            .addClass("laa-currency-prefix--error");
        }

        if (errorText) {
          var labelText = errorText;
        } else {
          var labelText = labelField.text().replace(/if yes, /i,"").replace(/os ydych, /i,"").replace(/os oes, /i,"").trim();
          //above lines are stripping the "if yes" (and Welsh variants) from the error summary.

          labelText = labelText.charAt(0).toUpperCase() + labelText.substr(1);
          //Ensures the first letter is uppercase.
        }

        errorSummary.push({
          label: labelText,
          name: name,
          errors: $this.find('> .govuk-error-message > .cla-error-message').map(function() {
            return $(this).text();
          })
        });
      });

      _.each(unattachedErrors, function(error) {
        errorSummary.push({
          errors: [error]
        });
      });

      return errorSummary;
    },

    loadErrors: function(errors) {
      var errorFields = this.formatErrors(errors);
      var self = this;
      var unattachedErrors = [];

      this.clearErrors();

      function insertError($afterElement, errors, fieldName) {
        $afterElement.after(self.fieldError({
          errors: errors,
          fieldName: fieldName
        }));
      }

      function addSimpleErrors(errors, fieldName) {
        if(!errors.length) {
          return;
        }

        $('#field-' + fieldName)
          .attr({
            'aria-invalid': true,
            'aria-describedby': 'error-' + fieldName
          })
          .closest('.govuk-form-group').addClass('govuk-form-group--error');

        var label = $('#field-label-' + fieldName);

        if (label.parents(".cla-currency-by-frequency").length) {
          label = label.parents(".cla-currency-by-frequency").children("legend");
        }

        if(!label.length) {
          unattachedErrors = _.extend(unattachedErrors, errors);
        } else if(label.parent().children('.govuk-hint').length) {
          insertError(label.parent().children('.govuk-hint'), errors, fieldName);
        } else if(label.is('legend')) {
          insertError(label, errors, fieldName);
        } else {
          insertError(label.closest('.govuk-label'), errors, fieldName);
        }
      }

      function addSubformErrors(errors, fieldName) {
        if(!errors.length) {
          return;
        }
        _.each(errors, function(subformErrors) {
          addErrors(subformErrors[1], fieldName + '-' + subformErrors[0]);
        });
      }

      function addRepeatedFieldErrors(errors, fieldName) {
        if(!errors.length) {
          return;
        }
        // Multiple forms (e.g. properties)
        _.each(errors, function(errors) {
          _.each(errors._errors, function(subformErrors, subformFieldName) {
            addErrors(subformErrors, fieldName + '-' + errors._index + '-' + subformFieldName);
          });
        });
      }

      function addErrors(errors, fieldName) {
        addSimpleErrors(_.filter(errors, _.isString), fieldName);
        addSubformErrors(_.filter(errors, _.isArray), fieldName);
        addRepeatedFieldErrors(_.filter(errors, function(error) {
          return _.isObject(error) && !_.isArray(error);
        }), fieldName);
      }

      _.each(errorFields, addErrors);

      if(this.$form.data('error-banner') !== false) {
        this.$form.closest('main').prepend(this.mainFormError({ errors: this.createErrorSummary(unattachedErrors)}));
        if (GOVUK.getCookie("locale") == "cy_GB") {
          $("title").prepend("Gwall: ");
        } else {
          $("title").prepend("Error: ");
        }
      }

      // Report to GA about form errors
      var errorFieldNames = _.keys(errorFields);
      if(!window.ga) {
        return;
      }
      window.ga('send', 'event', 'form-errors',
        window.location.pathname,
        errorFieldNames.join('|'),
        errorFieldNames.length
      );
    },

    loadTemplates: function() {
      this.mainFormError = _.template($('#mainFormError').html());
      this.fieldError = _.template($('#fieldError').html());
    },

    clearErrors: function() {
      $("title").text(
        $("title").text()
          .replace("Error: ", "")
          .replace("Gwall: ", "")
      );
      $('.govuk-error-message').remove();
      $('.govuk-error-summary').remove();
      $('.govuk-form-group--error')
        .removeClass('govuk-form-group--error')
        .removeAttr('aria-invalid');
      $(".govuk-input--error")
        .removeClass("govuk-input--error");
      $(".govuk-select--error")
        .removeClass("govuk-select--error");
      $(".laa-currency-prefix--error")
        .removeClass("laa-currency-prefix--error");
    }
  };
<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};

var server = http.createServer(function(request, response) {
  var filePath = false;

  if (request.url == '/') {
    filePath = 'public/index.html';
  } else {
    filePath = 'public' + request.url;
  }

  var absPath = './' + filePath;
  serveStatic(response, cache, absPath);
});

function send404(response) {
  response.writeHead(404, {'Content-Type': 'text/plain'});
  response.write('Error 404: resource not found.');
  response.end();
}

function sendFile(response, filePath, fileContents) {
  response.writeHead(
    200,
    {'Content-Type': mime.lookup(path.basename(filePath))}
  );
  response.end(fileContents);
}

function serveStatic(response, cache, absPath) {
  if (cache[absPath]) {
    sendFile(response, absPath, cache[absPath]);
  } else {
    fs.exists(absPath, function(exists) {
      if (exists) {
        fs.readFile(absPath, function(err, data) {
          if (err) {
            send404(response);
          } else {
            cache[absPath] = data;
            sendFile(response, absPath, data);
          }
        });
      } else {
        send404(response);
      }
    });
  }
}<commit_msg>Start http server<commit_after>var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};

var server = http.createServer(function(request, response) {
  var filePath = false;

  if (request.url == '/') {
    filePath = 'public/index.html';
  } else {
    filePath = 'public' + request.url;
  }

  var absPath = './' + filePath;
  serveStatic(response, cache, absPath);
});

server.listen(3000, function() {
  console.log('Server listening on port 3000.');
});

function send404(response) {
  response.writeHead(404, {'Content-Type': 'text/plain'});
  response.write('Error 404: resource not found.');
  response.end();
}

function sendFile(response, filePath, fileContents) {
  response.writeHead(
    200,
    {'Content-Type': mime.lookup(path.basename(filePath))}
  );
  response.end(fileContents);
}

function serveStatic(response, cache, absPath) {
  if (cache[absPath]) {
    sendFile(response, absPath, cache[absPath]);
  } else {
    fs.exists(absPath, function(exists) {
      if (exists) {
        fs.readFile(absPath, function(err, data) {
          if (err) {
            send404(response);
          } else {
            cache[absPath] = data;
            sendFile(response, absPath, data);
          }
        });
      } else {
        send404(response);
      }
    });
  }
}<|endoftext|>


<commit_before>
// include gulp
var gulp = require('gulp');

// include plug-ins
var uglify = require('gulp-uglify');
var usemin = require('gulp-usemin');
var replace = require('gulp-replace');
var wrap = require('gulp-wrap');
var gzip = require('gulp-gzip');
var concat = require('gulp-concat');
var watch = require('gulp-watch');

gulp.task('gzipFile', function(){
  //gulp.src('demo/hombre/anim2/data.json')
  gulp.src('demo/ninja/anim/data.js')
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('demo/'));
});

gulp.task('buildParser', function() {
    gulp.src([
            'parser/polyfills.js',
            'parser/global.js',
            'parser/AssetsManager.js',
            'parser/AsyncManager.js',
            'parser/DOMAnimationManager.js',
            'parser/EffectsParser.js',
            'parser/EffectsStrokeParser.js',
            'parser/extras.js',
            'parser/RQManager.js',
            'parser/LayerConverter.js',
            'parser/ShapesParser.js',
            'parser/CompConverter.js',
            'parser/UI.js'
        ])
        .pipe(concat('bodymovin_parser.jsx', {newLine: '\r\n'}))
        .pipe(wrap('var Gtlym = {};var bodymovinWindow = this;\r\n(function(){\r\n<%= contents %>\r\n}());'))
        .pipe(gulp.dest('build/parser/'))
});

gulp.task('joinModules', function() {
    gulp.src([
            'parser/polyfills.js',
            'parser/global.js',
            'parser/AssetsManager.js',
            'parser/AsyncManager.js',
            'parser/DOMAnimationManager.js',
            'parser/EffectsParser.js',
            'parser/EffectsStrokeParser.js',
            'parser/extras.js',
            'parser/RQManager.js',
            'parser/LayerConverter.js',
            'parser/ShapesParser.js',
            'parser/CompConverter.js',
            'parser/UI.js'
        ])
        .pipe(concat('bodymovin_parser.jsx', {newLine: '\r\n'}))
        .pipe(wrap('var Gtlym = {};var bodymovinWindow = this;\r\n(function(){\r\n<%= contents %>\r\n}());'))
        .pipe(gulp.dest('/Program Files/Adobe/Adobe After Effects CS6/Support Files/Scripts/ScriptUI Panels'))
});

  gulp.task('watch', function () {
    gulp.watch('./parser/*.js',['joinModules']);
});

gulp.task('buildPlayer', function(){
    gulp.src('./player/index.html')
        .pipe(usemin({
            js: [uglify()]
        }))
        //.pipe(wrap('(function(window){"use strict";<%= contents %>}(window));'))
        .pipe(wrap('(function(window){<%= contents %>}(window));'))
        .pipe(gulp.dest('build/player/v2/'));
});

gulp.task('buildGreensock', function(){
    gulp.src('./player/greensock.html')
        .pipe(usemin({
            js: [uglify()]
        }))
        .pipe(wrap('(function(window){"use strict";<%= contents %>}(window));'))
        .pipe(gulp.dest('build/player/greensock'));
});

gulp.task('buildCanvasPlayer', function(){
    gulp.src([
            'player/js/main.js',
            'player/js/3rd_party/transformation-matrix.js',
            'player/js/utils/MatrixManager.js',
            'player/js/utils/animationFramePolyFill.js',
            'player/js/utils/common.js',
            'player/js/utils/canvasPolyFill.js',
            'player/js/utils/functionExtensions.js',
            'player/js/utils/bez.js',
            'player/js/utils/DataManager.js',
            'player/js/renderers/CanvasRenderer.js',
            'player/js/mask.js',
            'player/js/elements/canvasElements/CVBaseElement.js',
            'player/js/elements/canvasElements/CVCompElement.js',
            'player/js/elements/canvasElements/CVImageElement.js',
            'player/js/elements/canvasElements/CVShapeElement.js',
            'player/js/elements/canvasElements/CVShapeItemElement.js',
            'player/js/elements/canvasElements/CVSolidElement.js',
            'player/js/elements/canvasElements/CVTextElement.js',
            'player/js/elements/canvasElements/CVMaskElement.js',
            'player/js/animation/AnimationManager.js',
            'player/js/animation/AnimationItem.js',
            'player/js/module.js'
        ])
        .pipe(concat('canvasPlayer.js', {newLine: '\r\n'}))
        .pipe(uglify())
        .pipe(wrap('(function(window){"use strict";<%= contents %>}(window));'))
        .pipe(gulp.dest('build/player/'));
});

gulp.task('gzipPlayer', function(){
    gulp.src('./player/index.html')
        .pipe(usemin({
            js: [uglify()]
        }))
        .pipe(wrap('(function(window){"use strict";<%= contents %>}(window));'))
        .pipe(gzip({ append: true }))
        .pipe(gulp.dest('build/'));
});

gulp.task('concatPlayer', function() {
    gulp.src([
            'player/js/main.js',
            'player/js/3rd_party/transformation-matrix.js',
            'player/js/3rd_party/canvasPoly.js',
            'player/js/utils/MatrixManager.js',
            'player/js/utils/animationFramePolyFill.js',
            'player/js/utils/common.js',
            'player/js/utils/canvasPolyFill.js',
            'player/js/utils/functionExtensions.js',
            'player/js/utils/bez.js',
            'player/js/utils/DataManager.js',
            'player/js/renderers/SVGRenderer.js',
            'player/js/renderers/CanvasRenderer.js',
            'player/js/mask.js',
            'player/js/elements/BaseElement.js',
            'player/js/elements/CompElement.js',
            'player/js/elements/ImageElement.js',
            'player/js/elements/ShapeElement.js',
            'player/js/elements/ShapeItemElement.js',
            'player/js/elements/SolidElement.js',
            'player/js/elements/TextElement.js',
            'player/js/elements/canvasElements/CVBaseElement.js',
            'player/js/elements/canvasElements/CVCompElement.js',
            'player/js/elements/canvasElements/CVImageElement.js',
            'player/js/elements/canvasElements/CVShapeElement.js',
            'player/js/elements/canvasElements/CVShapeItemElement.js',
            'player/js/elements/canvasElements/CVSolidElement.js',
            'player/js/elements/canvasElements/CVTextElement.js',
            'player/js/elements/canvasElements/CVMaskElement.js',
            'player/js/animation/AnimationManager.js',
            'player/js/animation/AnimationItem.js',
            'player/js/module.js'
        ])
        .pipe(concat('concat.js', {newLine: '\r\n'}))
        .pipe(wrap('\r\n(function(){\r\n\'use strict\';\r\n<%= contents %>\r\n}());'))
        .pipe(gulp.dest('build/player/'))
});<commit_msg>major update v2.0<commit_after>
// include gulp
var gulp = require('gulp');

// include plug-ins
var uglify = require('gulp-uglify');
var usemin = require('gulp-usemin');
var replace = require('gulp-replace');
var wrap = require('gulp-wrap');
var gzip = require('gulp-gzip');
var concat = require('gulp-concat');
var watch = require('gulp-watch');

gulp.task('gzipFile', function(){
  gulp.src('demo/miked/anim/data.js')
  //gulp.src('build/player/bodymovin.js')
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('demo/'));
});

gulp.task('buildParser', function() {
    gulp.src([
            'parser/polyfills.js',
            'parser/global.js',
            'parser/AssetsManager.js',
            'parser/AsyncManager.js',
            'parser/DOMAnimationManager.js',
            'parser/EffectsParser.js',
            'parser/EffectsStrokeParser.js',
            'parser/extras.js',
            'parser/RQManager.js',
            'parser/LayerConverter.js',
            'parser/ShapesParser.js',
            'parser/CompConverter.js',
            'parser/UI.js'
        ])
        .pipe(concat('bodymovin_parser.jsx', {newLine: '\r\n'}))
        .pipe(wrap('var Gtlym = {};var bodymovinWindow = this;\r\n(function(){\r\n<%= contents %>\r\n}());'))
        .pipe(gulp.dest('build/parser/'))
});

gulp.task('joinModules', function() {
    gulp.src([
            'parser/polyfills.js',
            'parser/global.js',
            'parser/AssetsManager.js',
            'parser/AsyncManager.js',
            'parser/DOMAnimationManager.js',
            'parser/EffectsParser.js',
            'parser/EffectsStrokeParser.js',
            'parser/extras.js',
            'parser/RQManager.js',
            'parser/LayerConverter.js',
            'parser/ShapesParser.js',
            'parser/CompConverter.js',
            'parser/UI.js'
        ])
        .pipe(concat('bodymovin_parser.jsx', {newLine: '\r\n'}))
        .pipe(wrap('var Gtlym = {};var bodymovinWindow = this;\r\n(function(){\r\n<%= contents %>\r\n}());'))
        .pipe(gulp.dest('/Program Files/Adobe/Adobe After Effects CS6/Support Files/Scripts/ScriptUI Panels'))
});

  gulp.task('watch', function () {
    gulp.watch('./parser/*.js',['joinModules']);
});

gulp.task('buildPlayer', function(){
    gulp.src('./player/index.html')
        .pipe(usemin({
            js: [uglify()]
        }))
        //.pipe(wrap('(function(window){"use strict";<%= contents %>}(window));'))
        .pipe(wrap('(function(window){<%= contents %>}(window));'))
        .pipe(gulp.dest('build/player/v2/'));
});

gulp.task('buildGreensock', function(){
    gulp.src('./player/greensock.html')
        .pipe(usemin({
            js: [uglify()]
        }))
        .pipe(wrap('(function(window){"use strict";<%= contents %>}(window));'))
        .pipe(gulp.dest('build/player/greensock'));
});

gulp.task('buildCanvasPlayer', function(){
    gulp.src([
            'player/js/main.js',
            'player/js/3rd_party/transformation-matrix.js',
            'player/js/utils/MatrixManager.js',
            'player/js/utils/animationFramePolyFill.js',
            'player/js/utils/common.js',
            'player/js/utils/canvasPolyFill.js',
            'player/js/utils/functionExtensions.js',
            'player/js/utils/bez.js',
            'player/js/utils/DataManager.js',
            'player/js/renderers/CanvasRenderer.js',
            'player/js/mask.js',
            'player/js/elements/canvasElements/CVBaseElement.js',
            'player/js/elements/canvasElements/CVCompElement.js',
            'player/js/elements/canvasElements/CVImageElement.js',
            'player/js/elements/canvasElements/CVShapeElement.js',
            'player/js/elements/canvasElements/CVShapeItemElement.js',
            'player/js/elements/canvasElements/CVSolidElement.js',
            'player/js/elements/canvasElements/CVTextElement.js',
            'player/js/elements/canvasElements/CVMaskElement.js',
            'player/js/animation/AnimationManager.js',
            'player/js/animation/AnimationItem.js',
            'player/js/module.js'
        ])
        .pipe(concat('canvasPlayer.js', {newLine: '\r\n'}))
        .pipe(uglify())
        .pipe(wrap('(function(window){"use strict";<%= contents %>}(window));'))
        .pipe(gulp.dest('build/player/'));
});

gulp.task('gzipPlayer', function(){
    gulp.src('./player/index.html')
        .pipe(usemin({
            js: [uglify()]
        }))
        .pipe(wrap('(function(window){"use strict";<%= contents %>}(window));'))
        .pipe(gzip({ append: true }))
        .pipe(gulp.dest('build/'));
});

gulp.task('concatPlayer', function() {
    gulp.src([
            'player/js/main.js',
            'player/js/3rd_party/transformation-matrix.js',
            'player/js/3rd_party/canvasPoly.js',
            'player/js/utils/MatrixManager.js',
            'player/js/utils/animationFramePolyFill.js',
            'player/js/utils/common.js',
            'player/js/utils/canvasPolyFill.js',
            'player/js/utils/functionExtensions.js',
            'player/js/utils/bez.js',
            'player/js/utils/DataManager.js',
            'player/js/renderers/SVGRenderer.js',
            'player/js/renderers/CanvasRenderer.js',
            'player/js/mask.js',
            'player/js/elements/BaseElement.js',
            'player/js/elements/CompElement.js',
            'player/js/elements/ImageElement.js',
            'player/js/elements/ShapeElement.js',
            'player/js/elements/ShapeItemElement.js',
            'player/js/elements/SolidElement.js',
            'player/js/elements/TextElement.js',
            'player/js/elements/canvasElements/CVBaseElement.js',
            'player/js/elements/canvasElements/CVCompElement.js',
            'player/js/elements/canvasElements/CVImageElement.js',
            'player/js/elements/canvasElements/CVShapeElement.js',
            'player/js/elements/canvasElements/CVShapeItemElement.js',
            'player/js/elements/canvasElements/CVSolidElement.js',
            'player/js/elements/canvasElements/CVTextElement.js',
            'player/js/elements/canvasElements/CVMaskElement.js',
            'player/js/animation/AnimationManager.js',
            'player/js/animation/AnimationItem.js',
            'player/js/module.js'
        ])
        .pipe(concat('concat.js', {newLine: '\r\n'}))
        .pipe(wrap('\r\n(function(){\r\n\'use strict\';\r\n<%= contents %>\r\n}());'))
        .pipe(gulp.dest('build/player/'))
});<|endoftext|>