<commit_before>// @flow

import {
    minBy,
    maxBy,
    sumBy,
    averageBy,
    medianBy
} from 'immutable-math';

import {
    fromJS,
    List,
    Record
} from 'immutable';

type Datum = string | number | boolean | null;

/**
 * @class
 *
 * ChartData is an Immutable Record used by pnut charts to represent chart data.
 */

class ChartData extends Record({
    columns: List(),
    rows: List()
}) {

    /**
     * Create a ChartData object
     *
     * @param {Array<Object>} rows An array of data rows
     * @param {Array<Object>} columns An array of columns
     *
     * @memberOf ChartData
     */

    constructor(rows: Array<Object>, columns: Array<Object>) {
        super({
            rows: fromJS(rows),
            columns: fromJS(columns)
        });
        this._memos = {};
    }

    _memoize(key: string, fn: Function): Datum {
        if(this._memos.hasOwnProperty(key)) {
            return this._memos[key];
        }
        const value: Datum = fn();
        this._memos[key] = value;
        return value;
    }

    /**
     * Get the minimum non-null value in a column.
     *
     * @param {string} columns The name of the column
     * @return {string|number|boolean|null} The minimum value, or null if no mininum value could be determined
     *
     * @memberOf ChartData
     */

    min(column: string): Datum {
        return this._memoize('min', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(minBy(ii => ii.get(column)));

            return isNaN(result) ? null : result;
        });
    }

    /**
     * Get the maximum value in a column.
     *
     * @param {string} columns The name of the column
     * @return {string|number|boolean|null} The maximum value, or null if no maximum value could be determined
     *
     * @memberOf ChartData
     */

    max(column: string): Datum {
        return this._memoize('max', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(maxBy(ii => ii.get(column)));

            return isNaN(result) ? null : result;
        });
    }

    /**
     * Get the sum of the values in a column.
     *
     * @param {string} columns The name of the column
     * @return {string|number|boolean|null} The sum of the values, or null if no sum could be determined
     *
     * @memberOf ChartData
     */

    sum(column: string): Datum {
        return this._memoize('sum', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(sumBy(ii => ii.get(column)));

            return result;
        });
    }

    /**
     * Get the average of the values in a column.
     *
     * @param {string} columns The name of the column
     * @return {string|number|boolean|null} The average of the values, or null if no average could be determined
     *
     * @memberOf ChartData
     */

    average(column: string): Datum {
        return this._memoize('average', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(averageBy(ii => ii.get(column)));

            return isNaN(result) ? null : result;
        });
    }

    /**
     * Get the median of the values in a column.
     *
     * @param {string} columns The name of the column
     * @return {string|number|boolean|null} The median of the values, or null if no median could be determined
     *
     * @memberOf ChartData
     */

    median(column: string): Datum {
        return this._memoize('median', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(medianBy(ii => ii.get(column)));

            return isNaN(result) ? null : result;
        });
    }
}

export default ChartData;
<commit_msg>Tweak docs<commit_after>// @flow

import {
    minBy,
    maxBy,
    sumBy,
    averageBy,
    medianBy
} from 'immutable-math';

import {
    fromJS,
    List,
    Record
} from 'immutable';

type Datum = string | number | boolean | null;

/**
 * @class
 *
 * ChartData is an Immutable Record used by pnut charts to represent chart data.
 */

class ChartData extends Record({
    columns: List(),
    rows: List()
}) {

    /**
     * Create a ChartData object
     *
     * @param {Array<Object>} rows An array of data rows
     * @param {Array<Object>} columns An array of columns
     *
     * @memberOf ChartData
     */

    constructor(rows: Array<Object>, columns: Array<Object>) {
        super({
            rows: fromJS(rows),
            columns: fromJS(columns)
        });
        this._memos = {};
    }

    _memoize(key: string, fn: Function): Datum {
        if(this._memos.hasOwnProperty(key)) {
            return this._memos[key];
        }
        const value: Datum = fn();
        this._memos[key] = value;
        return value;
    }

    /**
     * Get the minimum non-null value in a column.
     *
     * @param {string} columns The name of the column
     * @return {number|null} The minimum value, or null if no mininum value could be determined
     *
     * @memberOf ChartData
     */

    min(column: string): Datum {
        return this._memoize('min', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(minBy(ii => ii.get(column)));

            return isNaN(result) ? null : result;
        });
    }

    /**
     * Get the maximum value in a column.
     *
     * @param {string} columns The name of the column
     * @return {number|null} The maximum value, or null if no maximum value could be determined
     *
     * @memberOf ChartData
     */

    max(column: string): Datum {
        return this._memoize('max', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(maxBy(ii => ii.get(column)));

            return isNaN(result) ? null : result;
        });
    }

    /**
     * Get the sum of the values in a column.
     *
     * @param {string} columns The name of the column
     * @return {number} The sum of the values
     *
     * @memberOf ChartData
     */

    sum(column: string): Datum {
        return this._memoize('sum', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(sumBy(ii => ii.get(column)));

            return result;
        });
    }

    /**
     * Get the average of the values in a column.
     *
     * @param {string} columns The name of the column
     * @return {number|null} The average of the values, or null if no average could be determined
     *
     * @memberOf ChartData
     */

    average(column: string): Datum {
        return this._memoize('average', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(averageBy(ii => ii.get(column)));

            return isNaN(result) ? null : result;
        });
    }

    /**
     * Get the median of the values in a column.
     *
     * @param {string} columns The name of the column
     * @return {number|null} The median of the values, or null if no median could be determined
     *
     * @memberOf ChartData
     */

    median(column: string): Datum {
        return this._memoize('median', (): Datum => {
            const result = this.rows
                .filter(ii => ii.get(column) != null)
                .update(medianBy(ii => ii.get(column)));

            return isNaN(result) ? null : result;
        });
    }
}

export default ChartData;
<|endoftext|>


<commit_before>import * as actionTypes from '../constants/actionTypes';
import * as _ from 'lodash';

// a model with the same structure as the API provides, an object wraps the services
const initialState = {
  microservices: undefined,
  workloads: undefined,
};

// b/c this is a ro store we don't care about maintaining any local changes to it
export default function(state = initialState, action) {
  switch (action.type) {
    case actionTypes.SERVICES_SET:
      return Object.assign({}, state, action.services);
    case actionTypes.MICROSERVICES_SET:
      return Object.assign({}, state, {
        microservices: action.microservices,
      });
    case actionTypes.WORKLOADS_SET:
      return Object.assign({}, state, {
        workloads: action.workloads,
      });
    default:
      return state;
  };
}
<commit_msg>add microservice handling for reducer<commit_after>import * as actionTypes from '../constants/actionTypes';
import * as _ from 'lodash';

// a model with the same structure as the API provides, an object wraps the services
const initialState = {
  microservices: undefined,
  workloads: undefined,
};

/**
 * Extracts the organization from a microservice title
 * @param {string} item
 * @returns {string}
 */
const extractOrg = (item) => {
  return item.split('/')[0];
};

/**
 * Converts a hashmap to an array
 * @param {object} hash
 * @returns {array}
 */
const hashToArray = (hash) => {
  const keys = Object.keys(hash);
  return _.map(keys, (key) => {
    return { label: key, item: hash[key] };
  });
};

/**
 * Create a hashmap of organizations with microsrvices that belong to that organization
 * @param {array} microservices
 * @returns {hashmap}
 */
const parseMicroservices = (microservices) => {
  let msHash = {};
  const microservicesArray = hashToArray(microservices);

  // add microservice to hash based on orgs
  for (let i = 0; i < microservicesArray.length; i++) {
    const currentOrg = extractOrg(microservicesArray[i].label);

    if (typeof msHash[currentOrg] !== 'undefined') {
      msHash[currentOrg].push(microservicesArray[i].item);
    } else {
      msHash[currentOrg] = [microservicesArray[i].item];
    }
  }

  return msHash;
};

// b/c this is a ro store we don't care about maintaining any local changes to it
export default function(state = initialState, action) {
  switch (action.type) {
    case actionTypes.SERVICES_SET:
      return Object.assign({}, state, action.services);
    case actionTypes.MICROSERVICES_SET:
      return Object.assign({}, state, {
        microservices: parseMicroservices(action.microservices),
      });
    case actionTypes.WORKLOADS_SET:
      return Object.assign({}, state, {
        workloads: action.workloads,
      });
    default:
      return state;
  };
}
<|endoftext|>


<commit_before>import monsters from '../../data/5e-SRD-Monsters';

export const initialState = {
  modalIsVisible: false,
  monsterPaneIsVisable: false,
  monsters,
  selectedMonster: null
};
<commit_msg>Add encounter<commit_after>import monsters from '../../data/5e-SRD-Monsters';

export const initialState = {
  encounter: [],
  modalIsVisible: false,
  monsterPaneIsVisable: false,
  monsters,
  selectedMonster: null
};
<|endoftext|>


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

/*
* Skin retrieval methods are based on @jomo's CLI Crafatar implementation.
* https://github.com/jomo/Crafatar
*/
module.exports = {
  get_profile: function(uuid, callback) {
    https.get("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid, function(res) {
      if (res.statusCode == "204") {
        callback(null);
        return null;
      }
     res.on('data', function(d) {
       var profile = JSON.parse(d);
       if (profile.error) callback(null);
       callback(profile);
     });

    }).on('error', function(e) {
      console.error(e);
    });
  },

  skin_url: function(profile) {
    var url = null;
    if (profile && profile.properties) {
      profile.properties.forEach(function(prop) {
        if (prop.name == 'textures') {
          var json = Buffer(prop.value, 'base64').toString();
          var props = JSON.parse(json);
          url = props.textures.SKIN.url;
        }
      });
    }
    return url;
  },

  skin_file: function(url, filename, callback) {
    var file = fs.createWriteStream(filename);
    http.get(url, function(res) {
      res.on('data', function(data) {
        file.write(data);
      }).on('end', function() {
        file.end();
        callback();
      });
    });
  },
  extract_face: function(infile, size, callback) {
    lwip.open(infile, function(err, image){
      image.batch()
        .crop(8,8,15,15)
        .resize(size, size, "nearest-neighbor")
        .toBuffer('png', function(err, buffer){
          callback(buffer);
      });
    });
  }
};<commit_msg>Fix spacing<commit_after>var http = require('http');
var https = require('https');
var fs = require('fs');
var lwip = require('lwip');

/*
* Skin retrieval methods are based on @jomo's CLI Crafatar implementation.
* https://github.com/jomo/Crafatar
*/
module.exports = {
	get_profile: function(uuid, callback) {
		https.get("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid, function(res) {
			if (res.statusCode == "204") {
				callback(null);
				return null;
			}
			res.on('data', function(d) {
				var profile = JSON.parse(d);
				if (profile.error) callback(null);
				callback(profile);
			});

		}).on('error', function(e) {
			console.error(e);
		});
	},

	skin_url: function(profile) {
		var url = null;
		if (profile && profile.properties) {
			profile.properties.forEach(function(prop) {
				if (prop.name == 'textures') {
					var json = Buffer(prop.value, 'base64').toString();
					var props = JSON.parse(json);
					url = props.textures.SKIN.url;
				}
			});
		}
		return url;
	},

	skin_file: function(url, filename, callback) {
		var file = fs.createWriteStream(filename);
		http.get(url, function(res) {
			res.on('data', function(data) {
				file.write(data);
			}).on('end', function() {
				file.end();
				callback();
			});
		});
	},
	extract_face: function(infile, size, callback) {
		lwip.open(infile, function(err, image){
			image.batch()
			.crop(8,8,15,15)
			.resize(size, size, "nearest-neighbor")
			.toBuffer('png', function(err, buffer){
				callback(buffer);
			});
		});
	}
};<|endoftext|>


