<commit_before>'use strict';

const TEXTURE_URL_BASE = '/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/';

// TODO : Eventually make this into a configurable setting.
const CURSOR_DEFAULT_OPACITY = 0.90;

// TODO : Eventually make this into a configurable setting.
const SKYBOX_DEFAULT_OPACITY = 0.50;

function TextureGroup(texture_group, loading_manager) {
    this.__init__(texture_group, loading_manager);
}

// Utility variables.
const INDEX_FULL_URL     = 0;
const INDEX_TEXTURE_NAME = 1;
const INDEX_TEXTURE      = 2;

TextureGroup.prototype = {
    __init__: function(texture_group, loading_manager) {
        this._loading_manager  = loading_manager;
        this._texture_group    = texture_group;
        this._texture_base_url = TEXTURE_URL_BASE + this._texture_group;
        this._textures = [];
        this._add_textures_needed();
        this._number_of_textures_to_load = this._textures.length;
        this._number_of_loaded_textures = 0;

        this._loading_manager._number_of_textures_to_load += this._number_of_textures_to_load;
    },

    get_texture: function(texture_name) {
        for (var t = 0; t < this._number_of_textures_to_load; t++) {
            if (this._textures[t][INDEX_TEXTURE_NAME] === texture_name) {
                return this._textures[t][INDEX_TEXTURE];
            }
        }
    },

    _texture_loaded: function(texture, texture_full_url) {
        var texture_name = 'missing';
        for (var t = 0; t < this._number_of_textures_to_load; t++) {
            if (this._textures[t][INDEX_FULL_URL] === texture_full_url) {
                this._textures[t][INDEX_TEXTURE] = texture;
                this._number_of_loaded_textures += 1;

                texture_name = this._textures[t][INDEX_TEXTURE_NAME];
                this._loading_manager.update_text('Loaded ' + texture_name);

                break;
            }
        }

        switch (this._texture_group) {
        case TEXTURE_GROUP_CURSOR:
            var cursor_material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: CURSOR_DEFAULT_OPACITY});
            MANAGER_WORLD.world_login.provide_cursor_material(cursor_material, texture_name);
            MANAGER_WORLD.world_home.provide_cursor_material(cursor_material, texture_name);
            MANAGER_WORLD.world_settings.provide_cursor_material(cursor_material, texture_name);
            break;
        case TEXTURE_GROUP_ICONS:
            if (this._number_of_loaded_textures === this._number_of_textures_to_load) {
                // The parameters passed in are the icons not to load from the set of standard player menu icons.
                this.world_login.player_menu.load_icon_textures([ICON_ENTITY_GROUP, ICON_SAVE, ICON_SETTINGS, ICON_HOME, ICON_MULTIPLAYER]);
                this.world_home.player_menu.load_icon_textures([ICON_HOME]);
                this.world_settings.player_menu.load_icon_textures([ICON_SETTINGS, ICON_ENTITY_GROUP]);
            }
            break;
        }

        /*
        if (texture_name.includes('skybox')) {
            // Skybox.
            var position = -1;
            if (texture_name.includes(SKYBOX_FRONT)) {
                position = 0;
            } else if (texture_name.includes(SKYBOX_BACK)) {
                position = 1;
            } else if (texture_name.includes(SKYBOX_TOP)) {
                position = 2;
            } else if (texture_name.includes(SKYBOX_BOTTOM)) {
                position = 3;
            } else if (texture_name.includes(SKYBOX_RIGHT)) {
                position = 4;
            } else if (texture_name.includes(SKYBOX_LEFT)) {
                position = 5;
            }
            this.sky_box_textures.push([new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: SKYBOX_DEFAULT_OPACITY}), position]);

            this.number_of_sky_box_textures_loaded += 1;
            if (this.number_of_sky_box_textures_loaded === NUMBER_OF_SKYBOX_TEXTURES) {
                this.create_sky_boxes();
            }

        } else if (texture_name.includes('icons')) {
            // Icons.
            this.icon_textures.push([texture, texture_name]);
            this.number_of_icons_loaded += 1;
            if (this.number_of_icons_loaded === NUMBER_OF_ICON_TEXTURES) {
                // The parameters passed in are the icons not to load.
                this.world_login.player_menu.load_icon_textures([ICON_ENTITY_GROUP, ICON_SAVE, ICON_SETTINGS, ICON_HOME, ICON_MULTIPLAYER]);
                this.world_home.player_menu.load_icon_textures([ICON_HOME]);
                this.world_settings.player_menu.load_icon_textures([ICON_SETTINGS, ICON_ENTITY_GROUP]);
            }
        }*/
    },

    load_textures: function() {
        for (var t = 0; t < this._textures.length; t++) {

            new THREE.TextureLoader().load(this._textures[t][INDEX_FULL_URL],
                //function when resource is loaded
                function(texture) {
                    this._texture_loaded(arguments[1], arguments[0]);
                }.bind(this, this._textures[t][INDEX_TEXTURE_NAME]),
                // FOR_DEV_START
                function(xhr) {
                    l((xhr.loaded / xhr.total * 100) + '% loaded for texture file.');
                },
                function(xhr) {
                    l(xhr);
                });
            // FOR_DEV_END
        }

    },

    _add_texture_needed: function(texture_name) {
        this._textures.push([this._texture_base_url + texture_name, texture_name, null]);
    },

    _add_textures_needed: function() {
        switch (this._texture_group) {
        case TEXTURE_GROUP_CURSOR:
            this._add_texture_needed(CURSOR_TYPE_HORIZONTAL);
            this._add_texture_needed(CURSOR_TYPE_VERTICAL);
            this._add_texture_needed(CURSOR_TYPE_HAND);
            this._add_texture_needed(CURSOR_TYPE_POINTER);
            this._add_texture_needed(CURSOR_TYPE_LARGER);
            this._add_texture_needed(CURSOR_TYPE_MOUSE);
            break;
        case TEXTURE_GROUP_SKYBOX:
            this._add_texture_needed(SKYBOX_FRONT);
            this._add_texture_needed(SKYBOX_BACK);
            this._add_texture_needed(SKYBOX_TOP);
            this._add_texture_needed(SKYBOX_BOTTOM);
            this._add_texture_needed(SKYBOX_RIGHT);
            this._add_texture_needed(SKYBOX_LEFT);
            break;
        case TEXTURE_GROUP_ICONS:
            this._add_texture_needed(ICON_EXIT);
            this._add_texture_needed(ICON_SETTINGS);
            this._add_texture_needed(ICON_ENTITY_GROUP);
            this._add_texture_needed(ICON_HOME);
            this._add_texture_needed(ICON_MULTIPLAYER);
            this._add_texture_needed(ICON_SAVE);
            this._add_texture_needed(ICON_FULLSCREEN);
            this._add_texture_needed(ICON_LEFT);
            this._add_texture_needed(ICON_RIGHT);
            this._add_texture_needed(ICON_CROSS);
            this._add_texture_needed(ICON_LOCKED);
            this._add_texture_needed(ICON_UNLOCKED);
            this._add_texture_needed(ICON_WORLDS);
            this._add_texture_needed(ICON_WARNING);
            break;
        }
    }
};

function LoadingManager() {
    this.__init__();
}

LoadingManager.prototype = {

    __init__: function() {
        this.textures_cursor = new TextureGroup(TEXTURE_GROUP_CURSOR, this);
        this.textures_skybox = new TextureGroup(TEXTURE_GROUP_SKYBOX, this);
        this.textures_icon   = new TextureGroup(TEXTURE_GROUP_ICONS,  this);

        this._number_of_textures_to_load = 0;
        this._number_of_textures_loaded  = 0;
    },

    update_text: function(text) {
        this._number_of_textures_to_load += 1;
        GUI_PAUSED_MENU.set_text(round_to_n_decimal_places(this._number_of_textures_to_load / this._number_of_textures_loaded, 2) + '% loaded');
        GUI_PAUSED_MENU.set_sub_text(text);
    },

    get_texture: function(texture_group, texture_name) {
        switch (texture_group) {
        case TEXTURE_GROUP_CURSOR:
            return this.textures_cursor.get_texture(texture_name);
        case TEXTURE_GROUP_ICONS:
            return this.textures_icon.get_texture(texture_name);
        case TEXTURE_GROUP_SKYBOX:
            return this.textures_skybox.get_texture(texture_name);
        }
    },

    // Occurs only once on website start up.
    perform_initial_load: function() {
        l('Performing the initial load!!');

        this.textures_cursor.load_textures();
        this.textures_skybox.load_textures();
        this.textures_icon.load_textures();

        //GUI_PAUSED_MENU.make_visible();
        //this.currently_loading = false;
    },

    currently_loading: function() {
        return this._number_of_textures_loaded !== this._number_of_textures_to_load;
    }

};<commit_msg>general updating 65<commit_after>'use strict';

