<commit_before>function removeHistoryItem(id) {
    if (confirm('Are you sure?')) {
        $.ajax({
            url: '/sabnzbd/DeleteHistory?id=' + id,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                loadQueue(1);
                loadHistory();
            }
        });
    }
}

function retryHistoryItem(id) {
    if (confirm('Are you sure?')) {
        $.ajax({
            url: '/sabnzbd/Retry?id=' + id,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                loadQueue(1);
                loadHistory();
            }
        });
    }
}

function loadHistory() {
    $.ajax({
        url: '/sabnzbd/GetHistory?limit=10',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if (data.status == false) {
                $('#notification_area').addClass('alert alert-error');
                $('#notification_area').html('Error Could not connect to SABnzbd, go to settings');
                return false;
            }
            $('#history_table_body').html('');
            $.each(data.history.slots, function (i, slot) {
                var deleteImage = makeIcon('icon-remove', 'Delete');
                deleteImage.click(function () {
                    removeHistoryItem(slot.nzo_id);
                });

                var retryImage = null;
                if (slot.status == 'Failed') {
                    var retryImage = makeIcon('icon-repeat', 'Retry');
                    retryImage.click(function () {
                        retryHistoryItem(slot.nzo_id);
                    });
                }

                var failMessage = $('');
                failMessage.addClass('label');
                failMessage.addClass('label-important');
                failMessage.html(slot.fail_message);

                var row = $('
')
                if (slot.status == 'Failed') {
                    row.append($('').html(slot.name).append(' ').append(failMessage));
                } else {
                    row.append($('').html(slot.name));
                }
                row.append($('').html(slot.status));
                row.append($('').html(slot.size));
                row.append($('').append(deleteImage));
                row.append($('').append(retryImage));

                $('#history_table_body').append(row);
            });
        }
    });
}

function removeQueueItem(id) {
    if (confirm('Are you sure?')) {
        $.ajax({
            url: '/sabnzbd/DeleteNzb?id=' + id,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                loadQueue(1);
                loadHistory();
            }
        });
    }
}

function changeCategory(id, cat) {
    $.ajax({
        url: '/sabnzbd/ChangeCategory?id=' + id + '&cat=' + cat,
        type: 'get',
        dataType: 'json'
    });
}

var queueToggleStatusAction = '';