<commit_before>'use strict';

/**
 * @fileOverview sklad.
 */

var Response = require('Response');
var EventEmitter = require('EventEmitter');

var sklad;

function Sklad() {
    EventEmitter.call(this);
}

Sklad.prototype = new EventEmitter();

Sklad.prototype.constructor = Sklad;

Sklad.prototype.store = checkAndGetStorage();

/**
 * Проверяет доступность localStorage
 * @return {Boolean}
 */
Sklad.prototype.isSupported = function () {
    return !!this.store;
};

/**
 * Устанавливаем значение в localStorage
 * @param {*} key строка или все что может быть приведенно к строке
 *                ключ в localStorage для сохраняемого значения
 * @param {*} value сохраняемое значение
 * @param {Boolean} [strict] флаг для проверки сохраненного значения
 * @return {Response}
 */
Sklad.prototype.set = function (key, value, strict) {
    var r = new Response();
    var queue = new Response.Queue();
    var stringValue = JSON.stringify(value);

    if (!stringValue) {
        return r.reject("Bad param - value");
    }

    queue
        .setData('params', {
            key: key,
            val: stringValue
        })
        .push(setItem);

    if (strict) {
        queue
            .push(getItem)
            .push(checkSavedItem);
    } else {
        queue.push(queue.resolve);
    }

    queue.start();

    return r.listen(queue);
};

/**
 * Достаём значение из localStorage
 * @param {*} key строка или все что может быть приведенно к строке
 *                ключ сохраненного значения в localStorage
 * @param {String} [type] если указан как 'json' парсим значение
 *                      если нет отдаём строку
 * @return {Response}
 */
Sklad.prototype.get = function (key, type) {
    var r = new Response();
    var queue = new Response.Queue();

    queue
        .setData('params', {
            key: key,
            type: type
        })
        .push(getItem);

    if (type) {
        queue.push(parseData);
    }

    queue
        .push(queue.resolve)
        .start();

    return r.listen(queue);
};

/**
 * Метод для получения непосредственно значения
 * а не экземпляра Response
 * @param {*} key строка или все что может быть приведенно к строке
 *                ключ сохраненного значения в localStorage
 * @param {String} [type] если указан как 'json' парсим значение
 *                      если нет отдаём строку
 * @return {*} значение из localStorage
 */
Sklad.prototype.getValue = function (key, type) {
    return this
        .get(key, type)
        .getResult();
};

/**
 * Удаляем итэм из хранилища
 * @param {String} key ключ сохранённого значения
 * @return {Response}
 */
Sklad.prototype.remove = function (key) {
    var r = new Response();

    if (sklad.store) {
        r.invoke(sklad.store.removeItem, [key], sklad.store);
    } else {
        r.reject();
    }

    if (!r.isRejected()) {
        r.resolve();
    }

    return r;
}

sklad = new Sklad();

/**
 * Callback для события storage
 * @param {Object} event Объект события изменение значений в localStorage
 */
var triggerChangeEvent = function (event) {
    var event = 'change:' + event.key;

    this.emit(event, event.newValue);
}.bind(sklad);

/**
 * Подписываемся на изменение значений в localStorage
 * из других вкладок браузера
 */
subscribeToStorage(triggerChangeEvent);

module.exports = sklad;

/**
 * Проверяем наличие localStorage
 * если доступен возвращаем ссылку на него
 * если не доступен возвращаем false
 * @return {Storage|Boolean}
 */
function checkAndGetStorage() {
    var test = new Date();
    var _storage;
    var result;

    try {
        (_storage = window.localStorage).setItem(test, test);
        result = _storage.getItem(test) == test;
        _storage.removeItem(test);
        return result && _storage;
    } catch (error) {
        return undefined;
    }
}

/**
 * В зависимости от браузера возвращаем нужную функцию для подписки на событие 'storage'
 * @return {Function}
 */
function subscribeToStorage(handler) {
    if ('v'=='\v') {
        // Note: IE listens on document
        document.attachEvent('onstorage', handler);
    } else if (window.opera || /webkit/i.test( navigator.userAgent )){
        // Note: Opera and WebKits listens on window
        return window.addEventListener('storage', handler, false);
    } else {
        // Note: FF listens on document.body or document
        return document.body.addEventListener('storage', handler, false);
    }
}

/**
 * Безопасный метод для записи в localStorage
 * если ловим ошибки реджектим очередь
 * @this {Queue}
 */
function setItem() {
    var params = this.getData('params');

    if (sklad.store) {
        this.invoke(sklad.store.setItem, [params.key, params.val], sklad.store);
    } else {
        this.reject();
    }
}

/**
 * Безопасный метод для чтения из localStorage
 * @this {Queue}
 * @return {*} значение из localStorage
 */
function getItem() {
    var params = this.getData('params');

    if (sklad.store) {
        return this.invoke(sklad.store.getItem, [params.key], sklad.store);
    } else {
        this.reject();
        return;
    }
}

/**
 * В зависимости от ожидаемого формата ответа парсим строку в json
 * или отдаём сырые данные
 * @this {Queue}
 * @return {*}
 */
function parseData(data) {
    var params = this.getData('params');

    if (params.type === 'json') {
        return this.invoke(JSON.parse, [data]);
    } else {
        return data;
    }
}

/**
 * Проверяем сохраненное значение если указан strict режим
 * @this {Queue}
 */
function checkSavedItem(data) {
    var params = this.getData('params');

    if (data !== params.val) {
        this.reject();
    } else {
        this.resolve(data);
    }
}
<commit_msg>fix storage event callback<commit_after>'use strict';

/**
 * @fileOverview sklad.
 */

var Response = require('Response');
var EventEmitter = require('EventEmitter');

var sklad;

function Sklad() {
    EventEmitter.call(this);
}

Sklad.prototype = new EventEmitter();

Sklad.prototype.constructor = Sklad;

Sklad.prototype.store = checkAndGetStorage();

/**
 * Проверяет доступность localStorage
 * @return {Boolean}
 */
Sklad.prototype.isSupported = function () {
    return !!this.store;
};

/**
 * Устанавливаем значение в localStorage
 * @param {*} key строка или все что может быть приведенно к строке
 *                ключ в localStorage для сохраняемого значения
 * @param {*} value сохраняемое значение
 * @param {Boolean} [strict] флаг для проверки сохраненного значения
 * @return {Response}
 */
Sklad.prototype.set = function (key, value, strict) {
    var r = new Response();
    var queue = new Response.Queue();
    var stringValue = JSON.stringify(value);

    if (!stringValue) {
        return r.reject("Bad param - value");
    }

    queue
        .setData('params', {
            key: key,
            val: stringValue
        })
        .push(setItem);

    if (strict) {
        queue
            .push(getItem)
            .push(checkSavedItem);
    } else {
        queue.push(queue.resolve);
    }

    queue.start();

    return r.listen(queue);
};

/**
 * Достаём значение из localStorage
 * @param {*} key строка или все что может быть приведенно к строке
 *                ключ сохраненного значения в localStorage
 * @param {String} [type] если указан как 'json' парсим значение
 *                      если нет отдаём строку
 * @return {Response}
 */
Sklad.prototype.get = function (key, type) {
    var r = new Response();
    var queue = new Response.Queue();

    queue
        .setData('params', {
            key: key,
            type: type
        })
        .push(getItem);

    if (type) {
        queue.push(parseData);
    }

    queue
        .push(queue.resolve)
        .start();

    return r.listen(queue);
};

/**
 * Метод для получения непосредственно значения
 * а не экземпляра Response
 * @param {*} key строка или все что может быть приведенно к строке
 *                ключ сохраненного значения в localStorage
 * @param {String} [type] если указан как 'json' парсим значение
 *                      если нет отдаём строку
 * @return {*} значение из localStorage
 */
Sklad.prototype.getValue = function (key, type) {
    return this
        .get(key, type)
        .getResult();
};

/**
 * Удаляем итэм из хранилища
 * @param {String} key ключ сохранённого значения
 * @return {Response}
 */
Sklad.prototype.remove = function (key) {
    var r = new Response();

    if (sklad.store) {
        r.invoke(sklad.store.removeItem, [key], sklad.store);
    } else {
        r.reject();
    }

    if (!r.isRejected()) {
        r.resolve();
    }

    return r;
}

sklad = new Sklad();

/**
 * @param {Object} event Объект события изменение значений в localStorage
 */
var triggerChangeEvent = function (event) {
    var eventName = 'change:' + event.key;

    this.emit(eventName, event.newValue);
}.bind(sklad);

/**
 * Подписываемся на изменение значений в localStorage
 * из других вкладок браузера
 */
subscribeToStorage(triggerChangeEvent);

module.exports = sklad;

/**
 * Проверяем наличие localStorage
 * если доступен возвращаем ссылку на него
 * если не доступен возвращаем false
 * @return {Storage|Boolean}
 */
function checkAndGetStorage() {
    var test = new Date();
    var _storage;
    var result;

    try {
        (_storage = window.localStorage).setItem(test, test);
        result = _storage.getItem(test) == test;
        _storage.removeItem(test);
        return result && _storage;
    } catch (error) {
        return undefined;
    }
}

/**
 * В зависимости от браузера возвращаем нужную функцию для подписки на событие 'storage'
 * @return {Function}
 */
function subscribeToStorage(handler) {
    if (window.attachEvent) {
        // Note: IE listens on document
        document.attachEvent('onstorage', handler);
    } else if (window.opera || /webkit/i.test( navigator.userAgent )){
        // Note: Opera and WebKits listens on window
        return window.addEventListener('storage', handler, false);
    } else {
        // Note: FF listens on document.body or document
        return document.body.addEventListener('storage', handler, false);
    }
}

/**
 * Безопасный метод для записи в localStorage
 * если ловим ошибки реджектим очередь
 * @this {Queue}
 */
function setItem() {
    var params = this.getData('params');

    if (sklad.store) {
        this.invoke(sklad.store.setItem, [params.key, params.val], sklad.store);
    } else {
        this.reject();
    }
}

/**
 * Безопасный метод для чтения из localStorage
 * @this {Queue}
 * @return {*} значение из localStorage
 */
function getItem() {
    var params = this.getData('params');

    if (sklad.store) {
        return this.invoke(sklad.store.getItem, [params.key], sklad.store);
    } else {
        this.reject();
        return;
    }
}

/**
 * В зависимости от ожидаемого формата ответа парсим строку в json
 * или отдаём сырые данные
 * @this {Queue}
 * @return {*}
 */
function parseData(data) {
    var params = this.getData('params');

    if (params.type === 'json') {
        return this.invoke(JSON.parse, [data]);
    } else {
        return data;
    }
}