const TEXTURE_URL_BASE = '/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/';

// TODO : Eventually make this into a configurable setting.
const CURSOR_DEFAULT_OPACITY = 0.90;

// TODO : Eventually make this into a configurable setting.
const SKYBOX_DEFAULT_OPACITY = 0.50;

function TextureGroup(texture_group, loading_manager) {
    this.__init__(texture_group, loading_manager);
}

// Utility variables.
const INDEX_FULL_URL     = 0;
const INDEX_TEXTURE_NAME = 1;
const INDEX_TEXTURE      = 2;

TextureGroup.prototype = {
    __init__: function(texture_group, loading_manager) {
        this._loading_manager  = loading_manager;
        this._texture_group    = texture_group;
        this._texture_base_url = TEXTURE_URL_BASE + this._texture_group;
        this._textures = [];
        this._add_textures_needed();
        this._number_of_textures_to_load = this._textures.length;
        this._number_of_loaded_textures = 0;

        this._loading_manager._number_of_textures_to_load += this._number_of_textures_to_load;
    },

    get_texture: function(texture_name) {
        for (var t = 0; t < this._number_of_textures_to_load; t++) {
            if (this._textures[t][INDEX_TEXTURE_NAME] === texture_name) {
                return this._textures[t][INDEX_TEXTURE];
            }
        }
    },

    _texture_loaded: function(texture, texture_full_url) {

        l('Looking for : ');
        l(texture_full_url);

        var texture_name = 'missing';
        for (var t = 0; t < this._number_of_textures_to_load; t++) {

            l(this._textures[t][INDEX_FULL_URL]);
            l((this._textures[t][INDEX_FULL_URL]) === (texture_full_url));

            if (this._textures[t][INDEX_FULL_URL] === texture_full_url) {
                this._textures[t][INDEX_TEXTURE] = texture;
                this._number_of_loaded_textures += 1;

                texture_name = this._textures[t][INDEX_TEXTURE_NAME];
                this._loading_manager.update_text('Loaded ' + texture_name);

                break;
            }
        }

        switch (this._texture_group) {
        case TEXTURE_GROUP_CURSOR:
            var cursor_material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: CURSOR_DEFAULT_OPACITY});
            MANAGER_WORLD.world_login.provide_cursor_material(cursor_material, texture_name);
            MANAGER_WORLD.world_home.provide_cursor_material(cursor_material, texture_name);
            MANAGER_WORLD.world_settings.provide_cursor_material(cursor_material, texture_name);
            break;
        case TEXTURE_GROUP_ICONS:
            if (this._number_of_loaded_textures === this._number_of_textures_to_load) {
                // The parameters passed in are the icons not to load from the set of standard player menu icons.
                this.world_login.player_menu.load_icon_textures([ICON_ENTITY_GROUP, ICON_SAVE, ICON_SETTINGS, ICON_HOME, ICON_MULTIPLAYER]);
                this.world_home.player_menu.load_icon_textures([ICON_HOME]);
                this.world_settings.player_menu.load_icon_textures([ICON_SETTINGS, ICON_ENTITY_GROUP]);
            }
            break;
        }

        /*
        if (texture_name.includes('skybox')) {
            // Skybox.
            var position = -1;
            if (texture_name.includes(SKYBOX_FRONT)) {
                position = 0;
            } else if (texture_name.includes(SKYBOX_BACK)) {
                position = 1;
            } else if (texture_name.includes(SKYBOX_TOP)) {
                position = 2;
            } else if (texture_name.includes(SKYBOX_BOTTOM)) {
                position = 3;
            } else if (texture_name.includes(SKYBOX_RIGHT)) {
                position = 4;
            } else if (texture_name.includes(SKYBOX_LEFT)) {
                position = 5;
            }
            this.sky_box_textures.push([new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: SKYBOX_DEFAULT_OPACITY}), position]);

            this.number_of_sky_box_textures_loaded += 1;
            if (this.number_of_sky_box_textures_loaded === NUMBER_OF_SKYBOX_TEXTURES) {
                this.create_sky_boxes();
            }

        } else if (texture_name.includes('icons')) {
            // Icons.
            this.icon_textures.push([texture, texture_name]);
            this.number_of_icons_loaded += 1;
            if (this.number_of_icons_loaded === NUMBER_OF_ICON_TEXTURES) {
                // The parameters passed in are the icons not to load.
                this.world_login.player_menu.load_icon_textures([ICON_ENTITY_GROUP, ICON_SAVE, ICON_SETTINGS, ICON_HOME, ICON_MULTIPLAYER]);
                this.world_home.player_menu.load_icon_textures([ICON_HOME]);
                this.world_settings.player_menu.load_icon_textures([ICON_SETTINGS, ICON_ENTITY_GROUP]);
            }
        }*/
    },

    load_textures: function() {
        for (var t = 0; t < this._textures.length; t++) {

            new THREE.TextureLoader().load(this._textures[t][INDEX_FULL_URL],
                //function when resource is loaded
                function(texture) {
                    this._texture_loaded(arguments[1], arguments[0]);
                }.bind(this, this._textures[t][INDEX_TEXTURE_NAME]),
                // FOR_DEV_START
                function(xhr) {
                    l((xhr.loaded / xhr.total * 100) + '% loaded for texture file.');
                },
                function(xhr) {
                    l(xhr);
                });
            // FOR_DEV_END
        }

    },

    _add_texture_needed: function(texture_name) {
        this._textures.push([this._texture_base_url + texture_name, texture_name, null]);
    },

    _add_textures_needed: function() {
        switch (this._texture_group) {
        case TEXTURE_GROUP_CURSOR:
            this._add_texture_needed(CURSOR_TYPE_HORIZONTAL);
            this._add_texture_needed(CURSOR_TYPE_VERTICAL);
            this._add_texture_needed(CURSOR_TYPE_HAND);
            this._add_texture_needed(CURSOR_TYPE_POINTER);
            this._add_texture_needed(CURSOR_TYPE_LARGER);
            this._add_texture_needed(CURSOR_TYPE_MOUSE);
            break;
        case TEXTURE_GROUP_SKYBOX:
            this._add_texture_needed(SKYBOX_FRONT);
            this._add_texture_needed(SKYBOX_BACK);
            this._add_texture_needed(SKYBOX_TOP);
            this._add_texture_needed(SKYBOX_BOTTOM);
            this._add_texture_needed(SKYBOX_RIGHT);
            this._add_texture_needed(SKYBOX_LEFT);
            break;
        case TEXTURE_GROUP_ICONS:
            this._add_texture_needed(ICON_EXIT);
            this._add_texture_needed(ICON_SETTINGS);
            this._add_texture_needed(ICON_ENTITY_GROUP);
            this._add_texture_needed(ICON_HOME);
            this._add_texture_needed(ICON_MULTIPLAYER);
            this._add_texture_needed(ICON_SAVE);
            this._add_texture_needed(ICON_FULLSCREEN);
            this._add_texture_needed(ICON_LEFT);
            this._add_texture_needed(ICON_RIGHT);
            this._add_texture_needed(ICON_CROSS);
            this._add_texture_needed(ICON_LOCKED);
            this._add_texture_needed(ICON_UNLOCKED);
            this._add_texture_needed(ICON_WORLDS);
            this._add_texture_needed(ICON_WARNING);
            break;
        }
    }
};

function LoadingManager() {
    this.__init__();
}

LoadingManager.prototype = {

    __init__: function() {
        this.textures_cursor = new TextureGroup(TEXTURE_GROUP_CURSOR, this);
        this.textures_skybox = new TextureGroup(TEXTURE_GROUP_SKYBOX, this);
        this.textures_icon   = new TextureGroup(TEXTURE_GROUP_ICONS,  this);

        this._number_of_textures_to_load = 0;
        this._number_of_textures_loaded  = 0;
    },

    update_text: function(text) {
        this._number_of_textures_to_load += 1;
        GUI_PAUSED_MENU.set_text(round_to_n_decimal_places(this._number_of_textures_to_load / this._number_of_textures_loaded, 2) + '% loaded');
        GUI_PAUSED_MENU.set_sub_text(text);
    },

    get_texture: function(texture_group, texture_name) {
        switch (texture_group) {
        case TEXTURE_GROUP_CURSOR:
            return this.textures_cursor.get_texture(texture_name);
        case TEXTURE_GROUP_ICONS:
            return this.textures_icon.get_texture(texture_name);
        case TEXTURE_GROUP_SKYBOX:
            return this.textures_skybox.get_texture(texture_name);
        }
    },

    // Occurs only once on website start up.
    perform_initial_load: function() {
        l('Performing the initial load!!');

        this.textures_cursor.load_textures();
        this.textures_skybox.load_textures();
        this.textures_icon.load_textures();

        //GUI_PAUSED_MENU.make_visible();
        //this.currently_loading = false;
    },

    currently_loading: function() {
        return this._number_of_textures_loaded !== this._number_of_textures_to_load;
    }

};<|endoftext|>


