<commit_before>var fs = require('fs');
var jsonlint = require('jsonlint');
var http = require('http');

var validate = {};

var Ajv = require('ajv');

function loadSchema(json, file) {
	var versions = { "3.0":true,"3.1":true,"3.2":true,"3.3":true,"3.4":true, "4.0":true }
	var version = json.X3D["@version"];
	if (!versions[version]) {
		console.error("Can only validate version 3.0-4.0 presently. Switching version to 3.3.");
		version = "3.3";
	}
        if (typeof validate[version] === 'undefined') {
		var schema = fs.readFileSync(__dirname+"/x3d-"+version+"-JSONSchema.json").toString();
		var ajv = new Ajv({ allErrors:true});
		ajv.addFormat("uri", /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i);

		http.get('http://json-schema.org/draft-04/schema', (res) => {
		  const { statusCode } = res;
		  const contentType = res.headers['content-type'];

		  var error;
		  if (statusCode !== 200) {
		    error = new Error(`Request Failed.\n` +
				      `Status Code: ${statusCode}`);
		  } else if (!/^application\/octet-stream/.test(contentType)) {
		    error = new Error(`Invalid content-type.\n` +
				      `Expected application/json but received ${contentType}`);
		  }
		  if (error) {
		    console.error(error.message);
		    // consume response data to free up memory
		    res.resume();
		    return;
		  }

		  res.setEncoding('utf8');
		  var rawData = '';
		  res.on('data', (chunk) => { rawData += chunk; });
		  res.on('end', () => {
		    try {
		      console.log("MetaSchema received");
		      var metaschemajson = jsonlint.parse(rawData);
		      ajv.addMetaSchema(metaschemajson);
		      console.log("MetaSchema added");
		      var schemajson = jsonlint.parse(schema);
		      console.log("Schema", version, "parsed");
		      ajv.addSchema(schemajson);
		      console.log("Schema", version, "added");
		      validate[version] = ajv.compile(schemajson);
		      if (typeof validate[version] !== 'undefined') {
			      console.log("Schema compiled");
		      } else {
			      console.log("Schema not compiled");
		      }
		      doValidate(json, file);
		    } catch (e) {
		      console.error(e.message);
		    }
		  });
		}).on('error', (e) => {
		  console.error(`Got error: ${e.message}`);
		});
	}
}

function doValidate(json, file) {
	var version = json.X3D["@version"];
	if (typeof validate[version] !== 'undefined') {
		var valid = validate[version](json);
		if (!valid) {
			var errs = validate[version].errors;
			var error = ""
			for (var e in errs) {
				error += "\r\n dataPath: " + errs[e].dataPath + "\r\n";
				error += " message: " + errs[e].message + "\r\n";
				error += " params: " + JSON.stringify(errs[e].params) + "\r\n";
				error += " file: " + file + "\r\n";
			}
			if (error !== "") {
				console.error(error);
			}
		}
	}
}

function validateJSON(files) {

	for (var f in files) {
		var file = files[f];
		try {
			var str = fs.readFileSync(file).toString();
			if (typeof str === 'undefined') {
				throw("Read nothing, or possbile error");
			}
			var json = jsonlint.parse(str);
			var version = json.X3D["@version"];
			if (!validate[version]) {
				loadSchema(json, file);  // loads schema.
			} else {
				doValidate(json, file);
			}

		} catch (e) {
			console.error("Error reading", file, e);
		}
	}
}

module.exports = validateJSON
<commit_msg>added keyword<commit_after>var fs = require('fs');
var jsonlint = require('jsonlint');
var http = require('http');

var validate = {};

var Ajv = require('ajv');

function loadSchema(json, file) {
	var versions = { "3.0":true,"3.1":true,"3.2":true,"3.3":true,"3.4":true, "4.0":true }
	var version = json.X3D["@version"];
	if (!versions[version]) {
		console.error("Can only validate version 3.0-4.0 presently. Switching version to 3.3.");
		version = "3.3";
	}
        if (typeof validate[version] === 'undefined') {
		var schema = fs.readFileSync(__dirname+"/x3d-"+version+"-JSONSchema.json").toString();
		var ajv = new Ajv({ allErrors:true});
		ajv.addFormat("uri", /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i);

		http.get('http://json-schema.org/draft-04/schema', (res) => {
		  const { statusCode } = res;
		  const contentType = res.headers['content-type'];

		  var error;
		  if (statusCode !== 200) {
		    error = new Error(`Request Failed.\n` +
				      `Status Code: ${statusCode}`);
		  } else if (!/^application\/octet-stream/.test(contentType)) {
		    error = new Error(`Invalid content-type.\n` +
				      `Expected application/json but received ${contentType}`);
		  }
		  if (error) {
		    console.error(error.message);
		    // consume response data to free up memory
		    res.resume();
		    return;
		  }

		  res.setEncoding('utf8');
		  var rawData = '';
		  res.on('data', (chunk) => { rawData += chunk; });
		  res.on('end', () => {
		    try {
		      console.log("MetaSchema received");
		      var metaschemajson = jsonlint.parse(rawData);
		      ajv.addMetaSchema(metaschemajson);
		      console.log("MetaSchema added");
		      var schemajson = jsonlint.parse(schema);
		      console.log("Schema", version, "parsed");
		      ajv.addSchema(schemajson);
		      console.log("Schema", version, "added");
		      validate[version] = ajv.compile(schemajson);
		      if (typeof validate[version] !== 'undefined') {
			      console.log("Schema compiled");
		      } else {
			      console.log("Schema not compiled");
		      }
		      doValidate(json, file);
		    } catch (e) {
		      console.error(e.message);
		    }
		  });
		}).on('error', (e) => {
		  console.error(`Got error: ${e.message}`);
		});
	}
}

function doValidate(json, file) {
	var version = json.X3D["@version"];
	if (typeof validate[version] !== 'undefined') {
		var valid = validate[version](json);
		if (!valid) {
			var errs = validate[version].errors;
			var error = ""
			error += " errs: " + JSON.stringify(errs, null, 2) + "\r\n";
			for (var e in errs) {
				error += "\r\n keyword: " + errs[e].keyword + "\r\n";
				error += " dataPath: " + errs[e].dataPath + "\r\n";
				error += " message: " + errs[e].message + "\r\n";
				error += " params: " + JSON.stringify(errs[e].params) + "\r\n";
				error += " file: " + file + "\r\n";
			}
			if (error !== "") {
				console.error(error);
			}
		}
	}
}

function validateJSON(files) {

	for (var f in files) {
		var file = files[f];
		try {
			var str = fs.readFileSync(file).toString();
			if (typeof str === 'undefined') {
				throw("Read nothing, or possbile error");
			}
			var json = jsonlint.parse(str);
			var version = json.X3D["@version"];
			if (!validate[version]) {
				loadSchema(json, file);  // loads schema.
			} else {
				doValidate(json, file);
			}

		} catch (e) {
			console.error("Error reading", file, e);
		}
	}
}

module.exports = validateJSON
<|endoftext|>


<commit_before>const URL = require('url');
const ghGot = require('gh-got');
const delay = require('delay');
const parseLinkHeader = require('parse-link-header');
const endpoints = require('../../util/endpoints');

let cache = {};
let stats = {};