/**
 * Проверяем сохраненное значение если указан strict режим
 * @this {Queue}
 */
function checkSavedItem(data) {
    var params = this.getData('params');

    if (data !== params.val) {
        this.reject();
    } else {
        this.resolve(data);
    }
}
<|endoftext|>


<commit_before>/*
 * MelonJS Game Engine
 * Copyright (C) 2011 - 2014 Olivier Biot, Jason Oster, Aaron McLeod
 * http://www.melonjs.org
 *
 */
(function () {
    /**
     * A Simple object to display a sprite on screen.
     * @class
     * @extends me.Renderable
     * @memberOf me
     * @constructor
     * @param {Number} x the x coordinates of the sprite object
     * @param {Number} y the y coordinates of the sprite object
     * @param {Object} settings Contains additional parameters for the sprite
     * @param {Image|String} settings.image reference to the Sprite Image. See {@link me.loader#getImage}
     * @param {Number} [settings.frameX=0] Image source X-coordinate.
     * @param {Number} [settings.frameY=0] Image source Y-coordinate.
     * @param {Number} [settings.framewidth=settings.image.width] Image source width.
     * @param {Number} [settings.frameheight=settings.image.height] Image source height.
     * @param {Number} [settings.rotation] Initial rotation angle in radians.
     * @param {Boolean} [settings.flipX] Initial flip for X-axis.
     * @param {Boolean} [settings.flipY] Initial flip for Y-axis.
     * @example
     * // create a static Sprite Object
     * mySprite = new me.Sprite (100, 100, {
     *     image : me.loader.getImage("mySpriteImage")
     * });
     */
    me.Sprite = me.Renderable.extend(
    /** @scope me.Sprite.prototype */
    {
        /**
         * @ignore
         */
        init : function (x, y, settings) {

            /**
             * private/internal scale factor
             * @ignore
             */
            this._scale = new me.Vector2d(1, 1);

            // if true, image flipping/scaling is needed
            this.scaleFlag = false;

            // just to keep track of when we flip
            this.lastflipX = false;
            this.lastflipY = false;

            this.flipX(!!settings.flipX);
            this.flipY(!!settings.flipY);

            // current frame texture offset
            this.offset = new me.Vector2d(settings.frameX, settings.frameY);

            /**
             * Set the angle (in Radians) of a sprite to rotate it

             * WARNING: rotating sprites decreases performance with Canvas Renderer
             * @public
             * @type Number
             * @name me.Sprite#angle
             */
            this.angle = settings.rotation || 0;

            /**
             * Source rotation angle for pre-rotating the source image

             * Commonly used for TexturePacker
             * @ignore
             */
            this._sourceAngle = 0;

            // to manage the flickering effect
            this.flickering = false;
            this.flickerDuration = 0;
            this.flickercb = null;
            this.flickerState = false;

            // Used by the game engine to adjust visibility as the
            // sprite moves in and out of the viewport
            this.isSprite = true;

            var image = (
                (typeof(settings.image) === "string") ?
                me.loader.getImage(settings.image) :
                settings.image
            );

            // call the super constructor
            this._super(me.Renderable, "init", [
                x, y,
                settings.framewidth  || image.width,
                settings.frameheight || image.height
            ]);

            // cache image reference
            this.image = image;
        },

        /**
         * specify a transparent color
         * @name setTransparency
         * @memberOf me.Sprite
         * @function
         * @deprecated Use PNG or GIF with transparency instead
         * @param {String} color color key in "#RRGGBB" format
         */
        setTransparency : function (col) {
            // remove the # if present
            col = (col.charAt(0) === "#") ? col.substring(1, 7) : col;
            // applyRGB Filter (return a context object)
            this.image = me.video.renderer.applyRGBFilter(
                this.image,
                "transparent",
                col.toUpperCase()
            ).canvas;
        },

        /**
         * return the flickering state of the object
         * @name isFlickering
         * @memberOf me.Sprite
         * @function
         * @return {Boolean}
         */
        isFlickering : function () {
            return this.flickering;
        },

        /**
         * make the object flicker
         * @name flicker
         * @memberOf me.Sprite
         * @function
         * @param {Number} duration expressed in milliseconds
         * @param {Function} callback Function to call when flickering ends
         * @example
         * // make the object flicker for 1 second
         * // and then remove it
         * this.flicker(1000, function ()
         * {
         *    me.game.world.removeChild(this);
         * });
         */
        flicker : function (duration, callback) {
            this.flickerDuration = duration;
            if (this.flickerDuration <= 0) {
                this.flickering = false;
                this.flickercb = null;
            }
            else if (!this.flickering) {
                this.flickercb = callback;
                this.flickering = true;
            }
        },

        /**
         * Flip object on horizontal axis
         * @name flipX
         * @memberOf me.Sprite
         * @function
         * @param {Boolean} flip enable/disable flip
         */
        flipX : function (flip) {
            if (flip !== this.lastflipX) {
                this.lastflipX = flip;

                // invert the scale.x value
                this._scale.x = -this._scale.x;

                // set the scaleFlag
                this.scaleFlag = this._scale.x !== 1.0 || this._scale.y !== 1.0;
            }
        },

        /**
         * Flip object on vertical axis
         * @name flipY
         * @memberOf me.Sprite
         * @function
         * @param {Boolean} flip enable/disable flip
         */
        flipY : function (flip) {
            if (flip !== this.lastflipY) {
                this.lastflipY = flip;

                // invert the scale.x value
                this._scale.y = -this._scale.y;

                // set the scaleFlag
                this.scaleFlag = this._scale.x !== 1.0 || this._scale.y !== 1.0;
            }
        },

        /**
         * scale the sprite around his center

         * @name scale
         * @memberOf me.Sprite
         * @function
         * @param {Number} ratioX x scaling ratio
         * @param {Number} ratioY y scaling ratio
         */
        scale : function (ratioX, ratioY) {
            var x = ratioX;
            var y = typeof(ratioY) === "undefined" ? ratioX : ratioY;
            if (x > 0) {
                this._scale.x = this._scale.x < 0.0 ? -x : x;
            }
            if (y > 0) {
                this._scale.y = this._scale.y < 0.0 ? -y : y;
            }
            // set the scaleFlag
            this.scaleFlag = this._scale.x !== 1.0 || this._scale.y !== 1.0;

        },

        /**
         * scale the sprite around his center

         * @name scaleV
         * @memberOf me.Sprite
         * @function
         * @param {me.Vector2d} vector ratio
         */
        scaleV : function (ratio) {
            this.scale(ratio.x, ratio.y);
        },

        /**
         * sprite update

         * not to be called by the end user

         * called by the game manager on each game loop
         * @name update
         * @memberOf me.Sprite
         * @function
         * @protected
         * @return false
         **/
        update : function (dt) {
            //update the "flickering" state if necessary
            if (this.flickering) {
                this.flickerDuration -= dt;
                if (this.flickerDuration < 0) {
                    if (this.flickercb) {
                        this.flickercb();
                    }
                    this.flicker(-1);
                }
                return true;
            }
            return false;
        },

        /**
         * object draw

         * not to be called by the end user

         * called by the game manager on each game loop
         * @name draw
         * @memberOf me.Sprite
         * @function
         * @protected
         * @param {Renderer} a renderer object: me.CanvasRenderer or me.WebGLRenderer
         **/
        draw : function (renderer) {
            // do nothing if we are flickering
            if (this.flickering) {
                this.flickerState = !this.flickerState;
                if (!this.flickerState) {
                    return;
                }
            }
            // save global alpha
            var alpha = renderer.globalAlpha();
            // sprite alpha value
            renderer.setGlobalAlpha(alpha * this.getOpacity());

            // clamp position vector to pixel grid
            var xpos = ~~this.pos.x, ypos = ~~this.pos.y;

            var w = this.width, h = this.height;
            var angle = this.angle + this._sourceAngle;

            if ((this.scaleFlag) || (angle !== 0)) {
                // save context
                renderer.save();

                // calculate pixel pos of the anchor point
                var ax = w * this.anchorPoint.x, ay = h * this.anchorPoint.y;
                // translate to the defined anchor point
                renderer.translate(xpos + ax, ypos + ay);
                // scale
                if (this.scaleFlag) {
                    renderer.scale(this._scale.x, this._scale.y);
                }
                if (angle !== 0) {
                    renderer.rotate(angle);
                }

                if (this._sourceAngle !== 0) {
                    // swap w and h for rotated source images
                    w = this.height;
                    h = this.width;

                    xpos = -ay;
                    ypos = -ax;
                }
                else {
                    // reset coordinates back to upper left coordinates
                    xpos = -ax;
                    ypos = -ay;
                }
            }

            renderer.drawImage(
                this.image,
                this.offset.x, this.offset.y,   // sx,sy
                w, h,                           // sw,sh
                xpos, ypos,                     // dx,dy
                w, h                            // dw,dh
            );

            if ((this.scaleFlag) || (angle !== 0)) {
                // restore context
                renderer.restore();
            }
            // restore global alpha
            renderer.setGlobalAlpha(alpha);
        },

        /**
         * Destroy function

         * @ignore
         */
        destroy : function () {
            this.onDestroyEvent.apply(this, arguments);
        },

        /**
         * OnDestroy Notification function

         * Called by engine before deleting the object
         * @name onDestroyEvent
         * @memberOf me.Sprite
         * @function
         */
        onDestroyEvent : function () {
            // to be extended !
        }
    });

})();
<commit_msg>[#592] post-merge cleaning :P<commit_after>/*
 * MelonJS Game Engine
 * Copyright (C) 2011 - 2014 Olivier Biot, Jason Oster, Aaron McLeod
 * http://www.melonjs.org
 *
 */
(function () {
    /**
     * A Simple object to display a sprite on screen.
     * @class
     * @extends me.Renderable
     * @memberOf me
     * @constructor
     * @param {Number} x the x coordinates of the sprite object
     * @param {Number} y the y coordinates of the sprite object
     * @param {Object} settings Contains additional parameters for the sprite
     * @param {Image|String} settings.image reference to the Sprite Image. See {@link me.loader#getImage}
     * @param {Number} [settings.framewidth=settings.image.width] Image source width.
     * @param {Number} [settings.frameheight=settings.image.height] Image source height.
     * @param {Number} [settings.rotation] Initial rotation angle in radians.
     * @param {Boolean} [settings.flipX] Initial flip for X-axis.
     * @param {Boolean} [settings.flipY] Initial flip for Y-axis.
     * @example
     * // create a static Sprite Object
     * mySprite = new me.Sprite (100, 100, {
     *     image : me.loader.getImage("mySpriteImage")
     * });
     */
    me.Sprite = me.Renderable.extend(
    /** @scope me.Sprite.prototype */
    {
        /**
         * @ignore
         */
        init : function (x, y, settings) {

            /**
             * private/internal scale factor
             * @ignore
             */
            this._scale = new me.Vector2d(1, 1);

            // if true, image flipping/scaling is needed
            this.scaleFlag = false;

            // just to keep track of when we flip
            this.lastflipX = false;
            this.lastflipY = false;

            this.flipX(!!settings.flipX);
            this.flipY(!!settings.flipY);

            // current frame texture offset
            this.offset = new me.Vector2d(0, 0);

            /**
             * Set the angle (in Radians) of a sprite to rotate it

             * WARNING: rotating sprites decreases performance with Canvas Renderer
             * @public
             * @type Number
             * @name me.Sprite#angle
             */
            this.angle = settings.rotation || 0;

            /**
             * Source rotation angle for pre-rotating the source image

             * Commonly used for TexturePacker
             * @ignore
             */
            this._sourceAngle = 0;

            // to manage the flickering effect
            this.flickering = false;
            this.flickerDuration = 0;
            this.flickercb = null;
            this.flickerState = false;

            // Used by the game engine to adjust visibility as the
            // sprite moves in and out of the viewport
            this.isSprite = true;

            var image = (
                (typeof(settings.image) === "string") ?
                me.loader.getImage(settings.image) :
                settings.image
            );

            // call the super constructor
            this._super(me.Renderable, "init", [
                x, y,
                settings.framewidth  || image.width,
                settings.frameheight || image.height
            ]);

            // cache image reference
            this.image = image;
        },

        /**
         * specify a transparent color
         * @name setTransparency
         * @memberOf me.Sprite
         * @function
         * @deprecated Use PNG or GIF with transparency instead
         * @param {String} color color key in "#RRGGBB" format
         */
        setTransparency : function (col) {
            // remove the # if present
            col = (col.charAt(0) === "#") ? col.substring(1, 7) : col;
            // applyRGB Filter (return a context object)
            this.image = me.video.renderer.applyRGBFilter(
                this.image,
                "transparent",
                col.toUpperCase()
            ).canvas;
        },

        /**
         * return the flickering state of the object
         * @name isFlickering
         * @memberOf me.Sprite
         * @function
         * @return {Boolean}
         */
        isFlickering : function () {
            return this.flickering;
        },

        /**
         * make the object flicker
         * @name flicker
         * @memberOf me.Sprite
         * @function
         * @param {Number} duration expressed in milliseconds
         * @param {Function} callback Function to call when flickering ends
         * @example
         * // make the object flicker for 1 second
         * // and then remove it
         * this.flicker(1000, function ()
         * {
         *    me.game.world.removeChild(this);
         * });
         */
        flicker : function (duration, callback) {
            this.flickerDuration = duration;
            if (this.flickerDuration <= 0) {
                this.flickering = false;
                this.flickercb = null;
            }
            else if (!this.flickering) {
                this.flickercb = callback;
                this.flickering = true;
            }
        },

        /**
         * Flip object on horizontal axis
         * @name flipX
         * @memberOf me.Sprite
         * @function
         * @param {Boolean} flip enable/disable flip
         */
        flipX : function (flip) {
            if (flip !== this.lastflipX) {
                this.lastflipX = flip;

                // invert the scale.x value
                this._scale.x = -this._scale.x;

                // set the scaleFlag
                this.scaleFlag = this._scale.x !== 1.0 || this._scale.y !== 1.0;
            }
        },

        /**
         * Flip object on vertical axis
         * @name flipY
         * @memberOf me.Sprite
         * @function
         * @param {Boolean} flip enable/disable flip
         */
        flipY : function (flip) {
            if (flip !== this.lastflipY) {
                this.lastflipY = flip;

                // invert the scale.x value
                this._scale.y = -this._scale.y;

                // set the scaleFlag
                this.scaleFlag = this._scale.x !== 1.0 || this._scale.y !== 1.0;
            }
        },

        /**
         * scale the sprite around his center

         * @name scale
         * @memberOf me.Sprite
         * @function
         * @param {Number} ratioX x scaling ratio
         * @param {Number} ratioY y scaling ratio
         */
        scale : function (ratioX, ratioY) {
            var x = ratioX;
            var y = typeof(ratioY) === "undefined" ? ratioX : ratioY;
            if (x > 0) {
                this._scale.x = this._scale.x < 0.0 ? -x : x;
            }
            if (y > 0) {
                this._scale.y = this._scale.y < 0.0 ? -y : y;
            }
            // set the scaleFlag
            this.scaleFlag = this._scale.x !== 1.0 || this._scale.y !== 1.0;

        },

        /**
         * scale the sprite around his center

         * @name scaleV
         * @memberOf me.Sprite
         * @function
         * @param {me.Vector2d} vector ratio
         */
        scaleV : function (ratio) {
            this.scale(ratio.x, ratio.y);
        },

        /**
         * sprite update

         * not to be called by the end user

         * called by the game manager on each game loop
         * @name update
         * @memberOf me.Sprite
         * @function
         * @protected
         * @return false
         **/
        update : function (dt) {
            //update the "flickering" state if necessary
            if (this.flickering) {
                this.flickerDuration -= dt;
                if (this.flickerDuration < 0) {
                    if (this.flickercb) {
                        this.flickercb();
                    }
                    this.flicker(-1);
                }
                return true;
            }
            return false;
        },

        /**
         * object draw

         * not to be called by the end user

         * called by the game manager on each game loop
         * @name draw
         * @memberOf me.Sprite
         * @function
         * @protected
         * @param {Renderer} a renderer object: me.CanvasRenderer or me.WebGLRenderer
         **/
        draw : function (renderer) {
            // do nothing if we are flickering
            if (this.flickering) {
                this.flickerState = !this.flickerState;
                if (!this.flickerState) {
                    return;
                }
            }
            // save global alpha
            var alpha = renderer.globalAlpha();
            // sprite alpha value
            renderer.setGlobalAlpha(alpha * this.getOpacity());

            // clamp position vector to pixel grid
            var xpos = ~~this.pos.x, ypos = ~~this.pos.y;

            var w = this.width, h = this.height;
            var angle = this.angle + this._sourceAngle;

            if ((this.scaleFlag) || (angle !== 0)) {
                // save context
                renderer.save();

                // calculate pixel pos of the anchor point
                var ax = w * this.anchorPoint.x, ay = h * this.anchorPoint.y;
                // translate to the defined anchor point
                renderer.translate(xpos + ax, ypos + ay);
                // scale
                if (this.scaleFlag) {
                    renderer.scale(this._scale.x, this._scale.y);
                }
                if (angle !== 0) {
                    renderer.rotate(angle);
                }

                if (this._sourceAngle !== 0) {
                    // swap w and h for rotated source images
                    w = this.height;
                    h = this.width;

                    xpos = -ay;
                    ypos = -ax;
                }
                else {
                    // reset coordinates back to upper left coordinates
                    xpos = -ax;
                    ypos = -ay;
                }
            }

            renderer.drawImage(
                this.image,
                this.offset.x, this.offset.y,   // sx,sy
                w, h,                           // sw,sh
                xpos, ypos,                     // dx,dy
                w, h                            // dw,dh
            );

            if ((this.scaleFlag) || (angle !== 0)) {
                // restore context
                renderer.restore();
            }
            // restore global alpha
            renderer.setGlobalAlpha(alpha);
        },

        /**
         * Destroy function

         * @ignore
         */
        destroy : function () {
            this.onDestroyEvent.apply(this, arguments);
        },

        /**
         * OnDestroy Notification function

         * Called by engine before deleting the object
         * @name onDestroyEvent
         * @memberOf me.Sprite
         * @function
         */
        onDestroyEvent : function () {
            // to be extended !
        }
    });

})();
<|endoftext|>


<commit_before>// ==UserScript==
// @name         gmodstore Checker
// @namespace    meharryp.xyz
// @version      1.0.4
// @description  View a scriptfodder users profile information on their steam profile page.
// @author       meharryp
// @downloadURL  https://raw.githubusercontent.com/meharryp/sfprofile/master/sfprofile.js
// @match        http://steamcommunity.com/id/*
// @match        http://steamcommunity.com/profiles/*
// @match        https://steamcommunity.com/id/*
// @match        https://steamcommunity.com/profiles/*
// @require      https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @require      http://timeago.yarp.com/jquery.timeago.js
// @connect      gmodstore.com
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
	'use strict';

	var bans = {};
	var data = {};

	$(".profile_leftcol").prepend(`

gmodstore Details

	`);

	console.log();

	var steamid = "";

	$.ajax({
		url: window.location.href + "?xml=1",
	}).done(function(data){
		var $xml = $(data);
		steamid = $xml.find("steamID64").text();

		console.log(steamid);

		if (steamid === ""){ return; }

		// Get users bans
		GM_xmlhttpRequest({
			url: "https://gmodstore.com/api/users/banned/" + steamid,
			method: "GET",
			onload: function(res){
                console.log(res.responseText);
				bans = JSON.parse(res.responseText).bans;

				console.log(bans);

				// Get user data
				GM_xmlhttpRequest({
					url: "https://gmodstore.com/api/users/search/steam64/" + steamid,
					method: "GET",
					onload: function(res){
						data = JSON.parse(res.responseText);

                        var html = `
						Reputation: ${parseInt(data.user.scripts_rep) + parseInt(data.user.jobs_rep)}

						Registered ${$.timeago(new Date(parseInt(data.user.dateRegistered) * 1000))}

						Last online ${$.timeago(new Date(parseInt(data.user.lastAction) * 1000))}

						Country: ${data.user.country_code}

						Usergroup: ${(data.user.usergroup == "0" && "User" || data.user.usergroup == "1" && "Developer" || data.user.usergroup == "2" && "Moderator" || data.user.usergroup == "3" && "Admin")}

						`;

						if (bans.length > 0){
							for (var i=0; i < bans.length; i++){
								var ban = bans[i];
								html += `

								Banned ${$.timeago(new Date(parseInt(ban.ban_starttime) * 1000))}, ban ends in ${(parseInt(ban.ban_endtime) !== 0 && $.timeago(new Date(ban.ban_endtime)) || "Never")}.

Reason: ${ban.ban_reason}

Banned from:
`;

                                console.log(html);

								for (var i in ban.attributes){
									if (parseInt(ban.attributes[i])){
                                        html += `<li>`;
										switch (i){
											case "ban_create_appeal":
												html += "Creating ban appeals";
												break;
											case "ban_everything":
												html += "Everything";
												break;
											case "ban_forum_posting":
												html += "Posting on the forums";
												break;
											case "ban_job_applying":
												html += "Applying for jobs";
												break;
											case "ban_job_creation":
												html += "Creating new jobs";
												break;
											case "ban_script_creation":
												html += "Creating new scripts";
												break;
											case "ban_script_downloading":
												html += "Downloading scripts";
												break;
											case "ban_script_purchasing":
												html += "Purchasing scripts";
												break;
											case "ban_script_reviewing":
												html += "Reviewing scripts";
												break;
											case "ban_user_reviewing":
												html += "Reviewing users";
												break;
											default:
												html += "Something";
												break;
										}

										html += `</li>`;
									}
                                }
                                html += `</ul>`;
							}

						}

                        html += `<br><a href="https://gmodstore.com/users/view/${steamid}" target="_blank">gmodstore Profile</a>`;
						$("#sfholder").html(html);
					}
				});
			}
		});
	});
})();
<commit_msg>Update link<commit_after>// ==UserScript==
// @name         gmodstore Checker
// @namespace    meharryp.xyz
// @version      1.0.4
// @description  View a scriptfodder users profile information on their steam profile page.
// @author       meharryp
// @downloadURL  https://raw.githubusercontent.com/meharryp/sfprofile/master/sfprofile.user.js
// @match        http://steamcommunity.com/id/*
// @match        http://steamcommunity.com/profiles/*
// @match        https://steamcommunity.com/id/*
// @match        https://steamcommunity.com/profiles/*
// @require      https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @require      http://timeago.yarp.com/jquery.timeago.js
// @connect      gmodstore.com
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
	'use strict';

	var bans = {};
	var data = {};

	$(".profile_leftcol").prepend(`

gmodstore Details

	`);

	console.log();

	var steamid = "";

	$.ajax({
		url: window.location.href + "?xml=1",
	}).done(function(data){
		var $xml = $(data);
		steamid = $xml.find("steamID64").text();

		console.log(steamid);

		if (steamid === ""){ return; }

		// Get users bans
		GM_xmlhttpRequest({
			url: "https://gmodstore.com/api/users/banned/" + steamid,
			method: "GET",
			onload: function(res){
                console.log(res.responseText);
				bans = JSON.parse(res.responseText).bans;

				console.log(bans);

				// Get user data
				GM_xmlhttpRequest({
					url: "https://gmodstore.com/api/users/search/steam64/" + steamid,
					method: "GET",
					onload: function(res){
						data = JSON.parse(res.responseText);

                        var html = `
						Reputation: ${parseInt(data.user.scripts_rep) + parseInt(data.user.jobs_rep)}

						Registered ${$.timeago(new Date(parseInt(data.user.dateRegistered) * 1000))}

						Last online ${$.timeago(new Date(parseInt(data.user.lastAction) * 1000))}

						Country: ${data.user.country_code}

						Usergroup: ${(data.user.usergroup == "0" && "User" || data.user.usergroup == "1" && "Developer" || data.user.usergroup == "2" && "Moderator" || data.user.usergroup == "3" && "Admin")}

						`;

						if (bans.length > 0){
							for (var i=0; i < bans.length; i++){
								var ban = bans[i];
								html += `

								Banned ${$.timeago(new Date(parseInt(ban.ban_starttime) * 1000))}, ban ends in ${(parseInt(ban.ban_endtime) !== 0 && $.timeago(new Date(ban.ban_endtime)) || "Never")}.

Reason: ${ban.ban_reason}

Banned from:
`;

                                console.log(html);

								for (var i in ban.attributes){
									if (parseInt(ban.attributes[i])){
                                        html += `<li>`;
										switch (i){
											case "ban_create_appeal":
												html += "Creating ban appeals";
												break;
											case "ban_everything":
												html += "Everything";
												break;
											case "ban_forum_posting":
												html += "Posting on the forums";
												break;
											case "ban_job_applying":
												html += "Applying for jobs";
												break;
											case "ban_job_creation":
												html += "Creating new jobs";
												break;
											case "ban_script_creation":
												html += "Creating new scripts";
												break;
											case "ban_script_downloading":
												html += "Downloading scripts";
												break;
											case "ban_script_purchasing":
												html += "Purchasing scripts";
												break;
											case "ban_script_reviewing":
												html += "Reviewing scripts";
												break;
											case "ban_user_reviewing":
												html += "Reviewing users";
												break;
											default:
												html += "Something";
												break;
										}

										html += `</li>`;
									}
                                }
                                html += `</ul>`;
							}

						}

                        html += `<br><a href="https://gmodstore.com/users/view/${steamid}" target="_blank">gmodstore Profile</a>`;
						$("#sfholder").html(html);
					}
				});
			}
		});
	});
})();
<|endoftext|>