<commit_before>/* Get Programming with JavaScript
 * Listing 13.06
 * Using the spacer namespace
 */

console.log(spacer.box("It's like magic!", 20, "*"));

/* Further Adventures
 *
 * 1) Run the program.
 *
 * 2) One at a time, try different
 *    characters in the call to
 *    spacer.box.
 *
 * 3) At the prompt, type spacer
 *    and press Enter.
 *
 *    > spacer
 *
 * The spacer object will be displayed
 * along with its methods. spacer was
 * added to the global scope by the
 * module imported using an HTML
 * script element.
 *
 */<commit_msg>Update to the guessing game<commit_after>// Get Programming with JavaScript
// Listings 13.05 and 13.06
// Using the number generator in the guessing game
// tixina

var getGuesser = function (lowest, highest) {
  var secret = between(lowest, highest);

  return function (userNumber) {
    if (userNumber === secret) {
      return "Well done!";
    } else if (userNumber > secret) {
      return "Too high!";
    } else {
      return "Too low!";
    }
  };
};

var guess = getGuesser(5, 10);

/* Further Adventures
 *
 * 1) Run the program and play the game.
 *
 * 2) Change the arguments to getGuesser so that
 *    the number to guess is in a bigger range.
 *
 * 3) Update the game so that it keeps track of
 *    the number of guesses a player takes to
 *    find the secret number.
 *
 *    > Well done! You took 6 guesses.
 *
 */
<|endoftext|>


<commit_before>// Karma configuration

module.exports = function (config) {
  config.set({
    basePath: '',
    files: [
      'zone.js',
      'test/*.spec.js'
    ],

    reporters: ['progress'],

    port: 9876,
    colors: true,

    logLevel: config.LOG_INFO,

    browsers: ['Chrome'],
    frameworks: ['jasmine'],

    captureTimeout: 60000,

    autoWatch: true,
    singleRun: false
  });
};
<commit_msg>add patch.js to karma config<commit_after>// Karma configuration

module.exports = function (config) {
  config.set({
    basePath: '',
    files: [
      'zone.js',
      'patch.js',
      'test/*.spec.js'
    ],

    reporters: ['progress'],

    port: 9876,
    colors: true,

    logLevel: config.LOG_INFO,

    browsers: ['Chrome'],
    frameworks: ['jasmine'],

    captureTimeout: 60000,

    autoWatch: true,
    singleRun: false
  });
};
<|endoftext|>


<commit_before>import Ember from 'ember';
const { keys, create } = Object; // jshint ignore:line
const { computed, observer, $, run, on, typeOf, debug, isPresent } = Ember;  // jshint ignore:line
const { defineProperty, get, set, inject, isEmpty, merge } = Ember; // jshint ignore:line
const a = Ember.A; // jshint ignore:line

import layout from '../templates/components/ui-download';

export default Ember.Component.extend({
  layout: layout,
  classNameBindings: ['_file'],
  classNames: ['ui-download'],
  data: null,
  _data: computed('data', function() {
    return this.get('data') ? 'data-ready' : null;
  }),
  mime: 'text/plain',
  charset: 'utf-8',
  url: computed('mime', 'data', function() {
    let {mime, data, charset} = this.getProperties('mime', 'data', 'charset');
    data = charset === 'utf-8' || mime.slice(0, 4) === 'text' ? encodeURIComponent(data) : data;
    return `data:${mime};charset=${charset},${data}`;
  }),
  click(evt) {
    if(evt.target.className !== 'hidden-link') {
      const {data, filename} = this.getProperties();
      if(window.navigator.msSaveOrOpenBlob) {
        let fileData = [data];
        let blobObject = new Blob(fileData);
        $('.hidden-link').click(function(){
          window.navigator.msSaveOrOpenBlob(blobObject, filename);
        });
      } else {
        console.log('non-msSave approach');
        $('.hidden-link')[0].click();
      }
    }
  }
});
<commit_msg>fixed for IE<commit_after>import Ember from 'ember';
const { keys, create } = Object; // jshint ignore:line
const { computed, observer, $, run, on, typeOf, debug, isPresent } = Ember;  // jshint ignore:line
const { defineProperty, get, set, inject, isEmpty, merge } = Ember; // jshint ignore:line
const a = Ember.A; // jshint ignore:line

import layout from '../templates/components/ui-download';

