<commit_before>import { isTrue, isFalse, OPTION_KEYS } from '../../src/main';
import {
  printException,
  collectUrlParams,
  formatUrl,
  openImages,
  getOptions,
} from '../../src/main';

const makeResultParams = ({ format, name }) => {
  return {
    protocol: 'https:',
    host: 'pbs.twimg.com',
    pathname: '/media/hogefuga123',
    format,
    name: name || null,
  };
};

describe('Utils', () => {
  describe('printException', () => {
    it('エラーメッセージの表示(予期せぬ状況の確認)', () => {
      console.log = jest.fn();
      printException('exception message');
      expect(console.log.mock.calls[0][0]).toBe(
        'tooi: exception message at: http://localhost/'
      );
    });
  });

  describe('URLのツール', () => {
    // URLの変換のテストの場合たち
    const cases = [
      {
        title: '何もなし',
        url: 'https://pbs.twimg.com/media/hogefuga123',
        params: { format: 'jpg' },
      },
      {
        title: '.jpg',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg',
        params: { format: 'jpg' },
      },
      {
        title: '.png',
        url: 'https://pbs.twimg.com/media/hogefuga123.png',
        params: { format: 'png' },
      },
      {
        title: '.jpg:orig',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg:orig',
        params: { format: 'jpg', name: 'orig' },
      },
      {
        title: '.jpg:large',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg:large',
        params: { format: 'jpg', name: 'large' },
      },
      {
        title: '?format=jpg',
        url: 'https://pbs.twimg.com/media/hogefuga123?format=jpg',
        params: { format: 'jpg' },
      },
      {
        title: '?format=png',
        url: 'https://pbs.twimg.com/media/hogefuga123?format=png',
        params: { format: 'png' },
      },
      {
        title: '.jpg?format=jpg',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg?format=jpg',
        params: { format: 'jpg' },
      },
      {
        title: '.jpg?format=png',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg?format=png',
        params: { format: 'jpg' },
      },
      {
        title: '.png?format=jpg',
        url: 'https://pbs.twimg.com/media/hogefuga123.png?format=jpg',
        params: { format: 'png' },
      },
      {
        title: '.jpg?name=large',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg?name=large',
        params: { format: 'jpg', name: 'large' },
      },
      {
        title: '?format=jpg&name=large',
        url: 'https://pbs.twimg.com/media/hogefuga123?format=jpg&name=large',
        params: { format: 'jpg', name: 'large' },
      },
      {
        title: '.png?format=jpg&name=orig',
        url: 'https://pbs.twimg.com/media/hogefuga123.png?format=jpg&name=orig',
        params: { format: 'png', name: 'orig' },
      },
    ];

    describe('collectUrlParams 画像urlの要素を集める', () => {
      cases.forEach(singleCase => {
        const { title, url, params } = singleCase;
        it(title, () => {
          expect(collectUrlParams(url)).toStrictEqual(makeResultParams(params));
        });
      });

      it('twitterの画像URLでないときnull', () => {
        expect(collectUrlParams('https://twitter.com/tos')).toBe(null);
      });
    });

    describe('formatUrl 画像URLを https～?format=〜&name=orig に揃える', () => {
      cases.forEach(singleCase => {
        const { title, url, params } = singleCase;
        it(title, () => {
          expect(formatUrl(url)).toBe(
            `https://pbs.twimg.com/media/hogefuga123?format=${params.format}&name=orig`
          );
        });
      });

      it('twitterの画像URLでないときそのまま', () => {
        expect(formatUrl('https://twitter.com/tos')).toBe(
          'https://twitter.com/tos'
        );
      });
    });
  });

  describe('openImages 画像を開く', () => {
    it('画像URLを1つ渡したとき開く', () => {
      window.open = jest.fn();
      openImages(['https://pbs.twimg.com/media/1st?format=jpg&name=orig']);
      expect(window.open.mock.calls.length).toBe(1);
      expect(window.open.mock.calls[0][0]).toBe(
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig'
      );
    });

    it('画像URLを2つ渡したとき逆順に開く', () => {
      window.open = jest.fn();
      openImages([
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig',
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig',
      ]);
      expect(window.open.mock.calls.length).toBe(2);
      expect(window.open.mock.calls[0][0]).toBe(
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[1][0]).toBe(
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig'
      );
    });

    it('画像URLを4つ渡したとき逆順に開く', () => {
      window.open = jest.fn();
      openImages([
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig',
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig',
        'https://pbs.twimg.com/media/3rd?format=jpg&name=orig',
        'https://pbs.twimg.com/media/4th?format=jpg&name=orig',
      ]);
      expect(window.open.mock.calls.length).toBe(4);
      expect(window.open.mock.calls[0][0]).toBe(
        'https://pbs.twimg.com/media/4th?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[1][0]).toBe(
        'https://pbs.twimg.com/media/3rd?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[2][0]).toBe(
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[3][0]).toBe(
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig'
      );
    });

    it('画像URLでないURLを1つ渡したときもそのまま開く', () => {
      window.open = jest.fn();
      openImages(['https://twitter.com/tos']);
      expect(window.open.mock.calls.length).toBe(1);
      expect(window.open.mock.calls[0][0]).toBe('https://twitter.com/tos');
    });

    it('undefinedを1つ渡したとき開かない', () => {
      window.open = jest.fn();
      openImages([undefined]);
      expect(window.open.mock.calls.length).toBe(0);
    });

    it('URLとundefinedを混ぜたときURLだけ開いてundefinedは開かない', () => {
      window.open = jest.fn();
      openImages([
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig',
        undefined,
        'https://twitter.com/tos',
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig',
      ]);
      expect(window.open.mock.calls.length).toBe(3);
      expect(window.open.mock.calls[0][0]).toBe(
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[1][0]).toBe('https://twitter.com/tos');
      expect(window.open.mock.calls[2][0]).toBe(
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig'
      );
    });

    it('要素0個の配列を渡したとき開かない', () => {
      window.open = jest.fn();
      openImages([]);
      expect(window.open.mock.calls.length).toBe(0);
    });
  });

  describe('getOptions', () => {
    describe('Chrome拡張機能のとき', () => {
      const originalChrome = window.chrome;
      beforeAll(() => {
        delete window.chrome;
        window.chrome = { runtime: { id: 'id' } };
      });
      afterAll(() => {
        window.chrome = originalChrome;
      });

      it('初期設定を取得できる', () => {
        const expected = {};
        OPTION_KEYS.forEach(key => {
          expected[key] = isTrue;
        });
        window.chrome.runtime.sendMessage = jest.fn((_, callback) =>
          callback({ data: {} })
        );
        expect(getOptions()).resolves.toStrictEqual(expected);
      });

      it('設定した値を取得できる', () => {
        const expected = {};
        OPTION_KEYS.forEach((key, i) => {
          expected[key] = i % 2 === 0 ? isTrue : isFalse;
        });
        window.chrome.runtime.sendMessage = jest.fn((_, callback) =>
          callback({ data: { ...expected } })
        );
        return getOptions().then(options => {
          return expect(options).toStrictEqual(expected);
        });
      });

      it('設定が取得できなかったらreject', () => {
        const expected = {};
        OPTION_KEYS.forEach(key => {
          expected[key] = isTrue;
        });
        window.chrome.runtime.sendMessage = jest.fn((_, callback) =>
          callback({})
        );
        expect(getOptions()).rejects.toBeUndefined();
      });
    });

    describe('Chrome拡張機能でないとき', () => {
      const originalChrome = window.chrome;
      beforeAll(() => {
        delete window.chrome;
        window.chrome = undefined;
      });
      afterAll(() => {
        window.chrome = originalChrome;
      });

      it('初期設定を取得できる', () => {
        const expected = {};
        OPTION_KEYS.forEach(key => {
          expected[key] = isFalse;
        });
        expect(getOptions()).resolves.toStrictEqual(expected);
      });
    });
  });
});
<commit_msg>add test for setStyle<commit_after>import { isTrue, isFalse, OPTION_KEYS, setStyle } from '../../src/main';
import {
  printException,
  collectUrlParams,
  formatUrl,
  openImages,
  getOptions,
} from '../../src/main';

const makeResultParams = ({ format, name }) => {
  return {
    protocol: 'https:',
    host: 'pbs.twimg.com',
    pathname: '/media/hogefuga123',
    format,
    name: name || null,
  };
};