<commit_before>var EE = require('events').EventEmitter;
var util = require('util');
var format = require('util').format;

function Smell() {
  if (!(this instanceof Smell)) {
    return new Smell();
  }
  EE.call(this);
}
util.inherits(Smell, EE);

Smell.prototype.info = function () {
  var msg = format.apply(null, arguments);
  this.emit('info', msg);
};
Smell.prototype.warn = function () {
  var msg = format.apply(null, arguments);
  this.emit('warn', msg);
};
Smell.prototype.error = function () {
  var msg = format.apply(null, arguments);
  this.emit('err', msg);
};

module.exports = Smell;
<commit_msg>Object create way is more what I ususally do though - let's keep it that way<commit_after>var EE = require('events').EventEmitter;
var format = require('util').format;

function Smell() {
  if (!(this instanceof Smell)) {
    return new Smell();
  }
  EE.call(this);
}
Smell.prototype = Object.create(EE.prototype);

Smell.prototype.info = function () {
  var msg = format.apply(null, arguments);
  this.emit('info', msg);
};
Smell.prototype.warn = function () {
  var msg = format.apply(null, arguments);
  this.emit('warn', msg);
};
Smell.prototype.error = function () {
  var msg = format.apply(null, arguments);
  this.emit('err', msg);
};

module.exports = Smell;
<|endoftext|>