export default Ember.Component.extend({
  layout: layout,
  classNameBindings: ['_file'],
  classNames: ['ui-download'],
  data: null,
  _data: computed('data', function() {
    return this.get('data') ? 'data-ready' : null;
  }),
  mime: 'text/plain',
  charset: 'utf-8',
  url: computed('mime', 'data', function() {
    let {mime, data, charset} = this.getProperties('mime', 'data', 'charset');
    data = charset === 'utf-8' || mime.slice(0, 4) === 'text' ? encodeURIComponent(data) : data;
    return `data:${mime};charset=${charset},${data}`;
  }),
  click(evt) {
    if(evt.target.className !== 'hidden-link') {
      const {data, filename} = this.getProperties('data','filename');
      if(window.navigator.msSaveOrOpenBlob) {
        // Microsoft Strategy
        let fileData = [data];
        let blobObject = new Blob(fileData);
        window.navigator.msSaveOrOpenBlob(blobObject, filename);
      } else {
        // Non-microsoft startegy
        $('.hidden-link')[0].click();
      }
    }
  }
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         MastodonTranslate
// @namespace    https://niu.moe/@tomo
// @version      1.8.1
// @description  Provides a translate toot option for Mastodon users via GoogleTranslate
// @author       tomo@uchuu.io / https://niu.moe/@tomo
// @match        *://*/web/*
// @match        *://*/settings/preferences
// @connect      translate.uchuu.io
// @require      https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
// @grant        GM.getValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @grant        GM_xmlHttpRequest
// @grant        GM.xmlHttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // Set Defaults if not set
    if(!localStorage.getItem('toggle')) {
        localStorage.setItem('toggle', GM_getValue('toggle', 'false'));
    }
    if(!localStorage.getItem('lang')) {
        localStorage.setItem('lang', GM_getValue('lang', 'en'));
    }

    function getTranslation(status, language, text) {
        var encodedText = encodeURIComponent(text);
        var url = "https://translate.uchuu.io/"+language+'/'+encodedText;

        GM.xmlHttpRequest({
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            },
            url: url,
            onload: function(res) {
                var resJson = JSON.parse(res.responseText);
                var translatedText = resJson.text;

                var translateArea = document.createElement('p');
                translateArea.classList.add('toot__translation');
                translateArea.innerHTML = 'Translated: '+translatedText;

                status.querySelector('div.status__content').appendChild(translateArea);

                document.querySelector('li.translate__toot').remove();
                if (document.querySelector('div.dropdown-menu') !== null) {
                    status.querySelector('i.fa.fa-ellipsis-h').click();
                }
            },
            onabort: function() {
                console.log('There was an abort');
            },
            ontimeout: function() {
                console.log('It timeout');
            },
            onerror: function() {
                console.log('There was an error');
            }
        });
    }

    function addTranslateLink(status) {
        var statusText = status.querySelector('div.status__content').textContent;
        setTimeout(function() {
            // var dropdown = status.querySelector('div.status__action-bar-dropdown');
            var dropdown = document.querySelector('div.dropdown-menu ul');
            var separator = dropdown.querySelector('li.dropdown-menu__separator');

            var listItem = document.createElement('li');
            listItem.classList.add('dropdown-menu__item');
            listItem.classList.add('translate__toot');

            var link = document.createElement('a');
            // link.setAttribute('href', 'https://translate.google.com/#auto/en/'+statusText);
            link.setAttribute('href', '#');
            link.setAttribute('target', '_blank');
            link.textContent = 'Translate Toot';
            link.addEventListener('click', function(e) {
                e.preventDefault();
                if (localStorage.getItem('toggle') == 'true' && status.querySelectorAll('p.toot__translation').length === 0) {
                    link.textContent = 'Loading...';
                    getTranslation(status, localStorage.getItem('lang'), statusText);
                } else if (localStorage.getItem('toggle') == 'false') {
                    window.location.href = window.location.origin + '/settings/preferences#translation_notice';
                }
            }, false);

            listItem.appendChild(link);
            dropdown.insertBefore(listItem, separator);
        }, 100);
    }

    function saveSettings(event) {
        if (event.target.tagName.toLowerCase() === 'button' && event.target.getAttribute('type') === 'submit') {
            event.preventDefault();
            var toggle = document.getElementById('user_translation_enabled');
            var selectedToggle = toggle.checked;
            localStorage.setItem('toggle', selectedToggle);

            var input = document.getElementById('translation_locale');
            var selectedLanguage = input.options[input.selectedIndex].value;
            localStorage.setItem('lang', selectedLanguage);

            setTimeout(function() {
                document.querySelector('body').removeEventListener('click', saveSettings, false);
                actions.children[0].click();
            }, 500);
        }
    }

    function chromeClickChecker(event) {
        return(
            event.target.tagName.toLowerCase() === 'i' &&
            event.target.classList.contains('fa-ellipsis-h') &&
            document.querySelector('div.dropdown-menu') === null
        );
    }

    function firefoxClickChecker(event) {
        return(
            event.target.tagName.toLowerCase() === 'button' &&
            event.target.classList.contains('icon-button') &&
            document.querySelector('div.dropdown-menu') === null
        );
    }

    function activateMastodonTranslate() {
        document.querySelector('body').addEventListener('click', function(event) {
            if (chromeClickChecker(event) || firefoxClickChecker(event)) {
                // Get the status for this event
                var status = event.target.parentNode.parentNode.parentNode.parentNode.parentNode;
                addTranslateLink(status);
            }
        }, false);
    }

    // Launch Script
    window.addEventListener("load", function() {
        if (window.innerWidth > 630) {
            // Checks we're on a mastodon instance
            var settingsEl = document.querySelector('a.drawer__tab[title="Preferences"]');
            var settingsUrl = settingsEl.getAttribute('href');
            if (settingsUrl === '/settings/preferences') {
                activateMastodonTranslate();
            } else {
                // Probably on the mastofe of pleroma or something
            }
        } else {
            console.log('Sorry, only desktop');
        }
    }, false);

    if (window.location.pathname === '/settings/preferences') {
        // We're on the settings page
        var form = document.querySelector('form.simple_form');
        var actions = document.querySelector('div.actions');

        var settingsGroup = form.querySelector('div.fields-group').cloneNode(true);
        settingsGroup.children[1].remove(); // Remove the posting language
        settingsGroup.children[1].remove(); // Remove the filtered language

        var notice = document.createElement('div');
        var noticeMsg = 'Translation is currently provided by Google Translate, if you\'re not happy with this please don\'t check the checkbox below or just uninstall the script. I\'m looking to offer alternatives to Google which you can track here: https://github.com/tomouchuu/mastodon-translate/issues/6';
        noticeMsg += '
If you have an issue please give me a buzz @tomo@niu.moe via mastodon or raise an issue on Github';
        notice.setAttribute('id', 'translation_notice');
        notice.innerHTML = '
Tampermonkey Translation Script

'+noticeMsg+'
';

        var toggle = document.createElement('div');
        toggle.classList.add('input');
        toggle.classList.add('boolean');
        toggle.classList.add('optional');
        toggle.classList.add('user_translation_enabled');
        toggle.innerHTML = '
<input value="0" type="hidden" name="user[translation_enabled]"><input class="boolean optional" type="checkbox" value="1" name="user[translation_enabled]" id="user_translation_enabled">I\'m happy to use Google Translate
';
        var checkbox = toggle.querySelector('input#user_translation_enabled');
        checkbox.checked = (localStorage.getItem('toggle') == 'true');

        var languageDiv = settingsGroup.children[0];
        languageDiv.classList.remove('user_locale');
        languageDiv.classList.add('translation_locale');
        var label = languageDiv.children[0].children[0];
        label.setAttribute('for', 'translation_locale');
        label.textContent = 'Translation Language';
        var input = languageDiv.children[0].children[1];
        input.setAttribute('name', 'user[translation]');
        input.setAttribute('id', 'translation_locale');
        input.value = localStorage.getItem('lang');
        languageDiv.children[1].textContent = 'The language to translate toots into';

        settingsGroup.insertBefore(notice, languageDiv);
        settingsGroup.insertBefore(toggle, languageDiv);

        form.insertBefore(settingsGroup, actions.nextSibling);

        document.querySelector('body').addEventListener('click', saveSettings, false);
    }
})();<commit_msg>Console.log when script is activating<commit_after>// ==UserScript==
// @name         MastodonTranslate
// @namespace    https://niu.moe/@tomo
// @version      1.8.2
// @description  Provides a translate toot option for Mastodon users via GoogleTranslate
// @author       tomo@uchuu.io / https://niu.moe/@tomo
// @match        *://*/web/*
// @match        *://*/settings/preferences
// @connect      translate.uchuu.io
// @require      https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
// @grant        GM.getValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @grant        GM_xmlHttpRequest
// @grant        GM.xmlHttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // Set Defaults if not set
    if(!localStorage.getItem('toggle')) {
        localStorage.setItem('toggle', GM_getValue('toggle', 'false'));
    }
    if(!localStorage.getItem('lang')) {
        localStorage.setItem('lang', GM_getValue('lang', 'en'));
    }

    function getTranslation(status, language, text) {
        var encodedText = encodeURIComponent(text);
        var url = "https://translate.uchuu.io/"+language+'/'+encodedText;

        GM.xmlHttpRequest({
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            },
            url: url,
            onload: function(res) {
                var resJson = JSON.parse(res.responseText);
                var translatedText = resJson.text;

                var translateArea = document.createElement('p');
                translateArea.classList.add('toot__translation');
                translateArea.innerHTML = 'Translated: '+translatedText;

                status.querySelector('div.status__content').appendChild(translateArea);

                document.querySelector('li.translate__toot').remove();
                if (document.querySelector('div.dropdown-menu') !== null) {
                    status.querySelector('i.fa.fa-ellipsis-h').click();
                }
            },
            onabort: function() {
                console.log('There was an abort');
            },
            ontimeout: function() {
                console.log('It timeout');
            },
            onerror: function() {
                console.log('There was an error');
            }
        });
    }

    function addTranslateLink(status) {
        var statusText = status.querySelector('div.status__content').textContent;
        setTimeout(function() {
            // var dropdown = status.querySelector('div.status__action-bar-dropdown');
            var dropdown = document.querySelector('div.dropdown-menu ul');
            var separator = dropdown.querySelector('li.dropdown-menu__separator');

            var listItem = document.createElement('li');
            listItem.classList.add('dropdown-menu__item');
            listItem.classList.add('translate__toot');

            var link = document.createElement('a');
            // link.setAttribute('href', 'https://translate.google.com/#auto/en/'+statusText);
            link.setAttribute('href', '#');
            link.setAttribute('target', '_blank');
            link.textContent = 'Translate Toot';
            link.addEventListener('click', function(e) {
                e.preventDefault();
                if (localStorage.getItem('toggle') == 'true' && status.querySelectorAll('p.toot__translation').length === 0) {
                    link.textContent = 'Loading...';
                    getTranslation(status, localStorage.getItem('lang'), statusText);
                } else if (localStorage.getItem('toggle') == 'false') {
                    window.location.href = window.location.origin + '/settings/preferences#translation_notice';
                }
            }, false);

            listItem.appendChild(link);
            dropdown.insertBefore(listItem, separator);
        }, 100);
    }

    function saveSettings(event) {
        if (event.target.tagName.toLowerCase() === 'button' && event.target.getAttribute('type') === 'submit') {
            event.preventDefault();
            var toggle = document.getElementById('user_translation_enabled');
            var selectedToggle = toggle.checked;
            localStorage.setItem('toggle', selectedToggle);

            var input = document.getElementById('translation_locale');
            var selectedLanguage = input.options[input.selectedIndex].value;
            localStorage.setItem('lang', selectedLanguage);

            setTimeout(function() {
                document.querySelector('body').removeEventListener('click', saveSettings, false);
                actions.children[0].click();
            }, 500);
        }
    }

    function chromeClickChecker(event) {
        return(
            event.target.tagName.toLowerCase() === 'i' &&
            event.target.classList.contains('fa-ellipsis-h') &&
            document.querySelector('div.dropdown-menu') === null
        );
    }

    function firefoxClickChecker(event) {
        return(
            event.target.tagName.toLowerCase() === 'button' &&
            event.target.classList.contains('icon-button') &&
            document.querySelector('div.dropdown-menu') === null
        );
    }

    function activateMastodonTranslate() {
        document.querySelector('body').addEventListener('click', function(event) {
            if (chromeClickChecker(event) || firefoxClickChecker(event)) {
                // Get the status for this event
                var status = event.target.parentNode.parentNode.parentNode.parentNode.parentNode;
                addTranslateLink(status);
            }
        }, false);
    }

    // Launch Script
    console.log(`Translate Script v${GM.info.script.version} Activating...`);
    window.addEventListener("load", function() {
        if (window.innerWidth > 630) {
            // Checks we're on a mastodon instance
            var settingsEl = document.querySelector('a.drawer__tab[title="Preferences"]');
            var settingsUrl = settingsEl.getAttribute('href');
            if (settingsUrl === '/settings/preferences') {
                activateMastodonTranslate();
            } else {
                // Probably on the mastofe of pleroma or something
            }
        } else {
            console.log('Sorry, desktop only');
        }
    }, false);

    if (window.location.pathname === '/settings/preferences') {
        // We're on the settings page
        var form = document.querySelector('form.simple_form');
        var actions = document.querySelector('div.actions');

        var settingsGroup = form.querySelector('div.fields-group').cloneNode(true);
        settingsGroup.children[1].remove(); // Remove the posting language
        settingsGroup.children[1].remove(); // Remove the filtered language

        var notice = document.createElement('div');
        var noticeMsg = 'Translation is currently provided by Google Translate, if you\'re not happy with this please don\'t check the checkbox below or just uninstall the script. I\'m looking to offer alternatives to Google which you can track here: https://github.com/tomouchuu/mastodon-translate/issues/6';
        noticeMsg += '
If you have an issue please give me a buzz @tomo@niu.moe via mastodon or raise an issue on Github';
        notice.setAttribute('id', 'translation_notice');
        notice.innerHTML = '
Tampermonkey Translation Script

'+noticeMsg+'
';

        var toggle = document.createElement('div');
        toggle.classList.add('input');
        toggle.classList.add('boolean');
        toggle.classList.add('optional');
        toggle.classList.add('user_translation_enabled');
        toggle.innerHTML = '
<input value="0" type="hidden" name="user[translation_enabled]"><input class="boolean optional" type="checkbox" value="1" name="user[translation_enabled]" id="user_translation_enabled">I\'m happy to use Google Translate
';
        var checkbox = toggle.querySelector('input#user_translation_enabled');
        checkbox.checked = (localStorage.getItem('toggle') == 'true');

        var languageDiv = settingsGroup.children[0];
        languageDiv.classList.remove('user_locale');
        languageDiv.classList.add('translation_locale');
        var label = languageDiv.children[0].children[0];
        label.setAttribute('for', 'translation_locale');
        label.textContent = 'Translation Language';
        var input = languageDiv.children[0].children[1];
        input.setAttribute('name', 'user[translation]');
        input.setAttribute('id', 'translation_locale');
        input.value = localStorage.getItem('lang');
        languageDiv.children[1].textContent = 'The language to translate toots into';

        settingsGroup.insertBefore(notice, languageDiv);
        settingsGroup.insertBefore(toggle, languageDiv);

        form.insertBefore(settingsGroup, actions.nextSibling);

        document.querySelector('body').addEventListener('click', saveSettings, false);
    }
})();<|endoftext|>