describe('Utils', () => {
  describe('printException', () => {
    it('エラーメッセージの表示(予期せぬ状況の確認)', () => {
      console.log = jest.fn();
      printException('exception message');
      expect(console.log.mock.calls[0][0]).toBe(
        'tooi: exception message at: http://localhost/'
      );
    });
  });

  describe('URLのツール', () => {
    // URLの変換のテストの場合たち
    const cases = [
      {
        title: '何もなし',
        url: 'https://pbs.twimg.com/media/hogefuga123',
        params: { format: 'jpg' },
      },
      {
        title: '.jpg',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg',
        params: { format: 'jpg' },
      },
      {
        title: '.png',
        url: 'https://pbs.twimg.com/media/hogefuga123.png',
        params: { format: 'png' },
      },
      {
        title: '.jpg:orig',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg:orig',
        params: { format: 'jpg', name: 'orig' },
      },
      {
        title: '.jpg:large',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg:large',
        params: { format: 'jpg', name: 'large' },
      },
      {
        title: '?format=jpg',
        url: 'https://pbs.twimg.com/media/hogefuga123?format=jpg',
        params: { format: 'jpg' },
      },
      {
        title: '?format=png',
        url: 'https://pbs.twimg.com/media/hogefuga123?format=png',
        params: { format: 'png' },
      },
      {
        title: '.jpg?format=jpg',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg?format=jpg',
        params: { format: 'jpg' },
      },
      {
        title: '.jpg?format=png',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg?format=png',
        params: { format: 'jpg' },
      },
      {
        title: '.png?format=jpg',
        url: 'https://pbs.twimg.com/media/hogefuga123.png?format=jpg',
        params: { format: 'png' },
      },
      {
        title: '.jpg?name=large',
        url: 'https://pbs.twimg.com/media/hogefuga123.jpg?name=large',
        params: { format: 'jpg', name: 'large' },
      },
      {
        title: '?format=jpg&name=large',
        url: 'https://pbs.twimg.com/media/hogefuga123?format=jpg&name=large',
        params: { format: 'jpg', name: 'large' },
      },
      {
        title: '.png?format=jpg&name=orig',
        url: 'https://pbs.twimg.com/media/hogefuga123.png?format=jpg&name=orig',
        params: { format: 'png', name: 'orig' },
      },
    ];

    describe('collectUrlParams 画像urlの要素を集める', () => {
      cases.forEach(singleCase => {
        const { title, url, params } = singleCase;
        it(title, () => {
          expect(collectUrlParams(url)).toStrictEqual(makeResultParams(params));
        });
      });

      it('twitterの画像URLでないときnull', () => {
        expect(collectUrlParams('https://twitter.com/tos')).toBe(null);
      });
    });

    describe('formatUrl 画像URLを https～?format=〜&name=orig に揃える', () => {
      cases.forEach(singleCase => {
        const { title, url, params } = singleCase;
        it(title, () => {
          expect(formatUrl(url)).toBe(
            `https://pbs.twimg.com/media/hogefuga123?format=${params.format}&name=orig`
          );
        });
      });

      it('twitterの画像URLでないときそのまま', () => {
        expect(formatUrl('https://twitter.com/tos')).toBe(
          'https://twitter.com/tos'
        );
      });
    });
  });

  describe('openImages 画像を開く', () => {
    it('画像URLを1つ渡したとき開く', () => {
      window.open = jest.fn();
      openImages(['https://pbs.twimg.com/media/1st?format=jpg&name=orig']);
      expect(window.open.mock.calls.length).toBe(1);
      expect(window.open.mock.calls[0][0]).toBe(
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig'
      );
    });

    it('画像URLを2つ渡したとき逆順に開く', () => {
      window.open = jest.fn();
      openImages([
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig',
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig',
      ]);
      expect(window.open.mock.calls.length).toBe(2);
      expect(window.open.mock.calls[0][0]).toBe(
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[1][0]).toBe(
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig'
      );
    });

    it('画像URLを4つ渡したとき逆順に開く', () => {
      window.open = jest.fn();
      openImages([
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig',
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig',
        'https://pbs.twimg.com/media/3rd?format=jpg&name=orig',
        'https://pbs.twimg.com/media/4th?format=jpg&name=orig',
      ]);
      expect(window.open.mock.calls.length).toBe(4);
      expect(window.open.mock.calls[0][0]).toBe(
        'https://pbs.twimg.com/media/4th?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[1][0]).toBe(
        'https://pbs.twimg.com/media/3rd?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[2][0]).toBe(
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[3][0]).toBe(
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig'
      );
    });

    it('画像URLでないURLを1つ渡したときもそのまま開く', () => {
      window.open = jest.fn();
      openImages(['https://twitter.com/tos']);
      expect(window.open.mock.calls.length).toBe(1);
      expect(window.open.mock.calls[0][0]).toBe('https://twitter.com/tos');
    });

    it('undefinedを1つ渡したとき開かない', () => {
      window.open = jest.fn();
      openImages([undefined]);
      expect(window.open.mock.calls.length).toBe(0);
    });

    it('URLとundefinedを混ぜたときURLだけ開いてundefinedは開かない', () => {
      window.open = jest.fn();
      openImages([
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig',
        undefined,
        'https://twitter.com/tos',
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig',
      ]);
      expect(window.open.mock.calls.length).toBe(3);
      expect(window.open.mock.calls[0][0]).toBe(
        'https://pbs.twimg.com/media/2nd?format=jpg&name=orig'
      );
      expect(window.open.mock.calls[1][0]).toBe('https://twitter.com/tos');
      expect(window.open.mock.calls[2][0]).toBe(
        'https://pbs.twimg.com/media/1st?format=jpg&name=orig'
      );
    });

    it('要素0個の配列を渡したとき開かない', () => {
      window.open = jest.fn();
      openImages([]);
      expect(window.open.mock.calls.length).toBe(0);
    });
  });

  describe('getOptions', () => {
    describe('Chrome拡張機能のとき', () => {
      const originalChrome = window.chrome;
      beforeAll(() => {
        delete window.chrome;
        window.chrome = { runtime: { id: 'id' } };
      });
      afterAll(() => {
        window.chrome = originalChrome;
      });

      it('初期設定を取得できる', () => {
        const expected = {};
        OPTION_KEYS.forEach(key => {
          expected[key] = isTrue;
        });
        window.chrome.runtime.sendMessage = jest.fn((_, callback) =>
          callback({ data: {} })
        );
        expect(getOptions()).resolves.toStrictEqual(expected);
      });

      it('設定した値を取得できる', () => {
        const expected = {};
        OPTION_KEYS.forEach((key, i) => {
          expected[key] = i % 2 === 0 ? isTrue : isFalse;
        });
        window.chrome.runtime.sendMessage = jest.fn((_, callback) =>
          callback({ data: { ...expected } })
        );
        return getOptions().then(options => {
          return expect(options).toStrictEqual(expected);
        });
      });

      it('設定が取得できなかったらreject', () => {
        const expected = {};
        OPTION_KEYS.forEach(key => {
          expected[key] = isTrue;
        });
        window.chrome.runtime.sendMessage = jest.fn((_, callback) =>
          callback({})
        );
        expect(getOptions()).rejects.toBeUndefined();
      });
    });

    describe('Chrome拡張機能でないとき', () => {
      const originalChrome = window.chrome;
      beforeAll(() => {
        delete window.chrome;
        window.chrome = undefined;
      });
      afterAll(() => {
        window.chrome = originalChrome;
      });

      it('初期設定を取得できる', () => {
        const expected = {};
        OPTION_KEYS.forEach(key => {
          expected[key] = isFalse;
        });
        expect(getOptions()).resolves.toStrictEqual(expected);
      });
    });
  });

  describe('setStyle DOM要素にスタイルを当てる', () => {
    it('スタイル当たる', () => {
      const div = document.createElement('div');
      expect(div).toMatchSnapshot();
      setStyle(div, {
        display: 'none',
        color: '#123',
        'background-color': 'rgba(12, 34, 56, 0.7)',
      });
      expect(div).toMatchSnapshot();
    });
    it('空のスタイル渡すと何もしない', () => {
      const div = document.createElement('div');
      expect(div).toMatchSnapshot();
      setStyle(div, {});
      expect(div).toMatchSnapshot();
    });
    it('すでにあるスタイルは上書きされるが消えることはない', () => {
      const div = document.createElement('div');
      div.style.color = '#456';
      div.style.backgroundColor = '#789abc';
      div.style.fontSize = '150px';
      expect(div).toMatchSnapshot();
      setStyle(div, {
        display: 'none',
        color: '#123',
        'background-color': 'rgba(12, 34, 56, 0.7)',
      });
      expect(div).toMatchSnapshot();
    });
  });
});
<|endoftext|>


<commit_before>function Character(scene, spriteSheet) {

    var self = quicktigame2d.createSpriteSheet({
        image: 'assets/' + spriteSheet,
        width: 32,
        height: 48,
        border: 0,
        margin: 1
    });

    var textsprite = quicktigame2d.createTextSprite({
        text: 'Lorem ipsum dolor sit amet.',
        fontSize: 16,
        textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
        z: 2
    });
    textsprite.hide();

    self.halt = function() {
        // Ti.API.debug("Halt facing: " + self.direction);
        switch (self.direction) {
        case "UP":
            self.pauseAt(13);
            break;
        case "DOWN":
            self.pauseAt(0);
            break;
        case "LEFT":
            self.pauseAt(4);
            break;
        case "RIGHT":
            self.pauseAt(8);
            break;
        default:
            self.pauseAt(0);
        }
    };

    self.turnTowards = function(newDirection) {
        // Ti.API.debug("Moving towards: " + newDirection);

        if (self.direction !== newDirection) {
            switch (newDirection) {
            case "UP":
                self.animate(13, 4, 250, -1);
                break;
            case "DOWN":
                self.animate(0, 4, 250, -1);
                break;
            case "LEFT":
                self.animate(4, 4, 250, -1);
                break;
            case "RIGHT":
                self.animate(8, 4, 250, -1);
                break;
            default:
                self.animate(0, 4, 250, -1);
            }
            self.direction = newDirection;
        }
    }

    self.say = function(caption) {
        textsprite.text = caption;

        textsprite.x = self.x -(textsprite.width / 2);
        textsprite.y = self.y - textsprite.height - 15;

        textsprite.show();

        setTimeout(function() { textsprite.hide() }, 5000);
    }

    scene.add(self);
    scene.add(textsprite);

	return self;
}

module.exports = Character;<commit_msg>Chat and character select are now working<commit_after>function Character(scene, spriteSheet) {

    var self = quicktigame2d.createSpriteSheet({
        image: 'assets/' + spriteSheet,
        width: 32,
        height: 48,
        border: 0,
        margin: 1
    });

    var textsprite = quicktigame2d.createTextSprite({
        text: 'Lorem ipsum dolor sit amet.',
        fontSize: 24,
        textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
        z: 2
    });
    textsprite.color(0, 0, 1);
    textsprite.hide();

    self.halt = function() {
        // Ti.API.debug("Halt facing: " + self.direction);
        switch (self.direction) {
        case "UP":
            self.pauseAt(13);
            break;
        case "DOWN":
            self.pauseAt(0);
            break;
        case "LEFT":
            self.pauseAt(4);
            break;
        case "RIGHT":
            self.pauseAt(8);
            break;
        default:
            self.pauseAt(0);
        }
    };

    self.turnTowards = function(newDirection) {
        // Ti.API.debug("Moving towards: " + newDirection);

        if (self.direction !== newDirection) {
            switch (newDirection) {
            case "UP":
                self.animate(13, 4, 250, -1);
                break;
            case "DOWN":
                self.animate(0, 4, 250, -1);
                break;
            case "LEFT":
                self.animate(4, 4, 250, -1);
                break;
            case "RIGHT":
                self.animate(8, 4, 250, -1);
                break;
            default:
                self.animate(0, 4, 250, -1);
            }
            self.direction = newDirection;
        }
    }

    self.say = function(caption) {
        textsprite.text = caption;

        textsprite.x = self.x -(textsprite.width / 2);
        textsprite.y = self.y - textsprite.height - 15;

        textsprite.show();

        setTimeout(function() { textsprite.hide() }, 5000);
    }

    scene.add(self);
    scene.add(textsprite);

	return self;
}

module.exports = Character;<|endoftext|>


<commit_before>import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';
import Papa from 'npm:papaparse@4.1.2/papaparse.js';

@inject(HttpClient)
export class Start {
  graphData = {};

  // TODO baseUrl should be configurable
  // Works given that serverLocalCORS.py is started in canve/visualizer
  constructor(http){
    http.configure(config => {
      config
        .withBaseUrl('http://localhost:31338/');
    });

    this.http = http;
  }

  fetchNodes() {
    return this.http.fetch('canve-data/nodes', { headers: { 'Content-Type': 'text/plain' } })
      .then(nodesResponse => nodesResponse.text());
  }

  fetchEdges() {
    return this.http.fetch('canve-data/edges', { headers: { 'Content-Type': 'text/plain' } })
      .then(edgesResponse => edgesResponse.text());
  }

  // TODO Also need edges and some data cleaning - service?
  // TODO Background task for loading node-source files?
  // activate() {
  //   return this.http.fetch('canve-data/nodes', { headers: { 'Content-Type': 'text/plain' } })
  //     .then(nodesResponse => nodesResponse.text())
  //     .then(nodesText => Papa.parse(nodesText, {header: true}))
  //     .then(this.http.fetch('canve-data/edges', { headers: { 'Content-Type': 'text/plain' }}))
  //     // .then(edgesResponse => edgesResponse.text())
  //     // .then(edgesText => Papa.parse(edgesText, {header: true}))
  //     .catch(err => console.error(err.stack));
  // }
  activate() {
    return Promise.all([
      this.fetchNodes(),
      this.fetchEdges()
    ]).then(results => {
      this.graphData.nodes = Papa.parse(results[0], {header: true});
      this.graphData.edges = Papa.parse(results[1], {header: true});
      console.dir(this.graphData);
    }).catch(err => console.error(err.stack));
  }

}
<commit_msg>refactor code duplication and use template string<commit_after>import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';
import Papa from 'npm:papaparse@4.1.2/papaparse.js';