async function get(path, options, retries = 5) {
  const { host } = URL.parse(path);
  const opts = {
    ...endpoints.find({ platform: 'github', host }),
    ...options,
  };
  const method = opts.method || 'get';
  const useCache = opts.useCache || true;
  if (method === 'get' && useCache && cache[path]) {
    logger.trace({ path }, 'Returning cached result');
    return cache[path];
  }
  logger.trace(`${method.toUpperCase()} ${path}`);
  stats.requests = (stats.requests || []).concat([
    method.toUpperCase() + ' ' + path.replace(opts.endpoint, ''),
  ]);
  try {
    if (global.appMode) {
      const appAccept = 'application/vnd.github.machine-man-preview+json';
      opts.headers = Object.assign(
        {},
        {
          accept: appAccept,
          'user-agent':
            process.env.RENOVATE_USER_AGENT ||
            'https://github.com/renovatebot/renovate',
        },
        opts.headers
      );
      if (opts.headers.accept !== appAccept) {
        opts.headers.accept = `${appAccept}, ${opts.headers.accept}`;
      }
    }
    const res = await ghGot(path, opts);
    if (res && res.headers) {
      stats.rateLimit = res.headers['x-ratelimit-limit'];
      stats.rateLimitRemaining = res.headers['x-ratelimit-remaining'];
    }
    if (opts.paginate) {
      // Check if result is paginated
      const pageLimit = opts.pageLimit || 10;
      const linkHeader = parseLinkHeader(res.headers.link);
      if (linkHeader && linkHeader.next && linkHeader.last) {
        let lastPage = +linkHeader.last.page;
        if (!process.env.RENOVATE_PAGINATE_ALL) {
          lastPage = Math.min(pageLimit, lastPage);
        }
        const pageNumbers = Array.from(
          new Array(lastPage),
          (x, i) => i + 1
        ).slice(1);
        const pages = await Promise.all(
          pageNumbers.map(page => {
            const url = URL.parse(linkHeader.next.url, true);
            delete url.search;
            url.query.page = page;
            return get(URL.format(url), { ...opts, paginate: false }, retries);
          })
        );
        res.body = res.body.concat(
          ...pages.filter(Boolean).map(page => page.body)
        );
      }
    }
    if (
      method === 'get' &&
      (path.startsWith('repos/') ||
        path.startsWith('https://api.github.com/repos/'))
    ) {
      cache[path] = res;
    }
    // istanbul ignore if
    if (method === 'POST' && path === 'graphql') {
      if (res.errors && retries > 0) {
        logger.info('Retrying graphql query');
        return get(path, opts, 0);
      }
      if (res.data && retries === 0) {
        logger.info('Recovered graphql query');
      }
    }
    return res;
  } catch (err) {
    if (
      err.name === 'RequestError' &&
      (err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT')
    ) {
      throw new Error('platform-failure');
    }
    if (err.statusCode >= 500 && err.statusCode < 600) {
      if (retries > 0) {
        logger.info(
          { statusCode: err.statusCode, message: err.message },
          `Retrying request`
        );

        await delay(5000 / retries);

        return get(path, opts, retries - 1);
      }
      throw new Error('platform-failure');
    }
    if (
      retries > 0 &&
      err.statusCode === 403 &&
      err.message &&
      err.message.startsWith('You have triggered an abuse detection mechanism')
    ) {
      logger.info(
        {
          headers: err.headers,
          path,
          statusCode: err.statusCode,
          message: err.message,
        },
        `Retrying request`
      );

      await delay(180000 / (retries * retries));

      return get(path, opts, retries - 1);
    }
    if (
      err.statusCode === 403 &&
      err.message &&
      err.message.includes('rate limit exceeded')
    ) {
      logger.info({ err, headers: err.headers }, 'Rate limit exceeded');
      throw new Error('rate-limit-exceeded');
    } else if (
      err.statusCode === 403 &&
      err.message &&
      err.message.includes('blobs up to 1 MB in size')
    ) {
      throw err;
    } else if (err.statusCode === 403) {
      if (retries > 0) {
        logger.info(
          { statusCode: err.statusCode, message: err.message },
          `Retrying request`
        );

        await delay(60000 / (retries * retries));

        return get(path, opts, retries - 1);
      }
    } else if (
      err.statusCode === 401 &&
      err.message &&
      err.message.includes('Bad credentials')
    ) {
      const rateLimit = err.headers ? err.headers['x-ratelimit-limit'] : -1;
      logger.info(
        {
          token: maskToken(opts.token),
          err,
        },
        'Bad credentials'
      );
      if (rateLimit === '60') {
        throw new Error('platform-failure');
      }
      throw new Error('bad-credentials');
    }
    throw err;
  }
}

// istanbul ignore next
function maskToken(token) {
  if (!token) {
    return token;
  }
  return `${token.substring(0, 2)}${new Array(token.length - 3).join(
    '*'
  )}${token.slice(-2)}`;
}

const helpers = ['get', 'post', 'put', 'patch', 'head', 'delete'];

for (const x of helpers) {
  get[x] = (url, opts) =>
    get(url, Object.assign({}, opts, { method: x.toUpperCase() }));
}

get.setAppMode = function setAppMode() {
  // no-op
};

get.reset = function reset() {
  cache = null;
  cache = {};
  // istanbul ignore if
  if (stats.requests && stats.requests.length > 1) {
    logger.info(
      {
        rateLimit: parseInt(stats.rateLimit, 10),
        requestCount: stats.requests.length,
        rateLimitRemaining: parseInt(stats.rateLimitRemaining, 10),
      },
      'Request stats'
    );
    stats.requests.sort();
    logger.debug({ requests: stats.requests }, 'All requests');
    stats = {};
  }
};

module.exports = get;
<commit_msg>fix(github): graphql parsing<commit_after>const URL = require('url');
const ghGot = require('gh-got');
const delay = require('delay');
const parseLinkHeader = require('parse-link-header');
const endpoints = require('../../util/endpoints');

let cache = {};
let stats = {};

async function get(path, options, retries = 5) {
  const { host } = URL.parse(path);
  const opts = {
    ...endpoints.find({ platform: 'github', host }),
    ...options,
  };
  const method = opts.method || 'get';
  const useCache = opts.useCache || true;
  if (method === 'get' && useCache && cache[path]) {
    logger.trace({ path }, 'Returning cached result');
    return cache[path];
  }
  logger.trace(`${method.toUpperCase()} ${path}`);
  stats.requests = (stats.requests || []).concat([
    method.toUpperCase() + ' ' + path.replace(opts.endpoint, ''),
  ]);
  try {
    if (global.appMode) {
      const appAccept = 'application/vnd.github.machine-man-preview+json';
      opts.headers = Object.assign(
        {},
        {
          accept: appAccept,
          'user-agent':
            process.env.RENOVATE_USER_AGENT ||
            'https://github.com/renovatebot/renovate',
        },
        opts.headers
      );
      if (opts.headers.accept !== appAccept) {
        opts.headers.accept = `${appAccept}, ${opts.headers.accept}`;
      }
    }
    const res = await ghGot(path, opts);
    if (res && res.headers) {
      stats.rateLimit = res.headers['x-ratelimit-limit'];
      stats.rateLimitRemaining = res.headers['x-ratelimit-remaining'];
    }
    if (opts.paginate) {
      // Check if result is paginated
      const pageLimit = opts.pageLimit || 10;
      const linkHeader = parseLinkHeader(res.headers.link);
      if (linkHeader && linkHeader.next && linkHeader.last) {
        let lastPage = +linkHeader.last.page;
        if (!process.env.RENOVATE_PAGINATE_ALL) {
          lastPage = Math.min(pageLimit, lastPage);
        }
        const pageNumbers = Array.from(
          new Array(lastPage),
          (x, i) => i + 1
        ).slice(1);
        const pages = await Promise.all(
          pageNumbers.map(page => {
            const url = URL.parse(linkHeader.next.url, true);
            delete url.search;
            url.query.page = page;
            return get(URL.format(url), { ...opts, paginate: false }, retries);
          })
        );
        res.body = res.body.concat(
          ...pages.filter(Boolean).map(page => page.body)
        );
      }
    }
    if (
      method === 'get' &&
      (path.startsWith('repos/') ||
        path.startsWith('https://api.github.com/repos/'))
    ) {
      cache[path] = res;
    }
    // istanbul ignore if
    if (method === 'POST' && path === 'graphql') {
      const goodResult = '{"data":{';
      if (res.body.startsWith(goodResult)) {
        if (retries === 0) {
          logger.info('Recovered graphql query');
        }
      } else if (retries > 0) {
        logger.info('Retrying graphql query');
        return get(path, opts, 0);
      }
    }
    return res;
  } catch (err) {
    if (
      err.name === 'RequestError' &&
      (err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT')
    ) {
      throw new Error('platform-failure');
    }
    if (err.statusCode >= 500 && err.statusCode < 600) {
      if (retries > 0) {
        logger.info(
          { statusCode: err.statusCode, message: err.message },
          `Retrying request`
        );

        await delay(5000 / retries);

        return get(path, opts, retries - 1);
      }
      throw new Error('platform-failure');
    }
    if (
      retries > 0 &&
      err.statusCode === 403 &&
      err.message &&
      err.message.startsWith('You have triggered an abuse detection mechanism')
    ) {
      logger.info(
        {
          headers: err.headers,
          path,
          statusCode: err.statusCode,
          message: err.message,
        },
        `Retrying request`
      );

      await delay(180000 / (retries * retries));

      return get(path, opts, retries - 1);
    }
    if (
      err.statusCode === 403 &&
      err.message &&
      err.message.includes('rate limit exceeded')
    ) {
      logger.info({ err, headers: err.headers }, 'Rate limit exceeded');
      throw new Error('rate-limit-exceeded');
    } else if (
      err.statusCode === 403 &&
      err.message &&
      err.message.includes('blobs up to 1 MB in size')
    ) {
      throw err;
    } else if (err.statusCode === 403) {
      if (retries > 0) {
        logger.info(
          { statusCode: err.statusCode, message: err.message },
          `Retrying request`
        );

        await delay(60000 / (retries * retries));

        return get(path, opts, retries - 1);
      }
    } else if (
      err.statusCode === 401 &&
      err.message &&
      err.message.includes('Bad credentials')
    ) {
      const rateLimit = err.headers ? err.headers['x-ratelimit-limit'] : -1;
      logger.info(
        {
          token: maskToken(opts.token),
          err,
        },
        'Bad credentials'
      );
      if (rateLimit === '60') {
        throw new Error('platform-failure');
      }
      throw new Error('bad-credentials');
    }
    throw err;
  }
}

// istanbul ignore next
function maskToken(token) {
  if (!token) {
    return token;
  }
  return `${token.substring(0, 2)}${new Array(token.length - 3).join(
    '*'
  )}${token.slice(-2)}`;
}

const helpers = ['get', 'post', 'put', 'patch', 'head', 'delete'];

for (const x of helpers) {
  get[x] = (url, opts) =>
    get(url, Object.assign({}, opts, { method: x.toUpperCase() }));
}

get.setAppMode = function setAppMode() {
  // no-op
};

get.reset = function reset() {
  cache = null;
  cache = {};
  // istanbul ignore if
  if (stats.requests && stats.requests.length > 1) {
    logger.info(
      {
        rateLimit: parseInt(stats.rateLimit, 10),
        requestCount: stats.requests.length,
        rateLimitRemaining: parseInt(stats.rateLimitRemaining, 10),
      },
      'Request stats'
    );
    stats.requests.sort();
    logger.debug({ requests: stats.requests }, 'All requests');
    stats = {};
  }
};

module.exports = get;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Icon } from 'react-fa';
import moment from 'moment';
import { FormattedMessage } from 'react-intl';

import styles from './style.pcss';

export default class WeekSelection extends Component {
  handlePrevClick = e => {
    const { onPrevWeek } = this.props;

    onPrevWeek();
  };

  handleNextClick = e => {
    const { onNextWeek } = this.props;

    onNextWeek();
  };

  render() {
    const { date } = this.props;

    return (

          <Icon name="arrow-left" />

          <FormattedMessage
            id="weekSelector_week"
            defaultMessage="Week {week}"
            values={{ week: date.format('WW-GGGG') }}
          />

          <Icon name="arrow-right" />

    );
  }
}
<commit_msg>Remove unused import<commit_after>import React, { Component } from 'react';
import { Icon } from 'react-fa';
import { FormattedMessage } from 'react-intl';

import styles from './style.pcss';

export default class WeekSelection extends Component {
  handlePrevClick = e => {
    const { onPrevWeek } = this.props;

    onPrevWeek();
  };

  handleNextClick = e => {
    const { onNextWeek } = this.props;

    onNextWeek();
  };

  render() {
    const { date } = this.props;

    return (

          <Icon name="arrow-left" />

          <FormattedMessage
            id="weekSelector_week"
            defaultMessage="Week {week}"
            values={{ week: date.format('WW-GGGG') }}
          />

          <Icon name="arrow-right" />

    );
  }
}
<|endoftext|>


<commit_before>/**
 * KegListItem.
 *
 * Summary view of a Keg & Beer.
 */

import React from 'react';
import classnames from 'classnames/bind';

import styles from '../taps/taps.css';

import * as propTypes from '../../proptypes';

import KegSummary from './keg-summary';
import BeerSummary from '../beers/beer-summary';

const classes = classnames.bind(styles);

const Keg = (props) => {
  const { Beer, Tap } = props;
  const onTapClass = Tap ? 'on-tap' : '';

  return (
    <div className={`keg ${classes(['keg', onTapClass])}`}>
      <BeerSummary {...Beer} />
      <KegSummary {...props} />

  );
};

Keg.propTypes = {
  Tap: propTypes.tapModel,
  Beer: propTypes.beerModel,
};

export default Keg;
<commit_msg>fix keglistitem classname (#45)<commit_after>/**
 * KegListItem.
 *
 * Summary view of a Keg & Beer.
 */

import React from 'react';
import classnames from 'classnames/bind';

import styles from '../taps/taps.css';

import * as propTypes from '../../proptypes';

import KegSummary from './keg-summary';
import BeerSummary from '../beers/beer-summary';

const classes = classnames.bind(styles);

const Keg = (props) => {
  const { Beer, Tap } = props;
  const onTapClass = Tap ? 'on-tap' : '';

  return (
    <div className={`keg-list-item ${classes(['keg', onTapClass])}`}>
      <BeerSummary {...Beer} />
      <KegSummary {...props} />

  );
};

Keg.propTypes = {
  Tap: propTypes.tapModel,
  Beer: propTypes.beerModel,
};

export default Keg;
<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const os = require('os');

module.exports = function () {
    app.listen(80, () => {
        console.log('Listening on port 80.');
    });

    app.use(express.static('dashboard'));

    app.get('/api/stats', async (req, res) => {
        res.send(JSON.stringify({
            guilds: this.guilds.size,
            channels: `${this.channels.filter(c => c.type === 'voice').size} voice, ${this.channels.filter(c => c.type === 'text').size} text (${this.channels.size} total)`,
            users: `${this.guilds.map(g => parseInt(g.memberCount)).reduce((a, b) => { return a + b; })} (${this.users.size} online)`,
            ram: `${(process.memoryUsage().rss / 1048576).toFixed()}MB/${(os.totalmem() > 1073741824 ? `${(os.totalmem() / 1073741824).toFixed(1)}GB` : `${(os.totalmem() / 1048576).toFixed()}MB`)}
            (${(process.memoryUsage().rss / os.totalmem() * 100).toFixed(2)}%), ${(os.freemem() > 1073741824 ? `${(os.freemem() / 1073741824).toFixed(1)}GB` : `${(os.freemem() / 1048576).toFixed()}MB`)} free on server`,
            cpu: `${await getCPUUsage()}% (1/5/15 minute average: ${os.loadavg().map(p => p + '%').join('/')})`}
        ));
    });

    app.get('/api/uptime', (req, res) => {
        res.send(process.uptime().toString());
    });
};

function getCPUUsage () {
    return new Promise(resolve => {
        const startMeasure = cpuAverage();
        setTimeout(() => {
            const endMeasure = cpuAverage();
            const idleDifference = endMeasure.idle - startMeasure.idle;
            const totalDifference = endMeasure.total - startMeasure.total;
            const percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);
            resolve(percentageCPU);
        }, 100);
    });
}

function cpuAverage () {
    let totalIdle = 0, totalTick = 0;
    const cpu = os.cpus()[0];
    for (const type in cpu.times) {
        totalTick += cpu.times[type];
    }
    totalIdle += cpu.times.idle;
    return { idle: totalIdle,  total: totalTick };
}
<commit_msg>Attempt at fixing CPU statistics<commit_after>const express = require('express');
const app = express();
const os = require('os');

module.exports = function () {
    app.listen(80, () => {
        console.log('Listening on port 80.');
    });

    app.use(express.static('dashboard'));

    app.get('/api/stats', async (req, res) => {
        res.send(JSON.stringify({
            guilds: this.guilds.size,
            channels: `${this.channels.filter(c => c.type === 'voice').size} voice, ${this.channels.filter(c => c.type === 'text').size} text (${this.channels.size} total)`,
            users: `${this.guilds.map(g => parseInt(g.memberCount)).reduce((a, b) => { return a + b; })} (${this.users.size} online)`,
            ram: `${(process.memoryUsage().rss / 1048576).toFixed()}MB/${(os.totalmem() > 1073741824 ? `${(os.totalmem() / 1073741824).toFixed(1)}GB` : `${(os.totalmem() / 1048576).toFixed()}MB`)}
            (${(process.memoryUsage().rss / os.totalmem() * 100).toFixed(2)}%), ${(os.freemem() > 1073741824 ? `${(os.freemem() / 1073741824).toFixed(1)}GB` : `${(os.freemem() / 1048576).toFixed()}MB`)} free on server`,
            cpu: `${await getCPUUsage()}% (1/5/15 minute average: ${os.loadavg().map(p => `${(p * 100).toFixed(2)}%`).join('/')})`}
        ));
    });

    app.get('/api/uptime', (req, res) => {
        res.send(process.uptime().toString());
    });
};

function getCPUUsage () {
    return new Promise(resolve => {
        const startMeasure = cpuAverage();
        setTimeout(() => {
            var endMeasure = cpuAverage();
            var idleDifference = endMeasure.idle - startMeasure.idle;
            var totalDifference = endMeasure.total - startMeasure.total;
            var percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);
            resolve(percentageCPU);
        }, 100);
    });
}