<commit_before>// This file is part of the Kate project within KDE.
// (C) 2013 Dominik Haumann <dhaumann kde org>
// License: LGPL v2 or v3

require("cursor.js");

function DocumentCursor(doc, lineOrCursor, column) {

  if (arguments.length === 1) {
    if (doc instanceof DocumentCursor) {
      return doc.clone();
    } else {
      this.document = doc;
      this.line = 0;
      this.column = 0;
    }
  } else if (arguments.length === 2 && typeof lineOrCursor == "object") {
    this.document = doc;
    this.line = lineOrCursor.line;
    this.column = lineOrCursor.column;
  } else if (arguments.length === 3 && typeof lineOrCursor == "number"
                                    && typeof column == "number") {
    this.document = doc;
    this.line = parseInt(lineOrCursor, 10);
    this.column = parseInt(column, 10);
  } else {
    throw "Wrong usage of DocumentCursor constructor";
  }
}

DocumentCursor.prototype.clone = function() {
  return new DocumentCursor(this.document, this.line, this.column);
}

DocumentCursor.prototype.setPosition = function(line, column) {
  this.line = line;
  this.column = column;
}

DocumentCursor.prototype.isValid = function() {
  return (this.line >= 0) && (this.column >= 0);
}

DocumentCursor.prototype.compareTo = function(other) {
  if (this.line > other.line || (this.line === other.line && this.column > other.column)) {
    return 1;
  }
  if (this.line < other.line || (this.line === other.line && this.column < other.column)) {
    return -1;
  }
  return 0;
}

DocumentCursor.prototype.equals = function(other) {
  return (this.document === other.document && this.line === other.line && this.column === other.column);
}

DocumentCursor.prototype.toString = function() {
  if (this.isValid()) {
    return "DocumentCursor(" + this.line+ "," + this.column+ ")";
  } else {
    return "DocumentCursor()";
  }
}

DocumentCursor.invalid = function(doc) {
  return new DocumentCursor(doc, -1, -1);
}

DocumentCursor.prototype.isValidTextPosition = function() {
  return this.isValid() && this.line < this.document.lines() && this.column <= this.document.lineLength(this.line);
}

DocumentCursor.prototype.atStartOfLine = function() {
  return this.isValidTextPosition() && this.column === 0;
}

DocumentCursor.prototype.atEndOfLine = function() {
  return this.isValidTextPosition() && this.column === this.document.lineLength(this.line);
}

DocumentCursor.prototype.atStartOfDocument = function() {
  return this.line === 0 && this.column === 0;
}

DocumentCursor.prototype.atEndOfDocument = function() {
  return this.isValid() && (this.line === this.document.lines() - 1) && this.column === this.document.lineLength(this.line);
}

DocumentCursor.prototype.gotoNextLine = function() {
  var ok = this.isValid() && (this.line + 1 < this.document.lines());
  if (ok) {
    this.line = this.line + 1;
    this.column = 0;
  }
  return ok;
}

DocumentCursor.prototype.gotoPreviousLine = function() {
  var ok = this.line > 0 && this.column >= 0;
  if (ok) {
    this.line = this.line - 1;
    this.column = 0;
  }
  return ok;
}

DocumentCursor.prototype.move = function(nChars, wrapAtEol) {
  // validity checks
  if (typeof wrapAtEol != "boolean") {
    wrapAtEol = true;
  }

  if (!this.isValid()) {
    return false;
  }

  var c = new Cursor(this.line, this.column);

  // cache lineLength to minimize calls of KateDocument::lineLength(), as
  // results in locating the correct block in the text buffer every time,
  // which is relatively slow
  var lineLength = this.document.lineLength(c.line);

  // special case: cursor position is not in valid text, then the algo does
  // not work for Wrap mode. Hence, catch this special case by setting
  // c.column() to the lineLength()
  if (nChars > 0 && wrapAtEol && c.column > lineLength) {
    c.column = lineLength;
  }

  while (nChars !== 0) {
    if (nChars > 0) {
      if (wrapAtEol) {
        var advance = Math.min(lineLength - c.column, nChars);

        if (nChars > advance) {
          if (c.line + 1 >= this.document.lines()) {
            return false;
          }

          c.line += 1;
          c.column = 0;
          nChars -= advance + 1; // +1 because of end-of-line wrap

          // advanced one line, so cache correct line length again
          lineLength = this.document.lineLength(c.line);
        } else {
          c.column += nChars;
          nChars = 0;
        }
      } else { // NoWrap
        c.column = c.column + nChars;
        nChars = 0;
      }
    } else {
      var back = Math.min(c.column, -nChars);
      if (-nChars > back) {
        if (c.line === 0) {
          return false;
        }

        c.line -= 1;
        lineLength = this.document.lineLength(c.line);
        c.column = lineLength;
        nChars += back + 1; // +1 because of wrap-around at start-of-line
      } else {
        c.column += nChars;
        nChars = 0;
      }
    }
  }

  this.line = c.line;
  this.column = c.column;
  return true;
}

DocumentCursor.prototype.toCursor = function() {
  return new Cursor(this.line, this.column);
}

// kate: indent-width 2; replace-tabs on;
<commit_msg>add DocumentCursor.toVirtualCursor()<commit_after>// This file is part of the Kate project within KDE.
// (C) 2013 Dominik Haumann <dhaumann kde org>
// License: LGPL v2 or v3

require("cursor.js");

function DocumentCursor(doc, lineOrCursor, column) {

  if (arguments.length === 1) {
    if (doc instanceof DocumentCursor) {
      return doc.clone();
    } else {
      this.document = doc;
      this.line = 0;
      this.column = 0;
    }
  } else if (arguments.length === 2 && typeof lineOrCursor == "object") {
    this.document = doc;
    this.line = lineOrCursor.line;
    this.column = lineOrCursor.column;
  } else if (arguments.length === 3 && typeof lineOrCursor == "number"
                                    && typeof column == "number") {
    this.document = doc;
    this.line = parseInt(lineOrCursor, 10);
    this.column = parseInt(column, 10);
  } else {
    throw "Wrong usage of DocumentCursor constructor";
  }
}