@inject(HttpClient)
export class Start {
  graphData = {};

  // TODO baseUrl should be configurable
  // serverLocalCORS.py in canve/visualizer must be running
  constructor(http){
    http.configure(config => {
      config
        .withBaseUrl('http://localhost:31338/');
    });

    this.http = http;
  }

  fetchData(dataType) {
    // send and receive text/plain to avoid pre-flight OPTIONS request which simple python server can't do
    return this.http.fetch(`canve-data/${dataType}`, { headers: { 'Content-Type': 'text/plain' } })
      .then(edgesResponse => edgesResponse.text());
  }

  // TODO Data cleaning service?
  // TODO Background task for loading node-source files
  activate() {
    return Promise.all([
      this.fetchData('nodes'),
      this.fetchData('edges')
    ]).then(results => {
      this.graphData.nodes = Papa.parse(results[0], {header: true});
      this.graphData.edges = Papa.parse(results[1], {header: true});
      console.dir(this.graphData);
    }).catch(err => console.error(err.stack));
  }

}
<|endoftext|>


<commit_before>"use strict";

//-----------------------------------------------------------------------------

const [processPath, , exchangeId, methodName, ... params] = process.argv.filter (x => !x.startsWith ('--'))
const verbose = process.argv.includes ('--verbose')

//-----------------------------------------------------------------------------

const ccxt      = require ('../../ccxt.js')
    , fs        = require ('fs')
    , path      = require ('path')
    , asTable   = require ('as-table')
    , util      = require ('util')
    , log       = require ('ololog').configure ({ locate: false })

//-----------------------------------------------------------------------------

require ('ansicolor').nice;

//-----------------------------------------------------------------------------

process.on ('uncaughtException',  e => { log.bright.red.error (e); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })

//-----------------------------------------------------------------------------

const exchange = new (ccxt)[exchangeId] ({ verbose })

//-----------------------------------------------------------------------------

// set up keys and settings, if any
const keysGlobal = path.resolve ('keys.json')
const keysLocal = path.resolve ('keys.local.json')

let globalKeysFile = fs.existsSync (keysGlobal) ? keysGlobal : false
let localKeysFile = fs.existsSync (keysLocal) ? keysLocal : globalKeysFile
let settings = localKeysFile ? (require (localKeysFile)[exchangeId] || {}) : {}

Object.assign (exchange, settings)

//-----------------------------------------------------------------------------

let printSupportedExchanges = function () {
    log ('Supported exchanges:', ccxt.exchanges.join (', ').green)
}

//-----------------------------------------------------------------------------

 function printUsage () {
    log ('This is an example of a basic command-line interface to all exchanges')
    log ('Usage: node', process.argv[1], 'id'.green, 'method'.yellow, '"param1" param2 "param3" param4 ...'.blue)
    log ('Examples:')
    log ('node', process.argv[1], 'okcoinusd fetchOHLCV BTC/USD 15m')
    log ('node', process.argv[1], 'bitfinex fetchBalance')
    log ('node', process.argv[1], 'kraken fetchOrderBook ETH/BTC')
    printSupportedExchanges ()
}

//-----------------------------------------------------------------------------

async function main () {

    const requirements = exchangeId && methodName
    if (!requirements) {

        printUsage ()

    } else {

        let args = params.map (param =>
            param.match (/[a-zA-Z]/g) ? param : parseFloat (param))

        console.log (await exchange[methodName] (... args))

    }
}

//-----------------------------------------------------------------------------

main ()
<commit_msg>added properties to examples/js/cli<commit_after>"use strict";

//-----------------------------------------------------------------------------

const [processPath, , exchangeId, methodName, ... params] = process.argv.filter (x => !x.startsWith ('--'))
const verbose = process.argv.includes ('--verbose')

//-----------------------------------------------------------------------------

const ccxt      = require ('../../ccxt.js')
    , fs        = require ('fs')
    , path      = require ('path')
    , asTable   = require ('as-table')
    , util      = require ('util')
    , log       = require ('ololog').configure ({ locate: false })

//-----------------------------------------------------------------------------

require ('ansicolor').nice;

//-----------------------------------------------------------------------------

process.on ('uncaughtException',  e => { log.bright.red.error (e); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })

//-----------------------------------------------------------------------------

const exchange = new (ccxt)[exchangeId] ({ verbose })

//-----------------------------------------------------------------------------

// set up keys and settings, if any
const keysGlobal = path.resolve ('keys.json')
const keysLocal = path.resolve ('keys.local.json')

let globalKeysFile = fs.existsSync (keysGlobal) ? keysGlobal : false
let localKeysFile = fs.existsSync (keysLocal) ? keysLocal : globalKeysFile
let settings = localKeysFile ? (require (localKeysFile)[exchangeId] || {}) : {}

Object.assign (exchange, settings)

//-----------------------------------------------------------------------------

let printSupportedExchanges = function () {
    log ('Supported exchanges:', ccxt.exchanges.join (', ').green)
}

//-----------------------------------------------------------------------------

 function printUsage () {
    log ('This is an example of a basic command-line interface to all exchanges')
    log ('Usage: node', process.argv[1], 'id'.green, 'method'.yellow, '"param1" param2 "param3" param4 ...'.blue)
    log ('Examples:')
    log ('node', process.argv[1], 'okcoinusd fetchOHLCV BTC/USD 15m')
    log ('node', process.argv[1], 'bitfinex fetchBalance')
    log ('node', process.argv[1], 'kraken fetchOrderBook ETH/BTC')
    printSupportedExchanges ()
}

//-----------------------------------------------------------------------------

async function main () {

    const requirements = exchangeId && methodName
    if (!requirements) {

        printUsage ()

    } else {

        let args = params.map (param =>
            param.match (/[a-zA-Z]/g) ? param : parseFloat (param))

        if (typeof exchange[methodName] == 'function') {
            log (await exchange[methodName] (... args))
        } else {
            log (exchange[methodName])
        }

    }
}

//-----------------------------------------------------------------------------

main ()
<|endoftext|>


<commit_before>const log = require('./logger');
const pullRequest = require('./pull-request');
const repoBranch = require('./repo-branch');
const rx = require('rx');

const allBuilds = [ ];
const allPrs = { };
const prIncludes = { };
const prIncluded = { };
const submoduleRepos = { };
const submoduleBuilds = { };
const watchedRepos = new rx.Subject();

function addBuildConfig(buildConfig) {
	log.debug(`Adding Leeroy config for ${buildConfig.repo.id}`);

	allBuilds.push(buildConfig);

	for (let submodule in buildConfig.submodules) {
		const id = `${submodule}/${buildConfig.submodules[submodule]}`;
		submoduleBuilds[id] = submoduleBuilds[id] || [];
		submoduleBuilds[id].push(buildConfig);

		if (!submoduleRepos[submodule]) {
			submoduleRepos[submodule] = true;
			watchedRepos.onNext(submodule);
		}
    }
}

function addPullRequest(pr) {
	if (!allPrs[pr.id])
		allPrs[pr.id] = pr;
	else
		pr = allPrs[pr.id];
	log.debug(`Added ${pr.id}.`);
	return pr;
}

function addPullRequestDependency(parent, child) {
	log.info(`Adding link from ${parent} to ${child}`);
	prIncludes[parent] = prIncludes[parent] || [];
	prIncludes[parent].push(child);
	prIncluded[child] = prIncluded[child] || [];
	prIncluded[child].push(parent);
};

exports.addBuildConfig = addBuildConfig;
exports.addPullRequest = addPullRequest;
exports.addPullRequestDependency = addPullRequestDependency;
exports.watchedRepos = watchedRepos;
<commit_msg>Use Set.<commit_after>const log = require('./logger');
const pullRequest = require('./pull-request');
const repoBranch = require('./repo-branch');
const rx = require('rx');

const allBuilds = [ ];
const allPrs = { };
const prIncludes = { };
const prIncluded = { };
const submoduleRepos = new Set();
const submoduleBuilds = { };
const watchedRepos = new rx.Subject();

function addBuildConfig(buildConfig) {
	log.debug(`Adding Leeroy config for ${buildConfig.repo.id}`);

	allBuilds.push(buildConfig);

	for (let submodule in buildConfig.submodules) {
		const id = `${submodule}/${buildConfig.submodules[submodule]}`;
		submoduleBuilds[id] = submoduleBuilds[id] || [];
		submoduleBuilds[id].push(buildConfig);

		if (!submoduleRepos.has(submodule)) {
			submoduleRepos.add(submodule);
			watchedRepos.onNext(submodule);
		}
    }
}

function addPullRequest(pr) {
	if (!allPrs[pr.id])
		allPrs[pr.id] = pr;
	else
		pr = allPrs[pr.id];
	log.debug(`Added ${pr.id}.`);
	return pr;
}

function addPullRequestDependency(parent, child) {
	log.info(`Adding link from ${parent} to ${child}`);
	prIncludes[parent] = prIncludes[parent] || [];
	prIncludes[parent].push(child);
	prIncluded[child] = prIncluded[child] || [];
	prIncluded[child].push(parent);
};

exports.addBuildConfig = addBuildConfig;
exports.addPullRequest = addPullRequest;
exports.addPullRequestDependency = addPullRequestDependency;
exports.watchedRepos = watchedRepos;
<|endoftext|>


<commit_before>"use strict";

//-----------------------------------------------------------------------------

const [processPath, , exchangeId, methodName, ... params] = process.argv.filter (x => !x.startsWith ('--'))
const verbose = process.argv.includes ('--verbose')

//-----------------------------------------------------------------------------

const ccxt      = require ('../../ccxt.js')
    , fs        = require ('fs')
    , path      = require ('path')
    , asTable   = require ('as-table')
    , util      = require ('util')
    , log       = require ('ololog').configure ({ locate: false })
    , { ExchangeError, NetworkError } = ccxt

//-----------------------------------------------------------------------------

require ('ansicolor').nice

//-----------------------------------------------------------------------------

process.on ('uncaughtException',  e => { log.bright.red.error (e); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })

//-----------------------------------------------------------------------------

const exchange = new (ccxt)[exchangeId] ({ verbose })

//-----------------------------------------------------------------------------

// set up keys and settings, if any
const keysGlobal = path.resolve ('keys.json')
const keysLocal = path.resolve ('keys.local.json')

let globalKeysFile = fs.existsSync (keysGlobal) ? keysGlobal : false
let localKeysFile = fs.existsSync (keysLocal) ? keysLocal : globalKeysFile
let settings = localKeysFile ? (require (localKeysFile)[exchangeId] || {}) : {}