function cpuAverage () {
    var totalIdle = 0, totalTick = 0;
    var cpus = os.cpus();
    for (var i = 0, len = cpus.length; i < len; i++) {
        const cpu = cpus[i];
        for (type in cpu.times) {
            totalTick += cpu.times[type];
        }
        totalIdle += cpu.times.idle;
    }
    return { idle: totalIdle / cpus.length,  total: totalTick / cpus.length };
}
<|endoftext|>


<commit_before>var ungeradeWoche =
        '
' +
            '
' +
                '
09:50 - 11:20  IT7+c
' +
                '
' +
                    'Lehrer: Herr Wichmann' +
                    '
' +
                    'Raum: 311' +
                '
' +
            '
' +
            '
' +
                '
11:40 - 13:10  IT6+9
' +
                '
' +
                    'Lehrer: Herr Korte' +
                    '
' +
                    'Raum: 6' +
                '
' +
            '
' +
            '
' +
                '
13:30 - 15:00  Englisch
' +
                '
' +
                    'Lehrer: Herr Kriege' +
                    '
' +
                    'Raum: 4' +
                '
' +
            '
' +
        '
';

var geradeWoche =
        '
' +
                '
' +
                    '
08:00 - 09:30  IT6+9
' +
                    '
' +
                        'Lehrer: Herr Korte' +
                        '
' +
                        'Raum: 324' +
                    '
' +
                '
' +
                '
' +
                    '
09:50 - 11:20  IT6+9
' +
                    '
' +
                        'Lehrer: Herr Korte' +
                        '
' +
                        'Raum: 324' +
                    '
' +
                '
' +
                '
' +
                    '
11:40 - 13:10  IT7+c
' +
                    '
' +
                        'Lehrer: Herr Wichmann' +
                        '
' +
                        'Raum: 324' +
                    '
' +
                '
' +
                '
' +
                    '
13:30 - 15:00  Englisch
' +
                    '
' +
                        'Lehrer: Herr Kriege' +
                        '
' +
                        'Raum: 4' +
                    '
' +
                '
' +
            '
';

function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(+d);
    d.setHours(0, 0, 0);
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setDate(d.getDate() + 4 - (d.getDay() || 7));
    // Get first day of year
    var yearStart = new Date(d.getFullYear(), 0, 1);
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
    // Return array of year and week number
    return weekNo;
}

$(function () {
    "use strict";
        if (getWeekNumber(new Date()) % 2 == 0) {
            $("#dieseWoche").html(geradeWoche);
            $("#naechsteWoche").html(ungeradeWoche);
        }
        else {
            $("#dieseWoche").html(ungeradeWoche);
            $("#naechsteWoche").html(geradeWoche);
        }

        $(document).enhanceWithin();
});<commit_msg>Neuen Stundenplan für ungerade Woche hinzugefügt<commit_after>var ungeradeWoche =
        '
' +
            '
' +
                '
8:00 - 9:30  Politik
' +
                '
' +
                    'Lehrer: Herr Wichmann' +
                    '
' +
                    'Raum: 116' +
                '
' +
            '
' +
            '
' +
                '
9:50 - 11:20  IT7+c
' +
                '
' +
                    'Lehrer: Herr Wichmann' +
                    '
' +
                    'Raum: 311' +
                '
' +
            '
' +
            '
' +
                '
11:40 - 13:10  IT6+9
' +
                '
' +
                    'Lehrer: Herr Korte' +
                    '
' +
                    'Raum: 6' +
                '
' +
            '
' +
        '
';

var geradeWoche =
        '
' +
                '
' +
                    '
08:00 - 09:30  IT6+9
' +
                    '
' +
                        'Lehrer: Herr Korte' +
                        '
' +
                        'Raum: 324' +
                    '
' +
                '
' +
                '
' +
                    '
09:50 - 11:20  IT6+9
' +
                    '
' +
                        'Lehrer: Herr Korte' +
                        '
' +
                        'Raum: 324' +
                    '
' +
                '
' +
                '
' +
                    '
11:40 - 13:10  IT7+c
' +
                    '
' +
                        'Lehrer: Herr Wichmann' +
                        '
' +
                        'Raum: 324' +
                    '
' +
                '
' +
                '
' +
                    '
13:30 - 15:00  Englisch
' +
                    '
' +
                        'Lehrer: Herr Kriege' +
                        '
' +
                        'Raum: 4' +
                    '
' +
                '
' +
            '
';

function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(+d);
    d.setHours(0, 0, 0);
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setDate(d.getDate() + 4 - (d.getDay() || 7));
    // Get first day of year
    var yearStart = new Date(d.getFullYear(), 0, 1);
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
    // Return array of year and week number
    return weekNo;
}

$(function () {
    "use strict";
        if (getWeekNumber(new Date()) % 2 == 0) {
            $("#dieseWoche").html(geradeWoche);
            $("#naechsteWoche").html(ungeradeWoche);
        }
        else {
            $("#dieseWoche").html(ungeradeWoche);
            $("#naechsteWoche").html(geradeWoche);
        }

        $(document).enhanceWithin();
});
<|endoftext|>


<commit_before>'use babel'
import $ from 'JQuery'
import _ from 'lodash'
import Logger from '../logger/Logger.js'
import Handlebars from 'Handlebars';
import PluginManager from '../cordova/PluginManager'
import moment from 'moment'
import DEPluginsDataLoader from './deplugins_dataloader'
import registryUrl from 'registry-url'
import SDKManager from '../sdkmanagement/SDKManager'

var spawn = require('child_process').spawn;
var fs = require('fs');
var {allowUnsafeEval, allowUnsafeNewFunction} = require('loophole');
const remote = require('remote');
const dialog = remote.require('electron').dialog;

export default class DEPluginsViewUIHandler {

  constructor() {
    Logger.debug("create DEPluginsViewUIHandler");
    this.spawnRef = undefined;
    this.pluginManager = new PluginManager(Logger);
    Handlebars.registerHelper('formatRating', function(number) {
      return parseFloat(number).toFixed(1);
    });
    Handlebars.registerHelper('formatLastUpdate', function(date) {
      return moment(date).fromNow();
    });

    //offlineMode
    this.offlineMode=false;
  }

  init(){
    Logger.debug("onInit");
    var that = this;
    var path= atom.project.getPaths()[0];
    this.bindJS();
    $('#search-spinner').hide();

    //var dePluginsList = this.getDEPluginsList(); //TODO!!
    //this.displayDEPlugins(dePluginsList);
    this.updateUI();
  }

  bindJS(){
    Logger.debug("bindJS");

    var that = this;

    $('#install-vipera-npm-registry').off('click').on('click', (evt)=>{
        this.setViperaNPMRegistry();
    });
    $('#restore-default-npm-registry').off('click').on('click', (evt)=>{
        this.restoreDefaultNPMRegistry();
    });

    $('#current-npm-registry').html(registryUrl());

    //OFFLINE MANAGEMENT
    $("#offline-mode-button").off('click').on('click',() => {
      this.setOfflineMode(!this.offlineMode);
    });

    $('#current-offline-sdk-location').html(SDKManager.sdkLocation);

    $('#set-vipera-sdk-location').off('click').on('click', (evt)=>{
       var sdkPath = dialog.showOpenDialog({properties: ['openDirectory']});
       if(!sdkPath){
         return;
       }
       if(!fs.existsSync(sdkPath[0])){
         atom.notifications.addError("Invalid sdk path");
         return;
       }
       this.setViperaSdkLocation(sdkPath[0]);
       this.reloadPluginList();
    });

  }

  restoreDefaultNPMRegistry(){
    this.setNPMRegistry('https://registry.npmjs.org/');
  }

  setViperaNPMRegistry(){
    this.setNPMRegistry(atom.config.get('dynamicengine-tools.ViperaNPMRegistry'));
  }

  setNPMRegistry(registryURL){
    this.spawnRef = spawn("npm", ["set", "registry", registryURL], {});
    this.spawnRef.stdout.on('data', (data) => {
        if (Logger) {
            logger.info("[NPM Registry Set] " + data.toString())
        }
        //console.log(`[BrowserRunner]: ${data}`);
    });

    this.spawnRef.stderr.on('data', (data) => {
        if (Logger) {
            Logger.error("[scriptTools] " + data.toString())
        }
        //console.error(`[BrowserRunner]: ${data}`);
    });

    this.spawnRef.on('close', (code) => {
        //console.log(`[BrowserRunner] child process exited with code ${code}`);
        if (Logger) {
            Logger.info(`setNPMRegistry process exited with code ${code}`)
        }
        this.spawnRef = undefined;
        $('#current-npm-registry').html(registryUrl());
    });
  }