DocumentCursor.prototype.clone = function() {
  return new DocumentCursor(this.document, this.line, this.column);
}

DocumentCursor.prototype.setPosition = function(line, column) {
  this.line = line;
  this.column = column;
}

DocumentCursor.prototype.isValid = function() {
  return (this.line >= 0) && (this.column >= 0);
}

DocumentCursor.prototype.compareTo = function(other) {
  if (this.line > other.line || (this.line === other.line && this.column > other.column)) {
    return 1;
  }
  if (this.line < other.line || (this.line === other.line && this.column < other.column)) {
    return -1;
  }
  return 0;
}

DocumentCursor.prototype.equals = function(other) {
  return (this.document === other.document && this.line === other.line && this.column === other.column);
}

DocumentCursor.prototype.toString = function() {
  if (this.isValid()) {
    return "DocumentCursor(" + this.line+ "," + this.column+ ")";
  } else {
    return "DocumentCursor()";
  }
}

DocumentCursor.invalid = function(doc) {
  return new DocumentCursor(doc, -1, -1);
}

DocumentCursor.prototype.isValidTextPosition = function() {
  return this.isValid() && this.line < this.document.lines() && this.column <= this.document.lineLength(this.line);
}

DocumentCursor.prototype.atStartOfLine = function() {
  return this.isValidTextPosition() && this.column === 0;
}

DocumentCursor.prototype.atEndOfLine = function() {
  return this.isValidTextPosition() && this.column === this.document.lineLength(this.line);
}

DocumentCursor.prototype.atStartOfDocument = function() {
  return this.line === 0 && this.column === 0;
}

DocumentCursor.prototype.atEndOfDocument = function() {
  return this.isValid() && (this.line === this.document.lines() - 1) && this.column === this.document.lineLength(this.line);
}

DocumentCursor.prototype.gotoNextLine = function() {
  var ok = this.isValid() && (this.line + 1 < this.document.lines());
  if (ok) {
    this.line = this.line + 1;
    this.column = 0;
  }
  return ok;
}

DocumentCursor.prototype.gotoPreviousLine = function() {
  var ok = this.line > 0 && this.column >= 0;
  if (ok) {
    this.line = this.line - 1;
    this.column = 0;
  }
  return ok;
}

DocumentCursor.prototype.move = function(nChars, wrapAtEol) {
  // validity checks
  if (typeof wrapAtEol != "boolean") {
    wrapAtEol = true;
  }

  if (!this.isValid()) {
    return false;
  }

  var c = new Cursor(this.line, this.column);

  // cache lineLength to minimize calls of KateDocument::lineLength(), as
  // results in locating the correct block in the text buffer every time,
  // which is relatively slow
  var lineLength = this.document.lineLength(c.line);

  // special case: cursor position is not in valid text, then the algo does
  // not work for Wrap mode. Hence, catch this special case by setting
  // c.column() to the lineLength()
  if (nChars > 0 && wrapAtEol && c.column > lineLength) {
    c.column = lineLength;
  }

  while (nChars !== 0) {
    if (nChars > 0) {
      if (wrapAtEol) {
        var advance = Math.min(lineLength - c.column, nChars);

        if (nChars > advance) {
          if (c.line + 1 >= this.document.lines()) {
            return false;
          }

          c.line += 1;
          c.column = 0;
          nChars -= advance + 1; // +1 because of end-of-line wrap

          // advanced one line, so cache correct line length again
          lineLength = this.document.lineLength(c.line);
        } else {
          c.column += nChars;
          nChars = 0;
        }
      } else { // NoWrap
        c.column = c.column + nChars;
        nChars = 0;
      }
    } else {
      var back = Math.min(c.column, -nChars);
      if (-nChars > back) {
        if (c.line === 0) {
          return false;
        }

        c.line -= 1;
        lineLength = this.document.lineLength(c.line);
        c.column = lineLength;
        nChars += back + 1; // +1 because of wrap-around at start-of-line
      } else {
        c.column += nChars;
        nChars = 0;
      }
    }
  }

  this.line = c.line;
  this.column = c.column;
  return true;
}

DocumentCursor.prototype.toCursor = function() {
  return new Cursor(this.line, this.column);
}

DocumentCursor.prototype.toVirtualCursor = function() {
  return document.toVirtualCursor(this);
}

// kate: indent-width 2; replace-tabs on;
<|endoftext|>


<commit_before>// RequirementUpload class

'use strict';

var Map              = require('es6-map')
  , memoize          = require('memoizee/plain')
  , defineStringLine = require('dbjs-ext/string/string-line')
  , _                = require('mano').i18n.bind('Model: Submissions')
  , defineDocument   = require('./document');

module.exports = memoize(function (db) {
	var StringLine = defineStringLine(db)
	  , Document = defineDocument(db);

	// Enum for document upload status
	var RequirementUploadStatus = StringLine.createEnum('DocumentUploadStatus', new Map([
		['valid', {
			label: _("Valid")
		}],
		['invalid', {
			label: _("Invalid")
		}]
	]));

	// Enum for document upload reject reasn
	var RequirementUploadRejectReason = StringLine.createEnum('DocumentUploadRejectReason', new Map([
		["illegible", {
			label: _("The document is unreadable")
		}],
		["invalid", {
			label: _("The loaded document does not match the required document")
		}],
		["other", {
			label: _("Other") + "..."
		}]
	]));

	return db.Object.extend('RequirementUpload', {
		// Document which we upload
		document: { type: Document, nested: true },
		// Verification status of upload
		status: { type: RequirementUploadStatus, required: true },

		// Eventual rejection details
		rejectReasonTypes: { type: RequirementUploadRejectReason, multiple: true, required: true },
		rejectReasonMemo: { type: db.String, required: true, label: _("Explanation") },
		rejectReasons: { type: db.String, multiple: true, required: true,
			value: function () {
				var result = [], isInvalid = false;
				if (!this.rejectReasonTypes.size) return null;
				this.rejectReasonTypes.forEach(function (type) {
					if (type === 'other') {
						if (!this.rejectReasonMemo) {
							isInvalid = true;
							return;
						}
						result.push(this.rejectReasonMemo);
						return;
					}
					result.push(this.database.RejectReason.meta[type].label);
				}, this);
				if (isInvalid) return null;
				return result;
			}, selectField: 'rejectReasonType', otherField: 'rejectReasonMemo' },

		// Whether document upload was validated and all required properties
		// where provided
		// Returns null if validation is not complete, true if complete and valid,
		// false if complete and invalid
		isApproved: { type: db.Boolean, value: function () {
			if (this.status == null) return null;
			if (this.status === 'valid') {
				if (this.document.dataForm.progress !== 1) return null;
				return true;
			}
			if (this.rejectReason == null) return null;
			return false;
		} },

		// Wether uploaded documents should be verified at front-desk at certificates reception
		validateWithOriginal: { type: db.Boolean, value: true },

		// Whether uploaded files matches original document (decided at last front-desk processing step)
		matchesOriginal: { type: db.Boolean, required: true }
	});
}, { normalizer: require('memoizee/normalizers/get-1')() });
<commit_msg>-- whitespace<commit_after>// RequirementUpload class

'use strict';

var Map              = require('es6-map')
  , memoize          = require('memoizee/plain')
  , defineStringLine = require('dbjs-ext/string/string-line')
  , defineCreateEnum = require('dbjs-ext/create-enum')
  , _                = require('mano').i18n.bind('Model')
  , defineDocument   = require('./document');