Object.assign (exchange, settings)

//-----------------------------------------------------------------------------

let printSupportedExchanges = function () {
    log ('Supported exchanges:', ccxt.exchanges.join (', ').green)
}

//-----------------------------------------------------------------------------

 function printUsage () {
    log ('This is an example of a basic command-line interface to all exchanges')
    log ('Usage: node', process.argv[1], 'id'.green, 'method'.yellow, '"param1" param2 "param3" param4 ...'.blue)
    log ('Examples:')
    log ('node', process.argv[1], 'okcoinusd fetchOHLCV BTC/USD 15m')
    log ('node', process.argv[1], 'bitfinex fetchBalance')
    log ('node', process.argv[1], 'kraken fetchOrderBook ETH/BTC')
    printSupportedExchanges ()
}

//-----------------------------------------------------------------------------

async function main () {

    const requirements = exchangeId && methodName
    if (!requirements) {

        printUsage ()

    } else {

        let args = params.map (param => {
            if (param[0] === '{')
                return JSON.parse (param)
            return param.match (/[a-zA-Z]/g) ? param : parseFloat (param)
        })

        if (typeof exchange[methodName] == 'function') {
            try {
                log (await exchange[methodName] (... args))
            } catch (e) {
                if (e instanceof ExchangeError) {
                    log.red (e.constructor.name, e.message)
                } else if (e instanceof NetworkError) {
                    log.yellow (e.constructor.name, e.message)
                } else {
                    throw e
                }
            }
        } else {
            log (exchange[methodName])
        }

    }
}

//-----------------------------------------------------------------------------

main ()
<commit_msg>more verbose logging to cli da0cf38<commit_after>"use strict";

//-----------------------------------------------------------------------------

const [processPath, , exchangeId, methodName, ... params] = process.argv.filter (x => !x.startsWith ('--'))
const verbose = process.argv.includes ('--verbose')

//-----------------------------------------------------------------------------

const ccxt      = require ('../../ccxt.js')
    , fs        = require ('fs')
    , path      = require ('path')
    , asTable   = require ('as-table')
    , util      = require ('util')
    , log       = require ('ololog').configure ({ locate: false })
    , { ExchangeError, NetworkError } = ccxt

//-----------------------------------------------------------------------------

require ('ansicolor').nice

//-----------------------------------------------------------------------------

process.on ('uncaughtException',  e => { log.bright.red.error (e); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })

//-----------------------------------------------------------------------------

const exchange = new (ccxt)[exchangeId] ({ verbose })

//-----------------------------------------------------------------------------

// set up keys and settings, if any
const keysGlobal = path.resolve ('keys.json')
const keysLocal = path.resolve ('keys.local.json')

let globalKeysFile = fs.existsSync (keysGlobal) ? keysGlobal : false
let localKeysFile = fs.existsSync (keysLocal) ? keysLocal : globalKeysFile
let settings = localKeysFile ? (require (localKeysFile)[exchangeId] || {}) : {}

Object.assign (exchange, settings)

//-----------------------------------------------------------------------------

let printSupportedExchanges = function () {
    log ('Supported exchanges:', ccxt.exchanges.join (', ').green)
}

//-----------------------------------------------------------------------------

 function printUsage () {
    log ('This is an example of a basic command-line interface to all exchanges')
    log ('Usage: node', process.argv[1], 'id'.green, 'method'.yellow, '"param1" param2 "param3" param4 ...'.blue)
    log ('Examples:')
    log ('node', process.argv[1], 'okcoinusd fetchOHLCV BTC/USD 15m')
    log ('node', process.argv[1], 'bitfinex fetchBalance')
    log ('node', process.argv[1], 'kraken fetchOrderBook ETH/BTC')
    printSupportedExchanges ()
}

//-----------------------------------------------------------------------------

async function main () {

    const requirements = exchangeId && methodName
    if (!requirements) {

        printUsage ()

    } else {

        let args = params.map (param => {
            if (param[0] === '{')
                return JSON.parse (param)
            return param.match (/[a-zA-Z]/g) ? param : parseFloat (param)
        })

        if (typeof exchange[methodName] == 'function') {
            try {
                log (await exchange[methodName] (... args))
            } catch (e) {

                if (e instanceof ExchangeError) {

                    log.red (e.constructor.name, e.message)

                } else if (e instanceof NetworkError) {

                    log.yellow (e.constructor.name, e.message)

                }

                log.dim ('---------------------------------------------------')

                // rethrow for call-stack // other errors
                throw e

            }
        } else {
            log (exchange[methodName])
        }

    }
}

//-----------------------------------------------------------------------------

main ()
<|endoftext|>


<commit_before>const noLaunch = process.argv.includes('--no-launch')
const testMinified = process.argv.includes('--minified')
const isSauce = process.argv.includes('--sauce')
const isNetlify = process.argv.includes('--netlify')

if (isNetlify) {
  process.env.CHROME_BIN = require('puppeteer').executablePath()
}

const webpackConfig = {
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|dist)/,
        use: {
          loader: 'babel-loader',
          options: {/* babel options */}
        }
      }
    ]
  }
}

const karmaPlugins = [
  'karma-webpack',
  'karma-qunit',
  'karma-spec-reporter',
  'karma-sourcemap-loader',
  'karma-chrome-launcher',
  'karma-firefox-launcher',
  'karma-ie-launcher',
  'karma-sauce-launcher'
]

const preprocessors = {
  'test/qunit/**/*.js': [
    'webpack',
    'sourcemap'
  ],
}

const sauceLabsLaunchers = {
  safari: {
    base: 'SauceLabs',
    browserName: 'Safari',
    browserVersion: 'latest',
    platformName: 'macOS 10.15'
  },
  edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    browserVersion: '18.17763',
    platformName: 'Windows 10',
  },
  ie: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    browserVersion: 'latest',
    platformName: 'Windows 7'
  },
}

function checkSauceCredentials () {
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.error('SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables must be set')
    process.exit(1)
  }
}

function getFiles () {
  let files
  if (testMinified) {
    files = [
      'dist/sweetalert2.all.min.js'
    ]
  } else {
    files = [
      'dist/sweetalert2.css',
      'dist/sweetalert2.js'
    ]
  }
  return files.concat([
    'node_modules/promise-polyfill/dist/polyfill.min.js',
    'test/qunit/**/*.js'
  ])
}

function getBrowsers () {
  if (noLaunch) {
    return []
  }

  let browsers = ['ChromeHeadless']

  // Cron on GitHub Actions or check:qunit --sauce
  if (isSauce) {
    checkSauceCredentials()
    browsers = Object.keys(sauceLabsLaunchers)

  // GitHub Actions
  } else if (process.env.GITHUB_ACTION) {
    browsers = ['ChromeHeadless', 'FirefoxHeadless']
  }

  return browsers
}

module.exports = function (config) {
  config.set({
    port: 3000,
    plugins: karmaPlugins,

    frameworks: ['qunit'],
    qunit: { reorder: false },

    customLaunchers: sauceLabsLaunchers,

    files: getFiles(),
    browsers: getBrowsers(),
    reporters: ['spec', 'saucelabs'],
    preprocessors,

    webpack: webpackConfig,
    webpackMiddleware: {
      stats: 'errors-only'
    },

    captureTimeout: 360000,
    browserNoActivityTimeout: 360000
  })
}
<commit_msg>chore: fix karma config<commit_after>const noLaunch = process.argv.includes('--no-launch')
const testMinified = process.argv.includes('--minified')
const isSauce = process.argv.includes('--sauce')
const isNetlify = process.argv.includes('--netlify')

if (isNetlify) {
  process.env.CHROME_BIN = require('puppeteer').executablePath()
}

const webpackConfig = {
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|dist)/,
        use: {
          loader: 'babel-loader',
          options: {/* babel options */}
        }
      }
    ]
  }
}

const karmaPlugins = [
  'karma-webpack',
  'karma-qunit',
  'karma-spec-reporter',
  'karma-sourcemap-loader',
  'karma-chrome-launcher',
  'karma-firefox-launcher',
  'karma-ie-launcher',
  'karma-sauce-launcher'
]

const preprocessors = {
  'test/qunit/**/*.js': [
    'webpack',
    'sourcemap'
  ],
}

const sauceLabsLaunchers = {
  safari: {
    base: 'SauceLabs',
    browserName: 'Safari',
    browserVersion: 'latest',
    platformName: 'macOS 10.15'
  },
  edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    browserVersion: '18.17763',
    platformName: 'Windows 10',
  },
  ie: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    browserVersion: 'latest',
    platformName: 'Windows 7'
  },
}

function checkSauceCredentials () {
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.error('SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables must be set')
    process.exit(1)
  }
}

function getFiles () {
  let files
  if (testMinified) {
    files = [
      'dist/sweetalert2.all.min.js'
    ]
  } else {
    files = [
      'dist/sweetalert2.css',
      'dist/sweetalert2.js'
    ]
  }
  return files.concat([
    'node_modules/promise-polyfill/dist/polyfill.min.js',
    'test/qunit/**/*.js'
  ])
}

function getBrowsers () {
  if (noLaunch) {
    return []
  }

  let browsers = ['ChromeHeadless']

  // Cron on GitHub Actions or check:qunit --sauce
  if (isSauce) {
    checkSauceCredentials()
    browsers = Object.keys(sauceLabsLaunchers)

  // GitHub Actions
  } else if (process.env.GITHUB_ACTION) {
    browsers = ['ChromeHeadless', 'FirefoxHeadless']
  }

  return browsers
}

function getReporters () {
  return isSauce ? ['spec', 'saucelabs'] : ['spec']
}