  onRemove(){
    Logger.debug("onRemove");
  }

  displayDEPlugins(data){
    var that = this;
    var TemplatesView = require("./deplugins-list-template.js");
    var source = TemplatesView.render();
    var docTemplate = allowUnsafeEval(() => allowUnsafeNewFunction(() => Handlebars.compile(source)));
    var result = allowUnsafeEval(() => allowUnsafeNewFunction(() => docTemplate({ "data": data })));
    document.getElementById('deplugins-list-container').innerHTML = result;

    $('[btn-install-plugin]').on('click', function(evt){
      $(evt.currentTarget).addClass("is-installing");
      that.installPlugin($(evt.currentTarget).attr('pluginId'));
    });

  }

  installPlugin(pluginSpec){
    Logger.info("Installing plugin "+ pluginSpec +"...");
    var that = this;
    let options=undefined;
    if(this.offlineMode){
      options = SDKManager.getInstallOptions();
    }
    this.pluginManager.addPlugin(pluginSpec,options).then(()=>{
      $('[pluginId="' + pluginSpec +'"]').removeClass("is-installing");
      Logger.info("Plugin " + pluginSpec +" unistalled succesffully");
      atom.notifications.addSuccess("Plugin "+ pluginSpec + " installed successfully.", {dismissable:true});
      this.scanPlugins();
    }, (err)=>{
      $('[pluginId="' + pluginSpec +'"]').removeClass("is-installing");
      Logger.error("Install plugin error: ", err);
      atom.notifications.addError("Plugin "+ pluginSpec+ " installation error." , { dismissable: true, detail: err});
    });
  }

  getDEPluginsList(){
    var list = new Array();
    var loader = new DEPluginsDataLoader();
    var data = loader.loadData(this.offlineMode);
    return data;
  }

  setOfflineMode(value){
    console.log("Switch offlineMode from ",this.offlineMode," to ", value);
    this.offlineMode = value;
    this.updateUI();
  }

  setViperaSdkLocation(value){
    console.log("Set vipera sdk location: ",value);
    SDKManager.sdkLocation = value;
    $('#current-offline-sdk-location').html(SDKManager.sdkLocation);
  }

  updateUI(){
    if(this.offlineMode){
      $("[hide-for-offline]").hide();
      $("[show-for-offline]").show();
      this.reloadPluginList();
    }else{
      $("[hide-for-offline]").show();
      $("[show-for-offline]").hide();
      this.reloadPluginList();
    }
  }

  reloadPluginList(){
    var dePluginsList = this.getDEPluginsList();
    this.displayDEPlugins(dePluginsList);
  }

}
<commit_msg>add toggle effect for offline button<commit_after>'use babel'
import $ from 'JQuery'
import _ from 'lodash'
import Logger from '../logger/Logger.js'
import Handlebars from 'Handlebars';
import PluginManager from '../cordova/PluginManager'
import moment from 'moment'
import DEPluginsDataLoader from './deplugins_dataloader'
import registryUrl from 'registry-url'
import SDKManager from '../sdkmanagement/SDKManager'

var spawn = require('child_process').spawn;
var fs = require('fs');
var {allowUnsafeEval, allowUnsafeNewFunction} = require('loophole');
const remote = require('remote');
const dialog = remote.require('electron').dialog;

export default class DEPluginsViewUIHandler {

  constructor() {
    Logger.debug("create DEPluginsViewUIHandler");
    this.spawnRef = undefined;
    this.pluginManager = new PluginManager(Logger);
    Handlebars.registerHelper('formatRating', function(number) {
      return parseFloat(number).toFixed(1);
    });
    Handlebars.registerHelper('formatLastUpdate', function(date) {
      return moment(date).fromNow();
    });

    //offlineMode
    this.offlineMode=false;
  }

  init(){
    Logger.debug("onInit");
    var that = this;
    var path= atom.project.getPaths()[0];
    this.bindJS();
    $('#search-spinner').hide();

    //var dePluginsList = this.getDEPluginsList(); //TODO!!
    //this.displayDEPlugins(dePluginsList);
    this.updateUI();
  }

  bindJS(){
    Logger.debug("bindJS");

    var that = this;

    $('#install-vipera-npm-registry').off('click').on('click', (evt)=>{
        this.setViperaNPMRegistry();
    });
    $('#restore-default-npm-registry').off('click').on('click', (evt)=>{
        this.restoreDefaultNPMRegistry();
    });

    $('#current-npm-registry').html(registryUrl());

    //OFFLINE MANAGEMENT
    $("#offline-mode-button").off('click').on('click',() => {
      this.setOfflineMode(!this.offlineMode);
    });

    $('#current-offline-sdk-location').html(SDKManager.sdkLocation);

    $('#set-vipera-sdk-location').off('click').on('click', (evt)=>{
       var sdkPath = dialog.showOpenDialog({properties: ['openDirectory']});
       if(!sdkPath){
         return;
       }
       if(!fs.existsSync(sdkPath[0])){
         atom.notifications.addError("Invalid sdk path");
         return;
       }
       this.setViperaSdkLocation(sdkPath[0]);
       this.reloadPluginList();
    });

  }

  restoreDefaultNPMRegistry(){
    this.setNPMRegistry('https://registry.npmjs.org/');
  }

  setViperaNPMRegistry(){
    this.setNPMRegistry(atom.config.get('dynamicengine-tools.ViperaNPMRegistry'));
  }

  setNPMRegistry(registryURL){
    this.spawnRef = spawn("npm", ["set", "registry", registryURL], {});
    this.spawnRef.stdout.on('data', (data) => {
        if (Logger) {
            logger.info("[NPM Registry Set] " + data.toString())
        }
        //console.log(`[BrowserRunner]: ${data}`);
    });

    this.spawnRef.stderr.on('data', (data) => {
        if (Logger) {
            Logger.error("[scriptTools] " + data.toString())
        }
        //console.error(`[BrowserRunner]: ${data}`);
    });

    this.spawnRef.on('close', (code) => {
        //console.log(`[BrowserRunner] child process exited with code ${code}`);
        if (Logger) {
            Logger.info(`setNPMRegistry process exited with code ${code}`)
        }
        this.spawnRef = undefined;
        $('#current-npm-registry').html(registryUrl());
    });
  }

  onRemove(){
    Logger.debug("onRemove");
  }

  displayDEPlugins(data){
    var that = this;
    var TemplatesView = require("./deplugins-list-template.js");
    var source = TemplatesView.render();
    var docTemplate = allowUnsafeEval(() => allowUnsafeNewFunction(() => Handlebars.compile(source)));
    var result = allowUnsafeEval(() => allowUnsafeNewFunction(() => docTemplate({ "data": data })));
    document.getElementById('deplugins-list-container').innerHTML = result;

    $('[btn-install-plugin]').on('click', function(evt){
      $(evt.currentTarget).addClass("is-installing");
      that.installPlugin($(evt.currentTarget).attr('pluginId'));
    });

  }

  installPlugin(pluginSpec){
    Logger.info("Installing plugin "+ pluginSpec +"...");
    var that = this;
    let options=undefined;
    if(this.offlineMode){
      options = SDKManager.getInstallOptions();
    }
    this.pluginManager.addPlugin(pluginSpec,options).then(()=>{
      $('[pluginId="' + pluginSpec +'"]').removeClass("is-installing");
      Logger.info("Plugin " + pluginSpec +" unistalled succesffully");
      atom.notifications.addSuccess("Plugin "+ pluginSpec + " installed successfully.", {dismissable:true});
      this.scanPlugins();
    }, (err)=>{
      $('[pluginId="' + pluginSpec +'"]').removeClass("is-installing");
      Logger.error("Install plugin error: ", err);
      atom.notifications.addError("Plugin "+ pluginSpec+ " installation error." , { dismissable: true, detail: err});
    });
  }

  getDEPluginsList(){
    var list = new Array();
    var loader = new DEPluginsDataLoader();
    var data = loader.loadData(this.offlineMode);
    return data;
  }

  setOfflineMode(value){
    console.log("Switch offlineMode from ",this.offlineMode," to ", value);
    this.offlineMode = value;
    this.updateUI();
  }

  setViperaSdkLocation(value){
    console.log("Set vipera sdk location: ",value);
    SDKManager.sdkLocation = value;
    $('#current-offline-sdk-location').html(SDKManager.sdkLocation);
  }

  updateUI(){
    if(this.offlineMode){
      $("[hide-for-offline]").hide();
      $("[show-for-offline]").show();
      $("#offline-mode-button").addClass("selected");
      this.reloadPluginList();
    }else{
      $("[hide-for-offline]").show();
      $("[show-for-offline]").hide();
      $("#offline-mode-button").removeClass("selected");
      this.reloadPluginList();
    }
  }

  reloadPluginList(){
    var dePluginsList = this.getDEPluginsList();
    this.displayDEPlugins(dePluginsList);
  }

}
<|endoftext|>


<commit_before>import Vue from 'vue/dist/vue.esm';
import VueResource from 'vue-resource';
import VueTouch from 'vue-touch';
import accounting from 'accounting';
import BigNumber from 'bignumber.js';
import Velocity from 'velocity-animate';
import _ from 'lodash';
import moment from 'moment';
import { hiddenPatch, hiddenGet } from './hidden';
import omit from '../utils/omit';
import App from '../../templates/app.html';
import Loading from '../../components/loading-svg.html';
import Plaid from './plaid';
import Ptr from './ptr';
import { $Root } from '../root/root';

Velocity.defaults.mobileHA = false;
Velocity.defaults.duration = 250;

Vue.use(VueTouch);
Vue.use(VueResource);