module.exports = memoize(function (db) {
	var StringLine = defineStringLine(db)
	  , Document = defineDocument(db);

	defineCreateEnum(db);

	// Enum for document upload status
	var RequirementUploadStatus = StringLine.createEnum('DocumentUploadStatus', new Map([
		['valid', { label: _("Valid") }],
		['invalid', { label: _("Invalid") }]
	]));

	// Enum for document upload reject reasn
	var RequirementUploadRejectReason = StringLine.createEnum('DocumentUploadRejectReason', new Map([
		["illegible", { label: _("The document is unreadable") }],
		["invalid", { label: _("The loaded document does not match the required document") }],
		["other", { label: _("Other...") }]
	]));

	return db.Object.extend('RequirementUpload', {
		// Document which we upload
		document: { type: Document, nested: true },
		// Verification status of upload
		status: { type: RequirementUploadStatus, required: true },

		// Eventual rejection details
		rejectReasonTypes: { type: RequirementUploadRejectReason, multiple: true, required: true },
		rejectReasonMemo: { type: db.String, required: true, label: _("Explanation") },
		rejectReasons: { type: db.String, multiple: true, required: true,
			value: function () {
				var result = [], isInvalid = false;
				if (!this.rejectReasonTypes.size) return null;
				this.rejectReasonTypes.forEach(function (type) {
					if (type === 'other') {
						if (!this.rejectReasonMemo) {
							isInvalid = true;
							return;
						}
						result.push(this.rejectReasonMemo);
						return;
					}
					result.push(this.database.RejectReason.meta[type].label);
				}, this);
				if (isInvalid) return null;
				return result;
			}, selectField: 'rejectReasonType', otherField: 'rejectReasonMemo' },

		// Whether document upload was validated and all required properties
		// where provided
		// Returns null if validation is not complete, true if complete and valid,
		// false if complete and invalid
		isApproved: { type: db.Boolean, value: function () {
			if (this.status == null) return null;
			if (this.status === 'valid') {
				if (this.document.dataForm.progress !== 1) return null;
				return true;
			}
			if (this.rejectReason == null) return null;
			return false;
		} },

		// Wether uploaded documents should be verified at front-desk at certificates reception
		validateWithOriginal: { type: db.Boolean, value: true },

		// Whether uploaded files matches original document (decided at last front-desk processing step)
		matchesOriginal: { type: db.Boolean, required: true }
	});
}, { normalizer: require('memoizee/normalizers/get-1')() });
<|endoftext|>


<commit_before>var exec = require('../lib/exec'),
    fs = require('fs'),
    sourceMap = require('source-map');

describe('exec', function() {
  beforeEach(function() {
    var self = this;
    this.stub(fs, 'readFileSync', function(name) {
      return name;
    });
    this.stub(sourceMap, 'SourceMapConsumer', function(name) {
      if (/baz/.test(name)) {
        throw new Error();
      }

      this.originalPositionFor = self.spy(function(pos) {
        return {source: 'new' + name, line: pos.line+10, column: pos.column+10};
      });
    });
  });
  afterEach(function() {
    require('../lib/exec/source-map').reset();
  });

  describe('#rewriteStack', function() {
    it('should remap matched lines', function() {
      exec.rewriteStack(
          'Foo\n'
          + ' at functionName (foo/bar:10:20)\n'
          + ' at foo/fruit-loops/lib/bar\n'
          + ' at foo/fruit-loops/lib/bak\n'
          + ' at baz/bat\n'
        ).should.equal(
          'Foo\n'
          + '  at functionName (newfoo/bar.map:20:30)\n'
          + '  at (native)\n'
          + '  at (baz/bat)\n');

      fs.readFileSync.should
          .have.been.calledWith('foo/bar.map')
          .have.been.calledWith('baz/bat.map');
    });

    it('should handle array input', function() {
      exec.rewriteStack([
          'Foo',
          ' at functionName (foo/bar:10:20)',
          ' at foo/fruit-loops/lib/bar',
          ' at foo/fruit-loops/lib/bak',
          ' at baz/bat'
        ]).should.equal(
          'Foo\n'
          + '  at functionName (newfoo/bar.map:20:30)\n'
          + '  at (native)\n'
          + '  at (baz/bat)\n');

      fs.readFileSync.should
          .have.been.calledWith('foo/bar.map')
          .have.been.calledWith('baz/bat.map');
    });
  });
});
<commit_msg>Implement exec tests<commit_after>var exec = require('../lib/exec'),
    fs = require('fs'),
    sourceMap = require('source-map');

describe('exec', function() {
  beforeEach(function() {
    var self = this;
    this.stub(fs, 'readFileSync', function(name) {
      if (/^new/.test(name)) {
        return 'Line 1\nLine 2\nLine 3\nLine 4\nLine 5';
      } else {
        return name;
      }
    });
    this.stub(sourceMap, 'SourceMapConsumer', function(name) {
      if (/baz/.test(name)) {
        throw new Error();
      }

      this.originalPositionFor = self.spy(function(pos) {
        if (/exec.js/.test(name)) {
          return {source: 'new' + name, line: 2, column: pos.column+10};
        } else {
          return {source: 'new' + name, line: pos.line+10, column: pos.column+10};
        }
      });
    });
  });
  afterEach(function() {
    require('../lib/exec/source-map').reset();
  });

  describe('#exec', function() {
    it('should include error context', function() {
      try {
        exec.exec(function() {
          throw new Error();
        });
      } catch (err) {
        err.stack.should.match(/\t     1:  Line 1\n\t     2:> Line 2\n\t     3:  Line 3\n\t     4:  Line 4\n\t     5:  Line 5\n\n/);
      }
    });

    it('should rewriteStack', function() {
      try {
        exec.exec(function() {
          throw new Error();
        });
      } catch (err) {
        err.stack.should.match(/at \(new.*?exec.js.map.*?\)\n  at \(native\)\n/);
      }
    });
    it('should rewriteStack once', function() {
      try {
        exec.exec(function() {
          exec.exec(function() {
            throw new Error();
          });
        });
      } catch (err) {
        err.stack.should.match(/at \(new.*?exec.js.map.*?\)\n  at \(native\)\n/);
      }
    });
  });

  describe('#rewriteStack', function() {
    it('should remap matched lines', function() {
      exec.rewriteStack(
          'Foo\n'
          + ' at functionName (foo/bar:10:20)\n'
          + ' at foo/fruit-loops/lib/bar\n'
          + ' at foo/fruit-loops/lib/bak\n'
          + ' at baz/bat\n'
        ).should.equal(
          'Foo\n'
          + '  at functionName (newfoo/bar.map:20:30)\n'
          + '  at (native)\n'
          + '  at (baz/bat)\n');

      fs.readFileSync.should
          .have.been.calledWith('foo/bar.map')
          .have.been.calledWith('baz/bat.map');
    });

    it('should handle array input', function() {
      exec.rewriteStack([
          'Foo',
          ' at functionName (foo/bar:10:20)',
          ' at foo/fruit-loops/lib/bar',
          ' at foo/fruit-loops/lib/bak',
          ' at baz/bat'
        ]).should.equal(
          'Foo\n'
          + '  at functionName (newfoo/bar.map:20:30)\n'
          + '  at (native)\n'
          + '  at (baz/bat)\n');

      fs.readFileSync.should
          .have.been.calledWith('foo/bar.map')
          .have.been.calledWith('baz/bat.map');
    });
  });
});
<|endoftext|>


<commit_before>const React = require('react');
const h = require('react-hyperscript');
const classNames = require('classnames');

const INTERACTION_TYPES = {
  BINDING: 'Binding',
  PHOSPHORYLATION: 'Phosphorylation',
  EXPRESSION: 'Expression'
};

class InteractionsMenu extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      Binding: true,
      Phosphorylation: true,
      Expression: true
    };
  }

  toggleIntnType(type){
    let { cySrv } = this.props;
    let cy = cySrv.get();
    let edges = cy.edges(`.${type}`);
    let nodes = edges.connectedNodes();

    let nodeHasNoVisibleEdges = node => node.connectedEdges().every( edge => edge.hasClass('type-hidden') || edge.hasClass('metric-hidden'));

    if( this.state[type] ){
      edges.addClass('type-hidden');
      nodes.filter( nodeHasNoVisibleEdges ).addClass('type-hidden');
    } else {
      nodes.removeClass('type-hidden');
      edges.removeClass('type-hidden');
    }

    this.setState({[type]: !this.state[type] });
  }

  handleSliderChange(){
    let cy = this.props.cySrv.get();
    let metricCutoff = this.slider.value;

    let nodeHasNoVisibleEdges = node => node.connectedEdges().every( edge => edge.hasClass('type-hidden') || edge.hasClass('metric-hidden'));

    let nodesToHide = cy.nodes().sort( (n0, n1) => n0.data('metric') - n1.data('metric') ).slice(0, metricCutoff);
    let elesToHide = nodesToHide.union(nodesToHide.connectedEdges()).union(cy.nodes().filter( nodeHasNoVisibleEdges ));

    elesToHide.addClass('metric-hidden');
    cy.elements().difference(elesToHide).removeClass('metric-hidden');
  }

  render(){
    let { cySrv } = this.props;
    let { Binding, Expression, Phosphorylation } = this.state;
    let cy = cySrv.get();

    let hasType = (cy, type) => cy.edges(`.${type}`).length > 0;
    let { BINDING, PHOSPHORYLATION, EXPRESSION } = INTERACTION_TYPES;

    let hasPhosphorylations = hasType(cy, PHOSPHORYLATION);
    let hasExpressions = hasType(cy, EXPRESSION);
    let hasBindings = hasType(cy, BINDING);

    let InteractionToggleButton = props => {
      let { type, active } = props;
      return h('div', {
        onClick: () =>  this.toggleIntnType(type),
        className: classNames('interaction-filter-button', active ? 'interaction-filter-active' : 'interaction-filter-not-active'),

      }, [
        h('div', { className: classNames('interaction-filter-legend', { [type]: active } ) } ),
        h('h4.button-label', type)
      ]);
    };

    return h('div', [
      h('h3', 'Interaction Filters'),
      hasPhosphorylations ? h(InteractionToggleButton, { type: PHOSPHORYLATION, active: Phosphorylation }) : null,
      hasBindings ? h(InteractionToggleButton, { type: BINDING, active: Binding }) : null,
      hasExpressions ? h(InteractionToggleButton, { type: EXPRESSION, active: Expression }) : null,
      h('h3', 'Visible Entities'),
      h('input', {
        type: 'range',
        ref: ele => this.slider = ele,
        min: 0,
        max: 49,
        step: 1,
        defaultValue: 35,
        onInput: () => this.handleSliderChange()
       }),
       h('div.slider-bottom', [
         h('span.most', 'More'),
         h('span.least', 'Less')
       ])
    ]);
  }
}