module.exports = function (config) {
  config.set({
    port: 3000,
    plugins: karmaPlugins,

    frameworks: ['qunit'],
    qunit: { reorder: false },

    customLaunchers: sauceLabsLaunchers,

    files: getFiles(),
    browsers: getBrowsers(),
    reporters: getReporters(),
    preprocessors,

    webpack: webpackConfig,
    webpackMiddleware: {
      stats: 'errors-only'
    },

    captureTimeout: 360000,
    browserNoActivityTimeout: 360000
  })
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Thu Apr 18 2013 11:02:23 GMT-0500 (CDT)

// base path, that will be used to resolve files and exclude
basePath = '';

frameworks = ['jasmine'];

// list of files / patterns to load in the browser
files = [
  'src/main/webapp/resources/dev/js/vendor/jquery.js',
  'src/main/webapp/resources/dev/js/vendor/foundation/foundation.js',
  'src/main/webapp/resources/dev/js/vendor/foundation/foundation.reveal.js',
  'src/main/webapp/resources/dev/js/vendor/angular/angular.min.js',
  'src/main/webapp/resources/dev/js/vendor/angular/angular-resource.min.js',
  'src/test/js/lib/angular/angular-mocks.js',
  'src/main/webapp/resources/dev/js/**/*.js',
  'src/test/js/unit/*.spec.js'
];

// list of files to exclude
exclude = [

];

// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];

// web server port
port = 9876;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['PhantomJS'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;

plugins = [
  'karma-jasmine',
  'karma-phantomjs-launcher',
  'karma-junit-reporter'
];
<commit_msg>Renamed vendor to lib<commit_after>// Karma configuration
// Generated on Thu Apr 18 2013 11:02:23 GMT-0500 (CDT)

// base path, that will be used to resolve files and exclude
basePath = '';

frameworks = ['jasmine'];

// list of files / patterns to load in the browser
files = [
  'src/main/webapp/resources/dev/js/lib/jquery.js',
  'src/main/webapp/resources/dev/js/lib/foundation/foundation.js',
  'src/main/webapp/resources/dev/js/lib/foundation/foundation.reveal.js',
  'src/main/webapp/resources/dev/js/lib/angular/angular.min.js',
  'src/main/webapp/resources/dev/js/lib/angular/angular-resource.min.js',
  'src/test/js/lib/angular/angular-mocks.js',
  'src/main/webapp/resources/dev/js/**/*.js',
  'src/test/js/unit/*.spec.js'
];

// list of files to exclude
exclude = [

];

// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];

// web server port
port = 9876;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['PhantomJS'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;

plugins = [
  'karma-jasmine',
  'karma-phantomjs-launcher',
  'karma-junit-reporter'
];
<|endoftext|>


<commit_before>var sys = require('sys');
sys.puts('Running... Hit CTRL-C To Exit.');

var endtable = require('endtable');

var engine = new endtable.Engine({
	database: 'people_example',
	legacy: true,
	host: 'localhost',
	user: '',
	password: '',
	errorCallback: function(error) {
		// When views aren't found they raise a warning.
		sys.puts(JSON.stringify(error));
	}
});

var Person = endtable.Object.extend(
	{
		sayName: function() {
			sys.puts('Hello, my name is ' + this.name + '!');
		}
	},
	{
		engine: engine,
		type: 'person'
	}
);

function populateData() {
	sys.puts('Populating fake data.');

	var person = new Person({
		name: 'Christian',
		age: 28,
		sex: 'male'
	}, function(error, obj) {
		sys.puts('Created person.')
	})

	var ben = new Person({
		name: 'Benjamin Coe',
		age: 27,
		sex: 'male',
		interests: ['climbing']
	})

	setTimeout(function() {
		ben.awesome = true;
	}, 250);

	setTimeout(function() {
		ben.interests.push('programming');
	}, 500);

	person = new Person({
		name: 'Sally Johnson',
		age: 24,
		sex: 'female'
	})

	person = new Person({
		name: 'JBoss',
		age: 30,
		sex: 'male'
	})
}

function performQuery() {

	setTimeout(function() {

		sys.puts('Performing query.');

		new Person().load({
			keys: 'age',
			startkey: 28,
			endkey: 50
		}, function(error, obj) {
			for (var i = 0; i < obj.length; i++) {
				obj[i].sayName();
			}
		})

	}, 1000);
}

(function resetDatabase(callback) {
	sys.puts('Resetting database.');
	engine.connector.deleteDatabase(function() {
		engine.connector.createDatabase(function(error, doc) {
			callback();
		});
	});
})(function() {
	populateData();
	performQuery();
});<commit_msg>Updated example code so it does not connect to a legacy database.<commit_after>var sys = require('sys');
sys.puts('Running... Hit CTRL-C To Exit.');

var endtable = require('endtable');

var engine = new endtable.Engine({
	database: 'people_example',
	legacy: false,
	host: 'localhost',
	user: '',
	password: '',
	errorCallback: function(error) {
		// When views aren't found they raise a warning.
		sys.puts(JSON.stringify(error));
	}
});

var Person = endtable.Object.extend(
	{
		sayName: function() {
			sys.puts('Hello, my name is ' + this.name + '!');
		}
	},
	{
		engine: engine,
		type: 'person'
	}
);

function populateData() {
	sys.puts('Populating fake data.');

	var person = new Person({
		name: 'Christian',
		age: 28,
		sex: 'male'
	}, function(error, obj) {
		sys.puts('Created person.')
	})

	var ben = new Person({
		name: 'Benjamin Coe',
		age: 27,
		sex: 'male',
		interests: ['climbing']
	})

	setTimeout(function() {
		ben.awesome = true;
	}, 250);

	setTimeout(function() {
		ben.interests.push('programming');
	}, 500);

	person = new Person({
		name: 'Sally Johnson',
		age: 24,
		sex: 'female'
	})

	person = new Person({
		name: 'JBoss',
		age: 30,
		sex: 'male'
	})
}

function performQuery() {

	setTimeout(function() {

		sys.puts('Performing query.');

		new Person().load({
			keys: 'age',
			startkey: 28,
			endkey: 50
		}, function(error, obj) {
			for (var i = 0; i < obj.length; i++) {
				obj[i].sayName();
			}
		})

	}, 1000);
}

(function resetDatabase(callback) {
	sys.puts('Resetting database.');
	engine.connector.deleteDatabase(function() {
		engine.connector.createDatabase(function(error, doc) {
			callback();
		});
	});
})(function() {
	populateData();
	performQuery();
});<|endoftext|>


<commit_before>// Load modules

var Hapi = require('hapi');
var Tv = require('../');

// Declare internals

var internals = {};

var server = new Hapi.Server(8080);

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        return reply('1');
    }
});

server.pack.register(Tv, function (err) {

    if (err) {
        console.log(err);
        return;
    }

    server.start(function () {

        console.log('Server started at: ' + server.info.uri);
    });
});<commit_msg>added new line at end of file simple.js<commit_after>// Load modules

var Hapi = require('hapi');
var Tv = require('../');

// Declare internals

var internals = {};

var server = new Hapi.Server(8080);

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        return reply('1');
    }
});

server.pack.register(Tv, function (err) {

    if (err) {
        console.log(err);
        return;
    }

    server.start(function () {

        console.log('Server started at: ' + server.info.uri);
    });
});
<|endoftext|>


<commit_before>'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
app
.factory('socket', function ($rootScope) {
  var socket;
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      })
    },
    connect: function(){
      if(!socket){
//          socket = io.connect('http://www.ellisande.com:3000/');
          socket = io.connect('http://localhost:3000/');
      } else {
        //socket.socket.connect();
      }
    },
    disconnect: function(){
      socket.disconnect();
    }
  };
}).
factory('timerService', function(socket, $timeout){
    return function($scope){
        $scope.duration = moment.duration(3, 'minutes');
        var currentTimeout = {};

        var startTimeout = function(timer){
            var onTimeout = function(){
                timer.expired = moment().isAfter(timer.endTime);
                if(timer.expired){
                    $scope.duration = moment.duration(3, 'minutes');
                } else {
                    $scope.duration = timer.currentDuration();
                    currentTimeout = $timeout(onTimeout,1000);
                }
            }
            currentTimeout = $timeout(onTimeout,1000);
        };

        var timer = {
            endTime: moment(),
            currentDuration: function(){
              return moment.duration(this.endTime.diff(moment()));
            },
            start: function(duration){
                socket.emit('timer:start',{
                    duration:duration
                });
            },

            stop: function(){
                $scope.duration = moment.duration(3,'minutes');
                $timeout.cancel(currentTimeout);
                timer.expired = true;
                socket.emit('timer:stop',{});
            },

            expired: true
        };

        socket.on('timer:start', function(data){
            $timeout.cancel(currentTimeout);
            timer.endTime = moment().add(data.duration, 'milliseconds');
            startTimeout(timer);
            timer.expired = false;
        });

        socket.on('timer:stop', function(){
            if(!timer.expired){
                timer.stop()
            };
        });
        return timer;
    };
});
<commit_msg>Code cleanup.<commit_after>'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
app
.factory('socket', function ($rootScope) {
  var socket;
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      })
    },
    connect: function(){
      if(!socket){
          socket = io.connect('http://localhost:3000/');
      } else {
        //socket.socket.connect();
      }
    },
    disconnect: function(){
      socket.disconnect();
    }
  };
}).
factory('timerService', function(socket, $timeout){
    return function($scope){
        $scope.duration = moment.duration(3, 'minutes');
        var currentTimeout = {};

        var startTimeout = function(timer){
            var onTimeout = function(){
                timer.expired = moment().isAfter(timer.endTime);
                if(timer.expired){
                    $scope.duration = moment.duration(3, 'minutes');
                } else {
                    $scope.duration = timer.currentDuration();
                    currentTimeout = $timeout(onTimeout,1000);
                }
            }
            currentTimeout = $timeout(onTimeout,1000);
        };

        var timer = {
            endTime: moment(),
            currentDuration: function(){
              return moment.duration(this.endTime.diff(moment()));
            },
            start: function(duration){
                socket.emit('timer:start',{
                    duration:duration
                });
            },

            stop: function(){
                $scope.duration = moment.duration(3,'minutes');
                $timeout.cancel(currentTimeout);
                timer.expired = true;
                socket.emit('timer:stop',{});
            },

            expired: true
        };

        socket.on('timer:start', function(data){
            $timeout.cancel(currentTimeout);
            timer.endTime = moment().add(data.duration, 'milliseconds');
            startTimeout(timer);
            timer.expired = false;
        });

        socket.on('timer:stop', function(){
            if(!timer.expired){
                timer.stop()
            };
        });
        return timer;
    };
});
<|endoftext|>


<commit_before>'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('myApp.services', []).
  value('version', '0.1');
<commit_msg>version changed<commit_after>'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('myApp.services', []).
  value('version', '0.0');
<|endoftext|>


<commit_before>import Ember from "ember";
import QUnit from "qunit";
import config from '../../config/environment';

var DEFAULT_TIMEOUT = config.APP.defaultWaitForTimeout || 500;

var waitFor = function(callback, timeout) {
    timeout = timeout || DEFAULT_TIMEOUT;
    stop();
    Ember.run.later(function(){
        callback();
        start();
    }, timeout);
};

export {waitFor};
<commit_msg>[FEATURE] update waitFor API to take assert as first parameter<commit_after>import Ember from "ember";
import config from "../../config/environment";

var APP_TIMEOUT = config.APP.defaultWaitForTimeout;
var DEFAULT_TIMEOUT = APP_TIMEOUT !== undefined ? APP_TIMEOUT : 500;

var waitFor = function(assert, callback, timeout) {
    timeout = timeout || DEFAULT_TIMEOUT;
    var done = assert.async();
    Ember.run.later(function(){
        callback();
        done();
    }, timeout);
};

export {waitFor};
<|endoftext|>


<commit_before>