export const $App = {
  template: App,
  props: ['loggedIn', 'tmUser', 'tmToken'],
  data() {
    return {
      demo: window.location.host.indexOf('demo') !== -1,
      banks: JSON.parse(localStorage.getItem('BANKS')) || [],
      transactions: JSON.parse(localStorage.getItem('TRANSACTIONS')) || [],
      hidden: JSON.parse(localStorage.getItem('HIDDEN')) || [],
      user: JSON.parse(localStorage.getItem('USER')) || {},
      last: localStorage.getItem('LAST'),
      refreshing: false,
      scrolling: false,
      step: 0
    }
  },
  components: {
    'loading-svg': {
      template: Loading
    }
  },
  http: {
    root: 'https://tiny.money/v1/',
    headers: {
      Accept: 'application/json'
    }
  },
  created() {
    this.$options.http.headers.Authorization = `Bearer ${this.tmToken}`;

    Plaid(this);

    this.parseTransactions();

    if (
      !moment(this.last).add(1, 'minute').isAfter() ||
      this.transactions.length === 0
    ) {
      localStorage.setItem('LAST', moment().toDate());
      this.refresh();
    }
  },
  mounted() {
    Ptr(this);
  },
  watch: {

  },
  computed: {
    sortedTransactions() {
      return _.chain(this.transactions)
        .filter((t) => {
          return !t.hidden;
        })
        .orderBy([
          'pending',
          'hidden',
          'date',
          (t) => {return Math.abs(t.amount)},
          'name'
        ], [
          'desc',
          'asc',
          'desc',
          'desc',
          'desc'
        ])
        .value();
    },
    sortedTransactionsHidden() {
      return _.chain(this.transactions)
        .filter((t) => {
          return t.hidden;
        })
        .orderBy([
          'pending',
          'hidden',
          'date',
          (t) => {return Math.abs(t.amount)},
          'name'
        ], [
          'desc',
          'asc',
          'desc',
          'desc',
          'desc'
        ])
        .value();
    },
    sortedBanks() {
      return _.orderBy(this.banks, [
        (b) => {return Math.abs(b.net)},
        'name'
      ], [
        'desc',
        'desc'
      ]);
    }
  },
  filters: {
    money(raw, invert = false) {
      if (!raw)
        return '$0.00';

      if (invert)
        raw = -raw;

      const clean = new BigNumber(String(raw)).abs().toFixed(2);

      if (!invert || raw >= 0)
        return accounting.formatMoney(clean);

      else
        return accounting.formatMoney(clean, '-$');
    }
  },
  methods: {
    getTransactions(callback) {
      const lte = moment().endOf('month');
      const gte = this.demo ? moment('2016-03-01') : moment().subtract(1, 'month');

      this.$http.get(`${this.tmUser}/transactions`, {
        params: {
          step: this.step,
          pending: false,
          limit: 100,
          lte: lte.format('YYYY-MM-DD'),
          gte: gte.format('YYYY-MM-DD')
        }
      }).then((res) => {
        this.parseTransactions(res.data.transactions, gte);

        if (res.data.meta.pagination.has_more) {
          this.step++;
          this.getTransactions(callback);
        } else {
          this.step = 0;

          if (callback)
            callback();
        }
      }).catch((err) => {
        console.error(err);
        this.logout();

        if (callback)
          callback();
      });
    },
    parseTransactions(transactions, gte) {
      transactions = transactions || this.transactions;
      gte = gte || this.demo ? moment('2016-03-01') : moment().subtract(1, 'month');

      this.transactions = _
        .chain(this.transactions)
        .concat(transactions)
        .uniqBy('_id')
        .filter((t) => {
          return gte.isBefore(t.date)
        })
        .each((t) => {
          const date = moment(t.date);
          const bank = _.find(this.banks, {_id: t.bank_id});

          t.info = '';
          t.klass = [];
          t.day = date.date();
          t.month = date.format('MMM');

          if (t.pending)
            t.klass.push('pending');

          if (t.amount >= 0) {
            t.klass.push('negative');
          } else {
            t.klass.push('positive');
          }

          if (bank.name)
            t.info += `${bank.name} `;

          if (t.mask)
            t.info += `${t.mask} `;

          if (_.includes(this.hidden, t._id)) {
            Vue.set(t, 'hidden', true);
          } else {
            Vue.set(t, 'hidden', false);
          }
        })
        .value();

      const clone = _.cloneDeep(this.transactions);
      let clean = omit(clone, ['target', 'action', 'hidden']);

      localStorage.setItem('TRANSACTIONS', JSON.stringify(clean));
    },
    panStartTransaction(e, t) {
      if (Math.abs(e.overallVelocityY) >= Math.abs(e.overallVelocityX))
        return this.scrolling = true;

      if (e.target.classList.contains('transaction')) {
        t.target = e.target;
      } else {
        t.target = e.target.offsetParent;
      }

      t.action = t.target.lastChild;
      t.target.classList.remove('animate');
    },
    panTransaction(e, t) {
      if (this.scrolling)
        return;

      if (e.deltaX >= 0) {
        t.target.classList.add('left');
        t.target.classList.remove('right');
      } else {
        t.target.classList.add('right');
        t.target.classList.remove('left');
      }

      if (Math.abs(e.deltaX) >= 60) {
        t.action.classList.add('active');
      } else {
        t.action.classList.remove('active');
      }

      t.target.style.transform = `translateX(${e.deltaX}px)`;
    },
    panEndTransaction(e, t) {
      if (!this.scrolling) {

        // If we're pass the threshold, hide or show
        if (Math.abs(e.deltaX) >= 60) {
          let offset = t.target.offsetWidth;

          if (e.deltaX >= 0) {
            offset = e.deltaX - offset;
            this.animateTransaction(1, t, offset);
          } else {
            offset = e.deltaX + offset;
            this.animateTransaction(0, t, offset);
          }

          t.action.classList.remove('active');
        }

        // Otherwise just reset back to zero
        else {
          Velocity(t.target, {
            right: e.deltaX
          }, {
            complete: () => {
              t.target.style.transform = '';
              t.target.style.right = '';
            }
          });
        }
      }

      this.scrolling = false;
    },

    animateTransaction(direction, t, offset) {
      Velocity(t.target, {
        height: 0,
        right: offset
      }).then(() => {
        if (t.hidden) {
          this.hidden = _.without(this.hidden, t._id);
          Vue.set(t, 'hidden', false);
        } else {
          this.hidden.push(t._id);
          Vue.set(t, 'hidden', true);
        }

        t.target.style.right = '';
        t.target.style.transform = '';
        t.target.style.overflow = 'hidden';

        return hiddenPatch(this);
      }).then(() => {
        t.target.height = t.target.clientHeight;
        t.target.style.height = '0px';

        Velocity(t.target, {
          height: t.target.height
        }, {
          complete: () => {
            t.target.style.height = '';
            t.target.style.overflow = '';
          }
        });
      });
    },

    enterTransaction(target) {
      target.height = target.clientHeight;
      target.style.height = '0px';

      setTimeout(() => {
        Velocity(target, {
          height: target.height
        });
      }, 250);
    },

    getBanks(callback) {
      this.$http.get(`${this.tmUser}/banks`)
        .then((res) => {
          this.banks = res.data.banks;
          localStorage.setItem('BANKS', JSON.stringify(this.banks));

          if (callback)
            callback();
        })
        .catch((err) => {
          console.error(err);
          this.logout();

          if (callback)
            callback();
        });
    },

    getUser(callback) {
      this.$http.get(`users/${this.tmUser}`)
        .then((res) => {
          this.user = res.data.user;
          localStorage.setItem('USER', JSON.stringify(res.data.user));

          if (callback)
            callback();
        })
        .catch((err) => {
          console.error(err);
          this.logout();

          if (callback)
            callback();
        });
    },

    refresh() {
      return new Promise(resolve => {
        if (this.refreshing) {
          return resolve();
        } else {
          this.refreshing = true;
        }

        this.getUser(() => {
          this.getBanks(() => {
            hiddenGet(this, () => {
              this.getTransactions(() => {
                this.refreshing = false;
                resolve();
              });
            });
          });
        });
      });
    },

    accountKlass(a) {
      const balances = a.type === 'depository' ? -a.balances.current : a.balances.current;
      return balances >= 0 ? 'negative' : 'positive'
    },

    resetStorage() {
      this.banks = [];
      this.transactions = [];
      this.hidden = [];
      this.user = {};
      this.last = null;

      localStorage.removeItem('BANKS');
      localStorage.removeItem('TRANSACTIONS');
      localStorage.removeItem('HIDDEN');
      localStorage.removeItem('USER');
      localStorage.removeItem('LAST');

      this.refresh();
    },

    logout() {
      localStorage.removeItem('BANKS');
      localStorage.removeItem('TRANSACTIONS');
      localStorage.removeItem('HIDDEN');
      localStorage.removeItem('USER');
      localStorage.removeItem('LAST');

      localStorage.removeItem('tm_user');
      localStorage.removeItem('tm_token');
      $Root.tm_user = null;
      $Root.tm_token = null;
    }
  }
}<commit_msg>"other" accounts are positive by default<commit_after>import Vue from 'vue/dist/vue.esm';
import VueResource from 'vue-resource';
import VueTouch from 'vue-touch';
import accounting from 'accounting';
import BigNumber from 'bignumber.js';
import Velocity from 'velocity-animate';
import _ from 'lodash';
import moment from 'moment';
import { hiddenPatch, hiddenGet } from './hidden';
import omit from '../utils/omit';
import App from '../../templates/app.html';
import Loading from '../../components/loading-svg.html';
import Plaid from './plaid';
import Ptr from './ptr';
import { $Root } from '../root/root';

Velocity.defaults.mobileHA = false;
Velocity.defaults.duration = 250;

Vue.use(VueTouch);
Vue.use(VueResource);

