<commit_before>'use strict';

function powTwo(val) {
  return val * 2;
}

let Mathf = {
  Deg2Rad: (Math.PI * 2) / 360,

  Epsilon: Number.EPSILON || Math.pow(2, -52),

  Infinity: Infinity,

  NegativeInfinity: -Infinity,

  PI: Math.PI,

  Rad2Deg: 360 / (Math.PI * 2),

  abs: Math.abs,

  acos: Math.acos,

  approximately: (f1, f2) => {
    return Mathf.abs(f1 - f2) < Mathf.Epsilon;
  },

  asin: Math.asin,

  atan: Math.atan,

  atan2: Math.atan2,

  ceil: Math.ceil,

  clamp: (value, min, max) => {
    return value < min ? min : (value > max ? max : value);
  },

  clamp01: (value) => {
    return value < 0 ? 0 : (value > 1 ? 1 : value);
  },

  closestPowerOfTwo: (value) => {
    let closestValue = 1;

    if (value <= 2) return value;

    while (closestValue <= value) {
      closestValue = powTwo(closestValue);
      if (value < closestValue / 2 + closestValue) {
        break;
      }
    }

    return closestValue;
  },

  cos: Math.cos,

  deltaAngle: (current, target) => {
    if (current > 360) {
      current %= 360;
    }

    if (target > 360) {
      target %= 360;
    }

    return target - current;
  },

  exp: Math.exp,

  floor: Math.floor,

  gammaToLinearSpace: () => {},

  inverseLerp: () => {},

  isPowerOfTwo: () => {},

  lerp: () => {},

  lerpAngle: () => {},

  lerpUnclamped: () => {},

  linearToGammaSpace: () => {},

  log: Math.log,

  log10: Math.log10,

  max: Math.max,

  min: Math.min,

  moveTowards: () => {},

  moveTowardsAngle: () => {},

  nextPowerOfTwo: () => {},

  perlinNoise: () => {},

  pingPong: () => {},

  pow: Math.pow,

  repeat: () => {},

  round: (num) => {
    let ceilVal = num + 0.5;

    if (ceilVal === Math.ceil(num)) {
      return (ceilVal % 2 === 0) ? num + 0.5 : num - 0.5;
    }

    return Math.round(num);
  },

  sign: (f) => {
    f = +f;

    return (f >= 0) ? 1 : -1;
  },

  sin: Math.sin,

  smoothDamp: () => {},

  smoothDampAngle: () => {},

  smoothStep: () => {},

  sqrt: Math.sqrt,

  tan: Math.tan

};

module.exports = Mathf;
<commit_msg>add methods: * gammaToLinear * inverseLerp * lerp * linearToGammaSpace<commit_after>'use strict';

let Mathf = {
  Deg2Rad: (Math.PI * 2) / 360,

  Epsilon: Number.EPSILON || Math.pow(2, -52),

  Infinity: Infinity,

  NegativeInfinity: -Infinity,

  PI: Math.PI,

  Rad2Deg: 360 / (Math.PI * 2),

  abs: Math.abs,

  acos: Math.acos,

  approximately: (f1, f2) => {
    return Mathf.abs(f1 - f2) < Mathf.Epsilon;
  },

  asin: Math.asin,

  atan: Math.atan,

  atan2: Math.atan2,

  ceil: Math.ceil,

  clamp: (value, min, max) => {
    return value < min ? min : (value > max ? max : value);
  },

  clamp01: (value) => {
    return value < 0 ? 0 : (value > 1 ? 1 : value);
  },

  closestPowerOfTwo: (value) => {
    let closestValue = 1;

    if (value <= 2) return value;

    while (closestValue <= value) {
      closestValue *= 2;
      if (value < closestValue / 2 + closestValue) {
        break;
      }
    }

    return closestValue;
  },

  cos: Math.cos,

  deltaAngle: (current, target) => {
    if (current > 360) {
      current %= 360;
    }

    if (target > 360) {
      target %= 360;
    }

    return target - current;
  },

  exp: Math.exp,

  floor: Math.floor,

  gammaToLinearSpace: (value) => {
    return Math.pow(value, 2.2);
  },

  inverseLerp: (min, max, value) => {
    return (Mathf.clamp(value, Mathf.min(min, max), Mathf.max(min, max)) - min) / (max - min);
  },

  isPowerOfTwo: () => {},

  lerp: (a, b, t) => {
    return (b - a) * Mathf.clamp01(t) + a;
  },

  lerpAngle: () => {},

  lerpUnclamped: () => {},

  linearToGammaSpace: (value) => {
    return Math.pow(value, 0.45454545);
  },

  log: Math.log,

  log10: Math.log10,

  max: Math.max,

  min: Math.min,

  moveTowards: () => {},

  moveTowardsAngle: () => {},

  nextPowerOfTwo: () => {},

  perlinNoise: () => {},

  pingPong: () => {},

  pow: Math.pow,

  repeat: () => {},

  round: (num) => {
    let ceilVal = num + 0.5;

    if (ceilVal === Math.ceil(num)) {
      return (ceilVal % 2 === 0) ? num + 0.5 : num - 0.5;
    }

    return Math.round(num);
  },

  sign: (f) => {
    f = +f;

    return (f >= 0) ? 1 : -1;
  },

  sin: Math.sin,

  smoothDamp: () => {},

  smoothDampAngle: () => {},

  smoothStep: () => {},

  sqrt: Math.sqrt,

  tan: Math.tan

};

module.exports = Mathf;
<|endoftext|>


<commit_before>var when = require('when');

var extensions = {
    start: function(promise, boot) {
        var step = 0, state = {}, steps = this.steps;
        function next(/* error, arguments... */) {
            var fn = steps[step++]
                , args = Array.prototype.slice.call(arguments)
                , err = args.shift();
            if (err) {
                promise.reject(err);
                return;
            }
            if (!fn) {
                promise.resolve(args.shift());
                return;
            }
            args.push(next);
            try {
                fn.apply(state, args);
            }
            catch(e) {
                promise.reject(e);
            }
        }
        boot.unshift(null);
        next.apply(state, boot);
    }
};

exports.sequential = function (/* functions... */) {
    function flow() {
        var p = when.defer();
        flow.start(p, Array.prototype.slice.call(arguments));
        return p.promise;
    }
    flow.start = extensions.start;
    flow.steps = Array.prototype.slice.call(arguments);
    return flow;
};<commit_msg>add done()<commit_after>var when = require('when');

var extensions = {

    sequential: function(promise, boot) {
        var step = 0, state = {}, steps = this.steps;
        function done(result) {
            promise.resolve(result);
        }
        function next(/* error, arguments... */) {
            var fn = steps[step++]
                , args = Array.prototype.slice.call(arguments)
                , err = args.shift();
            if (err) {
                promise.reject(err);
                return;
            }
            if (!fn) {
                promise.resolve(args.shift());
                return;
            }
            args.push(next);
            args.push(done);
            try {
                fn.apply(state, args);
            }
            catch(e) {
                promise.reject(e);
            }
        }
        boot.unshift(null);
        next.apply(state, boot);
    }

};

exports.sequential = function (/* functions... */) {
    function flow() {
        var p = when.defer();
        flow.sequential(p, Array.prototype.slice.call(arguments));
        return p.promise;
    }
    flow.sequential = extensions.sequential;
    flow.steps = Array.prototype.slice.call(arguments);
    return flow;
};
<|endoftext|>


<commit_before><commit_msg>add header setter function option<commit_after><|endoftext|>


<commit_before>const fs = require('fs-extra');
const { join } = require('path');
const tmp = require('tmp-promise');
const Git = require('simple-git/promise');

class Storage {
  constructor() {
    let config = {};
    let git = null;
    let repoDir = null;

    Object.assign(this, {
      initRepo,
      cleanRepo,
      setBaseBranch,
      branchExists,
      commitFilesToBranch,
      createBranch,
      deleteBranch,
      getAllRenovateBranches,
      getBranchCommit,
      getBranchLastCommitTime,
      getCommitMessages,
      getFile,
      getFileList,
      isBranchStale,
      mergeBranch,
    });

    async function initRepo(args) {
      cleanRepo();
      logger.info('Git FS mode enabled');
      config = { ...args };
      repoDir = await tmp.dir({ unsafeCleanup: true });
      git = Git(repoDir.path).silent(true);
      await git.clone(config.url, '.');

      if (config.gitAuthor) {
        await git.raw(['config', 'user.name', config.gitAuthor.name]);
        await git.raw(['config', 'user.email', config.gitAuthor.address]);
        // not supported yet
        await git.raw(['config', 'commit.gpgsign', 'false']);
      }

      // see https://stackoverflow.com/a/44750379/1438522
      config.baseBranch =
        config.baseBranch ||
        (await git.raw(['symbolic-ref', 'refs/remotes/origin/HEAD']))
          .replace('refs/remotes/origin/', '')
          .trim();
    }

    async function createBranch(branchName, sha) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, sha]);
      await git.push(['origin', branchName, '--force']);
    }

    // Return the commit SHA for a branch
    async function getBranchCommit(branchName) {
      const res = await git.revparse(['origin/' + branchName]);
      return res.trim();
    }

    async function getCommitMessages() {
      logger.debug('getCommitMessages');
      const res = await git.log({
        n: 10,
        format: { message: '%s' },
      });
      return res.all.map(commit => commit.message);
    }

    function setBaseBranch(branchName) {
      if (branchName) {
        logger.debug(`Setting baseBranch to ${branchName}`);
        config.baseBranch = branchName;
      }
    }

    async function getFileList(branchName) {
      const branch = branchName || config.baseBranch;
      const exists = await branchExists(branch);
      if (!exists) {
        return [];
      }
      const files = await git.raw([
        'ls-tree',
        '-r',
        '--name-only',
        'origin/' + branch,
      ]);
      return files.split('\n').filter(Boolean);
    }

    async function branchExists(branchName) {
      try {
        await git.raw(['show-branch', 'origin/' + branchName]);
        return true;
      } catch (ex) {
        return false;
      }
    }

    async function getAllRenovateBranches(branchPrefix) {
      const branches = await git.branch(['--remotes', '--verbose']);
      return branches.all
        .map(localName)
        .filter(branchName => branchName.startsWith(branchPrefix));
    }

    async function isBranchStale(branchName) {
      const branches = await git.branch([
        '--remotes',
        '--verbose',
        '--contains',
        config.baseBranch,
      ]);
      return !branches.all.map(localName).includes(branchName);
    }

    async function deleteBranch(branchName) {
      await git.raw(['push', '--delete', 'origin', branchName]);
      try {
        await git.deleteLocalBranch(branchName);
      } catch (ex) {
        // local branch may not exist
      }
    }

    async function mergeBranch(branchName) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, 'origin/' + branchName]);
      await git.checkout(config.baseBranch);
      await git.merge([branchName]);
      await git.push('origin', config.baseBranch);
    }

    async function getBranchLastCommitTime(branchName) {
      try {
        const time = await git.show([
          '-s',
          '--format=%ai',
          'origin/' + branchName,
        ]);
        return new Date(Date.parse(time));
      } catch (ex) {
        return new Date();
      }
    }

    async function getFile(filePath, branchName) {
      if (branchName) {
        const exists = await branchExists(branchName);
        if (!exists) {
          logger.warn({ branchName }, 'getFile branch does not exist');
          return null;
        }
      }
      try {
        const content = await git.show([
          'origin/' + (branchName || config.baseBranch) + ':' + filePath,
        ]);
        return content;
      } catch (ex) {
        return null;
      }
    }

    async function commitFilesToBranch(
      branchName,
      files,
      message,
      parentBranch = config.baseBranch
    ) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, 'origin/' + parentBranch]);
      for (const file of files) {
        await fs.writeFile(
          join(repoDir.path, file.name),
          Buffer.from(file.contents)
        );
      }
      await git.add(files.map(f => f.name));
      await git.commit(message);
      await git.push(['origin', branchName, '--force']);
    }

    function cleanRepo() {
      if (repoDir) {
        repoDir.cleanup();
        repoDir = null;
      }
    }
  }
}