function loadQueue(once) {
    $.ajax({
        url: '/sabnzbd/GetStatus',
        type: 'get',
        dataType: 'json',
        success: function (object) {
            if (object.status == false) {
                $('#notification_area').addClass('alert alert-error');
                $('#notification_area').html('Error Could not connect to SABnzbd, go to settings');
                return false;
            }
            data = object.queue;
            if (once == 1) {
                $('#nzb_get_speed').val(data.speedlimit);
            }

            $('#nzb_pause_button').button('reset');
            if (data.status == 'Paused') {
                $('#nzb_pause_button').html(' Resume');
                queueToggleStatusAction = 'resume';
            } else {
                $('#nzb_pause_button').html(' Pause')
                queueToggleStatusAction = 'pause';
            }

            var state = data.status.toLowerCase();
            var formattedState = state.charAt(0).toUpperCase() + state.slice(1);

            $('#queue_state').html(formattedState);
            $('#queue_speed').html(data.speed + 'B/Sec');

            $('#active_table_body').html('');

            if (data.slots.length == 0) {
                var row = $('
')
                row.append($('').html('Queue is empty').attr('colspan', 5));
                $('#active_table_body').append(row);
            }

            $.each(data.slots, function (i, job) {
                var progressBar = $('
');
                progressBar.addClass('bar');
                progressBar.css('width', job.percentage + '%');

                var  progress = $('
');
                progress.addClass('progress');
                progress.append(progressBar);

                var row = $('
')
                row.append($('').html(job.filename));

                // Juiste categorie weergeven en kunnen aanpassen

                var categories = $('<select>');
                categories.addClass('span2');
                categories.change(function() {
                    changeCategory(job.nzo_id, $(this).val());
                });
                setCategories(categories, job.cat);

                row.append($('').html(categories));

                row.append($('').html(progress));
                row.append($('').html(job.timeleft + ' / ' + job.mbleft + 'MB').addClass('span3'));

                var deleteImage = $('');
                deleteImage.html('×');
                deleteImage.attr('alt', 'Remove');
                deleteImage.addClass('close');
                deleteImage.attr('href', '#');
                deleteImage.click(function () {
                    removeQueueItem(job.nzo_id);
                });

                row.append($('').html(deleteImage));

                $('#active_table_body').append(row);
            });
        }
    });
}

function loadWarnings() {
    $.ajax({
        url: '/sabnzbd/GetWarnings',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if (data.warnings == 0) {
                var row = $('
')
                row.append($('').html('No warnings'));
                $('#warning_table_body').append(row);
            }
            $.each(data.warnings, function (i, warning) {
                var row = $('
')
                row.append($('').html(warning));
                $('#warning_table_body').append(row);
            });
        }
    });
}

// Haal categorieen op
function setCategories(selector, select) {
    $.ajax({
        url: '/sabnzbd/GetCategories',
        type: 'post',
        dataType: 'json',
        success: function (data) {
            $.each(data.categories, function (i, cat) {
                var option = $('<option>');
                if (select == cat) {
                    option.attr('selected', true);
                }
                option.attr('value', cat);
                option.html(cat);
                $(selector).append(option);
            });
        }
    });
}
<commit_msg>Sabnzbd status labels (history)<commit_after>function removeHistoryItem(id) {
    if (confirm('Are you sure?')) {
        $.ajax({
            url: '/sabnzbd/DeleteHistory?id=' + id,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                loadQueue(1);
                loadHistory();
            }
        });
    }
}

function retryHistoryItem(id) {
    if (confirm('Are you sure?')) {
        $.ajax({
            url: '/sabnzbd/Retry?id=' + id,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                loadQueue(1);
                loadHistory();
            }
        });
    }
}

function loadHistory() {
    $.ajax({
        url: '/sabnzbd/GetHistory?limit=10',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if (data.status == false) {
                $('#notification_area').addClass('alert alert-error');
                $('#notification_area').html('Error Could not connect to SABnzbd, go to settings');
                return false;
            }
            $('#history_table_body').html('');
            $.each(data.history.slots, function (i, slot) {
                var deleteImage = makeIcon('icon-remove', 'Delete');
                deleteImage.click(function () {
                    removeHistoryItem(slot.nzo_id);
                });

                var retryImage = null;
                if (slot.status == 'Failed') {
                    var retryImage = makeIcon('icon-repeat', 'Retry');
                    retryImage.click(function () {
                        retryHistoryItem(slot.nzo_id);
                    });
                }

                var failMessage = $('');
                failMessage.addClass('label');
                failMessage.addClass('label-important');
                failMessage.html(slot.fail_message);

                var row = $('
')

                var name = $('').html(slot.name);
                if (slot.category != '*') {
                    name.append(' ').append(sabnzbdStatusLabel(slot.category));
                }
                if (slot.status == 'Failed') {
                    $(name).append(' ').append(failMessage);
                }

                row.append(name);
                row.append($('').append(sabnzbdStatusLabel(slot.status)));
                row.append($('').html(slot.size));
                row.append($('').append(deleteImage));
                row.append($('').append(retryImage));

                $('#history_table_body').append(row);
            });
        }
    });
}

function removeQueueItem(id) {
    if (confirm('Are you sure?')) {
        $.ajax({
            url: '/sabnzbd/DeleteNzb?id=' + id,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                loadQueue(1);
                loadHistory();
            }
        });
    }
}

function changeCategory(id, cat) {
    $.ajax({
        url: '/sabnzbd/ChangeCategory?id=' + id + '&cat=' + cat,
        type: 'get',
        dataType: 'json'
    });
}

var queueToggleStatusAction = '';

function loadQueue(once) {
    $.ajax({
        url: '/sabnzbd/GetStatus',
        type: 'get',
        dataType: 'json',
        success: function (object) {
            if (object.status == false) {
                $('#notification_area').addClass('alert alert-error');
                $('#notification_area').html('Error Could not connect to SABnzbd, go to settings');
                return false;
            }
            data = object.queue;
            if (once == 1) {
                $('#nzb_get_speed').val(data.speedlimit);
            }

            $('#nzb_pause_button').button('reset');
            if (data.status == 'Paused') {
                $('#nzb_pause_button').html(' Resume');
                queueToggleStatusAction = 'resume';
            } else {
                $('#nzb_pause_button').html(' Pause')
                queueToggleStatusAction = 'pause';
            }

            var state = data.status.toLowerCase();
            var formattedState = state.charAt(0).toUpperCase() + state.slice(1);

            $('#queue_state').html(formattedState);
            $('#queue_speed').html(data.speed + 'B/Sec');

            $('#active_table_body').html('');

            if (data.slots.length == 0) {
                var row = $('
')
                row.append($('').html('Queue is empty').attr('colspan', 5));
                $('#active_table_body').append(row);
            }

            $.each(data.slots, function (i, job) {
                var progressBar = $('
');
                progressBar.addClass('bar');
                progressBar.css('width', job.percentage + '%');

                var  progress = $('
');
                progress.addClass('progress');
                progress.append(progressBar);

                var row = $('
')
                row.append($('').html(job.filename));

                // Juiste categorie weergeven en kunnen aanpassen

                var categories = $('<select>');
                categories.addClass('span2');
                categories.change(function() {
                    changeCategory(job.nzo_id, $(this).val());
                });
                setCategories(categories, job.cat);

                row.append($('').html(categories));

                row.append($('').html(progress));
                row.append($('').html(job.timeleft + ' / ' + job.mbleft + 'MB').addClass('span3'));

                var deleteImage = $('');
                deleteImage.html('×');
                deleteImage.attr('alt', 'Remove');
                deleteImage.addClass('close');
                deleteImage.attr('href', '#');
                deleteImage.click(function () {
                    removeQueueItem(job.nzo_id);
                });

                row.append($('').html(deleteImage));

                $('#active_table_body').append(row);
            });
        }
    });
}

function loadWarnings() {
    $.ajax({
        url: '/sabnzbd/GetWarnings',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if (data.warnings == 0) {
                var row = $('
')
                row.append($('').html('No warnings'));
                $('#warning_table_body').append(row);
            }
            $.each(data.warnings, function (i, warning) {
                var row = $('
')
                row.append($('').html(warning));
                $('#warning_table_body').append(row);
            });
        }
    });
}

// Haal categorieen op
function setCategories(selector, select) {
    $.ajax({
        url: '/sabnzbd/GetCategories',
        type: 'post',
        dataType: 'json',
        success: function (data) {
            $.each(data.categories, function (i, cat) {
                var option = $('<option>');
                if (select == cat) {
                    option.attr('selected', true);
                }
                option.attr('value', cat);
                option.html(cat);
                $(selector).append(option);
            });
        }
    });
}

function sabnzbdStatusLabel(text){
  var statusOK = ['Completed'];
  var statusInfo = [];
  var statusError = ['Failed'];
  var statusWarning = [];

  var label = $('').addClass('label').text(text);

  if (statusOK.indexOf(text) != -1) {
    label.addClass('label-success');
  }
  else if (statusInfo.indexOf(text) != -1) {
    label.addClass('label-info');
  }
  else if (statusError.indexOf(text) != -1) {
    label.addClass('label-important');
  }
  else if (statusWarning.indexOf(text) != -1) {
    label.addClass('label-warning');
  }

  var icon = sabnzbdStatusIcon(text, true);
  if (icon != '') {
    label.prepend(' ').prepend(icon);
  }
  return label;
}

function sabnzbdStatusIcon(iconText, white){
  var text =[
    'Completed'
  ];
  var icons = [
    'icon-ok'
  ];

  if (text.indexOf(iconText) != -1) {
    var icon = $('').addClass(icons[text.indexOf(iconText)]);
    if (white == true) {
      icon.addClass('icon-white');
    }
    return icon;
  }
  return '';
}<|endoftext|>


<commit_before>'use strict';

const highlight = require('highlight.js');
const config = require('config');
const marked = require('marked');
const http = require('http');
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const orderObject = require('./util').orderObject;

/**
 * Reads a json file, if there is a problem reading
 * the file it returns null.
 * @param  {String} filePath
 * @return {Object}
 */
function readJSONFile (filePath) {
    try {
        return JSON.parse(fs.readFileSync(filePath));
    } catch (e) {
        return null;
    }
}

/**
 * Wraps a require so that if there is a problem reading
 * the file it returns null.
 * @param {String} filePath
 * @return {Object}
 */
function wrappedRequire (filePath) {
    try {
        return require(filePath);
    } catch (e) {
        return null;
    }
}

/**
 * Returns the array of permissions to be shown on the OAuth section of the docs.
 * @return {Object[]}
 */
function getPermissions () {
    try {
        return require('@mcph/beam-common').permissions;
    } catch (err) {
        if (err.code === 'MODULE_NOT_FOUND') {
            return [];
        }
        throw err;
    }
}

/**
 * Generates locals required for templating.
 * `permissions` is used for the REST API docs, they are displayed in a table.
 * @return {Object}
 */
function getLocals () {
    const restDoc = readJSONFile(path.join(__dirname, '/tmp/raml-doc.json'));
    marked.setOptions({
        highlight (code) {
            return require('highlight.js').highlightAuto(code).value;
        },
    });

    const permissions = getPermissions();
    const permissionKeys = Object.keys(permissions).sort();
    const out = {
        _,
        orderObject,
        // eslint-disable-next-line no-console
        log: console.log,
        marked,
        libraries: require('./tmp/libraries'), // eslint-disable-line import/no-unresolved
        liveEvents: require('../src/reference/constellation/events'),
        chat: require('../src/reference/chat/data'),
        cClients: {
            cpp: require('../src/reference/interactive/cplusplus/data.json').api,
            csharp: require('../src/reference/interactive/csharp/data.json').api,
        },
        rest: restDoc,
        beConfig: wrappedRequire('./tmp/backend/config/default.js'),
        permissions,
        permissionKeys,
        bsTabs: {},
        highlight: (lang, str) => {
            if (lang === 'text') return str;
            return highlight.highlight(lang, str).value
                .replace('AUTH_TOKEN', 'Click here to get your Token!');
        },
        readFile: (file) => fs.readFileSync(path.join(__dirname, '../src', file)),

        restUtil: {
            /**
             * Finds and extracts a trait definition from the `is` property of a method.
             * @param  {Object} method
             * @param  {String} type
             * @return {Object?}
             */
            getTraitInfo (method, type) {
                const temp = _.find(method.is, value => value[type]);
                return temp && temp[type];
            },
            /**
            * Get the root type of a type.
            * This is one of the types:
            * Object: 'Object'
            * Scalars: 'string', 'number', 'integer', 'boolean', 'date', 'file', 'scalar'
            */
            getRootType (type) {
                if (type.type.length > 1) {
                    // Multiple inheritence is only supported for object types.
                    return 'object';
                }

                const parent = type.type[0];
                if (restDoc.types && restDoc.types[parent]) {
                    return this.getRootType(restDoc.types[parent]);
                }

                return type.type[0];
            },
            /**
             * Checks if the type is a raml primitive.
             * @param  {String}  type
             * @return {Boolean}
             */
            isChildType (type) {
                const buildinTypes = [
                    'string',
                    'number',
                    'integer',
                    'boolean',
                    'date',
                    'file',
                    'scalar',
                ];
                return _.includes(buildinTypes, type);
            },
            isBaseType (type) {
                return type === 'object' || type === 'type' || this.isChildType(type);
            },
            securitySchemeWithName (name) {
                if (name && name.oauth_2_0) {
                    // oauth_2_0 is a special snowflake if it has scopes :>
                    name = 'oauth_2_0';
                }
                return _.find(restDoc.securitySchemes, scheme => scheme[name])[name];
            },
            isSecurityOAuth (security) {
                return !!security.oauth_2_0;
            },
            hasOAuthScopes (security) {
                return security.oauth_2_0.scopes.filter(scope => scope.length).length > 0;
            },
            getOAuthScopes (security) {
                return security.oauth_2_0.scopes;
            },
            /**
             * Attempts to look up an HTTP status message corresponding
             * to the provided numeric code.
             * @param  {Number} code
             * @return {String}
             */
            getStatusMessage (code) {
                return http.STATUS_CODES[code];
            },
            /**
             * Special handling for property names that have non alphanumeric names
             * such as regex wildcards and `//`.
             * @param  {String} name
             * @return {String}
             */
            prettifyPropertyName (name) {
                if (name === '//') {
                    return 'All keys';
                }
                if (name.startsWith('/') && name.endsWith('/')) {
                    return `Keys matching the RegEx ${name}`;
                }
                return name;
            },
        },
    };

    return out;
}

/**
 * Returns an object of options for Pug compilation.
 * @return {Object}
 */
function getPugOpts () {
    return {
        locals: getLocals(),
        pretty: !config.minify,
    };
}

/**
 * Registers a task that compiles
 * @param  {Gulp} gulp
 * @param  {Object} $ plugin loader
 * @return {Stream}
 */
module.exports = (gulp, $) => {
    gulp.task('html', ['html-raml']);

    gulp.task('html-raml', ['backend-doc', 'pull-client-repos'], () => {
        return gulp.src(config.src.html)
        .pipe($.pug(getPugOpts()))
        .pipe($.if(config.minify, $.minifyHtml()))
        .pipe(gulp.dest(config.dist.html));
    });

    gulp.task('html-quick', () => {
        return gulp.src(config.src.html)
        .pipe($.pug(getPugOpts()))
        .pipe($.if(config.minify, $.minifyHtml()))
        .pipe(gulp.dest(config.dist.html));
    });

    gulp.task('images', () => {
        return gulp.src(config.src.images)
        .pipe($.if(config.minify,
            $.if('*.{jpg,svg,png,gif}', $.imagemin())))
        .pipe(gulp.dest(config.dist.images));
    });

    gulp.task('js', () => {
        return gulp.src(config.src.js)
        .pipe($.concat('developers.js'))
        .pipe($.if(config.minify, $.uglify()).on('error', err => {
            if (err instanceof $.uglify.GulpUglifyError) {
                const { cause } = err;
                cause.message = `${cause.filename}:${cause.line}:${cause.col} ${cause.message}`;
                throw cause;
            }
            throw err;
        }))
        .pipe(gulp.dest(config.dist.js));
    });

    gulp.task('lint-json', () => {
        const files = [
            'src/reference/chat/data.json',
            'src/reference/interactive/cplusplus/data.json',
            'src/reference/interactive/csharp/data.json',
        ];

        files.forEach(file => {
            const contents = JSON.parse(fs.readFileSync(file, 'utf8'));
            const transformed = JSON.stringify(contents, null, '  ');
            if (contents === transformed) {
                return;
            }
            fs.writeFileSync(file, `${transformed}\n`);
        });
    });
};
<commit_msg>chore(build): warn when common is missing (#182)<commit_after>'use strict';

const highlight = require('highlight.js');
const config = require('config');
const marked = require('marked');
const http = require('http');
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const orderObject = require('./util').orderObject;

/**
 * Reads a json file, if there is a problem reading
 * the file it returns null.
 * @param  {String} filePath
 * @return {Object}
 */
function readJSONFile (filePath) {
    try {
        return JSON.parse(fs.readFileSync(filePath));
    } catch (e) {
        return null;
    }
}

/**
 * Wraps a require so that if there is a problem reading
 * the file it returns null.
 * @param {String} filePath
 * @return {Object}
 */
function wrappedRequire (filePath) {
    try {
        return require(filePath);
    } catch (e) {
        return null;
    }
}

/**
 * Returns the array of permissions to be shown on the OAuth section of the docs.
 * @return {Object[]}
 */
function getPermissions () {
    try {
        return require('@mcph/beam-common').permissions;
    } catch (err) {
        if (err.code === 'MODULE_NOT_FOUND') {
            // eslint-disable-next-line no-console
            console.warn('Cannot find common module. OAuth scope table will be omitted.');
            return [];
        }
        throw err;
    }
}

/**
 * Generates locals required for templating.
 * `permissions` is used for the REST API docs, they are displayed in a table.
 * @return {Object}
 */
function getLocals () {
    const restDoc = readJSONFile(path.join(__dirname, '/tmp/raml-doc.json'));
    marked.setOptions({
        highlight (code) {
            return require('highlight.js').highlightAuto(code).value;
        },
    });

    const permissions = getPermissions();
    const permissionKeys = Object.keys(permissions).sort();
    const out = {
        _,
        orderObject,
        // eslint-disable-next-line no-console
        log: console.log,
        marked,
        libraries: require('./tmp/libraries'), // eslint-disable-line import/no-unresolved
        liveEvents: require('../src/reference/constellation/events'),
        chat: require('../src/reference/chat/data'),
        cClients: {
            cpp: require('../src/reference/interactive/cplusplus/data.json').api,
            csharp: require('../src/reference/interactive/csharp/data.json').api,
        },
        rest: restDoc,
        beConfig: wrappedRequire('./tmp/backend/config/default.js'),
        permissions,
        permissionKeys,
        bsTabs: {},
        highlight: (lang, str) => {
            if (lang === 'text') return str;
            return highlight.highlight(lang, str).value
                .replace('AUTH_TOKEN', 'Click here to get your Token!');
        },
        readFile: (file) => fs.readFileSync(path.join(__dirname, '../src', file)),

        restUtil: {
            /**
             * Finds and extracts a trait definition from the `is` property of a method.
             * @param  {Object} method
             * @param  {String} type
             * @return {Object?}
             */
            getTraitInfo (method, type) {
                const temp = _.find(method.is, value => value[type]);
                return temp && temp[type];
            },
            /**
            * Get the root type of a type.
            * This is one of the types:
            * Object: 'Object'
            * Scalars: 'string', 'number', 'integer', 'boolean', 'date', 'file', 'scalar'
            */
            getRootType (type) {
                if (type.type.length > 1) {
                    // Multiple inheritence is only supported for object types.
                    return 'object';
                }

                const parent = type.type[0];
                if (restDoc.types && restDoc.types[parent]) {
                    return this.getRootType(restDoc.types[parent]);
                }

                return type.type[0];
            },
            /**
             * Checks if the type is a raml primitive.
             * @param  {String}  type
             * @return {Boolean}
             */
            isChildType (type) {
                const buildinTypes = [
                    'string',
                    'number',
                    'integer',
                    'boolean',
                    'date',
                    'file',
                    'scalar',
                ];
                return _.includes(buildinTypes, type);
            },
            isBaseType (type) {
                return type === 'object' || type === 'type' || this.isChildType(type);
            },
            securitySchemeWithName (name) {
                if (name && name.oauth_2_0) {
                    // oauth_2_0 is a special snowflake if it has scopes :>
                    name = 'oauth_2_0';
                }
                return _.find(restDoc.securitySchemes, scheme => scheme[name])[name];
            },
            isSecurityOAuth (security) {
                return !!security.oauth_2_0;
            },
            hasOAuthScopes (security) {
                return security.oauth_2_0.scopes.filter(scope => scope.length).length > 0;
            },
            getOAuthScopes (security) {
                return security.oauth_2_0.scopes;
            },
            /**
             * Attempts to look up an HTTP status message corresponding
             * to the provided numeric code.
             * @param  {Number} code
             * @return {String}
             */
            getStatusMessage (code) {
                return http.STATUS_CODES[code];
            },
            /**
             * Special handling for property names that have non alphanumeric names
             * such as regex wildcards and `//`.
             * @param  {String} name
             * @return {String}
             */
            prettifyPropertyName (name) {
                if (name === '//') {
                    return 'All keys';
                }
                if (name.startsWith('/') && name.endsWith('/')) {
                    return `Keys matching the RegEx ${name}`;
                }
                return name;
            },
        },
    };

    return out;
}

/**
 * Returns an object of options for Pug compilation.
 * @return {Object}
 */
function getPugOpts () {
    return {
        locals: getLocals(),
        pretty: !config.minify,
    };
}

/**
 * Registers a task that compiles
 * @param  {Gulp} gulp
 * @param  {Object} $ plugin loader
 * @return {Stream}
 */
module.exports = (gulp, $) => {
    gulp.task('html', ['html-raml']);

    gulp.task('html-raml', ['backend-doc', 'pull-client-repos'], () => {
        return gulp.src(config.src.html)
        .pipe($.pug(getPugOpts()))
        .pipe($.if(config.minify, $.minifyHtml()))
        .pipe(gulp.dest(config.dist.html));
    });

    gulp.task('html-quick', () => {
        return gulp.src(config.src.html)
        .pipe($.pug(getPugOpts()))
        .pipe($.if(config.minify, $.minifyHtml()))
        .pipe(gulp.dest(config.dist.html));
    });

    gulp.task('images', () => {
        return gulp.src(config.src.images)
        .pipe($.if(config.minify,
            $.if('*.{jpg,svg,png,gif}', $.imagemin())))
        .pipe(gulp.dest(config.dist.images));
    });

    gulp.task('js', () => {
        return gulp.src(config.src.js)
        .pipe($.concat('developers.js'))
        .pipe($.if(config.minify, $.uglify()).on('error', err => {
            if (err instanceof $.uglify.GulpUglifyError) {
                const { cause } = err;
                cause.message = `${cause.filename}:${cause.line}:${cause.col} ${cause.message}`;
                throw cause;
            }
            throw err;
        }))
        .pipe(gulp.dest(config.dist.js));
    });

    gulp.task('lint-json', () => {
        const files = [
            'src/reference/chat/data.json',
            'src/reference/interactive/cplusplus/data.json',
            'src/reference/interactive/csharp/data.json',
        ];

        files.forEach(file => {
            const contents = JSON.parse(fs.readFileSync(file, 'utf8'));
            const transformed = JSON.stringify(contents, null, '  ');
            if (contents === transformed) {
                return;
            }
            fs.writeFileSync(file, `${transformed}\n`);
        });
    });
};
<|endoftext|>


<commit_before>Runner.Game = function (game){
    this.mapGroup = null;
    this.map = null;
    Runner.distance = 0;
    this.character = null;
    this.obstacle = null;
    Runner.score = 0;

}

Runner.Game.prototype = {
    create: function (){
        this.spaceKey = this.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        this.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR ]);
        this.physics.startSystem(Phaser.Physics.ARCADE);
        this.physics.arcade.gravity.y = 10;
        this.add.image(this.world.centerX - (this.world.width/2) , this.world.centerY - (this.world.height/2), 'background')
        this.mapGroup = this.add.group()
        this.map = this.add.tileSprite(this.world.centerX, this.world.height, 736, 111, 'map');
        this.map.anchor.setTo(0.5,0.25)
        this.obstacle = this.add.sprite(this.world.width +30, this.world.height+150, 'obstacle')
        this.map.autoScroll(-200,0)
        this.physics.enable(this.map, Phaser.Physics.ARCADE)

        this.map.body.allowGravity = false
//        this.map.body.setCollision(80);

//        this.map.enableBody = true;
        this.map.body.checkCollision.up = true;
//	      this.map.body.checkCollision.up = true;

//        this.mapGroup.add(this.obstacle)
//        this.mapGroup.add(this.map);
//        this.mapGroup.physicsBodyType = Phaser.Physics.ARCADE;
//        this.mapGroup.enableBody = true;
//        this.mapGroup.anchor.setTo(0,1);
//        this.mapGroup.body.checkCollision.up = true;

        this.character = this.add.sprite(10, this.world.height, 'character','gb_0000s_0000_Layer-11.png');
        this.character.animations.add('run',[0,1,2,3,4,5], 10, true);
//        this.character.animations.add('jump',[2,3,4,5,6], false);
        this.character.animations.play('run')
        this.physics.enable(this.character, Phaser.Physics.ARCADE);
        this.character.allowGravity = true;
        this.character.body.collideWorldBounds = true;
        this.character.body.gravity.y = 10;

//        this.character.body.velocity.x = 50;

//        this.game.physics.arcade.collide(this.character, this.map, this.handleCollison, null, this);
//         console.log(this.obstacle.velocity)

         this.physics.enable(this.obstacle, Phaser.Physics.ARCADE)
        this.obstacle.body.allowGravity = false
        this.obstacle.body.collideWorldBounds = true;
//        this.obstacle.body.offset.y = -30;

    },
    update: function () {
        Runner.score += 1
        console.log(Runner.score);
        this.obstacle.body.velocity.x = -100;

        this.physics.arcade.collide(this.character, this.obstacle, this.handleCollison, null, this);
        this.map.body.checkCollision.up = true;

        this.physics.arcade.collide(this.character, this.obstacle);

        if (this.spaceKey.isDown){
            this.jump();
        }
    },

    jump: function (){
        if (this.character.body.onFloor())
        {
            this.character.body.gravity.y = 10*3.5;
            this.character.body.velocity.y = -this.obstacle.height *1.5;
            this.character.body.velocity.x *= -2
        }
        this.character.animations.play('run')
    },

    handleCollison: function(){
        // game over
//        this.state.start("GameOver")
    }

};<commit_msg>jump feature, respawn obstacle<commit_after>Runner.Game = function (game){
    this.mapGroup = null;
    this.map = null;
    Runner.distance = 0;
    this.character = null;
    this.obstacle = null;
    this.scoreboard = null
    Runner.score = 0;

}

Runner.Game.prototype = {
    create: function (){
        this.spaceKey = this.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        this.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR ]);

        // physics system
        this.physics.startSystem(Phaser.Physics.ARCADE);
        this.physics.arcade.gravity.y = 10;
        this.add.image(this.world.centerX - (this.world.width/2) , this.world.centerY - (this.world.height/2), 'background')

        // map
        this.map = this.add.tileSprite(this.world.centerX, this.world.height, 736, 111, 'map');
        this.map.anchor.setTo(0.5,0.25)
        this.map.autoScroll(-200,0)
        this.physics.enable(this.map, Phaser.Physics.ARCADE)
        this.map.body.allowGravity = false;

        // scoreboard
        this.scoreboard = this.add.image(this.world.width - 182, 20, 'score');
        this.scoreboard.anchor.setTo(0, 0)
        this.scoreboard.scale.setTo(0.5, 0.5);
        this.scoreboard.text = this.add.text(this.scoreboard.position.x+ 20, this.scoreboard.position.y + 20, 'score: 0', { font: "15px Arial", fill: "#ffffff", align: "left" });

        // character
        this.character = this.add.sprite(10, this.world.height, 'character','gb_0000s_0000_Layer-11.png');
        this.character.animations.add('run',[0,1,2,3,4,5], 10, true);
        this.character.animations.play('run', 10, true)
        this.physics.enable(this.character, Phaser.Physics.ARCADE);
        this.character.allowGravity = true;
        this.character.body.collideWorldBounds = true;
        this.character.body.gravity.y = 10;

        // obstacle
        this.obstacle = this.add.sprite(this.world.width +30, this.world.height+150, 'obstacle')
        this.physics.enable(this.obstacle, Phaser.Physics.ARCADE)
        this.obstacle.body.allowGravity = false
        this.obstacle.body.collideWorldBounds = true;

    },
    update: function () {
        Runner.score += 0.5
        this.scoreboard.text.text = 'score: '+ Runner.score
        this.obstacle.body.velocity.x = -100;
        this.physics.arcade.collide(this.character, this.obstacle, this.handleCollison, null, this);
        this.map.body.checkCollision.up = true;

        if (this.spaceKey.isDown){
            this.character.body.jump = true;
            this.jump();
        }

        if(this.obstacle.x == this.world.x){
            this.obstacle.body.x -=1;
            if(this.obstacle.body.x < this.world.x){
                this.obstacle.body.x = this.world.width;
//                console.log(this.obstacle.body.velocity.x)
//                this.obstacle.body.velocity.x = -200:
            }
        }
    },

    jump: function (){
        if (this.character.body.onFloor())
        {
            this.character.body.gravity.y = 190;
            this.character.body.velocity.y = -160;
        }
    },

    handleCollison: function(){
        this.state.shutdown()

    }

};<|endoftext|>


<commit_before>function hide_empty_menu() {
    var menu_element_count = $(".dropdown-menu-button ul li").length;

    if (menu_element_count == 0) {
        $(".dropdown-menu-button").hide();
    }

    console.log(menu_element_count);
}
<commit_msg>Update rdrf.js<commit_after>function hide_empty_menu() {
    var menu_element_count = $(".dropdown-menu-button ul li").length;

    if (menu_element_count == 0) {
        $(".dropdown-menu-button").hide();
    }
}
<|endoftext|>


<commit_before>angular.module('ngSockethubClient', []).

/**
 * settings service
 */
value('settings', {
  sockethub: function () {
    // figure out sockethub connect settings
    var settings = {
      host: 'localhost',
      port: '10550',
      path: '/sockethub',
      tls: false,
      secret: '1234567890'
    };

    return settings;
  },
  save: function (scope, factory) {
    scope.config = factory.config.data;
    scope.model = {};
    scope.model.submitMsg = '';
    scope.save = function () {
      scope.saving = true;
      factory.config.set().then(function () {
        scope.model.submitMsg = 'config saved!';
        scope.saving = false;
      }, function (err) {
        scope.model.submitMsg = err;
      });
    };
  }
}).

/**
 * connect to sockethub on startup
 */
run(['settings', 'SH', '$rootScope',
function (settings, SH, $rootScope) {
  var s = settings.sockethub();
  // connect to sockethub and register
  SH.setConfig(s.host, s.port,
               s.path, s.tls,
               s.secret).then(function () {
    return SH.connect();
  }).then(function () {
    return SH.register();
  }).then(function () {
    console.log('connected to sockethub');
  }, function (err) {
    console.log('error connection to sockethub: ', err);
    $rootScope.$broadcast('SockethubConnectFailed', {message: err});
  });
}]).

/**
 * factory: SH
 */
factory('SH', ['$rootScope', '$q',
function ($rootScope, $q) {

  var sc;
  var callbacks = {
    'error': {},
    'message': {},
    'response': {},
    'close': {}
  };

  var config = {
    host: '',
    port: '',
    path: '/sockethub',
    tls: false,
    secret: ''
  };

  function existsConfig() {
    if ((!config.host) && (config.host !== '') &&
        (!config.port) && (config.port !== '') &&
        (!config.path) && (config.path !== '') &&
        (!config.tls) && (config.tls !== '') &&
        (!config.secret) && (config.secret !== '')) {
      return true;
    } else {
      return false;
    }
  }

  function setConfig(host, port, path, tls, secret) {
    var defer = $q.defer();

    console.log('SH.setConfig: '+host+', '+port+', '+path+', TLS:'+tls+', SECRET:'+secret);
    config.host = host;
    config.port = port;
    config.path = path;
    config.tls = tls;
    config.secret = secret;

    defer.resolve();
    return defer.promise;
  }

  function isConnected() {
    if (sc) {
      return sc.isConnected();
    } else {
      return false;
    }
  }

  function isRegistered() {
    if (sc) {
      return sc.isRegistered();
    } else {
      return false;
    }
  }

  function register() {
    var defer = $q.defer();
    if (!isConnected()) { defer.reject('not connected to sockethub'); return defer.promise; }
    sc.register({
      secret: config.secret
    }).then(function () {
      //console.log('ngSockethubClient.register: registration success ['+sc.isConnected()+']');
      $rootScope.$apply(defer.resolve);
    }, function (err) { // sockethub registration fail
      console.log('ngSockethubClient.register: registration failed: ', err);
      $rootScope.$apply(function () {
        defer.reject(err.message);
      });
    });
    return defer.promise;
  }

  function connect() {
    var defer = $q.defer();
    var scheme = 'ws://';
    if (config.tls) {
      scheme = 'wss://';
    }
    SockethubClient.connect({
      host: scheme + config.host + ':' + config.port + config.path,
      confirmationTimeout: 3000   // timeout in miliseconds to wait for confirm
    }).then(function (connection) {
      sc = connection;
      sc.on('message', function (data) {
        //console.log('SH received message');
        if ((data.platform) &&
            (callbacks['message'][data.platform])) {
          console.log('SH passing message to platform: '+data.platform);
          $rootScope.$apply(callbacks['message'][data.platform](data));
        }
      });
      sc.on('error', function (data) {
        console.log('SH received error: ', data);
        if ((data.platform) &&
            (callbacks['error'][data.platform])) {
          console.log('SH passing error to platform: '+data.platform);
          $rootScope.$apply(callbacks['error'][data.platform](data));
        }
      });
      sc.on('response', function (data) {
        console.log('SH received response: ', data);
        if ((data.platform) &&
            (callbacks['response'][data.platform])) {
          console.log('SH passing response to platform: '+data.platform);
          $rootScope.$apply(callbacks['response'][data.platform](data));
        }
      });
      sc.on('close', function (data) {
        console.log('SH received close: ', data);
        if ((data) && (data.platform) &&
            (callbacks[close][data.platform])) {
          console.log('SH passing close to platform: '+data.platform);
          $rootScope.$apply(callbacks['close'][data.platform](data));
        }
      });
      $rootScope.$apply(function () {
        defer.resolve();
      });
    }, function (err) { // sockethub connection failed
      $rootScope.$apply(function () {
        defer.reject(err);
      });
    });
    return defer.promise;
  }

  function sendSet(platform, type, index, object) {
    var defer = $q.defer();
    if (!isConnected()) { defer.reject('not connected to sockethub'); return defer.promise; }
    var data = {};
    data[type] = {};
    data[type][index] = object;
    sc.set(platform, data).then(function () {
      $rootScope.$apply(function () {
        defer.resolve();
      });
    }, function () {
      $rootScope.$apply(function () {
        defer.reject();
      });
    });

    return defer.promise;
  }

  function sendSubmit(obj, timeout) {
    var defer = $q.defer();
    if (!isConnected()) { defer.reject('not connected to sockethub'); return defer.promise; }

    sc.submit(obj, timeout).then(function () {
      $rootScope.$apply(function () {
        defer.resolve();
      });

    }, function (resp) {
      console.log('ngSockethubClient submit rejection response: ', resp);
      $rootScope.$apply(function () {
        defer.reject(resp.message);
      });
    });

    return defer.promise;
  }

  var on = function on(platform, type, func) {
    callbacks[type][platform] = func;
  };

  return {
    config: config,
    existsConfig: existsConfig,
    setConfig: setConfig,
    connect: connect,
    register: register,
    isConnected: isConnected,
    isRegistered: isRegistered,
    set: sendSet,
    submit: sendSubmit,
    on: on
  };
}]);<commit_msg>ensure proper order of calls to sockethub, and queue up calls instead of fail them immediately<commit_after>angular.module('ngSockethubClient', []).

/**
 * settings service
 */
value('settings', {
  sockethub: function () {
    // figure out sockethub connect settings
    var settings = {
      host: 'localhost',
      port: '10550',
      path: '/sockethub',
      tls: false,
      secret: '1234567890'
    };

    return settings;
  },
  save: function (scope, factory) {
    scope.config = factory.config.data;
    scope.model = {};
    scope.model.submitMsg = '';
    scope.save = function () {
      scope.saving = true;
      factory.config.set().then(function () {
        scope.model.submitMsg = 'config saved!';
        scope.saving = false;
      }, function (err) {
        scope.model.submitMsg = err;
      });
    };
  }
}).

/**
 * connect to sockethub on startup
 */
run(['settings', 'SH', '$rootScope',
function (settings, SH, $rootScope) {
  var s = settings.sockethub();
  // connect to sockethub and register
  SH.setConfig(s.host, s.port,
               s.path, s.tls,
               s.secret).then(function () {
    return SH.connect();
  }).then(function () {
    return SH.register();
  }).then(function () {
    console.log('connected to sockethub');
  }, function (err) {
    console.log('error connection to sockethub: ', err);
    $rootScope.$broadcast('SockethubConnectFailed', {message: err});
  });
}]).

/**
 * factory: SH
 */
factory('SH', ['$rootScope', '$q', '$timeout',
function ($rootScope, $q, $timeout) {

  var sc;
  var callbacks = {
    'error': {},
    'message': {},
    'response': {},
    'close': {}
  };

  var config = {
    host: '',
    port: '',
    path: '/sockethub',
    tls: false,
    secret: ''
  };

  function existsConfig() {
    if ((!config.host) && (config.host !== '') &&
        (!config.port) && (config.port !== '') &&
        (!config.path) && (config.path !== '') &&
        (!config.tls) && (config.tls !== '') &&
        (!config.secret) && (config.secret !== '')) {
      return true;
    } else {
      return false;
    }
  }

  function setConfig(host, port, path, tls, secret) {
    var defer = $q.defer();

    console.log('SH.setConfig: '+host+', '+port+', '+path+', TLS:'+tls+', SECRET:'+secret);
    config.host = host;
    config.port = port;
    config.path = path;
    config.tls = tls;
    config.secret = secret;

    defer.resolve();
    return defer.promise;
  }

  function isConnected() {
    if (sc) {
      return sc.isConnected();
    } else {
      return false;
    }
  }

  function isRegistered() {
    if (sc) {
      return sc.isRegistered();
    } else {
      return false;
    }
  }

  function callOnReady(p) {
    var defer = $q.defer();
    (function __call() {
      if (p.testFunc()) {
        console.log('SH: calling: '+p.callFunc);
        sc[p.callFunc].apply(sc, p.callParams)
          .then(function (e) {
            $rootScope.$apply(defer.resolve(e));
          }, function (e) {
            $rootScope.$apply(defer.reject(e));
          });
      } else {
        console.log('SH: delaying call 1s');
        $timeout(__call, 1000);
      }
    })();
    return defer.promise;
  }

  function connect() {
    var defer = $q.defer();
    var scheme = 'ws://';
    if (config.tls) {
      scheme = 'wss://';
    }
    SockethubClient.connect({
      host: scheme + config.host + ':' + config.port + config.path,
      confirmationTimeout: 3000   // timeout in miliseconds to wait for confirm
    }).then(function (connection) {
      sc = connection;
      console.log('CONNECTED [connected: '+sc.isConnected()+'] [registered: '+sc.isRegistered()+']');
      sc.on('message', function (data) {
        //console.log('SH received message');
        if ((data.platform) &&
            (callbacks['message'][data.platform])) {
          console.log('SH passing message to platform: '+data.platform);
          $rootScope.$apply(callbacks['message'][data.platform](data));
        }
      });
      sc.on('error', function (data) {
        console.log('SH received error: ', data);
        if ((data.platform) &&
            (callbacks['error'][data.platform])) {
          console.log('SH passing error to platform: '+data.platform);
          $rootScope.$apply(callbacks['error'][data.platform](data));
        }
      });
      sc.on('response', function (data) {
        console.log('SH received response: ', data);
        if ((data.platform) &&
            (callbacks['response'][data.platform])) {
          console.log('SH passing response to platform: '+data.platform);
          $rootScope.$apply(callbacks['response'][data.platform](data));
        }
      });
      sc.on('close', function (data) {
        console.log('SH received close: ', data);
        if ((data) && (data.platform) &&
            (callbacks[close][data.platform])) {
          console.log('SH passing close to platform: '+data.platform);
          $rootScope.$apply(callbacks['close'][data.platform](data));
        }
      });
      $rootScope.$apply(function () {
        defer.resolve();
      });
    }, function (err) { // sockethub connection failed
      $rootScope.$apply(function () {
        defer.reject(err);
      });
    });
    return defer.promise;
  }

  function register() {
    var defer = $q.defer();
    console.log('SH.register() called');
    callOnReady({
      testFunc: isConnected,
      callFunc: 'register',
      callParams: [{
        secret: config.secret
      }]
    }).then(defer.resolve, defer.reject);
    return defer.promise;
  }

  function sendSet(platform, type, index, object) {
    var defer = $q.defer();
    var data = {};
    data[type] = {};
    data[type][index] = object;

    callOnReady({
      testFunc: isRegistered,
      callFunc: 'set',
      callParams: [platform, data]
    }).then(defer.resolve, defer.reject);

    return defer.promise;
  }

  function sendSubmit(obj, timeout) {
    var defer = $q.defer();

    callOnReady({
      testFunc: isRegistered,
      callFunc: 'submit',
      callParams: [obj, timeout]
    }).then(defer.resolve, defer.reject);

    return defer.promise;
  }

  var on = function on(platform, type, func) {
    callbacks[type][platform] = func;
  };

  return {
    config: config,
    existsConfig: existsConfig,
    setConfig: setConfig,
    connect: connect,
    register: register,
    isConnected: isConnected,
    isRegistered: isRegistered,
    set: sendSet,
    submit: sendSubmit,
    on: on
  };
}]);<|endoftext|>


<commit_before>/** nineleap.enchant.js v0.2.7 (2011/09/13)
 *
 * enchant.js extention for 9leap.net
 * @requires enchant.js v0.4.0 or later
 */

(function () {

enchant.nineleap = { assets: ['start.png', 'end.png'] };

/**
 * @scope enchant.nineleap.Game.prototype
 */
enchant.nineleap.Game = enchant.Class.create(enchant.Game, {

    initialize: function(width, height) {
        enchant.Game.call(this, width, height);
        this.addEventListener('load', function() {
            var game = this;
            this.startScene = new SplashScene();
            this.startScene.image = this.assets['start.png'];
            this.startScene.addEventListener('touchend', function() {
                if (game.started == false) {
                    if (game.onstart != null) game.onstart();
                    game.started = true;
                    gameStart = true;   // deprecated
                }
                if (game.currentScene == this) game.popScene();
                this.removeEventListener('touchend', arguments.callee);
            });
            this.addEventListener('keydown', function() {
                if (this.started == false) {
                    if(this.onstart != null) this.onstart();
                    this.started = true;
                    gameStart = true;   // deprecated
                }
                if (game.currentScene == game.startScene) game.popScene();
                this.removeEventListener('keydown', arguments.callee);
            });
            this.pushScene(this.startScene);

            this.endScene = new SplashScene();
            this.endScene.image = this.assets['end.png'];
        });
        this.scoreQueue = false;
        gameStart = false; // deprecated
        this.started = false;
    },

    loadImage: function(src, callback) {
        if (callback == null) callback = function() {};
        this.assets[src] = enchant.Surface.load(src);
        this.assets[src].addEventListener('load', callback);
    },

    start: function() {
        var game = this;

        if (this._intervalID) {
            window.clearInterval(this._intervalID);
        } else if (this._assets.length) {
            var o = {};
            var assets = this._assets.filter(function(asset) {
                return asset in o ? false : o[asset] = true;
            });
            var tAssets = (this._twitterAssets != undefined)? this._twitterAssets : [];
            var nAssets = (this._netpriceData != undefined)? this._netpriceData : [];
            var mAssets = (this._memoryAssets != undefined) ? this._memoryAssets : [];
            var loaded = 0;
            var total = assets.length + tAssets.length + nAssets.length + mAssets.length;
            for (var i = 0, len = assets.length; i < len; i++) {
                this.load(assets[i], function() {
                    var e = new enchant.Event('progress');
                    e.loaded = ++loaded;
                    e.total = total;
                    game.dispatchEvent(e);
                    if (loaded == total) {
                        game.removeScene(game.loadingScene);
                        game.dispatchEvent(new enchant.Event('load'));
                    }
                });
            }
            for (var i = 0, len = tAssets.length; i < len; i++) {
                this.loadImage(tAssets[i], function() {
                    var e = new enchant.Event('progress');
                    e.loaded = ++loaded;
                    e.total = total;
                    game.dispatchEvent(e);
                    if (loaded == total) {
                        game.removeScene(game.loadingScene);
                        game.dispatchEvent(new enchant.Event('load'));
                    }
                });
            }
            for (var i = 0, len = mAssets.length; i < len; i++) {
                this.loadImage(mAssets[i], function() {
                    var e = new enchant.Event('progress');
                    e.loaded = ++loaded;
                    e.total = total;
                    game.dispatchEvent(e);
                    if (loaded == total) {
                        game.removeScene(game.loadingScene);
                        game.dispatchEvent(new enchant.Event('load'));
                    }
                });
            }

            for (var i = 0, len = nAssets.length; i < len; i++) {
                this.loadImage(nAssets[i], function() {
                    var e = new enchant.Event('progress');
                    e.loaded = ++loaded;
                    e.total = total;
                    game.dispatchEvent(e);
                    if (loaded == total) {
                        game.removeScene(game.loadingScene);
                        game.dispatchEvent(new enchant.Event('load'));
                    }
                });
            }
            this.pushScene(this.loadingScene);
        } else {
            this.dispatchEvent(new enchant.Event('load'));
        }
        this.currentTime = Date.now();
        this._intervalID = window.setInterval(function() {
            game._tick()
        }, 1000 / this.fps);
        this.running = true;
    },

    end: function(score, result) {
        this.pushScene(this.endScene);
        if (location.hostname == 'r.jsgames.jp') {
            var submit = function() {
                var id = location.pathname.match(/^\/games\/(\d+)/)[1];
                location.replace([
                    'http://9leap.net/games/', id, '/result',
                    '?score=', encodeURIComponent(score),
                    '&result=', encodeURIComponent(result)
                ].join(''));
            }
            this.endScene.addEventListener('touchend', submit);
            window.setTimeout(submit, 3000);
        }
    },

});

/**
 * @scope enchant.nineleap.SplashScene.prototype
 */
enchant.nineleap.SplashScene = enchant.Class.create(enchant.Scene, {
    image: {
        get: function() {
            return this._image;
        },
        set: function(image) {
            this._image = image;

            while (this.firstChild) {
                this.removeChild(this.firstChild);
            }
            var sprite = new Sprite(image.width, image.height);
            sprite.image = image;
            sprite.x = (this.width - image.width) / 2;
            sprite.y = (this.height - image.height) / 2;
            this.addChild(sprite);
        }
    }
});

})();
<commit_msg>Add third argment in Game.end<commit_after>/** nineleap.enchant.js v0.2.8 (2012/02/19)
 *
 * enchant.js extention for 9leap.net
 * @requires enchant.js v0.4.0 or later
 */

(function () {

enchant.nineleap = { assets: ['start.png', 'end.png'] };

/**
 * @scope enchant.nineleap.Game.prototype
 */

enchant.nineleap.Game = enchant.Class.create(enchant.Game, {
    initialize: function(width, height) {
        enchant.Game.call(this, width, height);
        this.addEventListener('load', function() {
            var game = this;
            this.startScene = new SplashScene();
            this.startScene._element.style.zIndex = 10;
            this.startScene.image = this.assets['start.png'];
            this.startScene.addEventListener('touchend', function() {
                if (game.started == false) {
                    if (game.onstart != null) game.onstart();
                    game.started = true;
                    gameStart = true;   // deprecated
                }
                if (game.currentScene == this) game.popScene();
                this.removeEventListener('touchend', arguments.callee);
            });
            this.addEventListener('keydown', function() {
                if (this.started == false) {
                    if(this.onstart != null) this.onstart();
                    this.started = true;
                    gameStart = true;   // deprecated
                }
                if (game.currentScene == game.startScene) game.popScene();
                this.removeEventListener('keydown', arguments.callee);
            });
            this.pushScene(this.startScene);

            this.endScene = new SplashScene();
            this.endScene.image = this.assets['end.png'];
        });
        this.scoreQueue = false;
        this.started = false;
        gameStart = false; // deprecated
    },

    loadImage: function(src, callback) {
        if (callback == null) callback = function() {};
        this.assets[src] = enchant.Surface.load(src);
        this.assets[src].addEventListener('load', callback);
    },

    start: function() {
        var game = this;

        if (this._intervalID) {
            window.clearInterval(this._intervalID);
        } else if (this._assets.length) {
            var o = {};
            var assets = this._assets.filter(function(asset) {
                return asset in o ? false : o[asset] = true;
            });
            var tAssets = (this._twitterAssets != undefined)? this._twitterAssets : [];
            var nAssets = (this._netpriceData != undefined)? this._netpriceData : [];
            var mAssets = (this._memoryAssets != undefined) ? this._memoryAssets : [];
            var loaded = 0;
            var total = assets.length + tAssets.length + nAssets.length + mAssets.length;
            for (var i = 0, len = assets.length; i < len; i++) {
                this.load(assets[i], function() {
                    var e = new enchant.Event('progress');
                    e.loaded = ++loaded;
                    e.total = total;
                    game.dispatchEvent(e);
                    if (loaded == total) {
                        game.removeScene(game.loadingScene);
                        game.dispatchEvent(new enchant.Event('load'));
                    }
                });
            }
            for (var i = 0, len = tAssets.length; i < len; i++) {
                this.loadImage(tAssets[i], function() {
                    var e = new enchant.Event('progress');
                    e.loaded = ++loaded;
                    e.total = total;
                    game.dispatchEvent(e);
                    if (loaded == total) {
                        game.removeScene(game.loadingScene);
                        game.dispatchEvent(new enchant.Event('load'));
                    }
                });
            }
            for (var i = 0, len = mAssets.length; i < len; i++) {
                this.loadImage(mAssets[i], function() {
                    var e = new enchant.Event('progress');
                    e.loaded = ++loaded;
                    e.total = total;
                    game.dispatchEvent(e);
                    if (loaded == total) {
                        game.removeScene(game.loadingScene);
                        game.dispatchEvent(new enchant.Event('load'));
                    }
                });
            }

            for (var i = 0, len = nAssets.length; i < len; i++) {
                this.loadImage(nAssets[i], function() {
                    var e = new enchant.Event('progress');
                    e.loaded = ++loaded;
                    e.total = total;
                    game.dispatchEvent(e);
                    if (loaded == total) {
                        game.removeScene(game.loadingScene);
                        game.dispatchEvent(new enchant.Event('load'));
                    }
                });
            }
            this.pushScene(this.loadingScene);
        } else {
            this.dispatchEvent(new enchant.Event('load'));
        }
        this.currentTime = Date.now();
        this._intervalID = window.setInterval(function() {
            game._tick()
        }, 1000 / this.fps);
        this.running = true;
    },

    end: function(score, result, img) {
        if(img !== undefined){
            this.endScene.image = img;
        }
        this.pushScene(this.endScene);
        if (location.hostname == 'r.jsgames.jp') {
            var submit = function() {
                var id = location.pathname.match(/^\/games\/(\d+)/)[1];
                location.replace([
                    'http://9leap.net/games/', id, '/result',
                    '?score=', encodeURIComponent(score),
                    '&result=', encodeURIComponent(result)
                ].join(''));
            }
            this.endScene.addEventListener('touchend', submit);
            window.setTimeout(submit, 3000);
        }
    }

});

/**
 * @scope enchant.nineleap.SplashScene.prototype
 */
enchant.nineleap.SplashScene = enchant.Class.create(enchant.Scene, {
    image: {
        get: function() {
            return this._image;
        },
        set: function(image) {
            this._image = image;

            while (this.firstChild) {
                this.removeChild(this.firstChild);
            }
            var sprite = new Sprite(image.width, image.height);
            sprite.image = image;
            sprite.x = (this.width - image.width) / 2;
            sprite.y = (this.height - image.height) / 2;
            this.addChild(sprite);
        }
    }
});

})();
<|endoftext|>


<commit_before>import {Map} from 'immutable';
import {createReducer} from 'redux-immutablejs';

const DELETE_FOLDER_ENTRIES = 'garchen-panel/entry/DELETE_FOLDER_ENTRIES';
const DELETE_FOLDER_ENTRIES_SUCCESS = 'garchen-panel/entry/DELETE_FOLDER_ENTRIES_SUCCESS';
const DELETE_FOLDER_ENTRIES_FAIL = 'garchen-panel/entry/DELETE_FOLDER_ENTRIES_FAIL';

const GET_ENTRY = 'garchen-panel/entry/GET_ENTRY';
const GET_ENTRY_SUCCESS = 'garchen-panel/entry/GET_ENTRY_SUCCESS';
const GET_ENTRY_FAIL = 'garchen-panel/entry/GET_ENTRY_FAIL';

const UPDATE_ENTRY = 'garchen-panel/entry/UPDATE_ENTRY';
const UPDATE_ENTRY_SUCCESS = 'garchen-panel/entry/UPDATE_ENTRY_SUCCESS';
const UPDATE_ENTRY_FAIL = 'garchen-panel/entry/UPDATE_ENTRY_FAIL';

const initialState = Map({
  entry: null
});

export default createReducer(initialState, {
  [GET_ENTRY_SUCCESS]: (state, action) => {
    return state.set('entry', action.result);
  }
});

export function deleteEntries(data) {
  return {
    types: [DELETE_FOLDER_ENTRIES, DELETE_FOLDER_ENTRIES_SUCCESS, DELETE_FOLDER_ENTRIES_FAIL],
    promise: (client) => client.send('delete-entries', data)
  };
}

export function getEntry(data) {
  return {
    types: [GET_ENTRY, GET_ENTRY_SUCCESS, GET_ENTRY_FAIL],
    promise: (client) => client.send('get-entry', data)
  };
}

export function updateEntry(data) {
  return {
    types: [UPDATE_ENTRY, UPDATE_ENTRY_SUCCESS, UPDATE_ENTRY_FAIL],
    promise: (client) => client.send('update-entry', data)
  };
}
<commit_msg>handle updated data<commit_after>import {Map} from 'immutable';
import {createReducer} from 'redux-immutablejs';

const DELETE_FOLDER_ENTRIES = 'garchen-panel/entry/DELETE_FOLDER_ENTRIES';
const DELETE_FOLDER_ENTRIES_SUCCESS = 'garchen-panel/entry/DELETE_FOLDER_ENTRIES_SUCCESS';
const DELETE_FOLDER_ENTRIES_FAIL = 'garchen-panel/entry/DELETE_FOLDER_ENTRIES_FAIL';

const GET_ENTRY = 'garchen-panel/entry/GET_ENTRY';
const GET_ENTRY_SUCCESS = 'garchen-panel/entry/GET_ENTRY_SUCCESS';
const GET_ENTRY_FAIL = 'garchen-panel/entry/GET_ENTRY_FAIL';

const UPDATE_ENTRY = 'garchen-panel/entry/UPDATE_ENTRY';
const UPDATE_ENTRY_SUCCESS = 'garchen-panel/entry/UPDATE_ENTRY_SUCCESS';
const UPDATE_ENTRY_FAIL = 'garchen-panel/entry/UPDATE_ENTRY_FAIL';

const initialState = Map({
  entry: null
});

export default createReducer(initialState, {

  [GET_ENTRY_SUCCESS]: (state, action) => {
    return state.set('entry', action.result);
  },

  [UPDATE_ENTRY_SUCCESS]: (state, action) => {
    return state.set('entry', action.result);
  }
});

export function deleteEntries(data) {
  return {
    types: [DELETE_FOLDER_ENTRIES, DELETE_FOLDER_ENTRIES_SUCCESS, DELETE_FOLDER_ENTRIES_FAIL],
    promise: (client) => client.send('delete-entries', data)
  };
}

export function getEntry(data) {
  return {
    types: [GET_ENTRY, GET_ENTRY_SUCCESS, GET_ENTRY_FAIL],
    promise: (client) => client.send('get-entry', data)
  };
}

export function updateEntry(data) {
  return {
    types: [UPDATE_ENTRY, UPDATE_ENTRY_SUCCESS, UPDATE_ENTRY_FAIL],
    promise: (client) => client.send('update-entry', data)
  };
}
<|endoftext|>


<commit_before>// Copyright 2014-2015, University of Colorado Boulder

/**
 * Node that allows the user to select the various elements contained within
 * a carousel by presenting a set of radio-style push buttons, each with an
 * icon image of the selection that it represents.
 *
 * @author John Blanco
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // Modules
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  // var RadioButtonGroup = require( 'SUN/buttons/RadioButtonGroup' );

  // Constants
  var BUTTON_IMAGE_HEIGHT_OR_WIDTH = 50; // In screen coordinates, which is close to pixels.

  /**
   * @param {EnergySystemElementCarousel} carousel
   * @constructor
   */
  function EnergySystemElementSelector( carousel ) {
    Node.call( this );

    var buttonElementList = [];

    for ( var i = 0; i < carousel.managedElements.length; i++ ) {
      var element = carousel.managedElements[ i ];
      var buttonImageNode = new Image( element.iconImage );
      var width = buttonImageNode.getBounds().getWidth();
      var height = buttonImageNode.getBounds().getHeight();
      var denominator = ( width > height ) ? width : height;
      buttonImageNode.setScale( BUTTON_IMAGE_HEIGHT_OR_WIDTH / denominator );

      // TODO: null -> RadioButton??
      buttonElementList.push( null );
      // add( new RadioButtonStripControlPanelNode.Element < Integer > ( buttonImageNode, i, carousel.getElement( i ).getUserComponent() ) );
    }

    // TODO
    // addChild( new RadioButtonStripControlPanelNode < Integer > ( carousel.targetIndex,
    //   buttonElementList,
    //   5,
    //   EFACConstants.CONTROL_PANEL_BACKGROUND_COLOR,
    //   EFACConstants.CONTROL_PANEL_OUTLINE_STROKE,
    //   EFACConstants.CONTROL_PANEL_OUTLINE_COLOR,
    //   4 ) );

  }

  return inherit( Node, EnergySystemElementSelector );
} );
<commit_msg>Update copyright<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * Node that allows the user to select the various elements contained within
 * a carousel by presenting a set of radio-style push buttons, each with an
 * icon image of the selection that it represents.
 *
 * @author John Blanco
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // Modules
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  // var RadioButtonGroup = require( 'SUN/buttons/RadioButtonGroup' );

  // Constants
  var BUTTON_IMAGE_HEIGHT_OR_WIDTH = 50; // In screen coordinates, which is close to pixels.

  /**
   * @param {EnergySystemElementCarousel} carousel
   * @constructor
   */
  function EnergySystemElementSelector( carousel ) {
    Node.call( this );

    var buttonElementList = [];

    for ( var i = 0; i < carousel.managedElements.length; i++ ) {
      var element = carousel.managedElements[ i ];
      var buttonImageNode = new Image( element.iconImage );
      var width = buttonImageNode.getBounds().getWidth();
      var height = buttonImageNode.getBounds().getHeight();
      var denominator = ( width > height ) ? width : height;
      buttonImageNode.setScale( BUTTON_IMAGE_HEIGHT_OR_WIDTH / denominator );

      // TODO: null -> RadioButton??
      buttonElementList.push( null );
      // add( new RadioButtonStripControlPanelNode.Element < Integer > ( buttonImageNode, i, carousel.getElement( i ).getUserComponent() ) );
    }

    // TODO
    // addChild( new RadioButtonStripControlPanelNode < Integer > ( carousel.targetIndex,
    //   buttonElementList,
    //   5,
    //   EFACConstants.CONTROL_PANEL_BACKGROUND_COLOR,
    //   EFACConstants.CONTROL_PANEL_OUTLINE_STROKE,
    //   EFACConstants.CONTROL_PANEL_OUTLINE_COLOR,
    //   4 ) );

  }

  return inherit( Node, EnergySystemElementSelector );
} );
<|endoftext|>