<commit_before>var time = Date.now();
var gameOver = false;
var score = 0;

var Direction = {
  LEFT: 0,
  RIGHT: 1,
  UP: 2,
  DOWN: 3
}

function Point(x, y) {
  this.x = x;
  this.y = y;
}

function Snake() {
  this.points = [new Point(50, 50), new Point(40, 50), new Point(30, 50)];
  this.direction = Direction.RIGHT;

  this.headCollidesWithWall = function(canvas) {
    var head = this.points[0];
    var xCollides = 0 > head.x || head.x > canvas.width - 10;
    var yCollides = 0 > head.y || head.y > canvas.height - 10;
    return xCollides || yCollides;
  };

  this.headCollidesWithSelf = function() {
    var head = this.points[0];
    for (i = 1; i < this.points.length; i++) {
      if (head.x == this.points[i].x && head.y == this.points[i].y) {
        return true;
      }
    }

    return false;
  }

  this.headCollidesWithApple = function(apple){
    var head = this.points[0];
    return head.x === apple.x && head.y === apple.y;
  };

  this.turnLeft = function() {
    if (this.direction !== Direction.RIGHT)
      this.direction = Direction.LEFT;
  };

  this.turnRight = function() {
    if (this.direction !== Direction.LEFT)
      this.direction = Direction.RIGHT;
  };

  this.turnUp = function() {
    if (this.direction !== Direction.DOWN)
      this.direction = Direction.UP;
  };

  this.turnDown = function() {
    if (this.direction !== Direction.UP)
      this.direction = Direction.DOWN;
  };
}

function Apple(canvas) {
  this.x = generateX();
  this.y = generateY();

  function generateX() {
    var x = Math.random() * (canvas.width - 10);
    return Math.round(x / 10) * 10;
  }

  function generateY() {
    var y = Math.random() * (canvas.height - 10);
    return Math.round(y / 10) * 10;
  }
}

document.addEventListener('DOMContentLoaded', function() {
  var canvas = document.querySelector('#screen');
  var context =  canvas.getContext('2d');
  var snake = new Snake();
  var apple = new Apple(canvas);

  // reset button
  var resetButton = document.querySelector('#reset');
  resetButton.onclick = function() {
    gameOver = false;
    time = Date.now();
    score = 0;

    snake = new Snake();
    apple = new Apple(canvas);
  }

  // responsive canvas
  window.addEventListener('resize', resizeCanvas, false);

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    if (apple.x > canvas.width - 10 || apple.y > canvas.height - 10) {
      apple = new Apple(canvas);
    }

    drawSnake();
  }

  resizeCanvas();
  apple = new Apple(canvas);

  // game loop timing
  if (window.requestAnimationFrame !== null) {
    var recursiveAnim = function() {
      mainloop();
      window.requestAnimationFrame(recursiveAnim);
    };

    window.requestAnimationFrame(recursiveAnim);
  } else {
    setInterval(mainloop, 1000.0 / 60);
  }

  // handle keypress events
  window.addEventListener('keydown', keyPress, false);

  function keyPress(e) {
    var code = e.keyCode;
    switch (code) {
      case 37: snake.turnLeft(); break;
      case 38: snake.turnUp(); break;
      case 39: snake.turnRight(); break;
      case 40: snake.turnDown(); break;
    }
  }

  // game loop
  function mainloop() {
    if (!gameOver) {
      updateSnake();
      drawSnake();
    }
  }

  function updateSnake() {
    var newTime = Date.now();

    if (newTime - time > 50) {
      time = newTime;

      if (snake.headCollidesWithApple(apple)) {
        var last = snake.points[snake.points.length-1];
        snake.points.push(new Point(last.x, last.y));

        score++;

        apple = new Apple(canvas);
      }

      // update all but head of snake
      for (i = snake.points.length - 1; i > 0; i--) {
        snake.points[i].x = snake.points[i-1].x;
        snake.points[i].y = snake.points[i-1].y;
      }

      // update head
      if (snake.direction === Direction.LEFT) {
        snake.points[0].x -= 10;
      } else if (snake.direction === Direction.RIGHT) {
        snake.points[0].x += 10;
      } else if (snake.direction === Direction.UP) {
        snake.points[0].y -= 10;
      } else {
        snake.points[0].y += 10;
      }

      if (snake.headCollidesWithWall(canvas) || snake.headCollidesWithSelf()) {
        gameOver = true;
      }
    }
  }

  function drawSnake() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.fillStyle = 'black';

    // draw snake
    for (i = 0; i < snake.points.length; i++) {
      context.fillRect(snake.points[i].x, snake.points[i].y, 10, 10);
    }

    // draw apple
    context.fillRect(apple.x, apple.y, 10, 10);

    // draw score
    context.font = 'bold 36px sans-serif';
    context.fillStyle = 'rgba(0, 0, 0, 0.1)';
    context.fillText('Score: ' + score, 10, 41);
  }
});
<commit_msg>Snake should start as a single point<commit_after>var time = Date.now();
var gameOver = false;
var score = 0;

var Direction = {
  LEFT: 0,
  RIGHT: 1,
  UP: 2,
  DOWN: 3
}

function Point(x, y) {
  this.x = x;
  this.y = y;
}

function Snake() {
  this.points = [new Point(50, 50)];
  this.direction = Direction.RIGHT;

  this.headCollidesWithWall = function(canvas) {
    var head = this.points[0];
    var xCollides = 0 > head.x || head.x > canvas.width - 10;
    var yCollides = 0 > head.y || head.y > canvas.height - 10;
    return xCollides || yCollides;
  };

  this.headCollidesWithSelf = function() {
    var head = this.points[0];
    for (i = 1; i < this.points.length; i++) {
      if (head.x == this.points[i].x && head.y == this.points[i].y) {
        return true;
      }
    }

    return false;
  }

  this.headCollidesWithApple = function(apple){
    var head = this.points[0];
    return head.x === apple.x && head.y === apple.y;
  };

  this.turnLeft = function() {
    if (this.direction !== Direction.RIGHT)
      this.direction = Direction.LEFT;
  };

  this.turnRight = function() {
    if (this.direction !== Direction.LEFT)
      this.direction = Direction.RIGHT;
  };

  this.turnUp = function() {
    if (this.direction !== Direction.DOWN)
      this.direction = Direction.UP;
  };

  this.turnDown = function() {
    if (this.direction !== Direction.UP)
      this.direction = Direction.DOWN;
  };
}