(function() {

  // list of guis
  var guis = [];

  // default slider params
  var sliderMin = 0;
  var sliderMax = 100;
  var sliderStep = 1;

  // default gui provider
  var guiProvider = 'QuickSettings';

  // Create a GUI using QuickSettings (or DAT.GUI or ...)
  p5.prototype.createGui = function(label, x, y, provider) {

    label = label || 'GUI';
    x = x || 20;
    y = y || 20;
    provider = provider || guiProvider;

    var gui;

    // create a gui using the provider
    if(provider === 'QuickSettings') {
      if(QuickSettings) {
        console.log('Creating p5.gui powered by QuickSettings.');
        gui = new QSGui(label, x, y);
      } else {
        console.log('QuickSettings not found. Is the script included in your HTML?');
        gui = new DummyGui(label, x, y);
      }
    } else {
      console.log('Unknown GUI provider ' + provider);
      gui = new DummyGui(label, x, y);
    }

    // add it to the list of guis
    guis.push(gui);

    // return it
    return gui;

  };

  p5.prototype.removeGui = function(gui) {
    // TODO: implement this
  };

  // update defaults used for creation of sliders
  p5.prototype.sliderRange = function(vmin, vmax, vstep) {
    sliderMin = vmin;
    sliderMax = vmax;
    sliderStep = vstep;
  };

  // extend default behaviour of noLoop()
  p5.prototype.noLoop = function() {
    this._loop = false;
    for(var i = 0; i < guis.length; i++) {
      guis[i].noLoop();
    }
  };

  // extend default behaviour of loop()
  p5.prototype.loop = function() {
    for(var i = 0; i < guis.length; i++) {
      guis[i].loop();
    }
    this._loop = true;
    this._draw();
  };

  // interface for quicksettings
  function QSGui(label, x, y) {

    var qs = QuickSettings.create(x, y, label);
    this.prototype = qs;

    // addGlobals(global1, global2, ...) to add the selected globals
    this.addGlobals = function() {
      qs.bindGlobals(arguments);
    };

    // addObject(object) to add all params of the object
    // addObject(object, param1, param2, ...) to add selected params
    this.addObject = function() {
      // get object
      object = arguments[0];
      // get remaining params
      params = arguments.slice(1);
      // if no arguments are provided take all keys of the object
      if(params.length === 0) {
        params = object.keys();
      }
      qs.bindParams(object, params);
    };

    // noLoop() to call draw every time the gui changes when we are not looping
    this.noLoop = function() {
      qs.setGlobalChangeHandler(draw);
    };

    this.loop = function() {
      qs.setGlobalChangeHandler(null);
    };

    this.show = function() { qs.show(); };
    this.hide = function() { qs.hide(); };

  }

  // Just a Dummy object that provides the GUI interface
  function DummyGui() {
    var f = function() {};
    this.addGlobals = f;
    this.noLoop = f;
    this.addObject = f;
    this.show = f;
  }

  // Extend Quicksettings
  // so it can magically create a GUI for parameters passed by name
  QuickSettings.bindParams = function(object, params) {

    // iterate over all the arguments
    for(var i = 0; i < params.length; i++) {

      var arg = params[i];
      var val = object[arg];
      var typ = typeof val;

      // console.log(typ, arg, val);

      switch(typ) {

        case 'object':
          // color triple ?
          if(val instanceof Array && val.length === 3 && typeof val[0] === 'number') {
            // create color according to the current color mode
            var c = color(val[0], val[1], val[2]);
            // get decimal RGB values
            var c2 = c.levels.slice(0,3);
            // create HTML color code
            var vcolor = '#' + c2.map(function(value) {
              return ('0' + value.toString(16)).slice(-2);
            }).join('');
            this.bindColor(arg, vcolor, object);
          } else {
            // multiple choice drop down list
            this.bindDropDown(arg, val, object);
            object[arg] = val[0];
          }
          break;

        case 'number':
          // range from 0 to twice the value
          var vmin = min(val, sliderMin);
          var vmax = max(val, sliderMax);
          var vstep = sliderStep || 1;
          this.bindRange(arg, vmin, vmax, val, vstep, object);
          break;

        case 'string':
          var HEX6 = /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i;
          if(HEX6.test(val)) {
            // HTML color value (such as #ff0000)
            this.bindColor(arg, val, object);
          } else {
            // String value
            this.bindText(arg, val, object);
          }
          break;

        case 'boolean':
          this.bindBoolean(arg, object[arg], object);
          break;
      }
    }
  };

  // bind params that are defined globally
  QuickSettings.bindGlobals = function(params) {
    this.bindParams(window, params);
  };

})();
<commit_msg>set the slider boundaries with variables<commit_after>

(function() {

  // list of guis
  var guis = [];

  // default slider params
  var sliderMin = 0;
  var sliderMax = 100;
  var sliderStep = 1;

  // default gui provider
  var guiProvider = 'QuickSettings';

  // Create a GUI using QuickSettings (or DAT.GUI or ...)
  p5.prototype.createGui = function(label, x, y, provider) {

    label = label || 'GUI';
    x = x || 20;
    y = y || 20;
    provider = provider || guiProvider;

    var gui;

    // create a gui using the provider
    if(provider === 'QuickSettings') {
      if(QuickSettings) {
        console.log('Creating p5.gui powered by QuickSettings.');
        gui = new QSGui(label, x, y);
      } else {
        console.log('QuickSettings not found. Is the script included in your HTML?');
        gui = new DummyGui(label, x, y);
      }
    } else {
      console.log('Unknown GUI provider ' + provider);
      gui = new DummyGui(label, x, y);
    }

    // add it to the list of guis
    guis.push(gui);

    // return it
    return gui;

  };

  p5.prototype.removeGui = function(gui) {
    // TODO: implement this
  };

  // update defaults used for creation of sliders
  p5.prototype.sliderRange = function(vmin, vmax, vstep) {
    sliderMin = vmin;
    sliderMax = vmax;
    sliderStep = vstep;
  };

  // extend default behaviour of noLoop()
  p5.prototype.noLoop = function() {
    this._loop = false;
    for(var i = 0; i < guis.length; i++) {
      guis[i].noLoop();
    }
  };

  // extend default behaviour of loop()
  p5.prototype.loop = function() {
    for(var i = 0; i < guis.length; i++) {
      guis[i].loop();
    }
    this._loop = true;
    this._draw();
  };

  // interface for quicksettings
  function QSGui(label, x, y) {

    var qs = QuickSettings.create(x, y, label);
    this.prototype = qs;

    // addGlobals(global1, global2, ...) to add the selected globals
    this.addGlobals = function() {
      qs.bindGlobals(arguments);
    };

    // addObject(object) to add all params of the object
    // addObject(object, param1, param2, ...) to add selected params
    this.addObject = function() {
      // get object
      object = arguments[0];
      // get remaining params
      params = arguments.slice(1);
      // if no arguments are provided take all keys of the object
      if(params.length === 0) {
        params = object.keys();
      }
      qs.bindParams(object, params);
    };

    // noLoop() to call draw every time the gui changes when we are not looping
    this.noLoop = function() {
      qs.setGlobalChangeHandler(draw);
    };

    this.loop = function() {
      qs.setGlobalChangeHandler(null);
    };

    this.show = function() { qs.show(); };
    this.hide = function() { qs.hide(); };

  }

  // Just a Dummy object that provides the GUI interface
  function DummyGui() {
    var f = function() {};
    this.addGlobals = f;
    this.noLoop = f;
    this.addObject = f;
    this.show = f;
  }

  // Extend Quicksettings
  // so it can magically create a GUI for parameters passed by name
  QuickSettings.bindParams = function(object, params) {

    // iterate over all the arguments
    for(var i = 0; i < params.length; i++) {

      var arg = params[i];
      var val = object[arg];
      var typ = typeof val;

      // console.log(typ, arg, val);

      switch(typ) {

        case 'object':
          // color triple ?
          if(val instanceof Array && val.length === 3 && typeof val[0] === 'number') {
            // create color according to the current color mode
            var c = color(val[0], val[1], val[2]);
            // get decimal RGB values
            var c2 = c.levels.slice(0,3);
            // create HTML color code
            var vcolor = '#' + c2.map(function(value) {
              return ('0' + value.toString(16)).slice(-2);
            }).join('');
            this.bindColor(arg, vcolor, object);
          } else {
            // multiple choice drop down list
            this.bindDropDown(arg, val, object);
            object[arg] = val[0];
          }
          break;

        case 'number':
          // range from 0 to twice the value
          var vmin;
          var vmax;
          var vstep;
          if (object[arg+"Min"]) {
            vmin = object[arg+"Min"];
            }
          else {
            vmin = min(val, sliderMin);
          }

          if (object[arg+"Max"]) {
            vmax = object[arg+"Max"];
            }
          else {
            vmax = max(val, sliderMax);
          }

          if (object[arg+"Step"]) {
            vstep = object[arg+"Step"];
            }
          else {
            vstep = sliderStep || 1;
          }

          this.bindRange(arg, vmin, vmax, val, vstep, object);
          break;

        case 'string':
          var HEX6 = /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i;
          if(HEX6.test(val)) {
            // HTML color value (such as #ff0000)
            this.bindColor(arg, val, object);
          } else {
            // String value
            this.bindText(arg, val, object);
          }
          break;

        case 'boolean':
          this.bindBoolean(arg, object[arg], object);
          break;
      }
    }
  };

  // bind params that are defined globally
  QuickSettings.bindGlobals = function(params) {
    this.bindParams(window, params);
  };

})();
<|endoftext|>


<commit_before>//