export const $App = {
  template: App,
  props: ['loggedIn', 'tmUser', 'tmToken'],
  data() {
    return {
      demo: window.location.host.indexOf('demo') !== -1,
      banks: JSON.parse(localStorage.getItem('BANKS')) || [],
      transactions: JSON.parse(localStorage.getItem('TRANSACTIONS')) || [],
      hidden: JSON.parse(localStorage.getItem('HIDDEN')) || [],
      user: JSON.parse(localStorage.getItem('USER')) || {},
      last: localStorage.getItem('LAST'),
      refreshing: false,
      scrolling: false,
      step: 0
    }
  },
  components: {
    'loading-svg': {
      template: Loading
    }
  },
  http: {
    root: 'https://tiny.money/v1/',
    headers: {
      Accept: 'application/json'
    }
  },
  created() {
    this.$options.http.headers.Authorization = `Bearer ${this.tmToken}`;

    Plaid(this);

    this.parseTransactions();

    if (
      !moment(this.last).add(1, 'minute').isAfter() ||
      this.transactions.length === 0
    ) {
      localStorage.setItem('LAST', moment().toDate());
      this.refresh();
    }
  },
  mounted() {
    Ptr(this);
  },
  watch: {

  },
  computed: {
    sortedTransactions() {
      return _.chain(this.transactions)
        .filter((t) => {
          return !t.hidden;
        })
        .orderBy([
          'pending',
          'hidden',
          'date',
          (t) => {return Math.abs(t.amount)},
          'name'
        ], [
          'desc',
          'asc',
          'desc',
          'desc',
          'desc'
        ])
        .value();
    },
    sortedTransactionsHidden() {
      return _.chain(this.transactions)
        .filter((t) => {
          return t.hidden;
        })
        .orderBy([
          'pending',
          'hidden',
          'date',
          (t) => {return Math.abs(t.amount)},
          'name'
        ], [
          'desc',
          'asc',
          'desc',
          'desc',
          'desc'
        ])
        .value();
    },
    sortedBanks() {
      return _.orderBy(this.banks, [
        (b) => {return Math.abs(b.net)},
        'name'
      ], [
        'desc',
        'desc'
      ]);
    }
  },
  filters: {
    money(raw, invert = false) {
      if (!raw)
        return '$0.00';

      if (invert)
        raw = -raw;

      const clean = new BigNumber(String(raw)).abs().toFixed(2);

      if (!invert || raw >= 0)
        return accounting.formatMoney(clean);

      else
        return accounting.formatMoney(clean, '-$');
    }
  },
  methods: {
    getTransactions(callback) {
      const lte = moment().endOf('month');
      const gte = this.demo ? moment('2016-03-01') : moment().subtract(1, 'month');

      this.$http.get(`${this.tmUser}/transactions`, {
        params: {
          step: this.step,
          pending: false,
          limit: 100,
          lte: lte.format('YYYY-MM-DD'),
          gte: gte.format('YYYY-MM-DD')
        }
      }).then((res) => {
        this.parseTransactions(res.data.transactions, gte);

        if (res.data.meta.pagination.has_more) {
          this.step++;
          this.getTransactions(callback);
        } else {
          this.step = 0;

          if (callback)
            callback();
        }
      }).catch((err) => {
        console.error(err);
        this.logout();

        if (callback)
          callback();
      });
    },
    parseTransactions(transactions, gte) {
      transactions = transactions || this.transactions;
      gte = gte || this.demo ? moment('2016-03-01') : moment().subtract(1, 'month');

      this.transactions = _
        .chain(this.transactions)
        .concat(transactions)
        .uniqBy('_id')
        .filter((t) => {
          return gte.isBefore(t.date)
        })
        .each((t) => {
          const date = moment(t.date);
          const bank = _.find(this.banks, {_id: t.bank_id});

          t.info = '';
          t.klass = [];
          t.day = date.date();
          t.month = date.format('MMM');

          if (t.pending)
            t.klass.push('pending');

          if (t.amount >= 0) {
            t.klass.push('negative');
          } else {
            t.klass.push('positive');
          }

          if (bank.name)
            t.info += `${bank.name} `;

          if (t.mask)
            t.info += `${t.mask} `;

          if (_.includes(this.hidden, t._id)) {
            Vue.set(t, 'hidden', true);
          } else {
            Vue.set(t, 'hidden', false);
          }
        })
        .value();

      const clone = _.cloneDeep(this.transactions);
      let clean = omit(clone, ['target', 'action', 'hidden']);

      localStorage.setItem('TRANSACTIONS', JSON.stringify(clean));
    },
    panStartTransaction(e, t) {
      if (Math.abs(e.overallVelocityY) >= Math.abs(e.overallVelocityX))
        return this.scrolling = true;

      if (e.target.classList.contains('transaction')) {
        t.target = e.target;
      } else {
        t.target = e.target.offsetParent;
      }

      t.action = t.target.lastChild;
      t.target.classList.remove('animate');
    },
    panTransaction(e, t) {
      if (this.scrolling)
        return;

      if (e.deltaX >= 0) {
        t.target.classList.add('left');
        t.target.classList.remove('right');
      } else {
        t.target.classList.add('right');
        t.target.classList.remove('left');
      }

      if (Math.abs(e.deltaX) >= 60) {
        t.action.classList.add('active');
      } else {
        t.action.classList.remove('active');
      }

      t.target.style.transform = `translateX(${e.deltaX}px)`;
    },
    panEndTransaction(e, t) {
      if (!this.scrolling) {

        // If we're pass the threshold, hide or show
        if (Math.abs(e.deltaX) >= 60) {
          let offset = t.target.offsetWidth;

          if (e.deltaX >= 0) {
            offset = e.deltaX - offset;
            this.animateTransaction(1, t, offset);
          } else {
            offset = e.deltaX + offset;
            this.animateTransaction(0, t, offset);
          }

          t.action.classList.remove('active');
        }

        // Otherwise just reset back to zero
        else {
          Velocity(t.target, {
            right: e.deltaX
          }, {
            complete: () => {
              t.target.style.transform = '';
              t.target.style.right = '';
            }
          });
        }
      }

      this.scrolling = false;
    },

    animateTransaction(direction, t, offset) {
      Velocity(t.target, {
        height: 0,
        right: offset
      }).then(() => {
        if (t.hidden) {
          this.hidden = _.without(this.hidden, t._id);
          Vue.set(t, 'hidden', false);
        } else {
          this.hidden.push(t._id);
          Vue.set(t, 'hidden', true);
        }

        t.target.style.right = '';
        t.target.style.transform = '';
        t.target.style.overflow = 'hidden';

        return hiddenPatch(this);
      }).then(() => {
        t.target.height = t.target.clientHeight;
        t.target.style.height = '0px';

        Velocity(t.target, {
          height: t.target.height
        }, {
          complete: () => {
            t.target.style.height = '';
            t.target.style.overflow = '';
          }
        });
      });
    },

    enterTransaction(target) {
      target.height = target.clientHeight;
      target.style.height = '0px';

      setTimeout(() => {
        Velocity(target, {
          height: target.height
        });
      }, 250);
    },

    getBanks(callback) {
      this.$http.get(`${this.tmUser}/banks`)
        .then((res) => {
          this.banks = res.data.banks;
          localStorage.setItem('BANKS', JSON.stringify(this.banks));

          if (callback)
            callback();
        })
        .catch((err) => {
          console.error(err);
          this.logout();

          if (callback)
            callback();
        });
    },

    getUser(callback) {
      this.$http.get(`users/${this.tmUser}`)
        .then((res) => {
          this.user = res.data.user;
          localStorage.setItem('USER', JSON.stringify(res.data.user));

          if (callback)
            callback();
        })
        .catch((err) => {
          console.error(err);
          this.logout();

          if (callback)
            callback();
        });
    },

    refresh() {
      return new Promise(resolve => {
        if (this.refreshing) {
          return resolve();
        } else {
          this.refreshing = true;
        }

        this.getUser(() => {
          this.getBanks(() => {
            hiddenGet(this, () => {
              this.getTransactions(() => {
                this.refreshing = false;
                resolve();
              });
            });
          });
        });
      });
    },

    accountKlass(a) {
      const balances = a.type === 'depository' || a.type === 'other' ? -a.balances.current : a.balances.current;
      return balances >= 0 ? 'negative' : 'positive'
    },

    resetStorage() {
      this.banks = [];
      this.transactions = [];
      this.hidden = [];
      this.user = {};
      this.last = null;

      localStorage.removeItem('BANKS');
      localStorage.removeItem('TRANSACTIONS');
      localStorage.removeItem('HIDDEN');
      localStorage.removeItem('USER');
      localStorage.removeItem('LAST');

      this.refresh();
    },

    logout() {
      localStorage.removeItem('BANKS');
      localStorage.removeItem('TRANSACTIONS');
      localStorage.removeItem('HIDDEN');
      localStorage.removeItem('USER');
      localStorage.removeItem('LAST');

      localStorage.removeItem('tm_user');
      localStorage.removeItem('tm_token');
      $Root.tm_user = null;
      $Root.tm_token = null;
    }
  }
}<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var wolfram = require('wolfram-alpha').createClient(process.env.API_KEY, {
  width: 348
});
var port, router;

// Use bodyParser() and get data from POST
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

port = process.env.PORT || 8080
router = express.Router();

// The main shit here boys
router.get('/', function(request, response) {
  wolfram.query(request.query.i, function(err, result) {
    if (err) throw err;
    var url = 'http://www.wolframalpha.com/input/?i=' + encodeURIComponent(request.query.i);
    result.push({origin_url:url})
    response.json(result);
  });
});

// All routes prefix with /input
app.use('/input', router);

app.listen(port);
<commit_msg>change width to maxwidth<commit_after>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var wolfram = require('wolfram-alpha').createClient(process.env.API_KEY, {
  maxwidth: 348
});
var port, router;

// Use bodyParser() and get data from POST
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

port = process.env.PORT || 8080
router = express.Router();

// The main shit here boys
router.get('/', function(request, response) {
  wolfram.query(request.query.i, function(err, result) {
    if (err) throw err;
    var url = 'http://www.wolframalpha.com/input/?i=' + encodeURIComponent(request.query.i);
    result.push({origin_url:url})
    response.json(result);
  });
});

// All routes prefix with /input
app.use('/input', router);

app.listen(port);
<|endoftext|>


<commit_before>Template.homeResidentActivityLevelTrend.rendered = function () {
  // Get reference to template instance
  var instance = this;

  instance.autorun(function () {
    // Get reference to Route
    var router = Router.current();

    // Get current Home ID
    var homeId = router.params.homeId;

    // Get data for trend line chart
    var dailyActivityData = ReactiveMethod.call("getHomeActivityCountTrend", homeId);

    // Render the chart, if data is available
    if (dailyActivityData) {
      // Make sure all daily activity data is in user local timezone
      // (fixes chart legend 'misalignment' due to timezone offset)
      var userLocalTimezoneData = _.map(dailyActivityData, function (dailyActivity) {
        // Format daily activity date in YYYY-MM-DD
        // (stripping timezone and time from date object)
        dateString = moment(dailyActivity.date).format("YYYY-MM-DD");

        // Create new date object, based on cleaned date string
        dailyActivity.date = moment(dateString).toDate();

        return dailyActivity;
      });

      // Render the timezone adjusted data in a multi-line chart
      // coloring activity levels to match the 'traffic lights' theme :-)
      MG.data_graphic({
          title: "Number of residents per activity level for past seven days.",
          description: "Daily count of residents with inactive, semi-active, and active status.",
          data: userLocalTimezoneData,
          x_axis: true,
          y_label: "Number of residents",
          y_accessor: ['inactive', 'semiActive', 'active'],
          interpolate: 'basic',
          full_width: true,
          height: 333,
          right: 49,
          target: '#trend-chart',
          legend: ['Inactive','Semi-active','Active'],
          colors: ['red', 'gold', 'green'],
          aggregate_rollover: true
      });
    }
  });
}
<commit_msg>Get i18n strings<commit_after>Template.homeResidentActivityLevelTrend.rendered = function () {
  // Get reference to template instance
  var instance = this;

  instance.autorun(function () {
    // Get reference to Route
    var router = Router.current();

    // Get current Home ID
    var homeId = router.params.homeId;

    // Get data for trend line chart
    var dailyActivityData = ReactiveMethod.call("getHomeActivityCountTrend", homeId);

    // Render the chart, if data is available
    if (dailyActivityData) {
      // Make sure all daily activity data is in user local timezone
      // (fixes chart legend 'misalignment' due to timezone offset)
      var userLocalTimezoneData = _.map(dailyActivityData, function (dailyActivity) {
        // Format daily activity date in YYYY-MM-DD
        // (stripping timezone and time from date object)
        dateString = moment(dailyActivity.date).format("YYYY-MM-DD");

        // Create new date object, based on cleaned date string
        dailyActivity.date = moment(dateString).toDate();

        return dailyActivity;
      });

      // Get i18n texts for chart
      const activityLevelTrendTitle = TAPi18n.__("homeResidentActivityLevelTrend-chartTitle");
      const activityLevelTrendDescription = TAPi18n.__("homeResidentActivityLevelTrend-chartDescription");

      // Render the timezone adjusted data in a multi-line chart
      // coloring activity levels to match the 'traffic lights' theme :-)
      MG.data_graphic({
          title: activityLevelTrendTitle,
          description: activityLevelTrendDescription,
          data: userLocalTimezoneData,
          x_axis: true,
          y_label: "Number of residents",
          y_accessor: ['inactive', 'semiActive', 'active'],
          interpolate: 'basic',
          full_width: true,
          height: 333,
          right: 49,
          target: '#trend-chart',
          legend: ['Inactive','Semi-active','Active'],
          colors: ['red', 'gold', 'green'],
          aggregate_rollover: true
      });
    }
  });
}
<|endoftext|>