function Apple(canvas) {
  this.x = generateX();
  this.y = generateY();

  function generateX() {
    var x = Math.random() * (canvas.width - 10);
    return Math.round(x / 10) * 10;
  }

  function generateY() {
    var y = Math.random() * (canvas.height - 10);
    return Math.round(y / 10) * 10;
  }
}

document.addEventListener('DOMContentLoaded', function() {
  var canvas = document.querySelector('#screen');
  var context =  canvas.getContext('2d');
  var snake = new Snake();
  var apple = new Apple(canvas);

  // reset button
  var resetButton = document.querySelector('#reset');
  resetButton.onclick = function() {
    gameOver = false;
    time = Date.now();
    score = 0;

    snake = new Snake();
    apple = new Apple(canvas);
  }

  // responsive canvas
  window.addEventListener('resize', resizeCanvas, false);

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    if (apple.x > canvas.width - 10 || apple.y > canvas.height - 10) {
      apple = new Apple(canvas);
    }

    drawSnake();
  }

  resizeCanvas();
  apple = new Apple(canvas);

  // game loop timing
  if (window.requestAnimationFrame !== null) {
    var recursiveAnim = function() {
      mainloop();
      window.requestAnimationFrame(recursiveAnim);
    };

    window.requestAnimationFrame(recursiveAnim);
  } else {
    setInterval(mainloop, 1000.0 / 60);
  }

  // handle keypress events
  window.addEventListener('keydown', keyPress, false);

  function keyPress(e) {
    var code = e.keyCode;
    switch (code) {
      case 37: snake.turnLeft(); break;
      case 38: snake.turnUp(); break;
      case 39: snake.turnRight(); break;
      case 40: snake.turnDown(); break;
    }
  }

  // game loop
  function mainloop() {
    if (!gameOver) {
      updateSnake();
      drawSnake();
    }
  }

  function updateSnake() {
    var newTime = Date.now();

    if (newTime - time > 50) {
      time = newTime;

      if (snake.headCollidesWithApple(apple)) {
        var last = snake.points[snake.points.length-1];
        snake.points.push(new Point(last.x, last.y));

        score++;

        apple = new Apple(canvas);
      }

      // update all but head of snake
      for (i = snake.points.length - 1; i > 0; i--) {
        snake.points[i].x = snake.points[i-1].x;
        snake.points[i].y = snake.points[i-1].y;
      }

      // update head
      if (snake.direction === Direction.LEFT) {
        snake.points[0].x -= 10;
      } else if (snake.direction === Direction.RIGHT) {
        snake.points[0].x += 10;
      } else if (snake.direction === Direction.UP) {
        snake.points[0].y -= 10;
      } else {
        snake.points[0].y += 10;
      }

      if (snake.headCollidesWithWall(canvas) || snake.headCollidesWithSelf()) {
        gameOver = true;
      }
    }
  }

  function drawSnake() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.fillStyle = 'black';

    // draw snake
    for (i = 0; i < snake.points.length; i++) {
      context.fillRect(snake.points[i].x, snake.points[i].y, 10, 10);
    }

    // draw apple
    context.fillRect(apple.x, apple.y, 10, 10);

    // draw score
    context.font = 'bold 36px sans-serif';
    context.fillStyle = 'rgba(0, 0, 0, 0.1)';
    context.fillText('Score: ' + score, 10, 41);
  }
});
<|endoftext|>


<commit_before>var Direction = {
  LEFT: 0,
  RIGHT: 1,
  UP: 2,
  DOWN: 3
}

function Snake() {
  this.x = 0;
  this.y = 0;
  this.direction = Direction.RIGHT;

  this.turnLeft = function() {
    if (this.direction !== Direction.RIGHT)
      this.direction = Direction.LEFT;
  }
  this.turnRight = function() {
    if (this.direction !== Direction.LEFT)
      this.direction = Direction.RIGHT;
  }
  this.turnUp = function() {
    if (this.direction !== Direction.DOWN)
      this.direction = Direction.UP;
  }
  this.turnDown = function() {
    if (this.direction !== Direction.UP)
      this.direction = Direction.DOWN;
  }
}

document.addEventListener('DOMContentLoaded', function() {
  var canvas = document.querySelector('#screen');
  var context =  canvas.getContext('2d');
  var snake = new Snake();

  // responsive canvas
  window.addEventListener('resize', resizeCanvas, false);

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    drawSnake();
  }

  resizeCanvas();

  // game loop timing
  setInterval(mainloop, 1000.0 / 10);

  // handle keypress events
  window.addEventListener('keydown', keyPress, false);

  function keyPress(e) {
    var code = e.keyCode;
    switch (code) {
      case 37: snake.turnLeft(); break;
      case 38: snake.turnUp(); break;
      case 39: snake.turnRight(); break;
      case 40: snake.turnDown(); break;
    }
  }

  // game loop
  function mainloop() {
    updateSnake();
    drawSnake();
  }

  function updateSnake() {
    if (snake.direction === Direction.LEFT) {
      snake.x -= 10;
    } else if (snake.direction === Direction.RIGHT) {
      snake.x += 10;
    } else if (snake.direction === Direction.UP) {
      snake.y -= 10;
    } else {
      snake.y += 10;
    }
  }

  function drawSnake() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillRect(snake.x, snake.y, 10, 10);
  }
});
<commit_msg>Give snake a speed, improve gameloop timing<commit_after>var time = Date.now();

var Direction = {
  LEFT: 0,
  RIGHT: 1,
  UP: 2,
  DOWN: 3
}

function Snake() {
  this.x = 0;
  this.y = 0;
  this.speed = 200; // pixels per second
  this.direction = Direction.RIGHT;

  this.turnLeft = function() {
    if (this.direction !== Direction.RIGHT)
      this.direction = Direction.LEFT;
  }
  this.turnRight = function() {
    if (this.direction !== Direction.LEFT)
      this.direction = Direction.RIGHT;
  }
  this.turnUp = function() {
    if (this.direction !== Direction.DOWN)
      this.direction = Direction.UP;
  }
  this.turnDown = function() {
    if (this.direction !== Direction.UP)
      this.direction = Direction.DOWN;
  }
}

document.addEventListener('DOMContentLoaded', function() {
  var canvas = document.querySelector('#screen');
  var context =  canvas.getContext('2d');
  var snake = new Snake();

  // responsive canvas
  window.addEventListener('resize', resizeCanvas, false);

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    drawSnake();
  }

  resizeCanvas();

  // game loop timing
  if (window.requestAnimationFrame !== null) {
    var recursiveAnim = function() {
      mainloop();
      window.requestAnimationFrame(recursiveAnim);
    };

    window.requestAnimationFrame(recursiveAnim);
  } else {
    setInterval(mainloop, 1000.0 / 60);
  }

  // handle keypress events
  window.addEventListener('keydown', keyPress, false);

  function keyPress(e) {
    var code = e.keyCode;
    switch (code) {
      case 37: snake.turnLeft(); break;
      case 38: snake.turnUp(); break;
      case 39: snake.turnRight(); break;
      case 40: snake.turnDown(); break;
    }
  }

  // game loop
  function mainloop() {
    updateSnake();
    drawSnake();
  }

  function updateSnake() {
    var newTime = Date.now();

    // seconds since last draw
    var timeDelta = (newTime - time) / 1000;
    time = newTime;

    var distance = timeDelta * snake.speed;

    if (snake.direction === Direction.LEFT) {
      snake.x -= distance;
    } else if (snake.direction === Direction.RIGHT) {
      snake.x += distance;
    } else if (snake.direction === Direction.UP) {
      snake.y -= distance;
    } else {
      snake.y += distance;
    }
  }

  function drawSnake() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillRect(snake.x, snake.y, 10, 10);
  }
});
<|endoftext|>


<commit_before>// Starting from a copy-and-paste of https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode

if (typeof YAJT === 'undefined') {
    YAJT = {};
}

YAJT.audio = {
    context: null,
    generate: function (samples) {
        if (!YAJT.audio.context) {
            if (window.AudioContext) {
                YAJT.audio.context = new window.AudioContext();
            } else if (window.webkitAudioContext) {
                YAJT.audio.context = new window.webkitAudioContext();
            } else {
                alert("Error: window.AudioContext not supported");
                return;
            }
        }

        if (YAJT.audio.old_source) {
            YAJT.audio.old_source.stop(YAJT.audio.context.currentTime);
        }
        YAJT.audio.generate_from[YAJT.core.config.mode](samples);
    },
    generate_from: {
        waveform: function(samples) {
            var audio_context = YAJT.audio.context;
            var channels = 1;
            var frame_count = samples.length;

            var buffer = audio_context.createBuffer(channels, frame_count,
                    Math.pow(2, YAJT.core.config.tone / 6) * 440 * frame_count);
            var data = buffer.getChannelData(0);
            for (var i = 0; i < frame_count; i++) {
                //data[i] = Math.sin(i * 2* Math.PI/frame_count)
                data[i] = ((samples[i] / YAJT.core.config.height) - 0.5);
            }

            var source = audio_context.createBufferSource();
            source.buffer = buffer;
            source.loop = true;
            source.connect(audio_context.destination);

            source.start(audio_context.currentTime);
            YAJT.audio.old_source = source;
        },
        sequence: function(samples) {

        },
        spectrum: function(samples) {
            var audio_context = YAJT.audio.context;
            var oscillator = audio_context.createOscillator();

            oscillator.type = 'square';
            oscillator.frequency.value = Math.pow(2, YAJT.core.config.tone / 6) * 440;
            oscillator.connect(audio_context.destination);
            oscillator.start(audio_context.currentTime);

            YAJT.audio.old_source = oscillator;
        }
    }
};<commit_msg>periodicWave<commit_after>// Starting from a copy-and-paste of https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode

if (typeof YAJT === 'undefined') {
    YAJT = {};
}