(function() {

  // list of guis
  var guis = [];

  // default slider params
  var sliderMin = 0;
  var sliderMax = 100;
  var sliderStep = 1;

  // default gui provider
  var guiProvider = 'QuickSettings';

  // Create a GUI using QuickSettings (or DAT.GUI or ...)
  p5.prototype.createGui = function(label, x, y, provider) {

    label = label || 'GUI';
    x = x || 20;
    y = y || 20;
    provider = provider || guiProvider;

    var gui;

    // create a gui using the provider
    if(provider === 'QuickSettings') {
      if(QuickSettings) {
        console.log('Creating p5.gui powered by QuickSettings.');
        gui = new QSGui(label, x, y);
      } else {
        console.log('QuickSettings not found. Is the script included in your HTML?');
        gui = new DummyGui(label, x, y);
      }
    } else {
      console.log('Unknown GUI provider ' + provider);
      gui = new DummyGui(label, x, y);
    }

    // add it to the list of guis
    guis.push(gui);

    // return it
    return gui;

  };

  p5.prototype.removeGui = function(gui) {
    // TODO: implement this
  };

  // update defaults used for creation of sliders
  p5.prototype.sliderRange = function(vmin, vmax, vstep) {
    sliderMin = vmin;
    sliderMax = vmax;
    sliderStep = vstep;
  };

  // extend default behaviour of noLoop()
  p5.prototype.noLoop = function() {
    this._loop = false;
    for(var i = 0; i < guis.length; i++) {
      guis[i].noLoop();
    }
  };

  // extend default behaviour of loop()
  p5.prototype.loop = function() {
    for(var i = 0; i < guis.length; i++) {
      guis[i].loop();
    }
    this._loop = true;
    this._draw();
  };

  // interface for quicksettings
  function QSGui(label, x, y) {

    var qs = QuickSettings.create(x, y, label);
    this.prototype = qs;

    // addGlobals(global1, global2, ...) to add the selected globals
    this.addGlobals = function() {
      qs.bindGlobals(arguments);
    };

    // addObject(object) to add all params of the object
    // addObject(object, param1, param2, ...) to add selected params
    this.addObject = function() {
      // get object
      object = arguments[0];
      // convert arguments object to array
      var params = [];
      if(arguments.length > 1) {
        params = Array.prototype.slice.call(arguments)
        params = params.slice(1);
      }
      // if no arguments are provided take all keys of the object
      if(params.length === 0) {
        // won't work in Internet Explorer < 9 (use a polyfill)
        params = Object.keys(object);
      }
      qs.bindParams(object, params);
    };

    // noLoop() to call draw every time the gui changes when we are not looping
    this.noLoop = function() {
      qs.setGlobalChangeHandler(draw);
    };

    this.loop = function() {
      qs.setGlobalChangeHandler(null);
    };

    this.show = function() { qs.show(); };
    this.hide = function() { qs.hide(); };
    this.toggleVisibility = function() { qs.toggleVisibility(); };

  }

  // Just a Dummy object that provides the GUI interface
  function DummyGui() {
    var f = function() {};
    this.addGlobals = f;
    this.noLoop = f;
    this.addObject = f;
    this.show = f;
  }

  // Extend Quicksettings
  // so it can magically create a GUI for parameters passed by name
  QuickSettings.bindParams = function(object, params) {

    // iterate over all the arguments
    for(var i = 0; i < params.length; i++) {

      var arg = params[i];
      var val = object[arg];
      var typ = typeof val;

      // console.log(typ, arg, val);

      switch(typ) {

        case 'object':

          // color triple ?
          if(val instanceof Array && val.length === 3 && typeof val[0] === 'number') {
            // create color according to the current color mode
            var c = color(val[0], val[1], val[2]);
            // get decimal RGB values
            var c2 = c.levels.slice(0,3);
            // create HTML color code
            var vcolor = '#' + c2.map(function(value) {
              return ('0' + value.toString(16)).slice(-2);
            }).join('');
            this.bindColor(arg, vcolor, object);
          } else {
            // multiple choice drop down list
            this.bindDropDown(arg, val, object);
            object[arg] = val[0];
          }
          break;

        case 'number':

          // values as defined by magic variables or gui.sliderRange()
          var vmin = object[arg + 'Min'] || object[arg + 'min'] || sliderMin;
          var vmax = object[arg + 'Max'] || object[arg + 'max'] || sliderMax;
          var vstep = object[arg + 'Step'] || object[arg + 'step'] || sliderStep;

          // the actual values can still overrule the limits set by magic
          var vmin = min(val, vmin);
          var vmax = max(val, vmax);

          // set the range
          this.bindRange(arg, vmin, vmax, val, vstep, object);

          break;

        case 'string':

          var HEX6 = /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i;
          if(HEX6.test(val)) {
            // HTML color value (such as #ff0000)
            this.bindColor(arg, val, object);
          } else {
            // String value
            this.bindText(arg, val, object);
          }
          break;

        case 'boolean':

          this.bindBoolean(arg, object[arg], object);
          break;

      }
    }
  };

  // bind params that are defined globally
  QuickSettings.bindGlobals = function(params) {
    this.bindParams(window, params);
  };

})();
<commit_msg>added regex not to include sliders for Min and Max and Step for a range<commit_after>//

(function() {

  // list of guis
  var guis = [];

  // default slider params
  var sliderMin = 0;
  var sliderMax = 100;
  var sliderStep = 1;

  // default gui provider
  var guiProvider = 'QuickSettings';

  // Create a GUI using QuickSettings (or DAT.GUI or ...)
  p5.prototype.createGui = function(label, x, y, provider) {

    label = label || 'GUI';
    x = x || 20;
    y = y || 20;
    provider = provider || guiProvider;

    var gui;

    // create a gui using the provider
    if(provider === 'QuickSettings') {
      if(QuickSettings) {
        console.log('Creating p5.gui powered by QuickSettings.');
        gui = new QSGui(label, x, y);
      } else {
        console.log('QuickSettings not found. Is the script included in your HTML?');
        gui = new DummyGui(label, x, y);
      }
    } else {
      console.log('Unknown GUI provider ' + provider);
      gui = new DummyGui(label, x, y);
    }

    // add it to the list of guis
    guis.push(gui);

    // return it
    return gui;

  };

  p5.prototype.removeGui = function(gui) {
    // TODO: implement this
  };

  // update defaults used for creation of sliders
  p5.prototype.sliderRange = function(vmin, vmax, vstep) {
    sliderMin = vmin;
    sliderMax = vmax;
    sliderStep = vstep;
  };

  // extend default behaviour of noLoop()
  p5.prototype.noLoop = function() {
    this._loop = false;
    for(var i = 0; i < guis.length; i++) {
      guis[i].noLoop();
    }
  };

  // extend default behaviour of loop()
  p5.prototype.loop = function() {
    for(var i = 0; i < guis.length; i++) {
      guis[i].loop();
    }
    this._loop = true;
    this._draw();
  };

  // interface for quicksettings
  function QSGui(label, x, y) {

    var qs = QuickSettings.create(x, y, label);
    this.prototype = qs;

    // addGlobals(global1, global2, ...) to add the selected globals
    this.addGlobals = function() {
      qs.bindGlobals(arguments);
    };

    // addObject(object) to add all params of the object
    // addObject(object, param1, param2, ...) to add selected params
    this.addObject = function() {
      // get object
      object = arguments[0];
      // convert arguments object to array
      var params = [];
      if(arguments.length > 1) {
        params = Array.prototype.slice.call(arguments)
        params = params.slice(1);
      }
      // if no arguments are provided take all keys of the object
      if(params.length === 0) {
        // won't work in Internet Explorer < 9 (use a polyfill)
        params = Object.keys(object);
      }
      qs.bindParams(object, params);
    };

    // noLoop() to call draw every time the gui changes when we are not looping
    this.noLoop = function() {
      qs.setGlobalChangeHandler(draw);
    };

    this.loop = function() {
      qs.setGlobalChangeHandler(null);
    };

    this.show = function() { qs.show(); };
    this.hide = function() { qs.hide(); };
    this.toggleVisibility = function() { qs.toggleVisibility(); };

  }

  // Just a Dummy object that provides the GUI interface
  function DummyGui() {
    var f = function() {};
    this.addGlobals = f;
    this.noLoop = f;
    this.addObject = f;
    this.show = f;
  }

  // Extend Quicksettings
  // so it can magically create a GUI for parameters passed by name
  QuickSettings.bindParams = function(object, params) {

    // iterate over all the arguments
    for(var i = 0; i < params.length; i++) {

      var arg = params[i];
      var val = object[arg];
      var typ = typeof val;

      //console.log(typ, arg, val);

      // don't need to show the sliders for range min, max and step of a property
      var sliderConfigRegEx = /^(.*min|.*max|.*step)$/i;
      if( sliderConfigRegEx.test(arg)){
        continue;
      }
      switch(typ) {

        case 'object':

          // color triple ?
          if(val instanceof Array && val.length === 3 && typeof val[0] === 'number') {
            // create color according to the current color mode
            var c = color(val[0], val[1], val[2]);
            // get decimal RGB values
            var c2 = c.levels.slice(0,3);
            // create HTML color code
            var vcolor = '#' + c2.map(function(value) {
              return ('0' + value.toString(16)).slice(-2);
            }).join('');
            this.bindColor(arg, vcolor, object);
          } else {
            // multiple choice drop down list
            this.bindDropDown(arg, val, object);
            object[arg] = val[0];
          }
          break;

        case 'number':

          // values as defined by magic variables or gui.sliderRange()
          var vmin = object[arg + 'Min'] || object[arg + 'min'] || sliderMin;
          var vmax = object[arg + 'Max'] || object[arg + 'max'] || sliderMax;
          var vstep = object[arg + 'Step'] || object[arg + 'step'] || sliderStep;

          // the actual values can still overrule the limits set by magic
          var vmin = min(val, vmin);
          var vmax = max(val, vmax);

          // set the range
          this.bindRange(arg, vmin, vmax, val, vstep, object);

          break;

        case 'string':

          var HEX6 = /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i;
          if(HEX6.test(val)) {
            // HTML color value (such as #ff0000)
            this.bindColor(arg, val, object);
          } else {
            // String value
            this.bindText(arg, val, object);
          }
          break;

        case 'boolean':

          this.bindBoolean(arg, object[arg], object);
          break;

      }
    }
  };

  // bind params that are defined globally
  QuickSettings.bindGlobals = function(params) {
    this.bindParams(window, params);
  };

})();
<|endoftext|>