function localName(branchName) {
  return branchName.replace(/^origin\//, '');
}

module.exports = Storage;
<commit_msg>refactor(gitfs): clone depth 2<commit_after>const fs = require('fs-extra');
const { join } = require('path');
const tmp = require('tmp-promise');
const Git = require('simple-git/promise');

class Storage {
  constructor() {
    let config = {};
    let git = null;
    let repoDir = null;

    Object.assign(this, {
      initRepo,
      cleanRepo,
      setBaseBranch,
      branchExists,
      commitFilesToBranch,
      createBranch,
      deleteBranch,
      getAllRenovateBranches,
      getBranchCommit,
      getBranchLastCommitTime,
      getCommitMessages,
      getFile,
      getFileList,
      isBranchStale,
      mergeBranch,
    });

    async function initRepo(args) {
      cleanRepo();
      logger.info('Git FS mode enabled');
      config = { ...args };
      repoDir = await tmp.dir({ unsafeCleanup: true });
      git = Git(repoDir.path).silent(true);
      await git.clone(config.url, '.', ['--depth=2', '--no-single-branch']);

      if (config.gitAuthor) {
        await git.raw(['config', 'user.name', config.gitAuthor.name]);
        await git.raw(['config', 'user.email', config.gitAuthor.address]);
        // not supported yet
        await git.raw(['config', 'commit.gpgsign', 'false']);
      }

      // see https://stackoverflow.com/a/44750379/1438522
      config.baseBranch =
        config.baseBranch ||
        (await git.raw(['symbolic-ref', 'refs/remotes/origin/HEAD']))
          .replace('refs/remotes/origin/', '')
          .trim();
    }

    async function createBranch(branchName, sha) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, sha]);
      await git.push(['origin', branchName, '--force']);
    }

    // Return the commit SHA for a branch
    async function getBranchCommit(branchName) {
      const res = await git.revparse(['origin/' + branchName]);
      return res.trim();
    }

    async function getCommitMessages() {
      logger.debug('getCommitMessages');
      const res = await git.log({
        n: 10,
        format: { message: '%s' },
      });
      return res.all.map(commit => commit.message);
    }

    function setBaseBranch(branchName) {
      if (branchName) {
        logger.debug(`Setting baseBranch to ${branchName}`);
        config.baseBranch = branchName;
      }
    }

    async function getFileList(branchName) {
      const branch = branchName || config.baseBranch;
      const exists = await branchExists(branch);
      if (!exists) {
        return [];
      }
      const files = await git.raw([
        'ls-tree',
        '-r',
        '--name-only',
        'origin/' + branch,
      ]);
      return files.split('\n').filter(Boolean);
    }

    async function branchExists(branchName) {
      try {
        await git.raw(['show-branch', 'origin/' + branchName]);
        return true;
      } catch (ex) {
        return false;
      }
    }

    async function getAllRenovateBranches(branchPrefix) {
      const branches = await git.branch(['--remotes', '--verbose']);
      return branches.all
        .map(localName)
        .filter(branchName => branchName.startsWith(branchPrefix));
    }

    async function isBranchStale(branchName) {
      const branches = await git.branch([
        '--remotes',
        '--verbose',
        '--contains',
        config.baseBranch,
      ]);
      return !branches.all.map(localName).includes(branchName);
    }

    async function deleteBranch(branchName) {
      await git.raw(['push', '--delete', 'origin', branchName]);
      try {
        await git.deleteLocalBranch(branchName);
      } catch (ex) {
        // local branch may not exist
      }
    }

    async function mergeBranch(branchName) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, 'origin/' + branchName]);
      await git.checkout(config.baseBranch);
      await git.merge([branchName]);
      await git.push('origin', config.baseBranch);
    }

    async function getBranchLastCommitTime(branchName) {
      try {
        const time = await git.show([
          '-s',
          '--format=%ai',
          'origin/' + branchName,
        ]);
        return new Date(Date.parse(time));
      } catch (ex) {
        return new Date();
      }
    }

    async function getFile(filePath, branchName) {
      if (branchName) {
        const exists = await branchExists(branchName);
        if (!exists) {
          logger.warn({ branchName }, 'getFile branch does not exist');
          return null;
        }
      }
      try {
        const content = await git.show([
          'origin/' + (branchName || config.baseBranch) + ':' + filePath,
        ]);
        return content;
      } catch (ex) {
        return null;
      }
    }

    async function commitFilesToBranch(
      branchName,
      files,
      message,
      parentBranch = config.baseBranch
    ) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, 'origin/' + parentBranch]);
      for (const file of files) {
        await fs.writeFile(
          join(repoDir.path, file.name),
          Buffer.from(file.contents)
        );
      }
      await git.add(files.map(f => f.name));
      await git.commit(message);
      await git.push(['origin', branchName, '--force']);
    }

    function cleanRepo() {
      if (repoDir) {
        repoDir.cleanup();
        repoDir = null;
      }
    }
  }
}

function localName(branchName) {
  return branchName.replace(/^origin\//, '');
}

module.exports = Storage;
<|endoftext|>


<commit_before><commit_msg>export all the things<commit_after><|endoftext|>


<commit_before>const fs = require('fs-extra');
const { join } = require('path');
const path = require('path');
const URL = require('url');
const Git = require('simple-git/promise');
const convertHrtime = require('convert-hrtime');

class Storage {
  constructor() {
    let config = {};
    let git = null;
    let cwd = null;

    Object.assign(this, {
      initRepo,
      cleanRepo,
      getRepoStatus,
      setBaseBranch,
      branchExists,
      commitFilesToBranch,
      createBranch,
      deleteBranch,
      getAllRenovateBranches,
      getBranchCommit,
      getBranchLastCommitTime,
      getCommitMessages,
      getFile,
      getFileList,
      isBranchStale,
      mergeBranch,
    });

    // istanbul ignore next
    async function resetToBranch(branchName) {
      await git.raw(['reset', '--hard']);
      await git.checkout(branchName);
      await git.raw(['reset', '--hard', 'origin/' + branchName]);
    }

    // istanbul ignore next
    async function cleanLocalBranches() {
      const existingBranches = (await git.raw(['branch']))
        .split('\n')
        .map(branch => branch.trim())
        .filter(branch => branch.length)
        .filter(branch => !branch.startsWith('* '));
      logger.debug({ existingBranches });
      for (const branchName of existingBranches) {
        await deleteLocalBranch(branchName);
      }
    }

    async function initRepo(args) {
      cleanRepo();
      config = { ...args };
      cwd = config.localDir;
      logger.info('Initialising git repository into ' + cwd);
      const gitHead = path.join(cwd, '.git/HEAD');
      let clone = true;
      async function determineBaseBranch() {
        // see https://stackoverflow.com/a/44750379/1438522
        config.baseBranch =
          config.baseBranch ||
          (await git.raw(['symbolic-ref', 'refs/remotes/origin/HEAD']))
            .replace('refs/remotes/origin/', '')
            .trim();
      }
      // istanbul ignore if
      if (process.env.NODE_ENV !== 'test' && (await fs.exists(gitHead))) {
        try {
          git = Git(cwd).silent(true);
          await git.raw(['remote', 'set-url', 'origin', config.url]);
          const fetchStart = process.hrtime();
          await git.fetch(config.url, ['--depth=2', '--no-single-branch']);
          await determineBaseBranch();
          await resetToBranch(config.baseBranch);
          await cleanLocalBranches();
          await git.raw(['remote', 'prune', 'origin']);
          const fetchSeconds =
            Math.round(
              1 + 10 * convertHrtime(process.hrtime(fetchStart)).seconds
            ) / 10;
          logger.info({ fetchSeconds }, 'git fetch completed');
          clone = false;
        } catch (err) {
          logger.error({ err }, 'git fetch error');
        }
      }
      if (clone) {
        await fs.emptyDir(cwd);
        git = Git(cwd).silent(true);
        const cloneStart = process.hrtime();
        try {
          await git.clone(config.url, '.', ['--depth=2', '--no-single-branch']);
        } catch (err) /* istanbul ignore next */ {
          logger.debug({ err }, 'git clone error');
          throw new Error('platform-failure');
        }
        const cloneSeconds =
          Math.round(
            1 + 10 * convertHrtime(process.hrtime(cloneStart)).seconds
          ) / 10;
        logger.info({ cloneSeconds }, 'git clone completed');
      }

      if (config.gitAuthor) {
        await git.raw(['config', 'user.name', config.gitAuthor.name]);
        await git.raw(['config', 'user.email', config.gitAuthor.address]);
        // not supported yet
        await git.raw(['config', 'commit.gpgsign', 'false']);
      }

      await determineBaseBranch();
    }

    // istanbul ignore next
    function getRepoStatus() {
      return git.status();
    }

    async function createBranch(branchName, sha) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, sha]);
      await git.push(['origin', branchName, '--force']);
    }

    // Return the commit SHA for a branch
    async function getBranchCommit(branchName) {
      const res = await git.revparse(['origin/' + branchName]);
      return res.trim();
    }

    async function getCommitMessages() {
      logger.debug('getCommitMessages');
      const res = await git.log({
        n: 10,
        format: { message: '%s' },
      });
      return res.all.map(commit => commit.message);
    }

    async function setBaseBranch(branchName) {
      if (branchName) {
        logger.debug(`Setting baseBranch to ${branchName}`);
        config.baseBranch = branchName;
        if (branchName !== 'master') {
          config.baseBranchSha = (await git.raw([
            'rev-parse',
            'origin/' + branchName,
          ])).trim();
        }
      }
    }

    async function getFileList(branchName) {
      const branch = branchName || config.baseBranch;
      const exists = await branchExists(branch);
      if (!exists) {
        return [];
      }
      const files = await git.raw([
        'ls-tree',
        '-r',
        '--name-only',
        'origin/' + branch,
      ]);
      // istanbul ignore if
      if (!files) {
        return [];
      }
      return files.split('\n').filter(Boolean);
    }

    async function branchExists(branchName) {
      try {
        await git.raw(['show-branch', 'origin/' + branchName]);
        return true;
      } catch (ex) {
        return false;
      }
    }

    async function getAllRenovateBranches(branchPrefix) {
      const branches = await git.branch(['--remotes', '--verbose']);
      return branches.all
        .map(localName)
        .filter(branchName => branchName.startsWith(branchPrefix));
    }

    async function isBranchStale(branchName) {
      const branches = await git.branch([
        '--remotes',
        '--verbose',
        '--contains',
        config.baseBranchSha || config.baseBranch,
      ]);
      return !branches.all.map(localName).includes(branchName);
    }

    async function deleteLocalBranch(branchName) {
      await git.branch(['-D', branchName]);
    }

    async function deleteBranch(branchName) {
      try {
        await git.raw(['push', '--delete', 'origin', branchName]);
        logger.debug({ branchName }, 'Deleted remote branch');
      } catch (err) /* istanbul ignore next */ {
        logger.info({ branchName, err }, 'Error deleting remote branch');
        throw new Error('repository-changed');
      }
      try {
        await deleteLocalBranch(branchName);
        // istanbul ignore next
        logger.debug({ branchName }, 'Deleted local branch');
      } catch (err) {
        logger.debug({ branchName }, 'No local branch to delete');
      }
    }

    async function mergeBranch(branchName) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, 'origin/' + branchName]);
      await git.checkout(config.baseBranch);
      await git.merge([branchName]);
      await git.push('origin', config.baseBranch);
    }

    async function getBranchLastCommitTime(branchName) {
      try {
        const time = await git.show([
          '-s',
          '--format=%ai',
          'origin/' + branchName,
        ]);
        return new Date(Date.parse(time));
      } catch (ex) {
        return new Date();
      }
    }

    async function getFile(filePath, branchName) {
      if (branchName) {
        const exists = await branchExists(branchName);
        if (!exists) {
          logger.info({ branchName }, 'branch no longer exists - aborting');
          throw new Error('repository-changed');
        }
      }
      try {
        const content = await git.show([
          'origin/' + (branchName || config.baseBranch) + ':' + filePath,
        ]);
        return content;
      } catch (ex) {
        return null;
      }
    }

    async function commitFilesToBranch(
      branchName,
      files,
      message,
      parentBranch = config.baseBranch
    ) {
      try {
        await git.reset('hard');
        await git.checkout(['-B', branchName, 'origin/' + parentBranch]);
        for (const file of files) {
          await fs.writeFile(join(cwd, file.name), Buffer.from(file.contents));
        }
        await git.add(files.map(f => f.name));
        await git.commit(message);
        await git.push(['origin', branchName, '--force']);
      } catch (err) /* istanbul ignore next */ {
        logger.debug({ err }, 'Error commiting files');
        if (err.message.includes('[remote rejected]')) {
          throw new Error('repository-changed');
        }
        throw err;
      }
    }

    function cleanRepo() {}
  }
}