<commit_before>/* globals game */
/*-------------------
a player entity
-------------------------------- */
game.PlayerEntity = me.ObjectEntity.extend({

    /* -----
    constructor
    ------ */
    init: function(x, y, settings) {
        // call the constructor
        this.parent(x, y, settings);
        // set the default horizontal & vertical speed (accel vector)
        this.setVelocity(3, 3);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.gravity = 0;

        this.update();

    },

    /* -----
    update the player pos
    ------ */
    update: function(dt) {
        if (me.input.isKeyPressed('left')) {
            // flip the sprite on horizontal axis
            // update the entity velocity
            this.vel.x -= this.accel.x * me.timer.tick;
            this.vel.y = 0;
        } else if (me.input.isKeyPressed('right')) {
            // unflip the sprite
            // update the entity velocity
            this.vel.x += this.accel.x * me.timer.tick;
            this.vel.y = 0;
        }
        else {
            this.vel.x = 0;
        }
        if (me.input.isKeyPressed('up')) {
            this.vel.y -= this.accel.y * me.timer.tick;
            this.vel.x = 0;
            // set the jumping flage
        } else if (me.input.isKeyPressed('down')) {
            this.vel.y += this.accel.y * me.timer.tick;
            this.vel.x = 0;
        } else {
            this.vel.y = 0;
        }

        // check & update player movement
        this.updateMovement();

        // update animation if necessary
        if (this.vel.x !== 0 || this.vel.y !== 0) {
            // update object animation
            this.parent();
            return true;
        }

        // else inform the engine we did not perform
        // any update (e.g. position, animation)
        return false;
    },

    /* ---
       callback when everything is loaded
       ---  */
    loaded: function (){

    }
});
game.staticEntity = me.ObjectEntity.extend({

    /* -----

    constructor

    ------ */

    init: function(x, y, settings) {
        // call the constructor
        this.parent(x, y, settings);
        // set the default horizontal & vertical speed (accel vector)
        this.setVelocity(3, 3);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.gravity = 0;

        this.update();

        countDown = 100;

    },

    /* -----

    update the player pos

    ------ */
    update: function(dt) {
        dir = Math.floor(Math.random() * 4)
        if(dir == 0){
            this.vel.x = 0;
            this.vel.y = 0;
            this.vel.x -= Math.floor(Math.random() * 4);
        }else if(dir == 1){
            this.vel.x = 0;
            this.vel.y = 0;
            this.vel.x += Math.floor(Math.random() * 4);
        }else if(dir == 2){
            this.vel.x = 0;
            this.vel.y = 0;
            this.vel.y -= Math.floor(Math.random() * 4);
        }else{
            this.vel.x = 0;
            this.vel.y = 0;
            this.vel.y += Math.floor(Math.random() * 4);
        }

        this.updateMovement();

        return false;
        /*if (me.input.isKeyPressed('left')) {
            // flip the sprite on horizontal axis
            // update the entity velocity
            this.vel.x -= this.accel.x * me.timer.tick;
            this.vel.y = 0;
        } else if (me.input.isKeyPressed('right')) {
            // unflip the sprite
            // update the entity velocity
            this.vel.x += this.accel.x * me.timer.tick;
            this.vel.y = 0;
        }
        else {
            this.vel.x = 0;
        }
        if (me.input.isKeyPressed('up')) {
            this.vel.y -= this.accel.y * me.timer.tick;
            this.vel.x = 0;
            // set the jumping flage
        } else if (me.input.isKeyPressed('down')) {
            this.vel.y += this.accel.y * me.timer.tick;
            this.vel.x = 0;
        } else {
            this.vel.y = 0;
        }

        // check & update player movement
        this.updateMovement();

        // update animation if necessary
        if (this.vel.x !== 0 || this.vel.y !== 0) {
            // update object animation
            this.parent();
            return true;
        }

        // else inform the engine we did not perform
        // any update (e.g. position, animation)
        return false;*/
    },
    /* ---

       callback when everything is loaded

       ---  */

    loaded: function (){

    }
});<commit_msg>velocity<commit_after>/* globals game */
/*-------------------
a player entity
-------------------------------- */
game.PlayerEntity = me.ObjectEntity.extend({

    /* -----
    constructor
    ------ */
    init: function(x, y, settings) {
        // call the constructor
        this.parent(x, y, settings);
        // set the default horizontal & vertical speed (accel vector)
        this.setVelocity(5, 5);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.gravity = 0;

        this.update();

    },

    /* -----
    update the player pos
    ------ */
    update: function(dt) {
        if (me.input.isKeyPressed('left')) {
            // flip the sprite on horizontal axis
            // update the entity velocity
            this.vel.x -= this.accel.x * me.timer.tick;
            this.vel.y = 0;
        } else if (me.input.isKeyPressed('right')) {
            // unflip the sprite
            // update the entity velocity
            this.vel.x += this.accel.x * me.timer.tick;
            this.vel.y = 0;
        }
        else {
            this.vel.x = 0;
        }
        if (me.input.isKeyPressed('up')) {
            this.vel.y -= this.accel.y * me.timer.tick;
            this.vel.x = 0;
            // set the jumping flage
        } else if (me.input.isKeyPressed('down')) {
            this.vel.y += this.accel.y * me.timer.tick;
            this.vel.x = 0;
        } else {
            this.vel.y = 0;
        }

        // check & update player movement
        this.updateMovement();

        // update animation if necessary
        if (this.vel.x !== 0 || this.vel.y !== 0) {
            // update object animation
            this.parent();
            return true;
        }

        // else inform the engine we did not perform
        // any update (e.g. position, animation)
        return false;
    },

    /* ---
       callback when everything is loaded
       ---  */
    loaded: function (){

    }
});
game.staticEntity = me.ObjectEntity.extend({

    /* -----

    constructor

    ------ */

    init: function(x, y, settings) {
        // call the constructor
        this.parent(x, y, settings);
        // set the default horizontal & vertical speed (accel vector)
        this.setVelocity(3, 3);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.gravity = 0;

        this.update();

        countDown = 100;

    },

    /* -----

    update the player pos

    ------ */
    update: function(dt) {
        dir = Math.floor(Math.random() * 4)
        if(dir == 0){
            this.vel.x = 0;
            this.vel.y = 0;
            this.vel.x -= Math.floor(Math.random() * 4);
        }else if(dir == 1){
            this.vel.x = 0;
            this.vel.y = 0;
            this.vel.x += Math.floor(Math.random() * 4);
        }else if(dir == 2){
            this.vel.x = 0;
            this.vel.y = 0;
            this.vel.y -= Math.floor(Math.random() * 4);
        }else{
            this.vel.x = 0;
            this.vel.y = 0;
            this.vel.y += Math.floor(Math.random() * 4);
        }

        this.updateMovement();

        return false;
        /*if (me.input.isKeyPressed('left')) {
            // flip the sprite on horizontal axis
            // update the entity velocity
            this.vel.x -= this.accel.x * me.timer.tick;
            this.vel.y = 0;
        } else if (me.input.isKeyPressed('right')) {
            // unflip the sprite
            // update the entity velocity
            this.vel.x += this.accel.x * me.timer.tick;
            this.vel.y = 0;
        }
        else {
            this.vel.x = 0;
        }
        if (me.input.isKeyPressed('up')) {
            this.vel.y -= this.accel.y * me.timer.tick;
            this.vel.x = 0;
            // set the jumping flage
        } else if (me.input.isKeyPressed('down')) {
            this.vel.y += this.accel.y * me.timer.tick;
            this.vel.x = 0;
        } else {
            this.vel.y = 0;
        }

        // check & update player movement
        this.updateMovement();

        // update animation if necessary
        if (this.vel.x !== 0 || this.vel.y !== 0) {
            // update object animation
            this.parent();
            return true;
        }

        // else inform the engine we did not perform
        // any update (e.g. position, animation)
        return false;*/
    },
    /* ---

       callback when everything is loaded

       ---  */

    loaded: function (){

    }
});<|endoftext|>


<commit_before>'use strict';

$.ajaxHandler = {

	defaults: {
		isAjaxHandlerEnabled: false
	}

	, install: function (options) {
		$.ajaxHandler.origAjax = $.ajax;
		$.ajax = $.ajaxHandler.ajaxWrapper;

		return $.ajaxHandler.config(options || {});
	}

	/**
	 * Convenience method for removing the custom jQuery.ajaxHandler behavior
	 * (used by unit tests)
	 */
	, remove: function () {
		if ($.ajaxHandler.origAjax) {
			$.ajax = $.ajaxHandler.origAjax;
			$.ajaxHandler.origAjax = undefined;
		}

		delete $.ajaxHandler.options;
	}

	/**
	 *
	 * @param {Object} options
	 * @param {Object} options.requestHeaders
	 * @param {Function} options.on401
	 * @returns {Object}
	 */
	, config: function (options) {
		$.ajaxHandler.options = $.extend({}, $.ajaxHandler.defaults, options);
		return this.options;
	}

	/**
	 *
	 * @returns {Promise}
	 */
	, ajaxWrapper: function () {
		var args = Array.prototype.slice.call(arguments)
		, optionsIndex = typeof args[0] == 'string' ? 1 : 0
		, options = args[optionsIndex] || {}
		, ajaxHandlerOptions = options.ajaxHandlerOptions;

		// Merge per-request options with the runtime options
		ajaxHandlerOptions = $.extend({}, $.ajaxHandler.options, ajaxHandlerOptions);

		if (ajaxHandlerOptions.isAjaxHandlerEnabled) {
			if (optionsIndex == 1) {
				options.url = args[0];
			}

			options.ajaxHandlerOptions = ajaxHandlerOptions;
			return $.ajaxHandler.handleAjaxRequest.call(this, options);
		} else {
			return $.ajaxHandler.origAjax.apply(this, args);
		}
	}

	/**
	 * Implement our own version of jQuery.Ajax that wraps the original.
	 * This way we can add a default handler for ajax failures.
	 *
	 * @returns {Promise}
	 */
	, handleAjaxRequest: function () {
		var args = Array.prototype.slice.call(arguments)
		, options = args[0]
		, deferred = new $.Deferred()

		// The default error handler fires before any promise callbacks.
		// Store a reference to the default error handler and prevent the error from firing until we want it to.
		, errorHandler = options.error;

		options.error = null;

		// Save a reference to any existing `beforeSend` callback, we will want to call it later...
		if (options.beforeSend) {
			options.ajaxHandlerOptions.origBeforeSend = options.beforeSend;
		}

		$.ajaxHandler.ajax.apply(this, args)
			.done(function (response, statusText, jqXhr) {
				deferred.resolve(response, statusText, jqXhr);
			})
			.fail(function (jqXhr, statusText, error) {
				// Add the error handler
				this.error = errorHandler;

				if (jqXhr.status == 401 && options.ajaxHandlerOptions.on401) {
					options.ajaxHandlerOptions.on401.call(this, deferred, jqXhr, statusText, error);
				} else {
					$.ajaxHandler.onFail.call(this, deferred, jqXhr, statusText, error);
				}
			});

		return deferred.promise();
	}

	/**
	 * Calls the original $.ajax with some headers and modifies the url
	 *
	 * {Object} options
	 */
	, ajax: function (options) {
		// Install our own onBeforeSend handler
		options.beforeSend = $.ajaxHandler.onBeforeSend;

		return $.ajaxHandler.origAjax(options);
	}

	/**
	 *
	 * @param {Promise} deferred
	 * @param {Promise} jqXhr
	 * @param {String} statusText
	 * @param {String} error
	 * @returns {Promise}
	 */
	, onFail: function (deferred, jqXhr, statusText, error) {
		if (this.error) {
			this.error.call(this, jqXhr, statusText, error);
		}

		if (typeof $.ajaxHandler.options.onFail == 'function') {
			$.ajaxHandler.options.onFail.call(this, deferred, jqXhr, statusText, error);
		}

		return deferred.reject(jqXhr, statusText, error);
	}

	/**
	 *
	 * @param jqXhr
	 */
	, onBeforeSend: function (jqXhr, options) {
		var ajaxHandlerOptions = options.ajaxHandlerOptions;

		if (typeof ajaxHandlerOptions.url == 'function') {
			options.url = ajaxHandlerOptions.url.call(this, options);
		}

		// Add any custom request headers
		if (ajaxHandlerOptions.requestHeaders) {
			$.each(ajaxHandlerOptions.requestHeaders, function (name, header) {
				jqXhr.setRequestHeader(name, typeof header == 'function' ? header.call(jqXhr, options) : header);
			});
		}

		// Make sure to call any pre-existing .beforeSend() callbacks
		if (typeof ajaxHandlerOptions.origBeforeSend == 'function') {
			ajaxHandlerOptions.origBeforeSend.call(this, jqXhr, options);
		}
	}
};<commit_msg>fix - store reference to origUrl<commit_after>'use strict';