YAJT.audio = {
    context: null,
    generate: function (samples) {
        if (!YAJT.audio.context) {
            if (window.AudioContext) {
                YAJT.audio.context = new window.AudioContext();
            } else if (window.webkitAudioContext) {
                YAJT.audio.context = new window.webkitAudioContext();
            } else {
                alert("Error: window.AudioContext not supported");
                return;
            }
        }

        if (YAJT.audio.old_source) {
            YAJT.audio.old_source.stop(YAJT.audio.context.currentTime);
        }
        YAJT.audio.generate_from[YAJT.core.config.mode](samples);
    },
    generate_from: {
        waveform: function(samples) {
            var audio_context = YAJT.audio.context;
            var channels = 1;
            var frame_count = samples.length;

            var buffer = audio_context.createBuffer(channels, frame_count,
                    Math.pow(2, YAJT.core.config.tone / 6) * 440 * frame_count);
            var data = buffer.getChannelData(0);
            for (var i = 0; i < frame_count; i++) {
                //data[i] = Math.sin(i * 2* Math.PI/frame_count)
                data[i] = ((samples[i] / YAJT.core.config.height) - 0.5);
            }

            var source = audio_context.createBufferSource();
            source.buffer = buffer;
            source.loop = true;
            source.connect(audio_context.destination);

            source.start(audio_context.currentTime);
            YAJT.audio.old_source = source;
        },
        sequence: function(samples) {

        },
        spectrum: function(samples) {
            var audio_context = YAJT.audio.context;
            var oscillator = audio_context.createOscillator();

            var real = new Float32Array(2);
            var imag = new Float32Array(2);
            real[0] = 0;
            imag[0] = 0;
            real[1] = 1;
            imag[1] = 0;

            var wave = audio_context.createPeriodicWave(real, imag);

            oscillator.setPeriodicWave(wave);
            oscillator.frequency.value = Math.pow(2, YAJT.core.config.tone / 6) * 440;
            oscillator.connect(audio_context.destination);
            oscillator.start(audio_context.currentTime);

            YAJT.audio.old_source = oscillator;
        }
    }
};<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO(kgr): add rotation to CView to complete demo
CLASS({
  package: 'foam.demos.modeldiagram',
  name: 'ModelDiagramOW',
  extends: 'foam.graphics.CView',

  requires: [
    'foam.demos.modeldiagram.Person',
    'foam.demos.supersnake.Robot',
    'foam.ui.DetailView',
    'foam.ui.TableView',
    'foam.ui.HelpView',
    'foam.ui.md.DetailView as MDDetailView',
    'foam.documentation.DocViewPicker',
    'foam.documentation.diagram.DocDiagramView',
    'foam.graphics.CView',
    'foam.graphics.Rectangle',
    'foam.graphics.ImageCView',
    'foam.graphics.ViewCView',
    'foam.graphics.LabelledBox as Box',
    'foam.util.JavaSource',
    'foam.util.swift.SwiftSource',
    'foam.graphics.Circle'
  ],

  properties: [
    [ 'width', 1700 ],
    [ 'height', 1000 ]
  ],

  methods: {
    initCView: function() {
      var self  = this;
      var v     = this.Box.create({width: 500, height: 600, x:100, y: 145, text: 'Model', background: '#ccf', color: 'white', font: '28pt Arial'});
      var cls   = this.Box.create({width: 500, height: 600, x:800, y: 145, text: 'Class', font: '28pt Arial'});
      var robot = this.Robot.create({x:400,y:165,width:200,height:220,scaleX:0,scaleY:0});
      var display = self.ViewCView.create({
        innerView: { toHTML: function() { return '

'; }, initHTML: function() { } },
        x: 100,
        y: 600,
        width: 1260,
        height: 680
      });

      GLOBAL.robot = robot;
      this.addChildren(v, robot, cls, display);

      function addImage(parent, src) {
        var bg  = self.Rectangle.create({background: 'white', width: parent.width-1, height: parent.height-1});
        var img = self.ImageCView.create({src: src});

        parent.addChildren(bg);
        bg.addChildren(img);

        img.height$.addListener(function() {
          var scale = Math.min((parent.width-2)/img.width, (parent.height-2)/img.height);
          img.width = img.width*scale;
          img.height = img.height*scale;
        });

        return bg;
      }

      var m0, m1;
      var c0, c1;

      var anim = [
        [0],
        function() {
          c0 = addImage(cls, 'js/foam/demos/modeldiagram/PersonES6.png');
        },
        [0],
        function() {
          m0 = addImage(v, 'js/foam/demos/modeldiagram/PersonV0.png');
        },
        [0],
        function() {
          m0.parent.removeChild(m0);
          m0 = addImage(v, 'js/foam/demos/modeldiagram/PersonV05.png');
          c1 = addImage(cls, 'js/foam/demos/modeldiagram/PersonJava.png');
        },
        [0],
        [500, function() {
          cls.alpha = 0;
        }],
        function() {
          v.width += 200;
          m1 = addImage(v, 'js/foam/demos/modeldiagram/PersonV1.png');
        },
        [0],
        [500, function() {
          m0.alpha = m1.alpha = 0;
        }],
        [500, function() { v.width /= 4.5; v.height /= 4.5; cls.alpha = 0; } ],
        function() { self.removeChild(cls); },
        [500, function() { robot.scaleX = robot.scaleY = 3; } ],
        [0]
      ];

      var fnum = 0;
      function feature(f, anim, xo, yo, timeWarp) {
        var factory = f.factory;
        var pause   = f.factory || f.pause;

        timeWarp = timeWarp || 1;
        var b = self.Box.create({alpha: 0.7, width: v.width/5+15, height: v.height/5, x: robot.x, y: v.y, text: f.name, font: '14pt Arial'});
        var num = fnum++;
        var x = num % 5;
        var y = Math.floor(num/5);

//        if ( f.pause ) anim.push([[0]]);
        anim.push(function() { self.addChild(b); });
        if ( pause ) {
          if ( f.factory ) anim.push(function() { self.setDisplay(factory); });
          anim.push([300*timeWarp, function() { b.x += 250 + xo; b.y-=80; b.scaleX = b.scaleY = 3; }]);
          anim.push([[0]]);
          if ( factory ) anim.push(function() { self.setDisplay(); });
          anim.push([150*timeWarp, function() { b.scaleX = b.scaleY = 1; b.x += x * b.width*1.4; b.y += yo + b.height*1.2 * y; }]);
        } else {
          anim.push([500*timeWarp, function() { b.x += 250 + xo + x * b.width*1.4; b.y += yo + b.height*1.2 * y - 80; }]);
        }

        return b;
      }

      var p = this.Person.create({
        id: 1,
        firstName: 'John',
        lastName: 'Smith',
        age: 42,
        married: true
      });
      var people = [
        p,
        this.Person.create({id: 2, firstName: 'Janet', lastName: 'Jones', age: 38, married: true}),
        this.Person.create({id: 2, firstName: 'Jimmy', lastName: 'Jones', age: 8, married: false})      ];
      GLOBAL.p = p;

      var fs = [
        { name: 'Class', pause: true, factory: multiline(function() {/*
var p = this.Person.create({
   id: 1,
   firstName: 'John',
   lastName: 'Smith',
   age: 42,
   married: true
});
        */}) },
        { name: '.hashCode()', factory: multiline(function() {/*
> p.hashCode();
< 343020328
> p.firstName = 'Steve';
< "Steve"
> p.hashCode();
< 1609175968
*/}) },
        { name: '.copyFrom()' },
        { name: '.clone()' },
        { name: '.equals()' },
        { name: '.compareTo()' },
        { name: '.diff()' },
        { name: 'Observer' },
        { name: 'XML', factory: multiline(function() {/*
> p.toXML();
< "<foam>
<object model="Person">
  <property name="id">1</property>
  <property name="firstName">John</property>
  <property name="lastName">Smith</property>
  <property name="age">42</property>
  <property name="married">true</property>
</object>
</foam>"
*/}) },
        { name: 'JSON',  factory: multiline(function() {/*
> p.toJSON();"
< "{
   "model_": "foam.demos.modeldiagram.Person",
   "id": 1,
   "firstName": "John",
   "lastName": "Smith",
   "age": 42,
   "married": true
}"*/})  },
        { name: 'ProtoBuf' },
        { name: 'Detail View', factory: function() { return self.DetailView.create({data:p, showActions:true}); } },
        { name: 'MD View', factory: function() { return self.MDDetailView.create({data:p}); } },
        { name: 'Table View', factory: function() { return self.TableView.create({model:self.Person, dao: people}); } },
        { name: 'List View' },
        { name: 'Grid View', factory: function() { return { toHTML: function() { return ''; }, initHTML: function() { }}; } },
        { name: 'Query' },
        { name: 'Local Store' },
        { name: 'IndexedDB' },
        { name: 'ClientDAO' },
        { name: 'Offline' },
        { name: 'Cloud Store' },
        { name: 'Firebase' },
        { name: 'Controller', factory: function() { return { toHTML: function() { return ''; }, initHTML: function() { }}; } },
        { name: '...' }
      ];

      // JS
      fs.forEach(function(f) { feature(f, anim, 0, 0, 0.5); });

      // Java
      anim.push([0]);
      fs.forEach(function(f) { f.factory = false; f.pause = false; });
      fs[0].factory = self.JavaSource.create().generate(self.Person);
      anim.push([300, function() { self.scaleX = self.scaleY = 0.7; }]);
      fnum = 0;
      fs.forEach(function(f) { feature(f, anim, 900, 0, 0.1); });

      anim.push([0]);
      anim.push(function() {
        var cs = self.children;
        for ( var j = cs.length-1 ; j > -1 ; j-- ) {
          var c = cs[j];
          if ( self.Box.isInstance(c) && ( c.x > 1295 || c.y > 765 ) ) self.removeChild(c);
        }
      });
      anim.push([800, function() { robot.scaleX += 0.0001; self.scaleX = self.scaleY = 1.1; }]);

      anim.push([0]);
      anim.push(function() { robot.timer.stop(); robot.timer.i = 45; robot.timer.time = 0; });
      anim.push(function() {
        var cs = self.children.clone();
        for ( var i = 1 ; i < 15 ; i++ ) {
          setTimeout(function(i) {
          for ( var j = 0 ; j < cs.length ; j++ ) {
            var c = cs[j];
            if ( self.Box.isInstance(c) ) {
              if ( c.text === 'Class' || c.text === 'Model' || Math.random() < 0.5 ) {
                c = self.Box.create({text: c.text, font: c.font, x: c.x-7*i, y: c.y+6*i, width: c.width, height: c.height, color: c.color, background: c.background});
                self.addChildren(c);
              }
            }
          }
          }.bind(self, i), i * 50);
        }
      });

      anim.push([0]);
      anim.push(function() { self.removeChild(robot); self.addChildren(robot); });
      anim.push([1000, function() { robot.x = v.x-40; robot.y += 65; }]);
      anim.push([0]);
      anim.push([800, function() { robot.scaleX = robot.scaleY = 25; }]);
      anim.push([0]);
      anim.push([800, function() { robot.scaleX = robot.scaleY = 3; }]);

      /*
      anim.push([0]);
      anim.push(function() { self.removeChild(v); self.addChildren(v); });
      anim.push([1000, function() { v.scaleX = v.scaleY = 5; }]);
      anim.push([0]);
      anim.push(function() { self.removeChild(v); self.addChildren(v); v.font = '18pt Arial'; v.text = "Class Model"; });
      anim.push([0]);
      anim.push(function() { v.text = "Query Model"; });
      anim.push([0]);
      anim.push(function() { v.text = "Parser Model"; });
      anim.push([0]);
      anim.push(function() { v.font = '14pt Arial'; v.text = "Animation Model"; });
      anim.push([0]);
      anim.push(function() { v.alpha = 0; });
      */

      Movement.compile(anim)();
    },
    setDisplay: function(txt) {
      if ( typeof txt === 'function' ) {
        var v = txt();
        var t = txt.toString();
        t = t.length < 80 ? t.substring(26, t.length-2) : '';
        this.X.$('display').innerHTML = '
' + t + '

' + v.toHTML();
        v.initHTML();
      } else {
        this.X.$('display').innerHTML = txt ? '<textarea style="font-size:24px" rows="13" cols="77">' + txt + '</textarea>' : '';
      }
    }
  }
});
<commit_msg>ModelDiagramOW work.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO(kgr): add rotation to CView to complete demo
CLASS({
  package: 'foam.demos.modeldiagram',
  name: 'ModelDiagramOW',
  extends: 'foam.graphics.CView',

  requires: [
    'foam.demos.modeldiagram.Person',
    'foam.demos.supersnake.Robot',
    'foam.ui.DetailView',
    'foam.ui.TableView',
    'foam.ui.HelpView',
    'foam.ui.md.DetailView as MDDetailView',
    'foam.documentation.DocViewPicker',
    'foam.documentation.diagram.DocDiagramView',
    'foam.graphics.CView',
    'foam.graphics.Rectangle',
    'foam.graphics.ImageCView',
    'foam.graphics.ViewCView',
    'foam.graphics.LabelledBox as Box',
    'foam.util.JavaSource',
    'foam.util.swift.SwiftSource',
    'foam.graphics.Circle'
  ],

  properties: [
    [ 'width', 1700 ],
    [ 'height', 1000 ]
  ],

  methods: {
    initCView: function() {
      var self  = this;
      var v     = this.Box.create({width: 500, height: 600, x:100, y: 145, text: 'Model', background: '#ccf', color: 'white', font: '28pt Arial'});
      var cls   = this.Box.create({width: 500, height: 600, x:800, y: 145, text: 'Class', font: '28pt Arial'});
      var robot = this.Robot.create({x:400,y:165,width:200,height:220,scaleX:0,scaleY:0});
      var display = self.ViewCView.create({
        innerView: { toHTML: function() { return '

'; }, initHTML: function() { } },
        x: 100,
        y: 600,
        width: 1260,
        height: 680
      });

      GLOBAL.robot = robot;
      this.addChildren(v, robot, cls, display);

      function addImage(parent, src) {
        var bg  = self.Rectangle.create({background: 'white', width: parent.width-1, height: parent.height-1});
        var img = self.ImageCView.create({src: src});

        parent.addChildren(bg);
        bg.addChildren(img);

        img.height$.addListener(function() {
          var scale = Math.min((parent.width-2)/img.width, (parent.height-2)/img.height);
          img.width = img.width*scale;
          img.height = img.height*scale;
        });

        return bg;
      }

      var m0, m1;
      var c0, c1;

      var anim = [
        [0],
        function() {
          c0 = addImage(cls, 'js/foam/demos/modeldiagram/PersonES6.png');
        },
        [0],
        function() {
          m0 = addImage(v, 'js/foam/demos/modeldiagram/PersonV0.png');
        },
        [0],
        function() {
          m0.parent.removeChild(m0);
          m0 = addImage(v, 'js/foam/demos/modeldiagram/PersonV05.png');
          c1 = addImage(cls, 'js/foam/demos/modeldiagram/PersonJava.png');
        },
        [0],
        [500, function() {
          cls.alpha = 0;
        }],
        function() {
          v.width += 200;
          m1 = addImage(v, 'js/foam/demos/modeldiagram/PersonV1.png');
        },
        [0],
        [500, function() {
          m0.alpha = m1.alpha = 0;
        }],
        [500, function() { v.width /= 4.5; v.height /= 4.5; cls.alpha = 0; } ],
        function() { self.removeChild(cls); },
        [500, function() { robot.scaleX = robot.scaleY = 3; } ],
        [0]
      ];

      var fnum = 0;
      function feature(f, anim, xo, yo, timeWarp) {
        var factory = f.factory;
        var pause   = f.factory || f.pause;

        timeWarp = timeWarp || 1;
        var b = self.Box.create({alpha: 0.7, width: v.width/5+15, height: v.height/5, x: robot.x, y: v.y, text: f.name, font: '14pt Arial'});
        var num = fnum++;
        var x = num % 5;
        var y = Math.floor(num/5);

//        if ( f.pause ) anim.push([[0]]);
        anim.push(function() { self.addChild(b); });
        if ( pause ) {
          if ( f.factory ) anim.push(function() { self.setDisplay(factory); });
          anim.push([300*timeWarp, function() { b.x += 250 + xo; b.y-=80; b.scaleX = b.scaleY = 3; }]);
          anim.push([[0]]);
          if ( factory ) anim.push(function() { self.setDisplay(); });
          anim.push([150*timeWarp, function() { b.scaleX = b.scaleY = 1; b.x += x * b.width*1.4; b.y += yo + b.height*1.2 * y; }]);
        } else {
          anim.push([500*timeWarp, function() { b.x += 250 + xo + x * b.width*1.4; b.y += yo + b.height*1.2 * y - 80; }]);
        }

        return b;
      }

      var p = this.Person.create({
        id: 1,
        firstName: 'John',
        lastName: 'Smith',
        age: 42,
        married: true
      });
      var people = [
        p,
        this.Person.create({id: 2, firstName: 'Janet', lastName: 'Jones', age: 38, married: true}),
        this.Person.create({id: 2, firstName: 'Jimmy', lastName: 'Jones', age: 8, married: false})      ];
      GLOBAL.p = p;

      var fs = [
        { name: 'Class', pause: true, factory: multiline(function() {/*
var p = this.Person.create({
   id: 1,
   firstName: 'John',
   lastName: 'Smith',
   age: 42,
   married: true
});
        */}) },
        { name: '.hashCode()', factory: multiline(function() {/*
> p.hashCode();
< 343020328
> p.firstName = 'Steve';
< "Steve"
> p.hashCode();
< 1609175968
*/}) },
        { name: '.copyFrom()' },
        { name: '.clone()' },
        { name: '.equals()' },
        { name: '.compareTo()' },
        { name: '.diff()' },
        { name: 'Observer' },
        { name: 'XML', factory: multiline(function() {/*
> p.toXML();
< "<foam>
<object model="Person">
  <property name="id">1</property>
  <property name="firstName">John</property>
  <property name="lastName">Smith</property>
  <property name="age">42</property>
  <property name="married">true</property>
</object>
</foam>"
*/}) },
        { name: 'JSON',  factory: multiline(function() {/*
> p.toJSON();"
< "{
   "model_": "foam.demos.modeldiagram.Person",
   "id": 1,
   "firstName": "John",
   "lastName": "Smith",
   "age": 42,
   "married": true
}"*/})  },
        { name: 'ProtoBuf' },
        { name: 'Detail View', factory: function() { return self.DetailView.create({data:p, showActions:true}); } },
        { name: 'MD View', factory: function() { return self.MDDetailView.create({data:p}); } },
        { name: 'Table View', factory: function() { return self.TableView.create({model:self.Person, dao: people}); } },
        { name: 'List View' },
        { name: 'Grid View', factory: function() { return { toHTML: function() { return ''; }, initHTML: function() { }}; } },
        { name: 'Query' },
        { name: 'Local Store' },
        { name: 'IndexedDB' },
        { name: 'ClientDAO' },
        { name: 'Offline' },
        { name: 'Cloud Store' },
        { name: 'Firebase' },
        { name: 'Controller', factory: function() { return { toHTML: function() { return ''; }, initHTML: function() { }}; } },
        { name: '...' }
      ];

      // JS
      fs.forEach(function(f) { feature(f, anim, 0, 0, 0.5); });

      // Java
      anim.push([0]);
      fs.forEach(function(f) { f.factory = false; f.pause = false; });
      fs[0].factory = self.JavaSource.create().generate(self.Person);
      anim.push([300, function() { self.scaleX = self.scaleY = 0.7; }]);
      fnum = 0;
      fs.forEach(function(f) { feature(f, anim, 900, 0, 0.1); });

      anim.push([0]);
      anim.push(function() {
        var cs = self.children;
        for ( var j = cs.length-1 ; j > -1 ; j-- ) {
          var c = cs[j];
          if ( self.Box.isInstance(c) && ( c.x > 1295 || c.y > 765 ) ) self.removeChild(c);
        }
      });
      anim.push([800, function() { robot.scaleX += 0.0001; self.scaleX = self.scaleY = 1.1; }]);

      anim.push([0]);
      anim.push(function() { robot.timer.stop(); robot.timer.i = 45; robot.timer.time = 0; });
      anim.push(function() {
        var cs = self.children.clone();
        for ( var i = 1 ; i < 15 ; i++ ) {
          setTimeout(function(i) {
          for ( var j = 0 ; j < cs.length ; j++ ) {
            var c = cs[j];
            if ( self.Box.isInstance(c) ) {
              if ( c.text === 'Class' || c.text === 'Model' || Math.random() < 0.5 ) {
                c = self.Box.create({text: c.text, font: c.font, x: c.x-7*i, y: c.y+6*i, width: c.width, height: c.height, color: c.color, background: c.background});
                self.addChildren(c);
              }
            }
          }
          }.bind(self, i), i * 50);
        }
      });

      anim.push([0]);
      anim.push(function() { self.removeChild(robot); self.addChildren(robot); });
      anim.push([1000, function() { robot.x = v.x-40; robot.y += 65; }]);
      anim.push([0]);
      anim.push([800, function() { robot.scaleX = robot.scaleY = 25; }]);
      anim.push([0]);
      anim.push([800, function() { robot.scaleX = robot.scaleY = 3; }]);
      anim.push([0]);
      anim.push([400, function() { robot.y -= 600; }, Movement.easeIn(1)]);

      /*
      anim.push([0]);
      anim.push(function() { self.removeChild(v); self.addChildren(v); });
      anim.push([1000, function() { v.scaleX = v.scaleY = 5; }]);
      anim.push([0]);
      anim.push(function() { self.removeChild(v); self.addChildren(v); v.font = '18pt Arial'; v.text = "Class Model"; });
      anim.push([0]);
      anim.push(function() { v.text = "Query Model"; });
      anim.push([0]);
      anim.push(function() { v.text = "Parser Model"; });
      anim.push([0]);
      anim.push(function() { v.font = '14pt Arial'; v.text = "Animation Model"; });
      anim.push([0]);
      anim.push(function() { v.alpha = 0; });
      */

      Movement.compile(anim)();
    },
    setDisplay: function(txt) {
      if ( typeof txt === 'function' ) {
        var v = txt();
        var t = txt.toString();
        t = t.length < 80 ? t.substring(26, t.length-2) : '';
        this.X.$('display').innerHTML = '
' + t + '

' + v.toHTML();
        v.initHTML();
      } else {
        this.X.$('display').innerHTML = txt ? '<textarea style="font-size:24px" rows="13" cols="77">' + txt + '</textarea>' : '';
      }
    }
  }
});
<|endoftext|>


<commit_before>var i = 0;
function setup() {
  createCanvas(1024, 600);
}

function draw() {
  background(255,0,0, 0);
  //ellipse(50, i, 80, 80);
  ellipse(mouseX, mouseY, 60, 60);
  if (mouseIsPressed) {
    i += mouseY / 100;
  }
  if (i > height) i = 0;
}
<commit_msg>Update sketch.js<commit_after>function setup() {
  createCanvas(1024, 600);
}

function draw() {
  background(255,0,0, 50);
  ellipse(mouseX, mouseY, 60, 60);
}
<|endoftext|>