module.exports = InteractionsMenu;<commit_msg>use constant interaction types instead of implicit key matching for interaction menu state<commit_after>const React = require('react');
const h = require('react-hyperscript');
const classNames = require('classnames');

const INTERACTION_TYPES = {
  BINDING: 'Binding',
  PHOSPHORYLATION: 'Phosphorylation',
  EXPRESSION: 'Expression'
};

class InteractionsMenu extends React.Component {
  constructor(props){
    super(props);
    let { BINDING, PHOSPHORYLATION, EXPRESSION } = INTERACTION_TYPES;

    this.state = {
      [BINDING]: true,
      [PHOSPHORYLATION]: true,
      [EXPRESSION]: true
    };
  }

  toggleIntnType(type){
    let { cySrv } = this.props;
    let cy = cySrv.get();
    let edges = cy.edges(`.${type}`);
    let nodes = edges.connectedNodes();

    let nodeHasNoVisibleEdges = node => node.connectedEdges().every( edge => edge.hasClass('type-hidden') || edge.hasClass('metric-hidden'));

    if( this.state[type] ){
      edges.addClass('type-hidden');
      nodes.filter( nodeHasNoVisibleEdges ).addClass('type-hidden');
    } else {
      nodes.removeClass('type-hidden');
      edges.removeClass('type-hidden');
    }

    this.setState({[type]: !this.state[type] });
  }

  handleSliderChange(){
    let cy = this.props.cySrv.get();
    let metricCutoff = this.slider.value;

    let nodeHasNoVisibleEdges = node => node.connectedEdges().every( edge => edge.hasClass('type-hidden') || edge.hasClass('metric-hidden'));

    let nodesToHide = cy.nodes().sort( (n0, n1) => n0.data('metric') - n1.data('metric') ).slice(0, metricCutoff);
    let elesToHide = nodesToHide.union(nodesToHide.connectedEdges()).union(cy.nodes().filter( nodeHasNoVisibleEdges ));

    elesToHide.addClass('metric-hidden');
    cy.elements().difference(elesToHide).removeClass('metric-hidden');
  }

  render(){
    let { cySrv } = this.props;
    let { Binding, Expression, Phosphorylation } = this.state;
    let cy = cySrv.get();

    let hasType = (cy, type) => cy.edges(`.${type}`).length > 0;
    let { BINDING, PHOSPHORYLATION, EXPRESSION } = INTERACTION_TYPES;

    let hasPhosphorylations = hasType(cy, PHOSPHORYLATION);
    let hasExpressions = hasType(cy, EXPRESSION);
    let hasBindings = hasType(cy, BINDING);

    let InteractionToggleButton = props => {
      let { type, active } = props;
      return h('div', {
        onClick: () =>  this.toggleIntnType(type),
        className: classNames('interaction-filter-button', active ? 'interaction-filter-active' : 'interaction-filter-not-active'),

      }, [
        h('div', { className: classNames('interaction-filter-legend', { [type]: active } ) } ),
        h('h4.button-label', type)
      ]);
    };

    return h('div', [
      h('h3', 'Interaction Filters'),
      hasPhosphorylations ? h(InteractionToggleButton, { type: PHOSPHORYLATION, active: Phosphorylation }) : null,
      hasBindings ? h(InteractionToggleButton, { type: BINDING, active: Binding }) : null,
      hasExpressions ? h(InteractionToggleButton, { type: EXPRESSION, active: Expression }) : null,
      h('h3', 'Visible Entities'),
      h('input', {
        type: 'range',
        ref: ele => this.slider = ele,
        min: 0,
        max: 49,
        step: 1,
        defaultValue: 35,
        onInput: () => this.handleSliderChange()
       }),
       h('div.slider-bottom', [
         h('span.most', 'More'),
         h('span.least', 'Less')
       ])
    ]);
  }
}

module.exports = InteractionsMenu;<|endoftext|>


<commit_before>/**
 * ZeroDataStateNotifications component.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * WordPress dependencies
 */
import { Fragment } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
import { MODULES_ANALYTICS } from '../../modules/analytics/datastore/constants';
import { MODULES_SEARCH_CONSOLE } from '../../modules/search-console/datastore/constants';
import BannerNotification from './BannerNotification';
import { getTimeInSeconds } from '../../util';
import ZeroState from '../../../svg/graphics/zero-state-blue.svg';
const { useSelect, useInViewSelect } = Data;

export default function ZeroDataStateNotifications() {
	const isAnalyticsConnected = useSelect( ( select ) =>
		select( CORE_MODULES ).isModuleConnected( 'analytics' )
	);
	const hasAnalyticsZeroData = useInViewSelect( ( select ) =>
		isAnalyticsConnected ? select( MODULES_ANALYTICS ).hasZeroData() : false
	);
	const hasSearchConsoleZeroData = useInViewSelect( ( select ) =>
		select( MODULES_SEARCH_CONSOLE ).hasZeroData()
	);

	return (
		<Fragment>
			{ hasAnalyticsZeroData || hasSearchConsoleZeroData ? (
				<BannerNotification
					id="zero-data-notification"
					title={ __(
						'Not enough traffic yet to display stats',
						'google-site-kit'
					) }
					description={ __(
						'Site Kit will start showing stats on the dashboard as soon as enough people have visited your site. Keep working on your site to attract more visitors.',
						'google-site-kit'
					) }
					format="small"
					learnMoreLabel={ __( 'Learn more', 'google-site-kit' ) }
					learnMoreURL="https://sitekit.withgoogle.com/documentation/using-site-kit/dashboard-data-display/"
					dismiss={ __( 'Remind me later', 'google-site-kit' ) }
					isDismissible={ true }
					dismissExpires={ getTimeInSeconds( 'day' ) }
					SmallImageSVG={ ZeroState }
				/>
			) : null }
		</Fragment>
	);
}
<commit_msg>Rename vars as per the comments.<commit_after>/**
 * ZeroDataStateNotifications component.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * WordPress dependencies
 */
import { Fragment } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
import { MODULES_ANALYTICS } from '../../modules/analytics/datastore/constants';
import { MODULES_SEARCH_CONSOLE } from '../../modules/search-console/datastore/constants';
import BannerNotification from './BannerNotification';
import { getTimeInSeconds } from '../../util';
import ZeroState from '../../../svg/graphics/zero-state-blue.svg';
const { useSelect, useInViewSelect } = Data;

export default function ZeroDataStateNotifications() {
	const isAnalyticsConnected = useSelect( ( select ) =>
		select( CORE_MODULES ).isModuleConnected( 'analytics' )
	);
	const analyticsHasZeroData = useInViewSelect( ( select ) =>
		isAnalyticsConnected ? select( MODULES_ANALYTICS ).hasZeroData() : false
	);
	const searchConsoleHasZeroData = useInViewSelect( ( select ) =>
		select( MODULES_SEARCH_CONSOLE ).hasZeroData()
	);

	return (
		<Fragment>
			{ analyticsHasZeroData || searchConsoleHasZeroData ? (
				<BannerNotification
					id="zero-data-notification"
					title={ __(
						'Not enough traffic yet to display stats',
						'google-site-kit'
					) }
					description={ __(
						'Site Kit will start showing stats on the dashboard as soon as enough people have visited your site. Keep working on your site to attract more visitors.',
						'google-site-kit'
					) }
					format="small"
					learnMoreLabel={ __( 'Learn more', 'google-site-kit' ) }
					learnMoreURL="https://sitekit.withgoogle.com/documentation/using-site-kit/dashboard-data-display/"
					dismiss={ __( 'Remind me later', 'google-site-kit' ) }
					isDismissible={ true }
					dismissExpires={ getTimeInSeconds( 'day' ) }
					SmallImageSVG={ ZeroState }
				/>
			) : null }
		</Fragment>
	);
}
<|endoftext|>