function localName(branchName) {
  return branchName.replace(/^origin\//, '');
}

Storage.getUrl = ({ gitFs, auth, hostname, host, repository }) => {
  let protocol = gitFs || 'https';
  // istanbul ignore if
  if (protocol.toString() === 'true') {
    protocol = 'https';
  }
  if (protocol === 'ssh') {
    return `git@${hostname}:${repository}.git`;
  }
  return URL.format({
    protocol,
    auth,
    hostname,
    host,
    pathname: repository + '.git',
  });
};

module.exports = Storage;
<commit_msg>fix(gitFs): set explicit remote branch (#3229)<commit_after>const fs = require('fs-extra');
const { join } = require('path');
const path = require('path');
const URL = require('url');
const Git = require('simple-git/promise');
const convertHrtime = require('convert-hrtime');

class Storage {
  constructor() {
    let config = {};
    let git = null;
    let cwd = null;

    Object.assign(this, {
      initRepo,
      cleanRepo,
      getRepoStatus,
      setBaseBranch,
      branchExists,
      commitFilesToBranch,
      createBranch,
      deleteBranch,
      getAllRenovateBranches,
      getBranchCommit,
      getBranchLastCommitTime,
      getCommitMessages,
      getFile,
      getFileList,
      isBranchStale,
      mergeBranch,
    });

    // istanbul ignore next
    async function resetToBranch(branchName) {
      await git.raw(['reset', '--hard']);
      await git.checkout(branchName);
      await git.raw(['reset', '--hard', 'origin/' + branchName]);
    }

    // istanbul ignore next
    async function cleanLocalBranches() {
      const existingBranches = (await git.raw(['branch']))
        .split('\n')
        .map(branch => branch.trim())
        .filter(branch => branch.length)
        .filter(branch => !branch.startsWith('* '));
      logger.debug({ existingBranches });
      for (const branchName of existingBranches) {
        await deleteLocalBranch(branchName);
      }
    }

    async function initRepo(args) {
      cleanRepo();
      config = { ...args };
      cwd = config.localDir;
      logger.info('Initialising git repository into ' + cwd);
      const gitHead = path.join(cwd, '.git/HEAD');
      let clone = true;
      async function determineBaseBranch() {
        // see https://stackoverflow.com/a/44750379/1438522
        config.baseBranch =
          config.baseBranch ||
          (await git.raw(['symbolic-ref', 'refs/remotes/origin/HEAD']))
            .replace('refs/remotes/origin/', '')
            .trim();
      }
      // istanbul ignore if
      if (process.env.NODE_ENV !== 'test' && (await fs.exists(gitHead))) {
        try {
          git = Git(cwd).silent(true);
          await git.raw(['remote', 'set-url', 'origin', config.url]);
          const fetchStart = process.hrtime();
          await git.fetch(config.url, ['--depth=2', '--no-single-branch']);
          await determineBaseBranch();
          await resetToBranch(config.baseBranch);
          await cleanLocalBranches();
          await git.raw(['remote', 'prune', 'origin']);
          const fetchSeconds =
            Math.round(
              1 + 10 * convertHrtime(process.hrtime(fetchStart)).seconds
            ) / 10;
          logger.info({ fetchSeconds }, 'git fetch completed');
          clone = false;
        } catch (err) {
          logger.error({ err }, 'git fetch error');
        }
      }
      if (clone) {
        await fs.emptyDir(cwd);
        git = Git(cwd).silent(true);
        const cloneStart = process.hrtime();
        try {
          await git.clone(config.url, '.', ['--depth=2', '--no-single-branch']);
        } catch (err) /* istanbul ignore next */ {
          logger.debug({ err }, 'git clone error');
          throw new Error('platform-failure');
        }
        const cloneSeconds =
          Math.round(
            1 + 10 * convertHrtime(process.hrtime(cloneStart)).seconds
          ) / 10;
        logger.info({ cloneSeconds }, 'git clone completed');
      }

      if (config.gitAuthor) {
        await git.raw(['config', 'user.name', config.gitAuthor.name]);
        await git.raw(['config', 'user.email', config.gitAuthor.address]);
        // not supported yet
        await git.raw(['config', 'commit.gpgsign', 'false']);
      }

      await determineBaseBranch();
    }

    // istanbul ignore next
    function getRepoStatus() {
      return git.status();
    }

    async function createBranch(branchName, sha) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, sha]);
      await git.push(['origin', branchName, '--force']);
    }

    // Return the commit SHA for a branch
    async function getBranchCommit(branchName) {
      const res = await git.revparse(['origin/' + branchName]);
      return res.trim();
    }

    async function getCommitMessages() {
      logger.debug('getCommitMessages');
      const res = await git.log({
        n: 10,
        format: { message: '%s' },
      });
      return res.all.map(commit => commit.message);
    }

    async function setBaseBranch(branchName) {
      if (branchName) {
        logger.debug(`Setting baseBranch to ${branchName}`);
        config.baseBranch = branchName;
        if (branchName !== 'master') {
          config.baseBranchSha = (await git.raw([
            'rev-parse',
            'origin/' + branchName,
          ])).trim();
        }
      }
    }

    async function getFileList(branchName) {
      const branch = branchName || config.baseBranch;
      const exists = await branchExists(branch);
      if (!exists) {
        return [];
      }
      const files = await git.raw([
        'ls-tree',
        '-r',
        '--name-only',
        'origin/' + branch,
      ]);
      // istanbul ignore if
      if (!files) {
        return [];
      }
      return files.split('\n').filter(Boolean);
    }

    async function branchExists(branchName) {
      try {
        await git.raw(['show-branch', 'origin/' + branchName]);
        return true;
      } catch (ex) {
        return false;
      }
    }

    async function getAllRenovateBranches(branchPrefix) {
      const branches = await git.branch(['--remotes', '--verbose']);
      return branches.all
        .map(localName)
        .filter(branchName => branchName.startsWith(branchPrefix));
    }

    async function isBranchStale(branchName) {
      const branches = await git.branch([
        '--remotes',
        '--verbose',
        '--contains',
        config.baseBranchSha || config.baseBranch,
      ]);
      return !branches.all.map(localName).includes(branchName);
    }

    async function deleteLocalBranch(branchName) {
      await git.branch(['-D', branchName]);
    }

    async function deleteBranch(branchName) {
      try {
        await git.raw(['push', '--delete', 'origin', branchName]);
        logger.debug({ branchName }, 'Deleted remote branch');
      } catch (err) /* istanbul ignore next */ {
        logger.info({ branchName, err }, 'Error deleting remote branch');
        throw new Error('repository-changed');
      }
      try {
        await deleteLocalBranch(branchName);
        // istanbul ignore next
        logger.debug({ branchName }, 'Deleted local branch');
      } catch (err) {
        logger.debug({ branchName }, 'No local branch to delete');
      }
    }

    async function mergeBranch(branchName) {
      await git.reset('hard');
      await git.checkout(['-B', branchName, 'origin/' + branchName]);
      await git.checkout(config.baseBranch);
      await git.merge([branchName]);
      await git.push('origin', config.baseBranch);
    }

    async function getBranchLastCommitTime(branchName) {
      try {
        const time = await git.show([
          '-s',
          '--format=%ai',
          'origin/' + branchName,
        ]);
        return new Date(Date.parse(time));
      } catch (ex) {
        return new Date();
      }
    }

    async function getFile(filePath, branchName) {
      if (branchName) {
        const exists = await branchExists(branchName);
        if (!exists) {
          logger.info({ branchName }, 'branch no longer exists - aborting');
          throw new Error('repository-changed');
        }
      }
      try {
        const content = await git.show([
          'origin/' + (branchName || config.baseBranch) + ':' + filePath,
        ]);
        return content;
      } catch (ex) {
        return null;
      }
    }

    async function commitFilesToBranch(
      branchName,
      files,
      message,
      parentBranch = config.baseBranch
    ) {
      try {
        await git.reset('hard');
        await git.checkout(['-B', branchName, 'origin/' + parentBranch]);
        for (const file of files) {
          await fs.writeFile(join(cwd, file.name), Buffer.from(file.contents));
        }
        await git.add(files.map(f => f.name));
        await git.commit(message);
        await git.push([
          'origin',
          `${branchName}:${branchName}`,
          '--force',
          '-u',
        ]);
      } catch (err) /* istanbul ignore next */ {
        logger.debug({ err }, 'Error commiting files');
        if (err.message.includes('[remote rejected]')) {
          throw new Error('repository-changed');
        }
        throw err;
      }
    }

    function cleanRepo() {}
  }
}