<commit_before>module.exports = function (grunt) {
    var pkg = grunt.file.readJSON("package.json");

    grunt.initConfig({
        pkg: pkg,
        assemblyinfo: {
            options: {
                files: ['../Src/Veil.sln'],

                // Standard assembly info
                info: {
                    version: pkg.assemblyVersion,
                    fileVersion: pkg.assemblyVersion
                }
            }
        },
        msbuild: {
            options: {
                projectConfiguration: 'Release',
                target: ['Clean', 'Rebuild'],
                stdout: true,
                buildParameters: {
                    platform: 'AnyCPU'
                }
            },
            core: {
                src: ['../src/Veil/Veil.csproj'],
                options: {
                    buildParameters: {
                        documentationFile: 'Veil.xml'
                    }
                }
            },
            supersimple: {
                src: ['../src/Veil.SuperSimple/Veil.SuperSimple.csproj']
            },
            handlebars: {
                src: ['../src/Veil.Handlebars/Veil.Handlebars.csproj']
            },
            nancy: {
                src: ['../src/Nancy.ViewEngines.Veil/Nancy.ViewEngines.Veil.csproj']
            },
            mvc: {
                src: ['../src/Veil.Mvc5/Veil.Mvc5.csproj']
            },
            bench: {
                src: ['../src/Veil.Benchmark/Veil.Benchmark.csproj']
            },
            tests: {
                src: ['../src/Veil.Tests/Veil.Tests.csproj']
            }
        },
        clean: {
            dist: {
                src: ["./dist"]
            }
        },
        copy: {
            nuspec: {
                files: [{
                    expand: true,
                    cwd: '../Src/Nuspec/',
                    src: ['*.nuspec'],
                    dest: 'dist/'
                }]
            },
            lib: {
                files: [{
                    expand: true,
                    cwd: '../src/Veil/bin/Release/',
                    src: ['Veil.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil/',
                    src: ['Veil.xml'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.SuperSimple/bin/Release/',
                    src: ['Veil.SuperSimple.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.Handlebars/bin/Release/',
                    src: ['Veil.Handlebars.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Nancy.ViewEngines.Veil/bin/Release/',
                    src: ['Nancy.ViewEngines.Veil.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.Mvc5/bin/Release/',
                    src: ['Veil.Mvc5.*'],
                    dest: 'dist/lib/net45'
                }]
            }
        },
        nugetpack: {
            options: {
                version: pkg.version
            },
            core: {
                src: 'dist/Veil.nuspec',
                dest: 'dist/'
            },
            supersimple: {
                src: 'dist/Veil.SuperSimple.nuspec',
                dest: 'dist/'
            },
            handlebars: {
                src: 'dist/Veil.Handlebars.nuspec',
                dest: 'dist/'
            },
            nancy: {
                src: 'dist/Nancy.ViewEngines.Veil.nuspec',
                dest: 'dist/'
            },
            mvc: {
                src: 'dist/Veil.Mvc5.nuspec',
                dest: 'dist/'
            }
        },
        nugetpush: {
            dist: {
                src: 'dist/*.nupkg'
            }
        },
        nugetrestore: {
            restore: {
                src: '../src/**/packages.config',
                dest: '../src/packages/'
            }
        }
    });
    grunt.loadNpmTasks('grunt-nuget');
    grunt.loadNpmTasks('grunt-msbuild');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-dotnet-assembly-info');
    grunt.registerTask("build", ["nugetrestore", "msbuild"])
    grunt.registerTask("default", ["clean", "assemblyinfo", "build", "copy", "nugetpack"]);
    grunt.registerTask("push", ["default", "nugetpush"]);
};
<commit_msg>Fix for AppVeyor?<commit_after>module.exports = function (grunt) {
    var pkg = grunt.file.readJSON("package.json");

    grunt.initConfig({
        pkg: pkg,
        assemblyinfo: {
            options: {
                files: ['../Src/Veil.sln'],

                // Standard assembly info
                info: {
                    version: pkg.assemblyVersion,
                    fileVersion: pkg.assemblyVersion
                }
            }
        },
        msbuild: {
            options: {
                projectConfiguration: 'Release',
                target: ['Clean', 'Rebuild'],
                stdout: true,
                buildParameters: {
                    platform: 'AnyCPU'
                }
            },
            core: {
                src: ['../src/Veil/Veil.csproj'],
                options: {
                    buildParameters: {
                        documentationFile: 'Veil.xml',
                        platform: 'AnyCPU'
                    }
                }
            },
            supersimple: {
                src: ['../src/Veil.SuperSimple/Veil.SuperSimple.csproj']
            },
            handlebars: {
                src: ['../src/Veil.Handlebars/Veil.Handlebars.csproj']
            },
            nancy: {
                src: ['../src/Nancy.ViewEngines.Veil/Nancy.ViewEngines.Veil.csproj']
            },
            mvc: {
                src: ['../src/Veil.Mvc5/Veil.Mvc5.csproj']
            },
            bench: {
                src: ['../src/Veil.Benchmark/Veil.Benchmark.csproj']
            },
            tests: {
                src: ['../src/Veil.Tests/Veil.Tests.csproj']
            }
        },
        clean: {
            dist: {
                src: ["./dist"]
            }
        },
        copy: {
            nuspec: {
                files: [{
                    expand: true,
                    cwd: '../Src/Nuspec/',
                    src: ['*.nuspec'],
                    dest: 'dist/'
                }]
            },
            lib: {
                files: [{
                    expand: true,
                    cwd: '../src/Veil/bin/Release/',
                    src: ['Veil.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil/',
                    src: ['Veil.xml'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.SuperSimple/bin/Release/',
                    src: ['Veil.SuperSimple.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.Handlebars/bin/Release/',
                    src: ['Veil.Handlebars.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Nancy.ViewEngines.Veil/bin/Release/',
                    src: ['Nancy.ViewEngines.Veil.*'],
                    dest: 'dist/lib/net40'
                },{
                    expand: true,
                    cwd: '../src/Veil.Mvc5/bin/Release/',
                    src: ['Veil.Mvc5.*'],
                    dest: 'dist/lib/net45'
                }]
            }
        },
        nugetpack: {
            options: {
                version: pkg.version
            },
            core: {
                src: 'dist/Veil.nuspec',
                dest: 'dist/'
            },
            supersimple: {
                src: 'dist/Veil.SuperSimple.nuspec',
                dest: 'dist/'
            },
            handlebars: {
                src: 'dist/Veil.Handlebars.nuspec',
                dest: 'dist/'
            },
            nancy: {
                src: 'dist/Nancy.ViewEngines.Veil.nuspec',
                dest: 'dist/'
            },
            mvc: {
                src: 'dist/Veil.Mvc5.nuspec',
                dest: 'dist/'
            }
        },
        nugetpush: {
            dist: {
                src: 'dist/*.nupkg'
            }
        },
        nugetrestore: {
            restore: {
                src: '../src/**/packages.config',
                dest: '../src/packages/'
            }
        }
    });
    grunt.loadNpmTasks('grunt-nuget');
    grunt.loadNpmTasks('grunt-msbuild');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-dotnet-assembly-info');
    grunt.registerTask("build", ["nugetrestore", "msbuild"])
    grunt.registerTask("default", ["clean", "assemblyinfo", "build", "copy", "nugetpack"]);
    grunt.registerTask("push", ["default", "nugetpush"]);
};
<|endoftext|>