$.ajaxHandler = {

	defaults: {
		isAjaxHandlerEnabled: false
	}

	, install: function (options) {
		$.ajaxHandler.origAjax = $.ajax;
		$.ajax = $.ajaxHandler.ajaxWrapper;

		return $.ajaxHandler.config(options || {});
	}

	/**
	 * Convenience method for removing the custom jQuery.ajaxHandler behavior
	 * (used by unit tests)
	 */
	, remove: function () {
		if ($.ajaxHandler.origAjax) {
			$.ajax = $.ajaxHandler.origAjax;
			$.ajaxHandler.origAjax = undefined;
		}

		delete $.ajaxHandler.options;
	}

	/**
	 *
	 * @param {Object} options
	 * @param {Object} options.requestHeaders
	 * @param {Function} options.on401
	 * @returns {Object}
	 */
	, config: function (options) {
		$.ajaxHandler.options = $.extend({}, $.ajaxHandler.defaults, options);
		return this.options;
	}

	/**
	 *
	 * @returns {Promise}
	 */
	, ajaxWrapper: function () {
		var args = Array.prototype.slice.call(arguments)
		, optionsIndex = typeof args[0] == 'string' ? 1 : 0
		, options = args[optionsIndex] || {}
		, ajaxHandlerOptions = options.ajaxHandlerOptions;

		// Merge per-request options with the runtime options
		ajaxHandlerOptions = $.extend({}, $.ajaxHandler.options, ajaxHandlerOptions);

		if (ajaxHandlerOptions.isAjaxHandlerEnabled) {
			if (optionsIndex == 1) {
				options.url = args[0];
			}

			options.ajaxHandlerOptions = ajaxHandlerOptions;
			return $.ajaxHandler.handleAjaxRequest.call(this, options);
		} else {
			return $.ajaxHandler.origAjax.apply(this, args);
		}
	}

	/**
	 * Implement our own version of jQuery.Ajax that wraps the original.
	 * This way we can add a default handler for ajax failures.
	 *
	 * @returns {Promise}
	 */
	, handleAjaxRequest: function () {
		var args = Array.prototype.slice.call(arguments)
		, options = args[0]
		, deferred = new $.Deferred()

		// The default error handler fires before any promise callbacks.
		// Store a reference to the default error handler and prevent the error from firing until we want it to.
		, errorHandler = options.error;

		options.error = null;

		// Save a reference to any existing `beforeSend` callback, we will want to call it later...
		if (options.beforeSend) {
			options.ajaxHandlerOptions.origBeforeSend = options.beforeSend;
		}

		$.ajaxHandler.ajax.apply(this, args)
			.done(function (response, statusText, jqXhr) {
				deferred.resolve(response, statusText, jqXhr);
			})
			.fail(function (jqXhr, statusText, error) {
				// Add the error handler
				this.error = errorHandler;

				if (jqXhr.status == 401 && options.ajaxHandlerOptions.on401) {
					options.ajaxHandlerOptions.on401.call(this, deferred, jqXhr, statusText, error);
				} else {
					$.ajaxHandler.onFail.call(this, deferred, jqXhr, statusText, error);
				}
			});

		return deferred.promise();
	}

	/**
	 * Calls the original $.ajax with some headers and modifies the url
	 *
	 * {Object} options
	 */
	, ajax: function (options) {
		// Install our own onBeforeSend handler
		options.beforeSend = $.ajaxHandler.onBeforeSend;

		return $.ajaxHandler.origAjax(options);
	}

	/**
	 *
	 * @param {Promise} deferred
	 * @param {Promise} jqXhr
	 * @param {String} statusText
	 * @param {String} error
	 * @returns {Promise}
	 */
	, onFail: function (deferred, jqXhr, statusText, error) {
		if (this.error) {
			this.error.call(this, jqXhr, statusText, error);
		}

		if (typeof $.ajaxHandler.options.onFail == 'function') {
			$.ajaxHandler.options.onFail.call(this, deferred, jqXhr, statusText, error);
		}

		return deferred.reject(jqXhr, statusText, error);
	}

	/**
	 *
	 * @param jqXhr
	 */
	, onBeforeSend: function (jqXhr, options) {
		var origUrl
		, ajaxHandlerOptions = options.ajaxHandlerOptions;

		if (typeof ajaxHandlerOptions.corsUrl == 'function') {
			origUrl = options.url;
			options.url = ajaxHandlerOptions.corsUrl.call(this, options);
		}

		// Add any custom request headers
		if (ajaxHandlerOptions.requestHeaders) {
			$.each(ajaxHandlerOptions.requestHeaders, function (name, header) {
				jqXhr.setRequestHeader(name, typeof header == 'function' ? header.call(jqXhr, options) : header);
			});
		}

		if (origUrl) {
			options.url = origUrl;
		}

		// Make sure to call any pre-existing .beforeSend() callbacks
		if (typeof ajaxHandlerOptions.origBeforeSend == 'function') {
			ajaxHandlerOptions.origBeforeSend.call(this, jqXhr, options);
		}
	}
};<|endoftext|>


<commit_before>var express = require("express")
  , http = require("http")
  , socketio = require("socket.io")
  , hbs = require("hbs")
  , _ = require("underscore");

var sectionLength = 8;
var phraseLength = 8;
var rolesLength = 8;

var phraseRootValueStart = 30;
var phraseRootValueEnd = 60;

var Roles = require("./roles.js");
var roles = new Roles(rolesLength);

var app = express();
var server = http.createServer(app);
var io = socketio.listen(server);

// HBS TEMPLATE VARIABLE
var blocks = {};

//STATE UTILS
var setScale = function(scale) {
  state.scale = scale;
}

var setTempo = function(tempo) {
  state.tempo = tempo;
}

var generatePhrase = function(phraseLen) {
  var randNum = randNum = Math.floor((Math.random() * phraseLen));
  var rootNum = _.random(phraseRootValueStart, phraseRootValueEnd);
  return [randNum, rootNum];
}

var generateSection = function() {
  var section = [];
  var phrase = null;

  for(var i=0; i<phraseLength; i++){
    phrase = generatePhrase(phraseLength);
    section.push(phrase);
  }

  return section;
};

var generateSections = function() {
  for(var i=0, len=sectionLength; i<len; i++) {
    state.sections.push(generateSection());
  };
};

// GLOBAL STATE
var state = {};
state.tempo = null;
state.sections = [];

setTempo(120);
setScale('majorScale');
generateSections();

console.log(JSON.stringify(state));

// CONFIG
app.configure(function() {
  app.set('view engine', 'html');
  app.set('views', __dirname + '/views');
  app.engine('html', hbs.__express);
  app.use(express.static(__dirname + '/static'));
  app.use(express.bodyParser());
});

// TEMPLATE CONFIG
hbs.registerHelper('extend', function(name, context) {
  var block = blocks[name];
  if(!block) {
    block = blocks[name] = [];
  }
  block.push(context.fn(this));
});

hbs.registerHelper('block', function(name){
  var val = (blocks[name] || [].join('\n'));
  //clear block
  blocks[name] = [];
  return val;
});

hbs.registerHelper('safe', function(name) {
  var val = (blocks[name] || [].join('\n'));
  blocks[name] = [];
  return hbs.handlebars.SafeString(val);
});

// ROUTES
app.get('/', function (req, res, next) {
  return res.render('index', {});
});
app.get('/test', function (req, res, next) {
  return res.render('test', {});
});

// SOCKETS
io.sockets.on('connection', function (socket) {
  var assignedRole = roles.assignRole(socket);

  console.log('assignedRole:' + JSON.stringify(assignedRole));
  console.log('socketId = ' + socket.id);

  roles.print();

  socket.emit('init', {
    state: state,
    role: assignedRole
  });

  socket.emit('state.current', state);

  socket.on('state.change', function(data) {
    socket.broadcast.emit('state.change', state);
  });

  socket.on('disconnect', function() {
    roles.unassignRole(this.id);
    console.log('disconnect detected for id=' + this.id);
    roles.print();
  });
});

server.listen(8080, '0.0.0.0');
console.log("starting server!");<commit_msg>removing state.current<commit_after>var express = require("express")
  , http = require("http")
  , socketio = require("socket.io")
  , hbs = require("hbs")
  , _ = require("underscore");

var sectionLength = 8;
var phraseLength = 8;
var rolesLength = 8;

var phraseRootValueStart = 30;
var phraseRootValueEnd = 60;

var Roles = require("./roles.js");
var roles = new Roles(rolesLength);

var app = express();
var server = http.createServer(app);
var io = socketio.listen(server);

// HBS TEMPLATE VARIABLE
var blocks = {};

//STATE UTILS
var setScale = function(scale) {
  state.scale = scale;
}

var setTempo = function(tempo) {
  state.tempo = tempo;
}

var generatePhrase = function(phraseLen) {
  var randNum = randNum = Math.floor((Math.random() * phraseLen));
  var rootNum = _.random(phraseRootValueStart, phraseRootValueEnd);
  return [randNum, rootNum];
}

var generateSection = function() {
  var section = [];
  var phrase = null;

  for(var i=0; i<phraseLength; i++){
    phrase = generatePhrase(phraseLength);
    section.push(phrase);
  }

  return section;
};

var generateSections = function() {
  for(var i=0, len=sectionLength; i<len; i++) {
    state.sections.push(generateSection());
  };
};

// GLOBAL STATE
var state = {};
state.tempo = null;
state.sections = [];

setTempo(120);
setScale('majorScale');
generateSections();

console.log(JSON.stringify(state));

// CONFIG
app.configure(function() {
  app.set('view engine', 'html');
  app.set('views', __dirname + '/views');
  app.engine('html', hbs.__express);
  app.use(express.static(__dirname + '/static'));
  app.use(express.bodyParser());
});

// TEMPLATE CONFIG
hbs.registerHelper('extend', function(name, context) {
  var block = blocks[name];
  if(!block) {
    block = blocks[name] = [];
  }
  block.push(context.fn(this));
});

hbs.registerHelper('block', function(name){
  var val = (blocks[name] || [].join('\n'));
  //clear block
  blocks[name] = [];
  return val;
});

hbs.registerHelper('safe', function(name) {
  var val = (blocks[name] || [].join('\n'));
  blocks[name] = [];
  return hbs.handlebars.SafeString(val);
});

// ROUTES
app.get('/', function (req, res, next) {
  return res.render('index', {});
});
app.get('/test', function (req, res, next) {
  return res.render('test', {});
});

// SOCKETS
io.sockets.on('connection', function (socket) {
  var assignedRole = roles.assignRole(socket);

  console.log('assignedRole:' + JSON.stringify(assignedRole));
  console.log('socketId = ' + socket.id);

  roles.print();

  socket.emit('init', {
    state: state,
    role: assignedRole
  });

  socket.on('state.change', function(data) {
    socket.broadcast.emit('state.change', state);
  });

  socket.on('disconnect', function() {
    roles.unassignRole(this.id);
    console.log('disconnect detected for id=' + this.id);
    roles.print();
  });
});

server.listen(8080, '0.0.0.0');
console.log("starting server!");<|endoftext|>