function localName(branchName) {
  return branchName.replace(/^origin\//, '');
}

Storage.getUrl = ({ gitFs, auth, hostname, host, repository }) => {
  let protocol = gitFs || 'https';
  // istanbul ignore if
  if (protocol.toString() === 'true') {
    protocol = 'https';
  }
  if (protocol === 'ssh') {
    return `git@${hostname}:${repository}.git`;
  }
  return URL.format({
    protocol,
    auth,
    hostname,
    host,
    pathname: repository + '.git',
  });
};

module.exports = Storage;
<|endoftext|>


<commit_before><commit_msg>create folder, repeat task to download new chapters<commit_after><|endoftext|>


<commit_before><commit_msg>Tweaks (#130)<commit_after><|endoftext|>


<commit_before><commit_msg>use .bind()<commit_after><|endoftext|>


<commit_before><commit_msg>add 'text' property to returned attributes<commit_after><|endoftext|>


<commit_before><commit_msg>Don't try to get the undefined file<commit_after><|endoftext|>


<commit_before><commit_msg>Remove destructuring of core modules<commit_after><|endoftext|>


<commit_before><commit_msg>🆙 init state prior to call mutations + setup simple config options<commit_after><|endoftext|>


<commit_before><commit_msg>dont use isArray<commit_after><|endoftext|>


<commit_before>define( [
    'jquery',
    'underscore',
    'backbone',
    'd3',
    ],
function ($, _, Backbone, d3) {

  var BarChart = Backbone.View.extend({

  initialize: function(options) {

    var t = this;
    t.graph_config = t.options.graph_config;
    t.raw_data = t.options.raw_data;

    // Transform raw data to format needed by D3.
    t.data = t.map_raw_data(t.raw_data)

    var width = t.$el.width(),
      height = t.$el.height();

    t.x = d3.scale.linear()
        .domain([0, d3.max(t.data, function(d) { return d.val; })])
        .range(["0px", 0.8 * width + 'px']),

    t.chart = d3.select(t.el).append("div")
      .attr("class", "qgr-graph-barchart")
      .style("padding-top", height/3 + 'px');

    t.chart.selectAll("div")
      .data(t.data)
      .enter().append("div")
      .style("width", function(d) { return t.x(d.val); })
      .text(function(d) { return d.label + ': ' + d.val; });

  },

  update: function(raw_data){

    var t = this;

    t.raw_data = raw_data;

    t.data = t.map_raw_data(t.raw_data)

    var bar = t.chart.selectAll("div")
      .data(t.data)

    bar
      .enter()
      .append("div")
      .style("width", 0)
      .transition()
      .duration(500)
      .style("width", function(d) { return t.x(d.val); })
      .text(function(d) { return d.label + ': ' + d.val; });

    bar
      .transition()
      .style("width", function(d) { return t.x(d.val); })
      .text(function(d) { return d.label + ': ' + d.val; });

    bar
      .exit()
      .transition()
      .duration(500)
      .style("width", "0px")
      .remove()

  },

  map_raw_data: function(raw_data) {
    return _.map(raw_data, function(row) {
      return {
        val: row.val,
        label: row.species
      };
    });
  }

});

return BarChart;

});

<commit_msg>Get label from config object<commit_after>define( [
    'jquery',
    'underscore',
    'backbone',
    'd3',
    ],
function ($, _, Backbone, d3) {

  var BarChart = Backbone.View.extend({

  initialize: function(options) {

    var t = this;
    t.config = t.options.graph_config;
    t.raw_data = t.options.raw_data;

    // Transform raw data to format needed by D3.
    t.data = t.map_raw_data(t.raw_data, t.config.label)

    var width = t.$el.width(),
      height = t.$el.height();

    t.x = d3.scale.linear()
        .domain([0, d3.max(t.data, function(d) { return d.val; })])
        .range(["0px", 0.8 * width + 'px']),

    t.chart = d3.select(t.el).append("div")
      .attr("class", "qgr-graph-barchart")
      .style("padding-top", height/3 + 'px');

    t.chart.selectAll("div")
      .data(t.data)
      .enter().append("div")
      .style("width", function(d) { return t.x(d.val); })
      .text(function(d) { return d.label + ': ' + d.val; });

  },

  update: function(raw_data){

    var t = this;

    t.raw_data = raw_data;

    t.data = t.map_raw_data(t.raw_data, t.config.label)

    var bar = t.chart.selectAll("div")
      .data(t.data)

    bar
      .enter()
      .append("div")
      .style("width", 0)
      .transition()
      .duration(500)
      .style("width", function(d) { return t.x(d.val); })
      .text(function(d) { return d.label + ': ' + d.val; });

    bar
      .transition()
      .style("width", function(d) { return t.x(d.val); })
      .text(function(d) { return d.label + ': ' + d.val; });

    bar
      .exit()
      .transition()
      .duration(500)
      .style("width", "0px")
      .remove()

  },

  map_raw_data: function(raw_data, label_col) {
    return _.map(raw_data, function(row) {
      return {
        val: row.val,
        label: row[label_col]
      };
    });
  }

});

return BarChart;

});

<|endoftext|>


<commit_before>import styles  from '../Style/style.js'
import React, { Component } from 'react'
import MapView from 'react-native-maps'
import { View, StyleSheet, TextInput, Alert } from 'react-native'
import CreateLocation from './CreateLocation'
import ProfileView from './ProfileView'
import LocationListView from './LocationListView'

export default class HomeMap extends Component {
  constructor(props) {
    super(props)
    this.state = {
      currentUser: {},
      currentLocation: {
        latitude: 30.2689941,
        longitude: -97.7405441,
        latitudeDelta: 0.1,
        longitudeDelta: 0.1
      },
      nearbyLocations: [],
      searchText: 'Search for spots...',
      lastPosition: {}
    }
    this.addLocation = this.addLocation.bind(this)
    this.cancelLocationAdd = this.cancelLocationAdd.bind(this)
  }

  componentDidMount () {
    fetch('http://localhost:3000/auth/login', {
      method: 'GET',
      headers:{
         'Accept': 'application/json',
         'Content-Type': 'application/json',
         'Authorization': this.props.userToken
      }
    })
    .then( (response) => {
      console.log("response: ", response)
      return response.json()
    })
    .then( (data) => {
      console.log("DATA: ", data)
      this.setState({currentUser: data})
    })
    .catch( (err) => {
      console.log(err)
    })

    navigator.geolocation.getCurrentPosition(
      (position) => {
        let currentLocation = {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01
        }
        console.log('got here')
        this.setState({currentLocation: currentLocation})

        fetch(`http://localhost:3000/locations/bycoords?long=${position.coords.longitude}&lat=${position.coords.latitude}`)
          .then((response) => response.json())
          .then((locations) => {

            const nearby = []

            locations.forEach(function(location) {
              let loca = {}
              loca.coordinate = {
                latitude: location.loc[1],
                longitude: location.loc[0]
              }
              loca.title = location.address
              loca.description = location.description
              nearby.push(loca)
            })

            this.setState({nearbyLocations: nearby})
          })
          .catch((err) => {
            console.log('err', err)
          })
      },
      (error) => alert(error.message),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    )

    //Probably not needed for now
    // this.watchID = navigator.geolocation.watchPosition((position) => {
    //   let lastPosition = JSON.stringify(position);
    //   this.setState({lastPosition});
    // })
    // console.log('watchID: ',this.watchID)
  }

  searchLocationSubmit (event) {
    let searchString = event.nativeEvent.text
    fetch(`http://localhost:3000/locations/byaddr?q=${searchString}`)
      .then((response) => response.json())
      .then((locationsAndCoords) => {

        if (!locationsAndCoords.coords) {
          Alert.alert(
          'Try Again',
          'No address found at that location',
          {text: 'OK', onPress: () => console.log('OK Pressed')}
        )

        } else {
          console.log('thisiisisi',locationsAndCoords)
          if (locationsAndCoords.locations.length === 0) {
            Alert.alert(
              'Sorry',
              'No parking spots found near that address',
              {text: 'OK', onPress: () => console.log('OK Pressed')}
            )
          }

          const nearby = []

          locationsAndCoords.locations.forEach(function(location) {
            let loca = {}
            loca.coordinate = {
              latitude: location.loc[1],
              longitude: location.loc[0]
            }
            loca.title = location.address
            loca.description = location.description
            nearby.push(loca)
          })

          this.setState({
            nearbyLocations: nearby,
            currentLocation: {
              latitude: locationsAndCoords.coords[0],
              longitude: locationsAndCoords.coords[1],
              latitudeDelta: 0.01,
              longitudeDelta: 0.01
            }
          })
        }

      })
      .catch((err) => {
        console.log('err', err)
      })
  }

  //adds a pins to the map if the user opens the create location form
  addLocation () {
    let lat = this.state.currentLocation.latitude
    let long = this.state.currentLocation.longitude

    let newPin = {
      coordinate: {
        latitude: lat,
        longitude: long
      }
    }

    let newNearby = this.state.nearbyLocations.slice()

    newNearby.push(newPin)
    this.setState({
      nearbyLocations: newNearby
    })
  }

  //Removes the pin from the map if the user does not save the new location
  cancelLocationAdd () {
    let nearby = this.state.nearbyLocations.slice()
    nearby.pop()
    this.setState({
      nearbyLocations: nearby
    })
  }

  render () {
    console.log("HomeMap.js this.props: ", this.state.currentUser)
    return (
      <View style={styles.container}>
        <TextInput
          returnKeyType="search"
          style={styles.searchBar}
          onChangeText={(text) => this.setState({text})}
          placeholder={this.state.searchText}
          onSubmitEditing={(event) => this.searchLocationSubmit(event)}
        />
        <MapView
          style={styles.homeMap}
          region={this.state.currentLocation}
          style={{height: 500, width: 300}}
          showsUserLocation={true}
        >
          {this.state.nearbyLocations.map((marker, key) => (
            <MapView.Marker
              key={key}
              coordinate={marker.coordinate}
              title={marker.title}
              description={marker.description}
            />
          ))}
        </MapView>

        <LocationListView
          nearbyLocations={this.state.nearbyLocations}
        />

        <CreateLocation
          addLocation={this.addLocation}
          cancelLocationAdd={this.cancelLocationAdd}
          currentLocation={this.state.currentLocation}
        />
      <ProfileView currentUser={this.props.currentUser} />
      </View>
    )
  }
}<commit_msg>removes unneeded style<commit_after>import styles  from '../Style/style.js'
import React, { Component } from 'react'
import MapView from 'react-native-maps'
import { View, StyleSheet, TextInput, Alert } from 'react-native'
import CreateLocation from './CreateLocation'
import ProfileView from './ProfileView'
import LocationListView from './LocationListView'

export default class HomeMap extends Component {
  constructor(props) {
    super(props)
    this.state = {
      currentUser: {},
      currentLocation: {
        latitude: 30.2689941,
        longitude: -97.7405441,
        latitudeDelta: 0.1,
        longitudeDelta: 0.1
      },
      nearbyLocations: [],
      searchText: 'Search for spots...',
      lastPosition: {}
    }
    this.addLocation = this.addLocation.bind(this)
    this.cancelLocationAdd = this.cancelLocationAdd.bind(this)
  }

  componentDidMount () {
    fetch('http://localhost:3000/auth/login', {
      method: 'GET',
      headers:{
         'Accept': 'application/json',
         'Content-Type': 'application/json',
         'Authorization': this.props.userToken
      }
    })
    .then( (response) => {
      console.log("response: ", response)
      return response.json()
    })
    .then( (data) => {
      console.log("DATA: ", data)
      this.setState({currentUser: data})
    })
    .catch( (err) => {
      console.log(err)
    })

    navigator.geolocation.getCurrentPosition(
      (position) => {
        let currentLocation = {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01
        }
        console.log('got here')
        this.setState({currentLocation: currentLocation})

        fetch(`http://localhost:3000/locations/bycoords?long=${position.coords.longitude}&lat=${position.coords.latitude}`)
          .then((response) => response.json())
          .then((locations) => {

            const nearby = []

            locations.forEach(function(location) {
              let loca = {}
              loca.coordinate = {
                latitude: location.loc[1],
                longitude: location.loc[0]
              }
              loca.title = location.address
              loca.description = location.description
              nearby.push(loca)
            })

            this.setState({nearbyLocations: nearby})
          })
          .catch((err) => {
            console.log('err', err)
          })
      },
      (error) => alert(error.message),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    )

    //Probably not needed for now
    // this.watchID = navigator.geolocation.watchPosition((position) => {
    //   let lastPosition = JSON.stringify(position);
    //   this.setState({lastPosition});
    // })
    // console.log('watchID: ',this.watchID)
  }

  searchLocationSubmit (event) {
    let searchString = event.nativeEvent.text
    fetch(`http://localhost:3000/locations/byaddr?q=${searchString}`)
      .then((response) => response.json())
      .then((locationsAndCoords) => {

        if (!locationsAndCoords.coords) {
          Alert.alert(
          'Try Again',
          'No address found at that location',
          {text: 'OK', onPress: () => console.log('OK Pressed')}
        )

        } else {
          console.log('thisiisisi',locationsAndCoords)
          if (locationsAndCoords.locations.length === 0) {
            Alert.alert(
              'Sorry',
              'No parking spots found near that address',
              {text: 'OK', onPress: () => console.log('OK Pressed')}
            )
          }

          const nearby = []

          locationsAndCoords.locations.forEach(function(location) {
            let loca = {}
            loca.coordinate = {
              latitude: location.loc[1],
              longitude: location.loc[0]
            }
            loca.title = location.address
            loca.description = location.description
            nearby.push(loca)
          })

          this.setState({
            nearbyLocations: nearby,
            currentLocation: {
              latitude: locationsAndCoords.coords[0],
              longitude: locationsAndCoords.coords[1],
              latitudeDelta: 0.01,
              longitudeDelta: 0.01
            }
          })
        }

      })
      .catch((err) => {
        console.log('err', err)
      })
  }

  //adds a pins to the map if the user opens the create location form
  addLocation () {
    let lat = this.state.currentLocation.latitude
    let long = this.state.currentLocation.longitude

    let newPin = {
      coordinate: {
        latitude: lat,
        longitude: long
      }
    }

    let newNearby = this.state.nearbyLocations.slice()

    newNearby.push(newPin)
    this.setState({
      nearbyLocations: newNearby
    })
  }

  //Removes the pin from the map if the user does not save the new location
  cancelLocationAdd () {
    let nearby = this.state.nearbyLocations.slice()
    nearby.pop()
    this.setState({
      nearbyLocations: nearby
    })
  }

  render () {
    console.log("HomeMap.js this.props: ", this.state.currentUser)
    return (
      <View style={styles.container}>
        <TextInput
          returnKeyType="search"
          style={styles.searchBar}
          onChangeText={(text) => this.setState({text})}
          placeholder={this.state.searchText}
          onSubmitEditing={(event) => this.searchLocationSubmit(event)}
        />
        <MapView
          style={styles.homeMap}
          region={this.state.currentLocation}
          showsUserLocation={true}
        >
          {this.state.nearbyLocations.map((marker, key) => (
            <MapView.Marker
              key={key}
              coordinate={marker.coordinate}
              title={marker.title}
              description={marker.description}
            />
          ))}
        </MapView>

        <LocationListView
          nearbyLocations={this.state.nearbyLocations}
        />

        <CreateLocation
          addLocation={this.addLocation}
          cancelLocationAdd={this.cancelLocationAdd}
          currentLocation={this.state.currentLocation}
        />
      <ProfileView currentUser={this.props.currentUser} />
      </View>
    )
  }
}<|endoftext|>


<commit_before><commit_msg>remove old index.js<commit_after><|endoftext|>


<commit_before><commit_msg>Allow setting offset in directive (#7)<commit_after><|endoftext|>


<commit_before>var commandHistory = [];
if (commandHistoryStored = Lockr.get('commandHistory')) {
    commandHistory = commandHistoryStored;
}

updateCommandHistory(null);

function clearCommandHistory() {
    Lockr.rm("commandHistory")
    commandHistory = []
    updateCommandHistory(null);
}

var editor = CodeMirror.fromTextArea(document.getElementById("editor"), {
    lineNumbers: true,
    lineWrapping: true,
    mode: "elixir",
    theme: "text-ex-machina",
    extraKeys: {
        'Ctrl-Enter': function(){executeCode()}
    }
});

var consoleLog = CodeMirror.fromTextArea(document.getElementById("console-log"), {
    theme: "text-ex-machina",
    lineWrapping: true,
    readOnly: true
});

$(".task-modal").modal("show");
$("input[name=task]").change(function(){
    task = this.value
    if(task == "other") {
        $("#other-task-input").show()
    } else {
        $("#other-task-input").hide()
    }
})

$(".launch-shell").click(function(){
    task_choice = $("input[name=task]:checked").val()
    if(task_choice == "other") {
        task = $("#other-task-input").val()
    } else {
        task = task_choice
    }
    startShell(task);
})

ws = null;
if (!window.WebSocket) {
  alert("WebSocket not supported by this browser");
}

function go() {
    ws = new WebSocket("ws://" + location.host + "/websocket");
    ws.onopen = function () {}
    ws.onclose = function () {
      consoleLog.setValue("Launch again\nReason : disconnected from shell, shell terminated")
      setTimeout(function() {go()}, 10000);
    }
    ws.onmessage = function (e) {
        if(!isTerminated) {
            updateConsoleLog(e.data, false)
        }
    }
}

function startShell(task) {
    msg = JSON.stringify({task: task})
    ws.send(msg);
    isTerminated = false
}

function executeCode() {
    var inputType = $("input[name=inputType]:checked").val()
    var msg = {task: "execute", code: editor.getValue(), options: {inputType: inputType}}
    updateConsoleLog(msg.code, true)
    updateCommandHistory(msg.code)
    ws.send(JSON.stringify(msg))
}

function updateCommandHistory(msg) {
    if(msg) {
        commandHistory.push(msg)
        Lockr.set('commandHistory', commandHistory);
    }

    var tmpl = $.templates("#command-history-entry");
    $(".command-history-table").html("")
    for(var i=0; i<commandHistory.length; i++) {
        var entry = {
            id: i+1,
            command: commandHistory[commandHistory.length-i-1].replace(/(?:\r\n|\r|\n)/g, '
'),
            rawCommand: commandHistory[commandHistory.length-i-1]
        }
        var html = tmpl.render(entry);
        $(".command-history-table").append(html);
        new Clipboard('.history-code-segment');
    }
    if($("input[name=clear-on-send]").is(":checked")) {
        editor.setValue("")
    }
    $(".history-code-segment").hover(function() {
            $(this).find(".copy-command").show()
        }, function() {
            $(this).find(".copy-command").hide()
        }
    )
    $(".open-in-editor-btn").click(function() {
        $('.command-history-modal').modal('hide')
        editor.setValue($(this).data("raw-command"))
    })
}

var isTerminated = false;
$(".terminate-shell-btn").click(function(){
    msg = JSON.stringify({task: "terminate"})
    ws.send(msg);
    isTerminated = true
    ws = null
    go()
})

$(".clear-shell-btn").click(function() {
    consoleLog.setValue("Cleared \n")
})

function updateConsoleLog(data, isInput) {
    var doc = consoleLog.getDoc();
    var cursor = doc.getCursor();
    var initialSize = consoleLog.doc.size
    var line = doc.getLine(cursor.line);
    var pos = {
        line: (doc.size+5),
        ch: line.length - 1
    }
    doc.replaceRange('\n'+data, pos);
    var finalSize = consoleLog.doc.size
    if(isInput) {
        for(var i=initialSize; i<=finalSize; i++) {
            consoleLog.addLineClass(i-1, 'wrap', 'console-log-input')
        }
    }
    consoleLog.scrollTo(0,consoleLog.getScrollInfo().height);
}

$(document).on("ready", function(){
    restoreOptions();
    if($("input[name=restoreEditor]").is(":checked")) {
        editor.setValue(commandHistory[commandHistory.length-1]);
    }
    $("input").on("click", function() {
        saveOptions();
    })
})

function restoreOptions() {
    var default_options = {restoreEditor: "false", inputType: "single"};
    var options = Lockr.get("shell-options");
    options = $.extend(true, {}, default_options, options);
    if(options.restoreEditor=="true") {
        $("input[name='restoreEditor']").prop('checked', "checked");
    }
    $("input[name='inputType'][value="+options.inputType+"]").prop('checked', "checked");
}

function saveOptions() {
    var options = {};
    $("#shell-options").serializeArray().map(function(x){options[x.name] = x.value;});
    Lockr.set("shell-options", options)
}

go();
<commit_msg>console output doesn't need a blinking cursor :nail_care:<commit_after>var commandHistory = [];
if (commandHistoryStored = Lockr.get('commandHistory')) {
    commandHistory = commandHistoryStored;
}

updateCommandHistory(null);

function clearCommandHistory() {
    Lockr.rm("commandHistory")
    commandHistory = []
    updateCommandHistory(null);
}

var editor = CodeMirror.fromTextArea(document.getElementById("editor"), {
    lineNumbers: true,
    lineWrapping: true,
    mode: "elixir",
    theme: "text-ex-machina",
    extraKeys: {
        'Ctrl-Enter': function(){executeCode()}
    }
});

var consoleLog = CodeMirror.fromTextArea(document.getElementById("console-log"), {
    theme: "text-ex-machina",
    lineWrapping: true,
    readOnly: 'nocursor'
});

$(".task-modal").modal("show");
$("input[name=task]").change(function(){
    task = this.value
    if(task == "other") {
        $("#other-task-input").show()
    } else {
        $("#other-task-input").hide()
    }
})

$(".launch-shell").click(function(){
    task_choice = $("input[name=task]:checked").val()
    if(task_choice == "other") {
        task = $("#other-task-input").val()
    } else {
        task = task_choice
    }
    startShell(task);
})

ws = null;
if (!window.WebSocket) {
  alert("WebSocket not supported by this browser");
}

function go() {
    ws = new WebSocket("ws://" + location.host + "/websocket");
    ws.onopen = function () {}
    ws.onclose = function () {
      consoleLog.setValue("Launch again\nReason : disconnected from shell, shell terminated")
      setTimeout(function() {go()}, 10000);
    }
    ws.onmessage = function (e) {
        if(!isTerminated) {
            updateConsoleLog(e.data, false)
        }
    }
}

function startShell(task) {
    msg = JSON.stringify({task: task})
    ws.send(msg);
    isTerminated = false
}

function executeCode() {
    var inputType = $("input[name=inputType]:checked").val()
    var msg = {task: "execute", code: editor.getValue(), options: {inputType: inputType}}
    updateConsoleLog(msg.code, true)
    updateCommandHistory(msg.code)
    ws.send(JSON.stringify(msg))
}

function updateCommandHistory(msg) {
    if(msg) {
        commandHistory.push(msg)
        Lockr.set('commandHistory', commandHistory);
    }

    var tmpl = $.templates("#command-history-entry");
    $(".command-history-table").html("")
    for(var i=0; i<commandHistory.length; i++) {
        var entry = {
            id: i+1,
            command: commandHistory[commandHistory.length-i-1].replace(/(?:\r\n|\r|\n)/g, '
'),
            rawCommand: commandHistory[commandHistory.length-i-1]
        }
        var html = tmpl.render(entry);
        $(".command-history-table").append(html);
        new Clipboard('.history-code-segment');
    }
    if($("input[name=clear-on-send]").is(":checked")) {
        editor.setValue("")
    }
    $(".history-code-segment").hover(function() {
            $(this).find(".copy-command").show()
        }, function() {
            $(this).find(".copy-command").hide()
        }
    )
    $(".open-in-editor-btn").click(function() {
        $('.command-history-modal').modal('hide')
        editor.setValue($(this).data("raw-command"))
    })
}

var isTerminated = false;
$(".terminate-shell-btn").click(function(){
    msg = JSON.stringify({task: "terminate"})
    ws.send(msg);
    isTerminated = true
    ws = null
    go()
})

$(".clear-shell-btn").click(function() {
    consoleLog.setValue("Cleared \n")
})

function updateConsoleLog(data, isInput) {
    var doc = consoleLog.getDoc();
    var cursor = doc.getCursor();
    var initialSize = consoleLog.doc.size
    var line = doc.getLine(cursor.line);
    var pos = {
        line: (doc.size+5),
        ch: line.length - 1
    }
    doc.replaceRange('\n'+data, pos);
    var finalSize = consoleLog.doc.size
    if(isInput) {
        for(var i=initialSize; i<=finalSize; i++) {
            consoleLog.addLineClass(i-1, 'wrap', 'console-log-input')
        }
    }
    consoleLog.scrollTo(0,consoleLog.getScrollInfo().height);
}

$(document).on("ready", function(){
    restoreOptions();
    if($("input[name=restoreEditor]").is(":checked")) {
        editor.setValue(commandHistory[commandHistory.length-1]);
    }
    $("input").on("click", function() {
        saveOptions();
    })
})

function restoreOptions() {
    var default_options = {restoreEditor: "false", inputType: "single"};
    var options = Lockr.get("shell-options");
    options = $.extend(true, {}, default_options, options);
    if(options.restoreEditor=="true") {
        $("input[name='restoreEditor']").prop('checked', "checked");
    }
    $("input[name='inputType'][value="+options.inputType+"]").prop('checked', "checked");
}

function saveOptions() {
    var options = {};
    $("#shell-options").serializeArray().map(function(x){options[x.name] = x.value;});
    Lockr.set("shell-options", options)
}

go();
<|endoftext|>


<commit_before><commit_msg>add better error output<commit_after><|endoftext|>


<commit_before><commit_msg>Remember to reject ops if alt has already finished.<commit_after><|endoftext|>


<commit_before><commit_msg>Enable the other amps<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed missing semicolon.<commit_after><|endoftext|>


<commit_before><commit_msg>Whitespace tidy.<commit_after><|endoftext|>


<commit_before><commit_msg>link incomplete<commit_after><|endoftext|>


<commit_before><commit_msg>move debug<commit_after><|endoftext|>


<commit_before><commit_msg>fixed saving html from alternate log load<commit_after><|endoftext|>


<commit_before><commit_msg>Use Pulsing when Loading Subtitles<commit_after><|endoftext|>


<commit_before><commit_msg>Clean up JSDoc<commit_after><|endoftext|>


<commit_before><commit_msg>rings working, except for parent calculation when starting from within + logs<commit_after><|endoftext|>


<commit_before>
/*

  Utils.js

*/

var fs        = require("fs"),
    url       = require("url"),
    path      = require("path"),
    chokidar  = require("chokidar"),
    Utils;

module.exports = Utils = {};

/*

  function makePathAbsolute

*/

Utils.makePathAbsolute = function(p) {

  if (path.isAbsolute(p))
    return p;
  else
    return path.resolve(process.cwd(), p || "");

}

/*

  function isIndexFile

*/

Utils.isIndexFile = function(file) {
  return /^index[^\/]*$/i.test(file.name);
}

Utils.uniqueExtensions = function(p) {
  var exts = {}
  Utils.readDirectory(p).forEach(function(file) {
    if (file.ext && "" !== file.ext) exts[file.ext.toLowerCase()] = 1;
  });
  return Object.keys(exts);
};

/*

  function mapFiles

  Note that we remove leading "." from file extension

*/

Utils.mapFiles = function(p, options) {

  var files, i, indices, results = [];
  options = options || {};

  // Make path absolute before call (for comparison after)
  p = Utils.makePathAbsolute(p);

  files = Utils.readDirectory(p, options.recursive);

  // Sort in reverse order so that directory calls come last. Then move "index" to end.
  if (options.sort) {
    files.sort(function(a, b) { return (a.path < b.path) ? -1 : (a.path > b.path) ? 1 : 0; }).reverse();
    i = files.length;
    while (i-- > 0)
      if (Utils.isIndexFile(files[i]))
        Array.prototype.push.apply(files, files.splice(i, 1));
  }

  // Remove subdirectory files if index.* is encountered
  if (options.bundleFolders) {

    indices = [];

    // Filter out index files (outside of master directory)
    i = files.length;
    while (i-- > 0) {
      if (Utils.isIndexFile(files[i]) && (p !== files[i].dir))
        Array.prototype.push.apply(indices, files.splice(i, 1));
    }

    // Remove indices that are subdirectories of each other
    i = indices.length;
    while (i-- > 0)
      for (var j = 0, n = indices.length; j < n; j++) {
        if (i !== j && 0 === indices[i].path.indexOf(indices[j].dir)) {
          indices.splice(i, 1);
          break;
        }
      }

    // Remove files in subdirectories of indices
    i = files.length;
    while (i-- > 0)
      for (var j = 0, n = indices.length; j < n; j++)
        if (0 === files[i].path.indexOf(indices[j].dir)) {
          files.splice(i, 1);
          break;
        }

    // Denote indices as bundles
    indices.forEach(function(file) {
      file.bundle = true;
      file.ignored = [
        path.relative(process.cwd(), path.join(file.dir, "*")),
        path.relative(process.cwd(), file.dir + "." + options.ext)
      ];
    });

    // Rejoin indices back into files
    files = files.concat(indices);

  }

  files.forEach(function(file) {
    if (!options.filter || options.filter.indexOf(file.ext) > -1) {
      file.ext = file.ext.replace(/^\./, "");
      file.basePath = p;
      file.folder = path.relative(p, file.path.replace(new RegExp(file.base + "$"), ""));
      results.push(file);
    }
  });

  return results;

}

/*

  function makeRoutes

*/

Utils.makeRoutes = function(baseRoute, file, options) {

  var re = /\/\/+$/,
      route,
      routes,
      ext,
      options = options || {};

  // !!! WHAT TO DO ABOUT EXTENSIONLESS FILES?
  ext = options.type || file.ext || "";
  ext = ext.replace(/^\./, "");
  route = (url.resolve((route + "/").replace(re, "/"), file.folder) + "/").replace(re, "/");

  // Wildcard directories
  if (/^html?$/.test(ext) && options.query) {
    // If name starts with @, look for parent directory;
    if ("@" === file.name[0]) base = base.split("/").slice(0, -1).join("/")
    return [base + "/:slug"];
  }

  // Add file and default extension
  routes = [url.resolve(base, file.name + "." + ext)];

  // HTML files are special: not only can they be accessed sans extension, if they are named
  // "index", we allow access via a folder.
  if ("html" === ext) {
    routes.push(url.resolve(base, file.name));
    if (Utils.isIndexFile(file)) routes.push(base);
  }

  return routes;

}

/*

  function readDirectory

*/

Utils.readDirectory = function(p, recursive) {

  var results = [];

  // Set defaults
  if ("undefined" == typeof recursive) recursive = true;
  p = Utils.makePathAbsolute(p);

  // If directory doesn't exist, return nothing
  try {
    fs.lstatSync(p);
  } catch (err) {
    return results;
  }

  // Read in files
  fs.readdirSync(p).forEach(function(file) {

    var stats, parsed;

    // Read file and stats
    file = path.join(p, file);
    stats = fs.lstatSync(file);

    // Recursively walk directory, or add file
    if (stats.isDirectory()) {
      if (recursive)
        results = results.concat(Utils.readDirectory(file, true))
    } else {
      parsed = path.parse(file);
      parsed.path = file;
      results.push(parsed);
    }

  });

  return results;

}

/*

 function readFileHead

 Reads a limited number of characters from a file.

*/

Utils.readFileHead = function(path, chars) {

  var buffer = new Buffer(chars || 500),
      file   = fs.openSync(path, "r"),
      str,
      len;

  // Read in file
  len = fs.readSync(file, buffer, 0, chars, 0);

  // Convert to lines, and discard any fragments
  // (so that we can use template engines without through errors)
  str = buffer.slice(0, len).toString().split("\n");

  return str.slice(0, str.length - 1).join("\n")

}

/*

  function getRegExpMatches

*/

Utils.getRegExpMatches = function(str, re, idx) {

  var match,
      matches = [];

  // Clone the RE and add global flag (otherwise has endless loop)
  re = new RegExp(re);
  re.global = true;

  // Set default idx
  idx = idx || 0;

  while (match = re.exec(str))
    matches.push(match[idx]);

  return matches;

}

/*

  function watch

*/

Utils.watch = function(sourceDir, sourceExt, destExt, options) {

  if ("*" !== sourceExt) sourceExt = "*." + sourceExt.replace(/^[\*\.]+/g, "");
  if ("*" !== destExt) destExt = (destExt) ? ("*." + destExt.replace(/^[\*\.]+/g, "")) : sourceExt;

  options = options || {};

  chokidar.watch(path.join(sourceDir, "**", sourceExt), options).on("change", function(file) {
    global.server.reload(file);
  });

}

Utils.isProduction = function() {
  return /^prod/i.test(process.env.NODE_ENV);
};
<commit_msg>Utils#getRegExpMatches: better variable naming<commit_after>
/*

  Utils.js

*/

var fs        = require("fs"),
    url       = require("url"),
    path      = require("path"),
    chokidar  = require("chokidar"),
    Utils;

module.exports = Utils = {};

/*

  function makePathAbsolute

*/

Utils.makePathAbsolute = function(p) {

  if (path.isAbsolute(p))
    return p;
  else
    return path.resolve(process.cwd(), p || "");

}

/*

  function isIndexFile

*/

Utils.isIndexFile = function(file) {
  return /^index[^\/]*$/i.test(file.name);
}

Utils.uniqueExtensions = function(p) {
  var exts = {}
  Utils.readDirectory(p).forEach(function(file) {
    if (file.ext && "" !== file.ext) exts[file.ext.toLowerCase()] = 1;
  });
  return Object.keys(exts);
};

/*

  function mapFiles

  Note that we remove leading "." from file extension

*/

Utils.mapFiles = function(p, options) {

  var files, i, indices, results = [];
  options = options || {};

  // Make path absolute before call (for comparison after)
  p = Utils.makePathAbsolute(p);

  files = Utils.readDirectory(p, options.recursive);

  // Sort in reverse order so that directory calls come last. Then move "index" to end.
  if (options.sort) {
    files.sort(function(a, b) { return (a.path < b.path) ? -1 : (a.path > b.path) ? 1 : 0; }).reverse();
    i = files.length;
    while (i-- > 0)
      if (Utils.isIndexFile(files[i]))
        Array.prototype.push.apply(files, files.splice(i, 1));
  }

  // Remove subdirectory files if index.* is encountered
  if (options.bundleFolders) {

    indices = [];

    // Filter out index files (outside of master directory)
    i = files.length;
    while (i-- > 0) {
      if (Utils.isIndexFile(files[i]) && (p !== files[i].dir))
        Array.prototype.push.apply(indices, files.splice(i, 1));
    }

    // Remove indices that are subdirectories of each other
    i = indices.length;
    while (i-- > 0)
      for (var j = 0, n = indices.length; j < n; j++) {
        if (i !== j && 0 === indices[i].path.indexOf(indices[j].dir)) {
          indices.splice(i, 1);
          break;
        }
      }

    // Remove files in subdirectories of indices
    i = files.length;
    while (i-- > 0)
      for (var j = 0, n = indices.length; j < n; j++)
        if (0 === files[i].path.indexOf(indices[j].dir)) {
          files.splice(i, 1);
          break;
        }

    // Denote indices as bundles
    indices.forEach(function(file) {
      file.bundle = true;
      file.ignored = [
        path.relative(process.cwd(), path.join(file.dir, "*")),
        path.relative(process.cwd(), file.dir + "." + options.ext)
      ];
    });

    // Rejoin indices back into files
    files = files.concat(indices);

  }

  files.forEach(function(file) {
    if (!options.filter || options.filter.indexOf(file.ext) > -1) {
      file.ext = file.ext.replace(/^\./, "");
      file.basePath = p;
      file.folder = path.relative(p, file.path.replace(new RegExp(file.base + "$"), ""));
      results.push(file);
    }
  });

  return results;

}

/*

  function makeRoutes

*/

Utils.makeRoutes = function(baseRoute, file, options) {

  var re = /\/\/+$/,
      route,
      routes,
      ext,
      options = options || {};

  // !!! WHAT TO DO ABOUT EXTENSIONLESS FILES?
  ext = options.type || file.ext || "";
  ext = ext.replace(/^\./, "");
  route = (url.resolve((route + "/").replace(re, "/"), file.folder) + "/").replace(re, "/");

  // Wildcard directories
  if (/^html?$/.test(ext) && options.query) {
    // If name starts with @, look for parent directory;
    if ("@" === file.name[0]) base = base.split("/").slice(0, -1).join("/")
    return [base + "/:slug"];
  }

  // Add file and default extension
  routes = [url.resolve(base, file.name + "." + ext)];

  // HTML files are special: not only can they be accessed sans extension, if they are named
  // "index", we allow access via a folder.
  if ("html" === ext) {
    routes.push(url.resolve(base, file.name));
    if (Utils.isIndexFile(file)) routes.push(base);
  }

  return routes;

}

/*

  function readDirectory

*/

Utils.readDirectory = function(p, recursive) {

  var results = [];

  // Set defaults
  if ("undefined" == typeof recursive) recursive = true;
  p = Utils.makePathAbsolute(p);

  // If directory doesn't exist, return nothing
  try {
    fs.lstatSync(p);
  } catch (err) {
    return results;
  }

  // Read in files
  fs.readdirSync(p).forEach(function(file) {

    var stats, parsed;

    // Read file and stats
    file = path.join(p, file);
    stats = fs.lstatSync(file);

    // Recursively walk directory, or add file
    if (stats.isDirectory()) {
      if (recursive)
        results = results.concat(Utils.readDirectory(file, true))
    } else {
      parsed = path.parse(file);
      parsed.path = file;
      results.push(parsed);
    }

  });

  return results;

}

/*

 function readFileHead

 Reads a limited number of characters from a file.

*/

Utils.readFileHead = function(path, chars) {

  var buffer = new Buffer(chars || 500),
      file   = fs.openSync(path, "r"),
      str,
      len;

  // Read in file
  len = fs.readSync(file, buffer, 0, chars, 0);

  // Convert to lines, and discard any fragments
  // (so that we can use template engines without through errors)
  str = buffer.slice(0, len).toString().split("\n");

  return str.slice(0, str.length - 1).join("\n")

}

/*

  function getRegExpMatches

*/

Utils.getRegExpMatches = function(str, pattern, idx) {

  var match,
      matches = [];

  // Clone the RE and add global flag (otherwise has endless loop)
  pattern = new RegExp(pattern);
  pattern.global = true;

  // Set default idx
  idx = idx || 0;

  while (match = pattern.exec(str))
    matches.push(match[idx]);

  return matches;

}

/*

  function watch

*/

Utils.watch = function(sourceDir, sourceExt, destExt, options) {

  if ("*" !== sourceExt) sourceExt = "*." + sourceExt.replace(/^[\*\.]+/g, "");
  if ("*" !== destExt) destExt = (destExt) ? ("*." + destExt.replace(/^[\*\.]+/g, "")) : sourceExt;

  options = options || {};

  chokidar.watch(path.join(sourceDir, "**", sourceExt), options).on("change", function(file) {
    global.server.reload(file);
  });

}

Utils.isProduction = function() {
  return /^prod/i.test(process.env.NODE_ENV);
};
<|endoftext|>


<commit_before><commit_msg>Refs #5 - POST and PATCH body data load passed correctly<commit_after><|endoftext|>


<commit_before>var path = require("path");
var _ = require("underscore");

exports.filename = function(folder, fund, ext){

	if (ext.indexOf("?") != -1){

		ext = ext.split("?")[0];
		ext = ext.toLowerCase();

	}

	// var baseName = folder + [fund.body, fund.year, fund.quarter, fund.number].join("_");
	var baseName = path.join(folder,[fund.body, fund.year, fund.quarter, fund.number].join("_"));

    return (baseName + ext).toLowerCase();

	// var baseName = path.join(folder,[fund.body, fund.number, fund.year, fund.quarter].join("_"));

    // return baseName + ext;

};

exports.getFundObj = function(body, year, quarter, number){
	return {
		body: body,
		year: year,
		quarter: quarter,
		number: number
	}
}

exports.getFundFromFile = function(filename){
		var _s = filename.split("_");

		return {
			body : _s[0],
			year : _s[1],
			quarter :  _s[2],
			number : _s[3].split('.')[0]
		};
}

exports.filterFunds = function(allFunds, body, year, quarter, fund_number) {

	var chosenFunds = allFunds.filter(function(f){
		return (body == undefined? true: f.body == body ||  ( _.isArray(body) && body.indexOf(f.body) > -1 ) )
		&& (fund_number == undefined ? true: f.number == fund_number ||  ( _.isArray(fund_number) && fund_number.indexOf(f.number) > -1 ))
		&& (year == undefined ? true: f.year == year ||  ( _.isArray(year) && year.indexOf(f.year) > -1 ))
		&& (quarter == undefined? true: f.quarter == quarter ||  ( _.isArray(quarter) && quarter.indexOf(f.quarter) > -1 ))
	})

	return chosenFunds;
};

exports.filterFiles = function(allFiles, body, year, quarter, fund_number) {

	var funds = allFiles.map(exports.getFundFromFile);

	var chosenFiles = allFiles.filter(function(file){

		var f = exports.getFundFromFile(file);

		return (body == undefined? true: f.body == body ||  ( _.isArray(body) && body.indexOf(f.body) > -1 ) )
		&& (fund_number == undefined ? true: f.number == fund_number ||  ( _.isArray(fund_number) && fund_number.indexOf(f.number) > -1 ))
		&& (year == undefined ? true: f.year == year ||  ( _.isArray(year) && year.indexOf(f.year) > -1 ))
		&& (quarter == undefined? true: f.quarter == quarter ||  ( _.isArray(quarter) && quarter.indexOf(f.quarter) > -1 ))
	})

	return chosenFiles;
};

<commit_msg>more robust file name generation<commit_after>var path = require("path");
var _ = require("underscore");

exports.filename = function(folder, fund, ext){

	if (ext.indexOf("?") != -1){
		ext = ext.split("?")[0];
	}

	ext = ext.toLowerCase();

	var filename = [fund.body, fund.year, fund.quarter, fund.number].join("_").toLowerCase();

	var result = path.join(folder, filename) + ext;

    return result;

};

exports.getFundObj = function(body, year, quarter, number, url){
	var fund = {};
	if (body){
		fund.body = body;
	}
	if (year){
		fund.year = year;
	}
	if (quarter){
		fund.quarter = quarter;
	}
	if (number){
		fund.number = number;
	}
	if (url){
		fund.url = url;
	}

	return fund;
}

exports.getFundFromFile = function(filename){
		var _s = filename.split("_");

		return {
			body : _s[0],
			year : _s[1],
			quarter :  _s[2],
			number : _s[3].split('.')[0]
		};
}

exports.filterFunds = function(allFunds, body, year, quarter, fund_number) {

	var chosenFunds = allFunds.filter(function(f){
		return (body == undefined? true: f.body == body ||  ( _.isArray(body) && body.indexOf(f.body) > -1 ) )
		&& (fund_number == undefined ? true: f.number == fund_number ||  ( _.isArray(fund_number) && fund_number.indexOf(f.number) > -1 ))
		&& (year == undefined ? true: f.year == year ||  ( _.isArray(year) && year.indexOf(f.year) > -1 ))
		&& (quarter == undefined? true: f.quarter == quarter ||  ( _.isArray(quarter) && quarter.indexOf(f.quarter) > -1 ))
	})

	return chosenFunds;
};

exports.filterFiles = function(allFiles, body, year, quarter, fund_number) {

	var funds = allFiles.map(exports.getFundFromFile);

	var chosenFiles = allFiles.filter(function(file){

		var f = exports.getFundFromFile(file);

		return (body == undefined? true: f.body == body ||  ( _.isArray(body) && body.indexOf(f.body) > -1 ) )
		&& (fund_number == undefined ? true: f.number == fund_number ||  ( _.isArray(fund_number) && fund_number.indexOf(f.number) > -1 ))
		&& (year == undefined ? true: f.year == year ||  ( _.isArray(year) && year.indexOf(f.year) > -1 ))
		&& (quarter == undefined? true: f.quarter == quarter ||  ( _.isArray(quarter) && quarter.indexOf(f.quarter) > -1 ))
	})

	return chosenFiles;
};

<|endoftext|>


<commit_before>exports = module.exports = function() {
    utils.prototype.getXmlFileNameFromClip = function(clip) {
        return clip.playlist_id + "-" + clip.id + ".xml";
    };

    utils.prototype.getPlaylistIdFromXmlFileName = function(filename) {
        return filename.split("-")[0];
    };

    utils.prototype.getClipIdFromXmlFileName = function(filename) {
        return filename.split("-")[1];
    };
};<commit_msg>Fixed function declarations<commit_after>exports = module.exports = {
    getXmlFileNameFromClip: function(clip) {
        return clip.playlist_id + "-" + clip.id + ".xml";
    },

    getPlaylistIdFromXmlFileName: function(filename) {
        return filename.split("-")[0];
    },

    getClipIdFromXmlFileName: function(filename) {
        return filename.split("-")[1];
    }
};<|endoftext|>


<commit_before>'use strict';

var pos = require('pos'),
S = require('string'),
_ = require('lodash');

/*
* todo
* - move initial gathering templates to external file
* - make module export instance
* - store all bucketed data for conversation
* - use bucketed data to created more detailed qurstions later
*/
var templates = {
  N : [
    'Ugh, {{word}}, may be worth looking at libraries that handle {{word}}.',
    'Tell me more about {{word}}, I\'m not unfamiliar.'
  ],
  V : [
    'What exactly are you trying to {{word}}',
    'I\'ve {{word}} before, is there a better way to do it?'
  ]
};

function arrayRandom(array){
  var index = _.random(0, array.length - 1);
  return array[index];
}

module.exports = {
  ask : function(query, callback){

    if(_.isEmpty(query)) return callback(new Error('Empty input'));

    var words = new pos.Lexer().lex(query);
    var taggedWords = new pos.Tagger().tag(words);

    var bucketed = _.chain(taggedWords).
      groupBy(function(a){ return a[1]; }).
      reduce(function(result, bucket, key){
	result[key] = _.pluck(bucket,0);
	return result;
      }, {}).
      valueOf();

    // this is where things can evolve complicated, for now keep it simple
    // rebucked into nouns/verbs
    var rebucketed = _.reduce(bucketed, function(result, bucket, key){
      var index = key[0];
      if(_.has(result, index)) result[index] = _.merge(result[index], bucket);
      return result;
      }, {N : [], V : []});

    var order = ['N', 'V'];
    // 1/3rd of the time, switch key
    if(_.random(2) === 2) order.reverse();

    var message = undefined;

    order.forEach(function(key){
      if(message || (!rebucketed[key].length)) return;

      var template = arrayRandom(templates[key]);
      var word = arrayRandom(rebucketed[key]);
      message = S(template).template({word : word.toLowerCase()});
    });

    if(_.isUndefined(message)) return callback(new Error('Unable to parse query'));
    return callback(null, message);
  }
}
<commit_msg>more todo<commit_after>'use strict';

var pos = require('pos'),
S = require('string'),
_ = require('lodash');

/*
* todo
* - Grunt + jshint
* - move initial gathering templates to external file
* - make module export instance
* - store all bucketed data for conversation
* - use bucketed data to created more detailed qurstions later
*/
var templates = {
  N : [
    'Ugh, {{word}}, may be worth looking at libraries that handle {{word}}.',
    'Tell me more about {{word}}, I\'m not unfamiliar.'
  ],
  V : [
    'What exactly are you trying to {{word}}',
    'I\'ve {{word}} before, is there a better way to do it?'
  ]
};

function arrayRandom(array){
  var index = _.random(0, array.length - 1);
  return array[index];
}

module.exports = {
  ask : function(query, callback){

    if(_.isEmpty(query)) return callback(new Error('Empty input'));

    var words = new pos.Lexer().lex(query);
    var taggedWords = new pos.Tagger().tag(words);

    var bucketed = _.chain(taggedWords).
      groupBy(function(a){ return a[1]; }).
      reduce(function(result, bucket, key){
	result[key] = _.pluck(bucket,0);
	return result;
      }, {}).
      valueOf();

    // this is where things can evolve complicated, for now keep it simple
    // rebucked into nouns/verbs
    var rebucketed = _.reduce(bucketed, function(result, bucket, key){
      var index = key[0];
      if(_.has(result, index)) result[index] = _.merge(result[index], bucket);
      return result;
      }, {N : [], V : []});

    var order = ['N', 'V'];
    // 1/3rd of the time, switch key
    if(_.random(2) === 2) order.reverse();

    var message = undefined;

    order.forEach(function(key){
      if(message || (!rebucketed[key].length)) return;

      var template = arrayRandom(templates[key]);
      var word = arrayRandom(rebucketed[key]);
      message = S(template).template({word : word.toLowerCase()});
    });

    if(_.isUndefined(message)) return callback(new Error('Unable to parse query'));
    return callback(null, message);
  }
}
<|endoftext|>


<commit_before>/**
 * Microlib for translations with support for placeholders and multiple plural forms.
 *
 * v0.4.0
 *
 * Usage:
 *
 * var translate = require('translate.js')
 *
 * var messages = {
 *  translationKey: 'translationValue'
 * }
 *
 * var options = {
 *   // These are the defaults:
 *   debug: false,  //[Boolean]: Logs missing translations to console and add "@@" around output if `true`.
 *   array: false,  //[Boolean]: `true` returns translations with placeholder-replacements as Arrays.
 *   pluralize: function(n,translKey){ return Math.abs(n); } //[Function(count,translationKey)]: Provides a custom pluralization mapping function.
 * }
 *
 * var t = translate(messages, [options])
 *
 * t('translationKey')
 * t('translationKey', count)
 * t('translationKey', {replaceKey: 'replacevalue'})
 * t('translationKey', count, {replaceKey: 'replacevalue'})
 * t('translationKey', {replaceKey: 'replacevalue'}, count)
 *
 *
 * @author Jonas Girnatis <dermusterknabe@gmail.com>
 * @licence May be freely distributed under the MIT license.
 */

/* global console, module */
;(function () {
  'use strict'

  var isObject = function (obj) {
    return obj && typeof obj === 'object'
  }

  function assemble (parts, replacements, count, debug, asArray) {
    var result = asArray ? [parts[0]] : parts[0]
    var len = parts.length
    for (var i = 1; i < len; i += 2) {
      var part = parts[i]
      var val = replacements[part]
      if (val == null) {
        if (part === 'n' && count != null) {
          val = count
        } else {
          debug && console.warn('No "' + part + '" in placeholder object:', replacements)
          val = '{' + part + '}'
        }
      }
      if ( asArray ) {
        result[i] = val
        result[i+1] = parts[i+1]
      } else {
        result += val + parts[i+1]
      }
    }
    return result
  }

  var translatejs = function (messageObject, options) {
    options = options || {}
    var debug = options.debug

    function getPluralValue (translation, count) {
      // Opinionated assumption: Pluralization rules are the same for negative and positive values.
      // By normalizing all values to positive, pluralization functions become simpler, and less error-prone by accident.
      var mappedCount = Math.abs(count)

      if (translation[mappedCount] != null) {
        return translation[mappedCount]
      }
      var plFunc = (tFunc.opts || {}).pluralize
      mappedCount = plFunc ? plFunc(mappedCount, translation) : mappedCount
      if (translation[mappedCount] != null) {
        return translation[mappedCount]
      }
      if (translation.n != null) {
        return translation.n
      }
      debug && console.warn('No plural forms found for "' + count + '" in', translation)
    }

    var replCache = {}

    function replacePlaceholders (translation, replacements, count) {
      var result = replCache[translation]
      if (result == null) {
        var parts = translation
          // turn both curly braces around tokens into the a unified
          // (and now unique/safe) token `{x}` signifying boundry between
          // replacement variables and static text.
          .replace(/\{(\w+)\}/g, '{x}$1{x}')
          // Adjacent placeholders will always have an empty string between them.
          // The array will also always start with a static string (at least a '').
          .split('{x}') // stupid but works™

        // NOTE: parts no consists of alternating [text,replacement,text,replacement,text]
        // Cache a function that loops over the parts array - unless there's only text
        // (i.e. parts.length === 1) - then we simply cache the string.
        result = parts.length > 1 ? parts : parts[0]
        replCache[translation] = result
      }
      result = result.pop ? assemble(result, replacements, count, debug, tFunc.opts.array) : result
      return result
    }

    var tFunc = function (translationKey, count, replacements) {
      var translation = tFunc.keys[translationKey]
      var complex = count != null || replacements != null

      if (complex) {
        if (isObject(count)) {
          var tmp = replacements
          replacements = count
          count = tmp
        }
        replacements = replacements || {}
        count = typeof count === 'number' ? count : null

        if (count !== null && isObject(translation)) {
          // get appropriate plural translation string
          translation = getPluralValue(translation, count)
        }
      }

      if (typeof translation !== 'string') {
        translation = translationKey
        if (debug) {
          translation = '@@' + translation + '@@'
          console.warn('Translation for "' + translationKey + '" not found.')
        }
      } else if (complex || debug) {
        translation = replacePlaceholders(translation, replacements, count)
      }
      return translation
    }

    // Convenience function.
    tFunc.arr = function () {
        var opts = tFunc.opts
        var normalArrayOption = opts.array
        opts.array = true
        var result = tFunc.apply(null, arguments)
        opts.array = normalArrayOption
        return result
      };

    tFunc.keys = messageObject || {}
    tFunc.opts = options

    return tFunc
  }

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = translatejs
  } else {
    window.translatejs = translatejs
  }
})()

<commit_msg>Revert back to `slice` when assembling arrays<commit_after>/**
 * Microlib for translations with support for placeholders and multiple plural forms.
 *
 * v0.4.0
 *
 * Usage:
 *
 * var translate = require('translate.js')
 *
 * var messages = {
 *  translationKey: 'translationValue'
 * }
 *
 * var options = {
 *   // These are the defaults:
 *   debug: false,  //[Boolean]: Logs missing translations to console and add "@@" around output if `true`.
 *   array: false,  //[Boolean]: `true` returns translations with placeholder-replacements as Arrays.
 *   pluralize: function(n,translKey){ return Math.abs(n); } //[Function(count,translationKey)]: Provides a custom pluralization mapping function.
 * }
 *
 * var t = translate(messages, [options])
 *
 * t('translationKey')
 * t('translationKey', count)
 * t('translationKey', {replaceKey: 'replacevalue'})
 * t('translationKey', count, {replaceKey: 'replacevalue'})
 * t('translationKey', {replaceKey: 'replacevalue'}, count)
 *
 *
 * @author Jonas Girnatis <dermusterknabe@gmail.com>
 * @licence May be freely distributed under the MIT license.
 */

/* global console, module */
;(function () {
  'use strict'

  var isObject = function (obj) {
    return obj && typeof obj === 'object'
  }

  function assemble (parts, replacements, count, debug, asArray) {
    var result = asArray ? parts.slice() : parts[0]
    var len = parts.length
    for (var i = 1; i < len; i += 2) {
      var part = parts[i]
      var val = replacements[part]
      if (val == null) {
        if (part === 'n' && count != null) {
          val = count
        } else {
          debug && console.warn('No "' + part + '" in placeholder object:', replacements)
          val = '{' + part + '}'
        }
      }
      if ( asArray ) {
        result[i] = val
      } else {
        result += val + parts[i+1]
      }
    }
    return result
  }

  var translatejs = function (messageObject, options) {
    options = options || {}
    var debug = options.debug

    function getPluralValue (translation, count) {
      // Opinionated assumption: Pluralization rules are the same for negative and positive values.
      // By normalizing all values to positive, pluralization functions become simpler, and less error-prone by accident.
      var mappedCount = Math.abs(count)

      if (translation[mappedCount] != null) {
        return translation[mappedCount]
      }
      var plFunc = (tFunc.opts || {}).pluralize
      mappedCount = plFunc ? plFunc(mappedCount, translation) : mappedCount
      if (translation[mappedCount] != null) {
        return translation[mappedCount]
      }
      if (translation.n != null) {
        return translation.n
      }
      debug && console.warn('No plural forms found for "' + count + '" in', translation)
    }

    var replCache = {}

    function replacePlaceholders (translation, replacements, count) {
      var result = replCache[translation]
      if (result == null) {
        var parts = translation
          // turn both curly braces around tokens into the a unified
          // (and now unique/safe) token `{x}` signifying boundry between
          // replacement variables and static text.
          .replace(/\{(\w+)\}/g, '{x}$1{x}')
          // Adjacent placeholders will always have an empty string between them.
          // The array will also always start with a static string (at least a '').
          .split('{x}') // stupid but works™

        // NOTE: parts no consists of alternating [text,replacement,text,replacement,text]
        // Cache a function that loops over the parts array - unless there's only text
        // (i.e. parts.length === 1) - then we simply cache the string.
        result = parts.length > 1 ? parts : parts[0]
        replCache[translation] = result
      }
      result = result.pop ? assemble(result, replacements, count, debug, tFunc.opts.array) : result
      return result
    }

    var tFunc = function (translationKey, count, replacements) {
      var translation = tFunc.keys[translationKey]
      var complex = count != null || replacements != null

      if (complex) {
        if (isObject(count)) {
          var tmp = replacements
          replacements = count
          count = tmp
        }
        replacements = replacements || {}
        count = typeof count === 'number' ? count : null

        if (count !== null && isObject(translation)) {
          // get appropriate plural translation string
          translation = getPluralValue(translation, count)
        }
      }

      if (typeof translation !== 'string') {
        translation = translationKey
        if (debug) {
          translation = '@@' + translation + '@@'
          console.warn('Translation for "' + translationKey + '" not found.')
        }
      } else if (complex || debug) {
        translation = replacePlaceholders(translation, replacements, count)
      }
      return translation
    }

    // Convenience function.
    tFunc.arr = function () {
        var opts = tFunc.opts
        var normalArrayOption = opts.array
        opts.array = true
        var result = tFunc.apply(null, arguments)
        opts.array = normalArrayOption
        return result
      };

    tFunc.keys = messageObject || {}
    tFunc.opts = options

    return tFunc
  }

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = translatejs
  } else {
    window.translatejs = translatejs
  }
})()

<|endoftext|>