<commit_before>(function (window) {
    'use strict';

    var angular = window.angular,
        app = angular.module('pttr', ['ui.router', 'ui.bootstrap', 'firebase', 'pttr.firebase', 'pttr.auth', 'pttr.animal', 'pttr.user', 'pttr.shelter']);

    app.run(['$rootScope', '$state', 'AuthService', function ($rootScope, $state, AuthService) {

    }]);

    app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {

        $stateProvider

            .state('app', {
                url: '/app',
                abstract: true,
                controller: 'AppCtrl',
                templateUrl: 'app/main/partials/app.html'
            })

            .state('app.home', {
                url: '/home',
                templateUrl: 'app/main/partials/home.html'
            })
            .state('app.contact', {
                url: '/contact',
                templateUrl: 'app/main/partials/contact.html'
            })

            .state('app.user', {
                url: '/user',
                abstract: true
            })
            .state('app.user.login', {
                url: '/login',
                controller: 'UserLoginCtrl',
                templateUrl: 'app/auth/partials/userLogin.html'
            })
            .state('app.user.register', {
                url: '/register',
                controller: 'UserRegisterCtrl',
                templateUrl: 'app/auth/partials/userRegister.html'
            })
            .state('app.user.view', {
                url: '/:id',
                controller: 'UserViewCtrl',
                templateUrl: 'app/user/partials/view.html'
            })
            .state('app.user.edit', {
                url: '/:id/edit',
                controller: 'UserEditCtrl',
                templateUrl: 'app/user/partials/edit.html',
                data: {
                    authType: 'user'
                }
            })

            .state('app.shelter', {
                url: '/shelter',
                abstract: true
            })
            .state('app.shelter.login', {
                url: '/login',
                controller: 'ShelterLoginCtrl',
                templateUrl: 'app/auth/partials/shelterLogin.html'
            })
            .state('app.shelter.register', {
                url: '/register',
                controller: 'ShelterRegisterCtrl',
                templateUrl: 'app/auth/partials/shelterRegister.html'
            })
            .state('app.shelter.view', {
                url: '/:id',
                controller: 'ShelterViewCtrl',
                templateUrl: 'app/shelter/partials/view.html'
            })
            .state('app.shelter.edit', {
                url: '/:id/edit',
                controller: 'ShelterEditCtrl',
                templateUrl: 'app/shelter/partials/edit.html',
                data: {
                    authType: 'shelter'
                }
            })

            .state('app.animal', {
                url: '/animal',
                abstract: true
            })
            .state('app.animal.view', {
                url: '/:id',
                controller: 'AnimalViewCtrl',
                templateUrl: 'app/animal/partials/view.html'
            })
            .state('app.animal.edit', {
                url: '/:id/edit',
                controller: 'AnimalEditCtrl',
                templateUrl: 'app/animal/partials/edit.html',
                data: {
                    authType: 'shelter'
                }
            })

            .state('app.user.dashboard', {
                url: '/dashboard',
                controller: 'UserDashboardCtrl',
                templateUrl: 'app/user/partials/dashboard.html',
                data: {
                    authType: 'user'
                }
            })
            .state('app.shelter.dashboard', {
                url: '/dashboard',
                controller: 'ShelterDashboardCtrl',
                templateUrl: 'app/shelter/partials/dashboard.html',
                data: {
                    authtype: 'shelter'
                }
            });

        $urlRouterProvider.otherwise('/app/home');

    }]);

}(window));<commit_msg>Route Bug Fix In Angular UI Router, if you specify an abstract parent route, you have to have a template, whether it be a templateUrl or a template where a child view can be injected to.<commit_after>(function (window) {
    'use strict';

    var angular = window.angular,
        app = angular.module('pttr', ['ui.router', 'ui.bootstrap', 'firebase', 'pttr.firebase', 'pttr.auth', 'pttr.animal', 'pttr.user', 'pttr.shelter']);

    app.run(['$rootScope', '$state', 'AuthService', function ($rootScope, $state, AuthService) {

    }]);

    app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {

        $stateProvider

            .state('app', {
                url: '/app',
                abstract: true,
                controller: 'AppCtrl',
                templateUrl: 'app/main/partials/app.html'
            })

            .state('app.home', {
                url: '/home',
                templateUrl: 'app/main/partials/home.html'
            })
            .state('app.contact', {
                url: '/contact',
                templateUrl: 'app/main/partials/contact.html'
            })

            .state('app.user', {
                url: '/user',
                abstract: true,
                template: '<ui-view/>'
            })
            .state('app.user.login', {
                url: '/login',
                controller: 'UserLoginCtrl',
                templateUrl: 'app/auth/partials/userLogin.html'
            })
            .state('app.user.register', {
                url: '/register',
                controller: 'UserRegisterCtrl',
                templateUrl: 'app/auth/partials/userRegister.html'
            })
            .state('app.user.view', {
                url: '/:id',
                controller: 'UserViewCtrl',
                templateUrl: 'app/user/partials/view.html'
            })
            .state('app.user.edit', {
                url: '/:id/edit',
                controller: 'UserEditCtrl',
                templateUrl: 'app/user/partials/edit.html',
                data: {
                    authType: 'user'
                }
            })

            .state('app.shelter', {
                url: '/shelter',
                abstract: true,
                template: '<ui-view/>'
            })
            .state('app.shelter.login', {
                url: '/login',
                controller: 'ShelterLoginCtrl',
                templateUrl: 'app/auth/partials/shelterLogin.html'
            })
            .state('app.shelter.register', {
                url: '/register',
                controller: 'ShelterRegisterCtrl',
                templateUrl: 'app/auth/partials/shelterRegister.html'
            })
            .state('app.shelter.view', {
                url: '/:id',
                controller: 'ShelterViewCtrl',
                templateUrl: 'app/shelter/partials/view.html'
            })
            .state('app.shelter.edit', {
                url: '/:id/edit',
                controller: 'ShelterEditCtrl',
                templateUrl: 'app/shelter/partials/edit.html',
                data: {
                    authType: 'shelter'
                }
            })

            .state('app.animal', {
                url: '/animal',
                abstract: true,
                template: '<ui-view/>'
            })
            .state('app.animal.view', {
                url: '/:id',
                controller: 'AnimalViewCtrl',
                templateUrl: 'app/animal/partials/view.html'
            })
            .state('app.animal.edit', {
                url: '/:id/edit',
                controller: 'AnimalEditCtrl',
                templateUrl: 'app/animal/partials/edit.html',
                data: {
                    authType: 'shelter'
                }
            })

            .state('app.user.dashboard', {
                url: '/dashboard',
                controller: 'UserDashboardCtrl',
                templateUrl: 'app/user/partials/dashboard.html',
                data: {
                    authType: 'user'
                }
            })
            .state('app.shelter.dashboard', {
                url: '/dashboard',
                controller: 'ShelterDashboardCtrl',
                templateUrl: 'app/shelter/partials/dashboard.html',
                data: {
                    authtype: 'shelter'
                }
            });

        $urlRouterProvider.otherwise('/app/home');

    }]);

}(window));<|endoftext|>


<commit_before>'use strict'

module.exports = async ({page, worker, text, beforeWaitMS = 10000, sessionDurationMS = 20000, typeIntervalMS = 50, coolDownMS = 30000}) => {

  // // wait until everyone is onlube
  // const peersButton = await page.$('[data-peer-id]')
  // const peerId = await page.evaluate(el => el.dataset.peerId, peersButton)

  page.waitFor(beforeWaitMS)

  const editorSelector = '[class=CodeMirror-code][contenteditable=true]'
  const startedAt = Date.now()
  const endAt = startedAt + sessionDurationMS

  while (Date.now() < endAt) {
    await page.waitFor(typeIntervalMS)
    await page.type(editorSelector, text())
  }

  text.finished()
  await text.allDone()
  await page.waitFor(coolDownMS)
  const finalText = await page.evaluate(() => {
    return Promise.resolve(window.__peerPadEditor.getValue())
  })
  text.submitResult(finalText)
}

<commit_msg>increased replica cooldown time<commit_after>'use strict'

module.exports = async ({page, worker, text, beforeWaitMS = 10000, sessionDurationMS = 20000, typeIntervalMS = 50, coolDownMS = 40000}) => {

  // // wait until everyone is onlube
  // const peersButton = await page.$('[data-peer-id]')
  // const peerId = await page.evaluate(el => el.dataset.peerId, peersButton)

  page.waitFor(beforeWaitMS)

  const editorSelector = '[class=CodeMirror-code][contenteditable=true]'
  const startedAt = Date.now()
  const endAt = startedAt + sessionDurationMS

  while (Date.now() < endAt) {
    await page.waitFor(typeIntervalMS)
    await page.type(editorSelector, text())
  }

  text.finished()
  await text.allDone()
  await page.waitFor(coolDownMS)
  const finalText = await page.evaluate(() => {
    return Promise.resolve(window.__peerPadEditor.getValue())
  })
  text.submitResult(finalText)
}

<|endoftext|>


<commit_before>/**
 * RankingMapper: map internal team ids to external team ids, listen to and emit
 * update events, provide a get() function and cache the ranking results for
 * better performance.
 *
 * @return RankingMapper
 * @author Erik E. Lorenz <erik.e.lorenz@gmail.com>
 * @license MIT License
 * @see LICENSE
 */
define(['lib/extend', './model'], function(extend, Model) {
  /**
   * Constructor
   *
   * @param ranking
   *          a RankingModel instance with internal ids
   * @param teams
   *          a ListModel instance which maps internal to external ids
   */
  function RankingMapper(ranking, teams) {
    RankingMapper.superconstructor.call(this);

    this.cache = undefined;
    this.ranking = ranking;
    this.teams = teams;

    ranking.registerListener(this);
  }
  extend(RankingMapper, Model);

  /**
   * translate internal ids (pos) to external ids
   *
   * @param rankingcomponent
   *          an array of internal ids, i.e. positions
   * @param map
   *          a ListModel instance which maps positions to values
   * @return an array of re-mapped ids
   */
  RankingMapper.translateIDs = function(rankingcomponent, map) {
    return rankingcomponent.map(function(pos) {
      return map.get(pos);
    });
  };

  /**
   * read a ranking object with internal ids and map all internal ids to
   * external ids. Remapping should only be performed on
   * ranking.get().displayOrder
   */
  RankingMapper.updateCache = function() {
    var ranks, newcache;

    ranks = this.ranking.get();
    newcache = {};

    Object.keys(ranks).forEach(function(key) {
      var values;

      if (key === 'displayOrder') {
        values = RankingMapper.translateIDs(ranks[key], this.teams);
      } else {
        values = ranks[key].slice(0);
      }

      newcache[key] = values;
    }, this);

    this.cache = newcache;
  };

  /**
   * get the cached ranking or rebuild it if invalidated
   *
   * @return a ranking object
   */
  RankingMapper.prototype.get = function() {
    if (this.cache === undefined) {
      RankingMapper.updateCache.call(this);
    }

    return this.cache;
  };

  /**
   * force a rebuild of the ranking object (mapping only)
   */
  RankingMapper.prototype.invalidate = function() {
    this.cache = undefined;
    this.emit('update');
  };

  /**
   * callback function
   */
  RankingMapper.prototype.onupdate = function() {
    this.invalidate();
  };

  return RankingMapper;
});
<commit_msg>RankingMapper.invalidate(): don't emit 'update'<commit_after>/**
 * RankingMapper: map internal team ids to external team ids, listen to and emit
 * update events, provide a get() function and cache the ranking results for
 * better performance.
 *
 * @return RankingMapper
 * @author Erik E. Lorenz <erik.e.lorenz@gmail.com>
 * @license MIT License
 * @see LICENSE
 */
define(['lib/extend', './model'], function(extend, Model) {
  /**
   * Constructor
   *
   * @param ranking
   *          a RankingModel instance with internal ids
   * @param teams
   *          a ListModel instance which maps internal to external ids
   */
  function RankingMapper(ranking, teams) {
    RankingMapper.superconstructor.call(this);

    this.cache = undefined;
    this.ranking = ranking;
    this.teams = teams;

    ranking.registerListener(this);
  }
  extend(RankingMapper, Model);

  /**
   * translate internal ids (pos) to external ids
   *
   * @param rankingcomponent
   *          an array of internal ids, i.e. positions
   * @param map
   *          a ListModel instance which maps positions to values
   * @return an array of re-mapped ids
   */
  RankingMapper.translateIDs = function(rankingcomponent, map) {
    return rankingcomponent.map(function(pos) {
      return map.get(pos);
    });
  };

  /**
   * read a ranking object with internal ids and map all internal ids to
   * external ids. Remapping should only be performed on
   * ranking.get().displayOrder
   */
  RankingMapper.updateCache = function() {
    var ranks, newcache;

    ranks = this.ranking.get();
    newcache = {};

    Object.keys(ranks).forEach(function(key) {
      var values;

      if (key === 'displayOrder') {
        values = RankingMapper.translateIDs(ranks[key], this.teams);
      } else {
        values = ranks[key].slice(0);
      }

      newcache[key] = values;
    }, this);

    this.cache = newcache;
  };

  /**
   * get the cached ranking or rebuild it if invalidated
   *
   * @return a ranking object
   */
  RankingMapper.prototype.get = function() {
    if (this.cache === undefined) {
      RankingMapper.updateCache.call(this);
    }

    return this.cache;
  };

  /**
   * force a rebuild of the ranking object (mapping only)
   */
  RankingMapper.prototype.invalidate = function() {
    this.cache = undefined;
  };

  /**
   * callback function
   */
  RankingMapper.prototype.onupdate = function() {
    this.invalidate();
    this.emit('update');
  };

  return RankingMapper;
});
<|endoftext|>