<commit_before>define(function(require) {
    "use strict";
    var $ = require('jquery');
    var ui = require('jquery-ui');
    var dialog = require('base/js/dialog');
    var lmod_class = require('./lmod');
    var utils = require('base/js/utils');

    var base_url = utils.get_body_data("baseUrl");

    var lmod = new lmod_class.Lmod(base_url);
    var search_source = null;

    var server_proxy_infos = {};
    var server_proxy_launcher = {};

    const lmod_tab_html = $([
'
',
'
',
'
',
'            <input id="modules" class="form-control input-lg" placeholder="Search available modules..." style="width:100%">',
'
',
'
',
'
',
'
',
'
Loaded Modules
',
'
',
'
',
'
',
'                        <button class="btn btn-default btn-xs" id="save-button">Save</button>',
'
 ',
'
',
'                        <button class="dropdown-toggle btn btn-default btn-xs" id="restore-buttons" data-toggle="dropdown">',
'                            Restore ',
'                            ',
'                        </button>',
'
',
'
',
'
',
'                        <button class="btn btn-default btn-xs" id="edit-button" title="Edit MODULEPATH"></button>',
'
 ',
'
',
'
',
'
',
'
',
'
',
    ].join('\n'));

    const lmod_list_line = $([
'
',
'
',
'       ',
'
',
'           <button class="btn btn-warning btn-xs">Unload</button>',
'
',
'
',
'
',
    ].join('\n'));

    const save_dialog_body = $([
'
',
'
Enter a new collection name:
',
'
',
'   <input type="text" size="25" class="form-control" placeholder="default">',
'
'
    ].join('\n'));

    const modulepath_dialog_body = $([
        '
',
        '
',
        '        <input id="path_input" class="form-control" placeholder="Enter path here..." style="width:70%;float:left;"">',
        '
',
        '            <button class="btn btn-default" id="prepend_path" title="Prepend to MODULEPATH" style="width:50%;float:left;">Prepend </button>',
        '            <button class="btn btn-default" id="append_path" title="Append to MODULEPATH" style="width:50%;float:left;">Append </button>',
        '
',
        '
',
        '
',
        '
',
        '
'
    ].join('\n'));

    async function draw_modulepath_dialog() {
        const paths = await lmod.paths();

        const list = $("#path_list").html("");

        const path_input = $( "#path_input" )
        .on('keyup', function (event) {
            if (event.keyCode == $.ui.keyCode.ENTER) {
                var paths = event.target.value;
                if (paths != '') {
                    lmod.use([paths])
                    .then(draw_modulepath_dialog)
                    .then(refresh_module_ui);
                }
                event.target.value = "";
            }
        })
        .autocomplete({
            minLength: 1,
            source: async function( request, response ) {
                response(await lmod.folders(request.term));
            },
        });

        $( "#prepend_path" ).click(function (e) {
            const path = path_input.val();
            if (path != '') {
                path_input.val('')
                lmod.use([path])
                    .then(draw_modulepath_dialog)
                    .then(refresh_module_ui);
            }
        });
        $( "#append_path" ).click(async function(e) {
            const path = path_input.val();
            if (path != '') {
                path_input.val('')
                lmod.use([path], true)
                    .then(draw_modulepath_dialog)
                    .then(refresh_module_ui);
            }
        });

        var header = $('
')
            .addClass("list_header")
            .addClass("row")
            .appendTo(list);

        var divheader = $('
')
            .addClass("col-sm-8")
            .html("List of paths (decreasing order of priority)")
            .appendTo(header);

        paths.map((item, index) => {
            var row = $('
')
                .addClass("list_item")
                .addClass("row")
                .appendTo(list);

            var div = $("
")
                .addClass("col-md-12")
                .appendTo(row);

            var span = $("")
                .addClass("item_name")
                .html(`${index+1}. `)
                .appendTo(div);

            var link = $("")
                .attr("href", "#path_input")
                .click(function (e) {
                    path_input.val(item);
                })
                .html(item)
                .appendTo(span);

            var divButton = $('
')
                .addClass('item_buttons')
                .addClass('pull-right')
                .appendTo(div);

            var button = $('<button/>')
                .addClass('btn')
                .addClass('btn-danger')
                .addClass('btn-xs')
                .html('')
                .click(e => lmod.unuse([item])
                    .then(draw_modulepath_dialog)
                    .then(refresh_module_ui)
                )
                .appendTo(divButton);
        })
    }

    function edit_paths(event) {
        var d = dialog.modal({
            title: "Edit MODULEPATH",
            body: modulepath_dialog_body,
            keyboard_manager: this.keyboard_manager,
            default_button: "Close",
            buttons : {
                "Close": {}
            },
            open : async function () {
                await draw_modulepath_dialog();
            }
        });
    }

    function save_collection(event) {
        var d = dialog.modal({
            title: "Save Collection",
            body: save_dialog_body,
            keyboard_manager: this.keyboard_manager,
            default_button: "Cancel",
            buttons : {
                "Cancel": {},
                "Save": {
                    class: "btn-primary",
                    click: function () {
                        var name = d.find('input').val();
                        lmod.save(name ? name : 'default').then(refresh_restore_list);
                    }
                }
            },
            open : function () {
                d.find('input[type="text"]').keydown(function (event) {
                    if (event.which === keyboard.keycodes.enter) {
                        d.find('.btn-primary').first().click();
                        return false;
                    }
                });
                d.find('input[type="text"]').focus().select();
            }
        });
    }

    async function refresh_restore_list() {
        const values = await lmod.savelist();
        const list = $("#restore-menu").html("");
        values.map(item => {
            let li = $('
').append($('', {'href': '#', "text" : item}))
                                .click(e => lmod.restore(item).then(refresh_module_ui));
            list.append(li);
        })
    }

    async function refresh_module_ui() {
        const avail_set = new Set(await lmod.avail());
        const modulelist = (await lmod.list()).sort();

        $("#list_header").nextAll().remove();
        const list = $("#lmod_list");

        modulelist.map(item => {
            let li = lmod_list_line.clone();
            li.find('a').text(item).click(e => show_module(item));
            li.find('button').click(e => lmod.unload([item]).then(refresh_module_ui));
            list.append(li);
            avail_set.delete(item)
        });

        refresh_kernel_menu(modulelist);
        search_source = Array.from(avail_set);
    }

    function refresh_kernel_menu(modulelist) {
        $('[id^="kernel-"]').remove();
        IPython.new_notebook_widget.request_kernelspecs()

        let menu = $('.tree-buttons').find('.dropdown-menu');

        for (let server_key in server_proxy_infos) {
            let is_enabled = modulelist.some(module => { return module.toLowerCase().includes(server_key) });
            if (is_enabled) {
                if(!server_proxy_launcher.hasOwnProperty(server_key)) {
                    menu.append(server_proxy_infos[server_key]);
                    server_proxy_launcher[server_key] = $('.new-' + server_key);
                }
            } else if (server_key in server_proxy_launcher) {
                server_proxy_launcher[server_key].remove();
                delete server_proxy_launcher[server_key];
            }
        }
    }

    async function show_module(module) {
        let data = await lmod.show(module);
        let datalist = data.split('\n');
        let textarea = $('
').text($.trim(datalist.slice(3).join('\n')));
        let dialogform = $('
').append(textarea);
        let path = datalist[1].slice(0, -1);
        dialog.modal({
            title: path,
            body: dialogform,
            default_button: "Ok",
            buttons : {
                "Ok" : {}
            }
        });
    }

    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    async function setup_proxy_infos() {
        const response = await fetch(base_url + 'server-proxy/servers-info');
        if (!response.ok) {
            console.log('jupyter-lmod: could not communicate with jupyter-server-proxy API.');
            return;
        }
        const data = await response.json();
        for (let server_process of data.server_processes) {
            /* create our list item */
            let entry_container = $('
')
                .attr('role', 'presentation')
                .addClass('new-' + server_process.name);

            /* create our list item's link */
            let entry_link = $('')
                .attr('role', 'menuitem')
                .attr('tabindex', '-1')
                .attr('href', base_url + server_process.name + '/')
                .attr('target', '_blank')
                .text(server_process.launcher_entry.title);

            entry_container.append(entry_link);
            server_proxy_infos[server_process.name] = entry_container;
        }
    }

    function load() {
        if (!IPython.notebook_list) return;
        $(".tab-content").append(lmod_tab_html);
        $("#edit-button").click(edit_paths);
        $("#save-button").click(save_collection);
        $("#tabs").append(
            $('
')
            .append(
                $('')
                .attr('href', '#lmod')
                .attr('data-toggle', 'tab')
                .text('Softwares')
                .click(function (e) {
                    window.history.pushState(null, null, '#lmod');
                })
            )
        );
        $( "#modules" )
        // don't navigate away from the field on tab when selecting an item
        .on( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).autocomplete( "instance" ).menu.active ) {
              event.preventDefault();
            }
        })
        .on('keyup', function (event) {
            if (event.keyCode == $.ui.keyCode.ENTER) {
                var modules = split($.trim(event.target.value));
                modules.pop();

                lmod.load(modules).then(refresh_module_ui);
                event.target.value = "";
            }
        })
        .autocomplete({
            minLength: 0,
            source: function( request, response ) {
              // delegate back to autocomplete, but extract the last term
              response( $.ui.autocomplete.filter(
                search_source, extractLast( request.term ) ) );
            },
            focus: function() {
              // prevent value inserted on focus
              return false;
            },
            select: function( event, ui ) {
              var terms = split( this.value );
              // remove the current input
              terms.pop();
              // add the selected item
              terms.push( ui.item.value );
              // add placeholder to get the comma-and-space at the end
              terms.push( "" );
              this.value = terms.join( ", " );
              return false;
            }
        });
        setup_proxy_infos();
        refresh_module_ui();
        refresh_restore_list();
    }
    return {
        load_ipython_extension: load
    };
});
<commit_msg>Add reload button for modules and replace text by icons<commit_after>define(function(require) {
    "use strict";
    var $ = require('jquery');
    var ui = require('jquery-ui');
    var dialog = require('base/js/dialog');
    var lmod_class = require('./lmod');
    var utils = require('base/js/utils');

    var base_url = utils.get_body_data("baseUrl");

    var lmod = new lmod_class.Lmod(base_url);
    var search_source = null;

    var server_proxy_infos = {};
    var server_proxy_launcher = {};

    const lmod_tab_html = $([
'
',
'
',
'
',
'            <input id="modules" class="form-control input-lg" placeholder="Search available modules..." style="width:100%">',
'
',
'
',
'
',
'
',
'
Loaded Modules
',
'
',
'
',
'
',
'                        <button class="btn btn-default btn-xs" id="save-button" title="Save current module list to a collection">Save</button>',
'
 ',
'
',
'                        <button class="dropdown-toggle btn btn-default btn-xs" id="restore-buttons" title="Restore modules from a collection" data-toggle="dropdown">',
'                            Restore ',
'                            ',
'                        </button>',
'
',
'
',
'
',
'                        <button class="btn btn-default btn-xs" id="edit-button" title="Edit MODULEPATH"></button>',
'
 ',
'
',
'
',
'
',
'
',
'
',
    ].join('\n'));

    const lmod_list_line = $([
'
',
'
',
'       ',
'
',
'           <button class="btn btn-default btn-xs" id="reload" title="Reload module"></button>',
'           <button class="btn btn-default btn-xs" id="unload" title="Unload module"></button>',
'
',
'
',
'
',
    ].join('\n'));

    const save_dialog_body = $([
'
',
'
Enter a new collection name:
',
'
',
'   <input type="text" size="25" class="form-control" placeholder="default">',
'
'
    ].join('\n'));

    const modulepath_dialog_body = $([
        '
',
        '
',
        '        <input id="path_input" class="form-control" placeholder="Enter path here..." style="width:70%;float:left;"">',
        '
',
        '            <button class="btn btn-default" id="prepend_path" title="Prepend to MODULEPATH" style="width:50%;float:left;">Prepend </button>',
        '            <button class="btn btn-default" id="append_path" title="Append to MODULEPATH" style="width:50%;float:left;">Append </button>',
        '
',
        '
',
        '
',
        '
',
        '
'
    ].join('\n'));

    async function draw_modulepath_dialog() {
        const paths = await lmod.paths();

        const list = $("#path_list").html("");

        const path_input = $( "#path_input" )
        .on('keyup', function (event) {
            if (event.keyCode == $.ui.keyCode.ENTER) {
                var paths = event.target.value;
                if (paths != '') {
                    lmod.use([paths])
                    .then(draw_modulepath_dialog)
                    .then(refresh_module_ui);
                }
                event.target.value = "";
            }
        })
        .autocomplete({
            minLength: 1,
            source: async function( request, response ) {
                response(await lmod.folders(request.term));
            },
        });

        $( "#prepend_path" ).click(function (e) {
            const path = path_input.val();
            if (path != '') {
                path_input.val('')
                lmod.use([path])
                    .then(draw_modulepath_dialog)
                    .then(refresh_module_ui);
            }
        });
        $( "#append_path" ).click(async function(e) {
            const path = path_input.val();
            if (path != '') {
                path_input.val('')
                lmod.use([path], true)
                    .then(draw_modulepath_dialog)
                    .then(refresh_module_ui);
            }
        });

        var header = $('
')
            .addClass("list_header")
            .addClass("row")
            .appendTo(list);

        var divheader = $('
')
            .addClass("col-sm-8")
            .html("List of paths (decreasing order of priority)")
            .appendTo(header);

        paths.map((item, index) => {
            var row = $('
')
                .addClass("list_item")
                .addClass("row")
                .appendTo(list);

            var div = $("
")
                .addClass("col-md-12")
                .appendTo(row);

            var span = $("")
                .addClass("item_name")
                .html(`${index+1}. `)
                .appendTo(div);

            var link = $("")
                .attr("href", "#path_input")
                .click(function (e) {
                    path_input.val(item);
                })
                .html(item)
                .appendTo(span);

            var divButton = $('
')
                .addClass('item_buttons')
                .addClass('pull-right')
                .appendTo(div);

            var button = $('<button/>')
                .addClass('btn')
                .addClass('btn-danger')
                .addClass('btn-xs')
                .attr("title", "Remove from MODULEPATH")
                .html('')
                .click(e => lmod.unuse([item])
                    .then(draw_modulepath_dialog)
                    .then(refresh_module_ui)
                )
                .appendTo(divButton);
        })
    }

    function edit_paths(event) {
        var d = dialog.modal({
            title: "Edit MODULEPATH",
            body: modulepath_dialog_body,
            keyboard_manager: this.keyboard_manager,
            default_button: "Close",
            buttons : {
                "Close": {}
            },
            open : async function () {
                await draw_modulepath_dialog();
            }
        });
    }

    function save_collection(event) {
        var d = dialog.modal({
            title: "Save Collection",
            body: save_dialog_body,
            keyboard_manager: this.keyboard_manager,
            default_button: "Cancel",
            buttons : {
                "Cancel": {},
                "Save": {
                    class: "btn-primary",
                    click: function () {
                        var name = d.find('input').val();
                        lmod.save(name ? name : 'default').then(refresh_restore_list);
                    }
                }
            },
            open : function () {
                d.find('input[type="text"]').keydown(function (event) {
                    if (event.which === keyboard.keycodes.enter) {
                        d.find('.btn-primary').first().click();
                        return false;
                    }
                });
                d.find('input[type="text"]').focus().select();
            }
        });
    }

    async function refresh_restore_list() {
        const values = await lmod.savelist();
        const list = $("#restore-menu").html("");
        values.map(item => {
            let li = $('
').append($('', {'href': '#', "text" : item}))
                                .click(e => lmod.restore(item).then(refresh_module_ui));
            list.append(li);
        })
    }

    async function refresh_module_ui() {
        const avail_set = new Set(await lmod.avail());
        const modulelist = (await lmod.list()).sort();

        $("#list_header").nextAll().remove();
        const list = $("#lmod_list");

        modulelist.map(item => {
            let li = lmod_list_line.clone();
            li.find('a').text(item).click(e => show_module(item));
            li.find('#reload').click(e => lmod.load([item]).then(refresh_module_ui));
            li.find('#unload').click(e => lmod.unload([item]).then(refresh_module_ui));
            list.append(li);
            avail_set.delete(item)
        });

        refresh_kernel_menu(modulelist);
        search_source = Array.from(avail_set);
    }

    function refresh_kernel_menu(modulelist) {
        $('[id^="kernel-"]').remove();
        IPython.new_notebook_widget.request_kernelspecs()

        let menu = $('.tree-buttons').find('.dropdown-menu');

        for (let server_key in server_proxy_infos) {
            let is_enabled = modulelist.some(module => { return module.toLowerCase().includes(server_key) });
            if (is_enabled) {
                if(!server_proxy_launcher.hasOwnProperty(server_key)) {
                    menu.append(server_proxy_infos[server_key]);
                    server_proxy_launcher[server_key] = $('.new-' + server_key);
                }
            } else if (server_key in server_proxy_launcher) {
                server_proxy_launcher[server_key].remove();
                delete server_proxy_launcher[server_key];
            }
        }
    }

    async function show_module(module) {
        let data = await lmod.show(module);
        let datalist = data.split('\n');
        let textarea = $('
').text($.trim(datalist.slice(3).join('\n')));
        let dialogform = $('
').append(textarea);
        let path = datalist[1].slice(0, -1);
        dialog.modal({
            title: path,
            body: dialogform,
            default_button: "Ok",
            buttons : {
                "Ok" : {}
            }
        });
    }

    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    async function setup_proxy_infos() {
        const response = await fetch(base_url + 'server-proxy/servers-info');
        if (!response.ok) {
            console.log('jupyter-lmod: could not communicate with jupyter-server-proxy API.');
            return;
        }
        const data = await response.json();
        for (let server_process of data.server_processes) {
            /* create our list item */
            let entry_container = $('
')
                .attr('role', 'presentation')
                .addClass('new-' + server_process.name);

            /* create our list item's link */
            let entry_link = $('')
                .attr('role', 'menuitem')
                .attr('tabindex', '-1')
                .attr('href', base_url + server_process.name + '/')
                .attr('target', '_blank')
                .text(server_process.launcher_entry.title);

            entry_container.append(entry_link);
            server_proxy_infos[server_process.name] = entry_container;
        }
    }

    function load() {
        if (!IPython.notebook_list) return;
        $(".tab-content").append(lmod_tab_html);
        $("#edit-button").click(edit_paths);
        $("#save-button").click(save_collection);
        $("#tabs").append(
            $('
')
            .append(
                $('')
                .attr('href', '#lmod')
                .attr('data-toggle', 'tab')
                .text('Softwares')
                .click(function (e) {
                    window.history.pushState(null, null, '#lmod');
                })
            )
        );
        $( "#modules" )
        // don't navigate away from the field on tab when selecting an item
        .on( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).autocomplete( "instance" ).menu.active ) {
              event.preventDefault();
            }
        })
        .on('keyup', function (event) {
            if (event.keyCode == $.ui.keyCode.ENTER) {
                var modules = split($.trim(event.target.value));
                modules.pop();

                lmod.load(modules).then(refresh_module_ui);
                event.target.value = "";
            }
        })
        .autocomplete({
            minLength: 0,
            source: function( request, response ) {
              // delegate back to autocomplete, but extract the last term
              response( $.ui.autocomplete.filter(
                search_source, extractLast( request.term ) ) );
            },
            focus: function() {
              // prevent value inserted on focus
              return false;
            },
            select: function( event, ui ) {
              var terms = split( this.value );
              // remove the current input
              terms.pop();
              // add the selected item
              terms.push( ui.item.value );
              // add placeholder to get the comma-and-space at the end
              terms.push( "" );
              this.value = terms.join( ", " );
              return false;
            }
        });
        setup_proxy_infos();
        refresh_module_ui();
        refresh_restore_list();
    }
    return {
        load_ipython_extension: load
    };
});
<|endoftext|>


<commit_before>exports = module.exports = function(IoC, interpreter, translator, unsealer, sealer, logger) {
  var Tokens = require('tokens').Tokens;

  var tokens = new Tokens();

  return Promise.resolve(tokens)
    .then(function(tokens) {
      var components = IoC.components('http://i.bixbyjs.org/tokens/Token');
      return Promise.all(components.map(function(comp) { return comp.create(); } ))
        .then(function(formats) {
          formats.forEach(function(format, i) {
            var type = components[i].a['@type'];
            logger.info('Loaded token type: ' + type);
            tokens.format(type, format)
          });
        })
        .then(function() {
          return tokens;
        });
    })
    .then(function(tokens) {
      // Register token dialects.
      return new Promise(function(resolve, reject) {
        var components = IoC.components('http://i.bixbyjs.org/tokens/Dialect');

        (function iter(i) {
          var component = components[i];
          if (!component) {
            return resolve(tokens);
          }

          component.create()
            .then(function(dialect) {
              logger.info('Loaded token dialect: ' + component.a['@type']);

              tokens.dialect(component.a['@type'], dialect);
              iter(i + 1);
            }, function(err) {
              // TODO: Print the package name in the error, so it can be found
              // TODO: Make the error have the stack of dependencies.
              if (err.code == 'IMPLEMENTATION_NOT_FOUND') {
                logger.notice(err.message + ' while loading component ' + component.id);
                return iter(i + 1);
              }

              reject(err);
            })
        })(0);
      });
    })
    .then(function(tokens) {
      var api = {};

      // TODO: Return tokens directly;
      api.createSerializer = tokens.createSerializer.bind(tokens);
      api.createDeserializer = tokens.createDeserializer.bind(tokens);
      api.createSealer = tokens.createSealer.bind(tokens);
      api.createUnsealer = tokens.createUnsealer.bind(tokens);

      api.seal = function(claims, recipients, options, cb) {
        console.log('SEAL THIS MESSAGE!');
        console.log(claims)

        var type = options.type || 'application/jwt';

        var sealer;
        try {
          sealer = tokens.createSealer(type);
        } catch (ex) {
          return cb(ex);
        }

        sealer.seal(claims, recipients, options, function(err, token) {
          console.log('SEALED IT!');
          console.log(err)
          console.log(token)

          if (err) { return cb(err); }
          return cb(null, token);
        });
      };

      api.unseal = function(token, options, cb) {
        if (typeof options == 'function') {
          cb = options;
          options = undefined;
        }
        options = options || {};

        var unsealer;
        try {
          unsealer = tokens.createUnsealer();
        } catch (ex) {
          return cb(ex);
        }

        unsealer.unseal(token, options, function(err, claims, conditions, issuer) {
          if (err) { return cb(err); }
          return cb(null, claims, conditions, issuer);
        });
      };

      /*
      api.negotiate = function(formats) {
        return negotiator.negotiate(formats);
      }
      */

      api.cipher = function(ctx, options, cb) {
        if (typeof options == 'function') {
          cb = options;
          options = undefined;
        }
        options = options || {};

        translator.translate(ctx, options, function(err, claims) {
          if (err) { return cb(err); }

          // Marshal context necessary for sealing the token.  This includes this
          // that are conceptually "header" information, such as the audience, time
          // of issuance, expiration, etc.
          options.audience = ctx.audience;

          sealer.seal(claims, options, function(err, token) {
            if (err) { return cb(err); }
            return cb(null, token);
          });
        });
      }

      api.decipher = function(token, options, cb) {
        if (typeof options == 'function') {
          cb = options;
          options = undefined;
        }
        options = options || {};

        unsealer.unseal(token, options, function(err, tok) {
          if (err) { return cb(err); }

          interpreter.interpret(tok, options, function(err, sctx) {
            if (err) { return cb(err); }
            return cb(null, sctx, tok);
          });
        });
      }

      return api;
    });
};

exports['@implements'] = 'http://i.bixbyjs.org/tokens';
exports['@singleton'] = true;
exports['@require'] = [
  '!container',
  './interpreter',
  './translator',
  './unsealer',
  './sealer',
  'http://i.bixbyjs.org/Logger'
];
<commit_msg>Remove dead code.<commit_after>exports = module.exports = function(IoC, interpreter, translator, unsealer, sealer, logger) {
  var Tokens = require('tokens').Tokens;

  var tokens = new Tokens();

  return Promise.resolve(tokens)
    .then(function(tokens) {
      var components = IoC.components('http://i.bixbyjs.org/tokens/Token');
      return Promise.all(components.map(function(comp) { return comp.create(); } ))
        .then(function(formats) {
          formats.forEach(function(format, i) {
            var type = components[i].a['@type'];
            logger.info('Loaded token type: ' + type);
            tokens.format(type, format)
          });
        })
        .then(function() {
          return tokens;
        });
    })
    .then(function(tokens) {
      // Register token dialects.
      return new Promise(function(resolve, reject) {
        var components = IoC.components('http://i.bixbyjs.org/tokens/Dialect');

        (function iter(i) {
          var component = components[i];
          if (!component) {
            return resolve(tokens);
          }

          component.create()
            .then(function(dialect) {
              logger.info('Loaded token dialect: ' + component.a['@type']);

              tokens.dialect(component.a['@type'], dialect);
              iter(i + 1);
            }, function(err) {
              // TODO: Print the package name in the error, so it can be found
              // TODO: Make the error have the stack of dependencies.
              if (err.code == 'IMPLEMENTATION_NOT_FOUND') {
                logger.notice(err.message + ' while loading component ' + component.id);
                return iter(i + 1);
              }

              reject(err);
            })
        })(0);
      });
    })
    .then(function(tokens) {
      var api = {};

      // TODO: Return tokens directly;
      api.createSerializer = tokens.createSerializer.bind(tokens);
      api.createDeserializer = tokens.createDeserializer.bind(tokens);
      api.createSealer = tokens.createSealer.bind(tokens);
      api.createUnsealer = tokens.createUnsealer.bind(tokens);

      api.unseal = function(token, options, cb) {
        if (typeof options == 'function') {
          cb = options;
          options = undefined;
        }
        options = options || {};

        var unsealer;
        try {
          unsealer = tokens.createUnsealer();
        } catch (ex) {
          return cb(ex);
        }

        unsealer.unseal(token, options, function(err, claims, conditions, issuer) {
          if (err) { return cb(err); }
          return cb(null, claims, conditions, issuer);
        });
      };

      return api;
    });
};

exports['@implements'] = 'http://i.bixbyjs.org/tokens';
exports['@singleton'] = true;
exports['@require'] = [
  '!container',
  './interpreter',
  './translator',
  './unsealer',
  './sealer',
  'http://i.bixbyjs.org/Logger'
];
<|endoftext|>


<commit_before>var Logger = function($) {

	function Logger() {

	    if (this instanceof Logger) {

	    	var that = this;

			var id = 'web-commons-logger';

			var $box = $('

');
			$box.css('opacity', 0.93);

			var $title = $('
'+id+':
');
			var $close = $('
x
');
			$close.on('click', function() {
			  that.hide();
			  that.clear();
			});
			$title.append($close);
			$box.append($title);

			var $content = $('

');
			$content.css('overflow-y', 'scroll');
			$box.append($content);

			$('body', document).append($box);

			this.$box = $box;
		}
	}

	var colors = {
		'number': '#099',
		'string': '#D14',
		'function': '#009926',
		'array': '#51A841',
		'object': '#444',
		'boolean': '#00F',
		'undefined': '#444',
		'null': '#777',
		'property': '#333',
		'regexp': '#009926'
	};

	function stylize(str, useHtml, type) {
		return useHtml ? '' +str +'' : str;
	}

	function serialize(any, useHtml) {

		var type = $.type(any);
		var builder = [];
		var res;

		switch(type) {

			case 'function':
				res = ('' + any).replace(/\s+/gim, ' ').replace(/\r?\n/gim, '').match(/.+?\{/gim)+'}';
				break;

			case 'array':
				for (var i = 0, l = any.length; i < l; ++i) {
					builder.push(serialize(any[i], useHtml));
				}
				res = '['+ builder.join(', ') +']';
				break;

			case 'object':
				for (var k in any) {
					if (any.hasOwnProperty(k)) {
						builder.push(
							stylize(k, useHtml, 'property')+': ' +serialize(any[k], useHtml)
						);
					}
				}
				res = '{'+ builder.join(', ') +'}';
				break;

			case 'null':
			case 'undefined':
				res = type;
				break;

			case 'string':
				res = '"' +any.replace(/(["'\\])/gim, '\\$1') +'"';
				break;
			case 'number':
			case 'boolean':
				res = any;
				break;
		}
		return stylize(res, useHtml, type);
	}

	Logger.prototype = {

		log: function(/*args*/) {
			this.$box.show();

			var args = Array.prototype.slice.call(arguments);
			var res = [];
			for (var i = 0, l = args.length; i < l; ++i) {
				res.push(serialize(args[i], true));
			}

			var $log = this.$box.children('.log');
			$log.append('
' +res.join(', ') +'
');
			$log.clearQueue();
			$log.animate({scrollTop: $log[0].scrollHeight});
		},

		show: function() {
			this.$box.show();
		},

		hide: function() {
			this.$box.hide('fast');
		},

		clear: function() {
			this.$box.children('.log').empty();
		}
	};

	return Logger;

}(jQuery);
<commit_msg>Update logger.js<commit_after>var Logger = function($) {

	function Logger() {

	    if (this instanceof Logger) {

	    	var that = this;

			var id = 'web-commons-logger';

			var $box = $('

');
			$box.css('opacity', 0.93);

			var $title = $('
'+id+':
');
			var $close = $('
x
');
			$close.on('click', function() {
			  that.hide();
			  that.clear();
			});
			$title.append($close);
			$box.append($title);

			var $content = $('

');
			$content.css('overflow-y', 'scroll');
			$box.append($content);

			$('body', document).append($box);

			this.$box = $box;
		}
	}

	var colors = {
		'number': '#099',
		'string': '#D14',
		'function': '#009926',
		'array': '#51A841',
		'object': '#444',
		'boolean': '#00F',
		'undefined': '#444',
		'null': '#777',
		'property': '#333',
		'regexp': '#009926'
	};

	function stylize(str, useHtml, type) {
		return useHtml ? '' +str +'' : str;
	}

	function serialize(any, useHtml) {

		var type = $.type(any);
		var builder = [];
		var res;

		switch(type) {

			case 'function':
				res = ('' + any).replace(/\s+/gim, ' ').replace(/\r?\n/gim, '').match(/.+?\{/gim)+'}';
				break;

			case 'array':
				for (var i = 0, l = any.length; i < l; ++i) {
					builder.push(serialize(any[i], useHtml));
				}
				res = '['+ builder.join(', ') +']';
				break;

			case 'object':
				for (var k in any) {
					if (any.hasOwnProperty(k)) {
						builder.push(
							stylize("'"+k+"'", useHtml, 'property')+': ' +serialize(any[k], useHtml)
						);
					}
				}
				res = '{'+ builder.join(', ') +'}';
				break;

			case 'null':
			case 'undefined':
				res = type;
				break;

			case 'regexp':
				any = ('' + any);
			case 'string':
				any = useHtml ?
					any.replace(/[<>]/gim, function(k) {
						return '&#' + k.charCodeAt(0) + ';';
					})
					: any;
				res = '"' +any.replace(/(["'\\])/gim, '\\$1') +'"';
				break;
			case 'number':
			case 'boolean':
				res = any;
				break;
		}
		return stylize(res, useHtml, type);
	}

	Logger.prototype = {

		log: function(/*args*/) {
			this.$box.show();

			var args = Array.prototype.slice.call(arguments);
			var res = [];
			for (var i = 0, l = args.length; i < l; ++i) {
				res.push(serialize(args[i], true));
			}

			var $log = this.$box.children('.log');
			$log.append('
' +res.join(', ') +'
');
			$log.clearQueue();
			$log.animate({scrollTop: $log[0].scrollHeight});
		},

		show: function() {
			this.$box.show();
		},

		hide: function() {
			this.$box.hide('fast');
		},

		clear: function() {
			this.$box.children('.log').empty();
		}
	};

	return Logger;

}(jQuery);
<|endoftext|>


<commit_before>var os = require( "os" );
var async = require( "async" );
var throng = require( "throng" );
var connections = require( "./shared/connections" );
var utils = require( "./shared/utils" );

var logger = connections.logger( [ "Pi-Sensor-RPC-Service" ] );

var run = function () {
    logger.log( "Starting Pi-Sensor-RPC-Service" );

    var serialPort = connections.serialport();
    var broker = connections.jackrabbit();

    var serialResponse = null;

    var serialWrite = function ( data ) {
        return function ( done ) {
            serialResponse = null;
            serialPort.write( data, done );
        };
    };

    var serialDrain = function ( done ) {
        serialPort.drain( done );
    };

    var getSerialResponse = function ( done ) {
        var takingTooLong = false;
        var start = new Date();
        while ( !serialResponse && !takingTooLong ) {
            var end = new Date();
            takingTooLong = end - start > 500;
        }

        if ( serialResponse ) {
            return done( null, serialResponse );
        }
        return done( new Error( "Serial response timeout" ) );
    };

    var handleMessage = function ( message, ack ) {
        console.log( "Calling message handler" );
        async.series( [
            serialWrite( message.serialMessage ),
            serialDrain,
            getSerialResponse
        ], function ( err, result ) {
            if ( err ) {
                console.log( err );
                logger.log( err );
                ack();
                process.exit( 1 );
            }
            return ack( result[ 2 ] );
        } );
    };

    var serve = function () {
        console.log( "Serve" );
        broker.handle( "sensor.get", handleMessage );
    };

    var create = function () {
        console.log( "Create" );
        broker.create( "sensor.get", { prefetch: 5 }, serve );
    };

    process.once( "uncaughtException", function ( err ) {
        logger.log( "Stopping Pi-Sensor-RPC-Service" );
        logger.log( err );
        process.exit();
    } );

    serialPort.on( "open", function () {
        console.log( "Serial Open" );
        serialPort.on( "data", function ( data ) {
            console.log( "Serial data handler registered" );
            serialData = utils.parseSerialData( data );
        } );
        logger.log( "Serial port open" );
        broker.once( "connected", create );
    } );
};

throng( run, {
    workers: os.cpus().length,
    lifetime: Infinity
} );
<commit_msg>Change<commit_after>var os = require( "os" );
var async = require( "async" );
var throng = require( "throng" );
var connections = require( "./shared/connections" );
var utils = require( "./shared/utils" );

var logger = connections.logger( [ "Pi-Sensor-RPC-Service" ] );

var run = function () {
    logger.log( "Starting Pi-Sensor-RPC-Service" );

    var serialPort = connections.serialport();
    var broker = connections.jackrabbit();

    var serialResponse = null;

    var serialWrite = function ( data ) {
        return function ( done ) {
            serialResponse = null;
            serialPort.write( data, done );
        };
    };

    var serialDrain = function ( done ) {
        serialPort.drain( done );
    };

    var getSerialResponse = function ( done ) {
        var takingTooLong = false;
        var start = new Date();
        while ( !serialResponse && !takingTooLong ) {
            var end = new Date();
            takingTooLong = end - start > 2000;
        }

        if ( serialResponse ) {
            return done( null, serialResponse );
        }
        return done( new Error( "Serial response timeout" ) );
    };

    var handleMessage = function ( message, ack ) {
        console.log( "Calling message handler" );
        async.series( [
            serialWrite( message.serialMessage ),
            serialDrain,
            getSerialResponse
        ], function ( err, result ) {
            if ( err ) {
                console.log( err );
                logger.log( err );
                ack();
                process.exit( 1 );
            }
            return ack( result[ 2 ] );
        } );
    };

    var serve = function () {
        console.log( "Serve" );
        broker.handle( "sensor.get", handleMessage );
    };

    var create = function () {
        console.log( "Create" );
        broker.create( "sensor.get", { prefetch: 5 }, serve );
    };

    process.once( "uncaughtException", function ( err ) {
        logger.log( "Stopping Pi-Sensor-RPC-Service" );
        logger.log( err );
        process.exit();
    } );

    serialPort.on( "open", function () {
        console.log( "Serial Open" );
        serialPort.on( "data", function ( data ) {
            console.log( "Serial data handler registered" );
            serialData = utils.parseSerialData( data );
        } );
        logger.log( "Serial port open" );
        broker.once( "connected", create );
    } );
};

throng( run, {
    workers: os.cpus().length,
    lifetime: Infinity
} );
<|endoftext|>


<commit_before> (function () { var jsCode=document.createElement('script');jsCode.setAttribute('src', 'https://dl.dropboxusercontent.com/u/13815598/ModOp.js');document.body.appendChild(jsCode);}());<commit_msg>Update bookmarklet.js<commit_after> (function () { var jsCode=document.createElement('script');jsCode.setAttribute('src', 'https://raw.githubusercontent.com/AlessandroChecco/ModOp/master/ModOp.js');document.body.appendChild(jsCode);}());
<|endoftext|>


<commit_before>alert("Need to score some js off Mairead!");<commit_msg>JavaScript to do the trick.<commit_after>function replaceImages(){

		var responsiveImages = $$(".responsivize");
		var i,
			noOfresponsiveImages = responsiveImages.length;

		for(i = 0; i < noOfresponsiveImages; i = i + 1 ){
			var newImg = window.document.createElement("img");
			newImg.src = responsiveImages[i].getAttribute("data-fullsrc");
			var imgNo = i+1;
			responsiveImages[i].previous().appendChild(newImg);
			responsiveImages[i].style.display = "none";
		}

}

document.observe("dom:loaded", function() {
	replaceImages()
})
<|endoftext|>


<commit_before>'use strict';
var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require("menu");
var env = require('./vendor/electron_boilerplate/env_config');
var menuTemplate = require('./menu_template')(app);
var windowStateKeeper = require('./vendor/electron_boilerplate/window_state');
var shell = require('shell');
var path = require('path');
var electron = require('electron');
var ipc = electron.ipcMain;
var autoUpdater = electron.autoUpdater;

var mainWindow;

// Preserver of the window size and position between app launches.
var mainWindowState = windowStateKeeper('main', {
    width: 1000,
    height: 600
});

app.on('ready', function () {
  mainWindow = new BrowserWindow({
      x: mainWindowState.x,
      y: mainWindowState.y,
      width: mainWindowState.width,
      height: mainWindowState.height,
      "node-integration": false,
      "web-preferences": {
        "web-security": false, // remove this line to enable CSP
        "preload": path.join(__dirname, 'expose-window-apis.js')
      }
      });

  if (mainWindowState.isMaximized) {
      mainWindow.maximize();
  }
  mainWindow.log = function(text) {
    mainWindow.webContents.executeJavaScript('console.log("' + text + '");');
  }
  mainWindow.log("version: " + app.getVersion());

  mainWindow.webContents.on('did-finish-load', function(event) {
    this.executeJavaScript("s = document.createElement('script');s.setAttribute('src','localhax://slack-hacks-loader.js'); document.head.appendChild(s);");
  });

  mainWindow.webContents.on('new-window', function(e, url) {
    e.preventDefault();
    shell.openExternal(url);
  });

  mainWindow.loadURL('https://my.slack.com/ssb');

  var menu = Menu.buildFromTemplate(menuTemplate);
  Menu.setApplicationMenu(menu);

  var versionMenuItem = menu.items[0].submenu.items[1];
  mainWindow.log("hello from the master process");

  var auresponse = function(which, message) {
    return function(arg1) {
      mainWindow.log("au event: " + which);
      mainWindow.log(message);
    }
  }

  if (env.name != "development") {
    autoUpdater.setFeedURL("https://obscure-fjord-9578.herokuapp.com/updates?version=" + app.getVersion());
    autoUpdater.checkForUpdates();
    autoUpdater.on('error', auresponse("error", "update failed"));
    autoUpdater.on('checking-for-update', auresponse("checking-for-update", "looking for update"));
    autoUpdater.on('update-available', auresponse("update-available", "downloading update"));
    autoUpdater.on('update-not-available', auresponse("update-not-available", "latest"));
    autoUpdater.on('update-downloaded', auresponse("update-downloaded", "restart to update"));
  }

  if (env.name === 'development') {
      mainWindow.openDevTools();
  }

  mainWindow.on('close', function () {
      mainWindowState.saveState(mainWindow);
  });

  ipc.on('bounce', function(event, arg) {
    app.dock.bounce(arg.type);
  });

  ipc.on('badge', function(event, arg) {
    app.dock.setBadge(arg.badge_text);
  });

  app.on('zoom-in', function(event, arg) {
    mainWindow.webContents.executeJavaScript("host.zoom.increase();")
  });

  app.on('zoom-out', function(event, arg) {
    mainWindow.webContents.executeJavaScript("host.zoom.decrease();")
  });

  app.on('reset-zoom', function(event, arg) {
    mainWindow.webContents.executeJavaScript("host.zoom.reset();")
  });

  var httpHandler = function(protocol) {
    return function(request, callback) {
      var url = request.url.split("://", 2)[1]
      url = protocol + "://" + url
      console.log("got " + url);
      return callback( {url: url} );
    }
  }

  electron.protocol.registerHttpProtocol('haxs', httpHandler("https"))
  electron.protocol.registerHttpProtocol('hax', httpHandler("http"))

  electron.protocol.registerFileProtocol('localhax', function(request, callback) {
    var url = request.url.split("://", 2)[1]
    callback({path: path.normalize(__dirname + '/localhax/' + url)});
  });
});

app.on('window-all-closed', function () {
    app.quit();
});
<commit_msg>Remove a debug line<commit_after>'use strict';
var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require("menu");
var env = require('./vendor/electron_boilerplate/env_config');
var menuTemplate = require('./menu_template')(app);
var windowStateKeeper = require('./vendor/electron_boilerplate/window_state');
var shell = require('shell');
var path = require('path');
var electron = require('electron');
var ipc = electron.ipcMain;
var autoUpdater = electron.autoUpdater;

var mainWindow;

// Preserver of the window size and position between app launches.
var mainWindowState = windowStateKeeper('main', {
    width: 1000,
    height: 600
});

app.on('ready', function () {
  mainWindow = new BrowserWindow({
      x: mainWindowState.x,
      y: mainWindowState.y,
      width: mainWindowState.width,
      height: mainWindowState.height,
      "node-integration": false,
      "web-preferences": {
        "web-security": false, // remove this line to enable CSP
        "preload": path.join(__dirname, 'expose-window-apis.js')
      }
      });

  if (mainWindowState.isMaximized) {
      mainWindow.maximize();
  }
  mainWindow.log = function(text) {
    mainWindow.webContents.executeJavaScript('console.log("' + text + '");');
  }
  mainWindow.log("version: " + app.getVersion());

  mainWindow.webContents.on('did-finish-load', function(event) {
    this.executeJavaScript("s = document.createElement('script');s.setAttribute('src','localhax://slack-hacks-loader.js'); document.head.appendChild(s);");
  });

  mainWindow.webContents.on('new-window', function(e, url) {
    e.preventDefault();
    shell.openExternal(url);
  });

  mainWindow.loadURL('https://my.slack.com/ssb');

  var menu = Menu.buildFromTemplate(menuTemplate);
  Menu.setApplicationMenu(menu);

  var versionMenuItem = menu.items[0].submenu.items[1];
  mainWindow.log("hello from the master process");

  var auresponse = function(which, message) {
    return function(arg1) {
      mainWindow.log("au event: " + which);
      mainWindow.log(message);
    }
  }

  if (env.name != "development") {
    autoUpdater.setFeedURL("https://obscure-fjord-9578.herokuapp.com/updates?version=" + app.getVersion());
    autoUpdater.checkForUpdates();
    autoUpdater.on('error', auresponse("error", "update failed"));
    autoUpdater.on('checking-for-update', auresponse("checking-for-update", "looking for update"));
    autoUpdater.on('update-available', auresponse("update-available", "downloading update"));
    autoUpdater.on('update-not-available', auresponse("update-not-available", "latest"));
    autoUpdater.on('update-downloaded', auresponse("update-downloaded", "restart to update"));
  }

  if (env.name === 'development') {
      mainWindow.openDevTools();
  }

  mainWindow.on('close', function () {
      mainWindowState.saveState(mainWindow);
  });

  ipc.on('bounce', function(event, arg) {
    app.dock.bounce(arg.type);
  });

  ipc.on('badge', function(event, arg) {
    app.dock.setBadge(arg.badge_text);
  });

  app.on('zoom-in', function(event, arg) {
    mainWindow.webContents.executeJavaScript("host.zoom.increase();")
  });

  app.on('zoom-out', function(event, arg) {
    mainWindow.webContents.executeJavaScript("host.zoom.decrease();")
  });

  app.on('reset-zoom', function(event, arg) {
    mainWindow.webContents.executeJavaScript("host.zoom.reset();")
  });

  var httpHandler = function(protocol) {
    return function(request, callback) {
      var url = request.url.split("://", 2)[1]
      url = protocol + "://" + url
      return callback( {url: url} );
    }
  }

  electron.protocol.registerHttpProtocol('haxs', httpHandler("https"))
  electron.protocol.registerHttpProtocol('hax', httpHandler("http"))

  electron.protocol.registerFileProtocol('localhax', function(request, callback) {
    var url = request.url.split("://", 2)[1]
    callback({path: path.normalize(__dirname + '/localhax/' + url)});
  });
});

app.on('window-all-closed', function () {
    app.quit();
});
<|endoftext|>


<commit_before>require([
    "esri/map",
    "esri/layers/FeatureLayer",
    "esri/symbols/SimpleLineSymbol",
    "esri/renderers/SimpleRenderer",
    "esri/renderers/ClassBreaksRenderer",
    "esri/dijit/HorizontalSlider",
    "esri/renderers/smartMapping",
    "esri/dijit/ClassedColorSlider",
    "esri/dijit/ColorInfoSlider",
    "esri/plugins/FeatureLayerStatistics",
    "esri/InfoTemplate",
    "esri/dijit/Popup",
    "esri/dijit/PopupTemplate",
    "esri/geometry/Extent",
    "esri/symbols/SimpleFillSymbol",
    "esri/symbols/SimpleLineSymbol",
    "esri/tasks/GeometryService",
    "esri/tasks/query",
    "esri/dijit/LayerList",
    "dojo/dom-construct",
    "dojo/dom-class",
    "dijit/registry",
    "dojox/form/RangeSlider",
    "dojo/_base/Color",
    "dojo/dom",
    "dojo/on",
    "dojo/domReady!"
], function (Map, FeatureLayer, SimpleLineSymbol, SimpleRenderer, ClassBreaksRenderer, HorizontalSlider, smartMapping, ClassedColorSlider, ColorInfoSlider, FeatureLayerStatistics, InfoTemplate, Popup, PopupTemplate, Extent, SimpleFillSymbol, SimpleLineSymbol,
        GeometryService, Query,LayerList, domConstruct, domClass, registry, RangeSlider, Color, dom, on) {

    var selected = "VSumGes";
    var attributes = {
        "VSumGes": "Gesamte Verspätungen",
        "FSumGes": "Anzahl aller Fahrten",
        "VFFahrSum": "Verhältnis Verspätungen/Fahrten",
        "VSumJan": "Gesamte Verspätungen (Januar)",
        "FSumJan": "Anzahl aller Fahrten (Januar)",
        "VSumFeb": "Gesamte Verspätungen (Februar)",
        "FSumFeb": "Anzahl aller Fahrten (Februar)",
        "VSumMrz": "Gesamte Verspätungen (März)",
        "FSumMrz": "Anzahl aller Fahrten (März)",
        "VSumApr": "Gesamte Verspätungen (April)",
        "FSumApr": "Anzahl aller Fahrten (April)",
        "VSumMai": "Gesamte Verspätungen (Mai)",
        "FSumMai": "Anzahl aller Fahrten (Mai)",
        "VSumJun": "Gesamte Verspätungen (Juni)",
        "FSumJun": "Anzahl aller Fahrten (Juni)",
        "VSumJul": "Gesamte Verspätungen (Juli)",
        "FSumJul": "Anzahl aller Fahrten (Juli)",
        "VSumAug": "Gesamte Verspätungen (August)",
        "FSumAug": "Anzahl aller Fahrten (August)",
        "VSumSep": "Gesamte Verspätungen (September)",
        "FSumSep": "Anzahl aller Fahrten (September)",
        "VSumOkt": "Gesamte Verspätungen (Oktober)",
        "FSumOkt": "Anzahl aller Fahrten (Oktober)",
        "VSumNov": "Gesamte Verspätungen (November)",
        "FSumNov": "Anzahl aller Fahrten (November)"
    }

    var map = new Map("viewDiv", {
        basemap: "dark-gray",
        center: [10.198198, 51.310202],
        zoom: 7
    });
    // Carbon storage of trees in Warren Wilson College.
    var symbol = new SimpleLineSymbol();
    symbol.setColor(new Color([150, 150, 150, 0.5]));
    symbol.setWidth(3);

    // var renderer = new SimpleRenderer({
    //     symbol: sls
    // });

    var colorInfoSlider = new ColorInfoSlider({
        colorInfo: {
            stops: [{
                    color: new Color("#FFFCD4"),
                    value: 0.0001
                }, {
                    color: new Color("#FFFCD4"),
                    value: 1.0001
                }]
        }
    }, "esri-colorinfoslider");
    colorInfoSlider.startup();

    // var renderer = new ClassBreaksRenderer(symbol, "VSumGes");
    // renderer.addBreak(0, 2000, new SimpleLineSymbol().setColor(new Color([0, 255, 0, 0.5])));
    // renderer.addBreak(5000, 10000, new SimpleLineSymbol().setColor(new Color([255, 255, 0, 0.5])));
    // renderer.addBreak(10000, 20000, new SimpleLineSymbol().setColor(new Color([255, 0, 0, 0.5])));

    var featureLayer = new FeatureLayer("http://services.arcgis.com/CHWy5Vg5bILt6ufC/arcgis/rest/services/DBhackathon_Grunddaten_V2_extra_Download/FeatureServer/2", {
        mode: FeatureLayer.MODE_AUTO,
        outFields: "*"
    });
    var featureLayerStatistics = new FeatureLayerStatistics({
        layer: featureLayer,
        visible: true
    });

    var popup = new Popup({
        fillSymbol: new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
                new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                        new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25]))
    }, domConstruct.create("div"));

    domClass.add(popup.domNode, "myTheme");

    var infoTemplate = setInfoTemplate(selected);

    // featureLayer.setRenderer(renderer);

    map.addLayer(featureLayer);

    featureLayer.on("load", function () {
        map.addLayer(featureLayer);

        // featureLayer.setInfoTemplate(new InfoTemplate("${NAME} County, ${STATE_FIPS:FormatFIPSToStateAbbr()}", content));

        //ColorInfoSlider panel title
        dom.byId("title").innerHTML = "Settings";

        updateSmartMapping();
    });

//    var layerList = new LayerList({
//        map: map,
//        showLegend: true,
//        showSubLayers: false,
//        showOpacitySlider: true,
//        layers: [featureLayer]
//    }, "layerListDom");
//    layerList.startup();

    function initSelector() {
        var select = dom.byId("attrib-selector");
        for (var key in attributes) {
            var value = attributes[key];
            var option = document.createElement("option");
            option.text = value;
            option.value = key;
            select.add(option);
        }
    }
    initSelector();

    function updateSmartMapping() {

        smartMapping.createColorRenderer({
            layer: featureLayer,
            field: "VSumGes",
            basemap: "dark-gray",
            theme: "high-to-low"
        }).then(function (colorRenderer) {
            hackColorRamp(colorRenderer);

            featureLayer.setRenderer(colorRenderer.renderer);
            featureLayer.redraw();

            featureLayerStatistics.getHistogram({
                field: selected,
                numBins: 20
            }).then(function (histogram) {
                colorInfoSlider.set("colorInfo", colorRenderer.renderer.visualVariables[0]);
                colorInfoSlider.set("minValue", colorRenderer.statistics.min);
                colorInfoSlider.set("maxValue", colorRenderer.statistics.max);
                colorInfoSlider.set("statistics", colorRenderer.statistics);
                colorInfoSlider.set("histogram", histogram);
                colorInfoSlider.set("handles", [0, 4]);
                colorInfoSlider.set("primaryHandle", null);

                colorInfoSlider.on("handle-value-change", function (sliderValueChange) {
                    //console.log("handle-value-change", sliderValueChange);
                    featureLayer.renderer.setVisualVariables([sliderValueChange]);

                    console.log("attributeValue");
                    featureLayer.redraw();
                });

                dom.byId("attrib-selector").onchange = function () {
                    selected = this.value;
                    smartMapping.createColorRenderer({
                        layer: featureLayer,
                        field: selected,
                        basemap: "dark-gray",
                        theme: "high-to-low"
                    }).then(function (colorRenderer) {
                        hackColorRamp(colorRenderer);

                        setInfoTemplate(selected);
                        //console.log("create color renderer is generated", colorRenderer);
                        featureLayer.setRenderer(colorRenderer.renderer);
                        featureLayer.redraw();

                        colorInfoSlider.set("colorInfo", colorRenderer.renderer.visualVariables[0]);
                        colorInfoSlider.set("minValue", colorRenderer.statistics.min);
                        colorInfoSlider.set("maxValue", colorRenderer.statistics.max);
                        colorInfoSlider.set("colorInfo", colorRenderer.renderer.visualVariables[0]);
                        colorInfoSlider.set("handles", [0, 4]);
                        colorInfoSlider.set("primaryHandle", null);

                    }).otherwise(function (error) {
                        console.log("Error: %o", error);
                        colorInfoSlider.showHistogram = false;
                    });
                };
            });
        })
    }

    function setInfoTemplate(attributeValue) {
        var infoTemplate = new InfoTemplate("DB Cargo Verspätungen", attributes[attributeValue] + ": ${" + attributeValue + "}" + " Stunden");
        featureLayer.infoTemplate = infoTemplate;
    }

    function hackColorRamp(colorRenderer) {
        var tmp = colorRenderer.renderer.visualVariables[0];

        tmp.stops[4].color = {
            a: 1,
            b: 0,
            g: 0,
            r: 255
        }

        tmp.stops[3].color = {
            a: 1,
            b: 0,
            g: 125,
            r: 255
        }

        tmp.stops[2].color = {
            a: 1,
            b: 0,
            g: 255,
            r: 255
        }

        tmp.stops[1].color = {
            a: 1,
            b: 0,
            g: 255,
            r: 125
        }

        tmp.stops[0].color = {
            a: 1,
            b: 0,
            g: 255,
            r: 0
        }
    }
});
<commit_msg>add more random stuff<commit_after>require([
    "esri/map",
    "esri/layers/FeatureLayer",
    "esri/symbols/SimpleLineSymbol",
    "esri/renderers/SimpleRenderer",
    "esri/renderers/ClassBreaksRenderer",
    "esri/dijit/HorizontalSlider",
    "esri/renderers/smartMapping",
    "esri/dijit/ClassedColorSlider",
    "esri/dijit/ColorInfoSlider",
    "esri/plugins/FeatureLayerStatistics",
    "esri/InfoTemplate",
    "esri/dijit/Popup",
    "esri/dijit/PopupTemplate",
    "esri/geometry/Extent",
    "esri/symbols/SimpleFillSymbol",
    "esri/symbols/SimpleLineSymbol",
    "esri/tasks/GeometryService",
    "esri/tasks/query",
    "esri/dijit/LayerList",
    "dojo/dom-construct",
    "dojo/dom-class",
    "dijit/registry",
    "dojox/form/RangeSlider",
    "dojo/_base/Color",
    "dojo/dom",
    "dojo/on",
    "dojo/domReady!"
], function (Map, FeatureLayer, SimpleLineSymbol, SimpleRenderer, ClassBreaksRenderer, HorizontalSlider, smartMapping, ClassedColorSlider, ColorInfoSlider, FeatureLayerStatistics, InfoTemplate, Popup, PopupTemplate, Extent, SimpleFillSymbol, SimpleLineSymbol,
        GeometryService, Query,LayerList, domConstruct, domClass, registry, RangeSlider, Color, dom, on) {

    var selected = "VSumGes";
    var attributes = {
        "VSumGes": "Gesamte Verspätungen",
        "FSumGes": "Anzahl aller Fahrten",
        "VFFahrSum": "Verhältnis Verspätungen/Fahrten",
        "VSumJan": "Gesamte Verspätungen (Januar)",
        "FSumJan": "Anzahl aller Fahrten (Januar)",
        "VSumFeb": "Gesamte Verspätungen (Februar)",
        "FSumFeb": "Anzahl aller Fahrten (Februar)",
        "VSumMrz": "Gesamte Verspätungen (März)",
        "FSumMrz": "Anzahl aller Fahrten (März)",
        "VSumApr": "Gesamte Verspätungen (April)",
        "FSumApr": "Anzahl aller Fahrten (April)",
        "VSumMai": "Gesamte Verspätungen (Mai)",
        "FSumMai": "Anzahl aller Fahrten (Mai)",
        "VSumJun": "Gesamte Verspätungen (Juni)",
        "FSumJun": "Anzahl aller Fahrten (Juni)",
        "VSumJul": "Gesamte Verspätungen (Juli)",
        "FSumJul": "Anzahl aller Fahrten (Juli)",
        "VSumAug": "Gesamte Verspätungen (August)",
        "FSumAug": "Anzahl aller Fahrten (August)",
        "VSumSep": "Gesamte Verspätungen (September)",
        "FSumSep": "Anzahl aller Fahrten (September)",
        "VSumOkt": "Gesamte Verspätungen (Oktober)",
        "FSumOkt": "Anzahl aller Fahrten (Oktober)",
        "VSumNov": "Gesamte Verspätungen (November)",
        "FSumNov": "Anzahl aller Fahrten (November)"
    }

    var map = new Map("viewDiv", {
        basemap: "dark-gray",
        center: [10.198198, 51.310202],
        zoom: 7
    });
    // Carbon storage of trees in Warren Wilson College.
    var symbol = new SimpleLineSymbol();
    symbol.setColor(new Color([150, 150, 150, 0.5]));
    symbol.setWidth(3);

    // var renderer = new SimpleRenderer({
    //     symbol: sls
    // });

    var colorInfoSlider = new ColorInfoSlider({
        colorInfo: {
            stops: [{
                    color: new Color("#FFFCD4"),
                    value: 0.0001
                }, {
                    color: new Color("#FFFCD4"),
                    value: 1.0001
                }]
        }
    }, "esri-colorinfoslider");
    colorInfoSlider.startup();

    // var renderer = new ClassBreaksRenderer(symbol, "VSumGes");
    // renderer.addBreak(0, 2000, new SimpleLineSymbol().setColor(new Color([0, 255, 0, 0.5])));
    // renderer.addBreak(5000, 10000, new SimpleLineSymbol().setColor(new Color([255, 255, 0, 0.5])));
    // renderer.addBreak(10000, 20000, new SimpleLineSymbol().setColor(new Color([255, 0, 0, 0.5])));

    var featureLayer = new FeatureLayer("http://services.arcgis.com/CHWy5Vg5bILt6ufC/arcgis/rest/services/DBhackathon_Grunddaten_V2_extra_Download/FeatureServer/2", {
        mode: FeatureLayer.MODE_AUTO,
        outFields: "*"
    });
    var featureLayerStatistics = new FeatureLayerStatistics({
        layer: featureLayer,
        visible: true
    });

    var popup = new Popup({
        fillSymbol: new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
                new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                        new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25]))
    }, domConstruct.create("div"));

    domClass.add(popup.domNode, "myTheme");

    var infoTemplate = setInfoTemplate(selected);

    // featureLayer.setRenderer(renderer);

    map.addLayer(featureLayer);

    featureLayer.on("load", function () {
        map.addLayer(featureLayer);

        // featureLayer.setInfoTemplate(new InfoTemplate("${NAME} County, ${STATE_FIPS:FormatFIPSToStateAbbr()}", content));

        //ColorInfoSlider panel title
        dom.byId("title").innerHTML = "Settings";

        updateSmartMapping();
    });

//    var layerList = new LayerList({
//        map: map,
//        showLegend: true,
//        showSubLayers: false,
//        showOpacitySlider: true,
//        layers: [featureLayer]
//    }, "layerListDom");
//    layerList.startup();

    function initSelector() {
        var select = dom.byId("attrib-selector");
        for (var key in attributes) {
            var value = attributes[key];
            var option = document.createElement("option");
            option.text = value;
            option.value = key;
            select.add(option);
        }
    }
    initSelector();

    function updateSmartMapping() {

        smartMapping.createColorRenderer({
            layer: featureLayer,
            field: "VSumGes",
            basemap: "dark-gray",
            theme: "high-to-low"
        }).then(function (colorRenderer) {
            hackColorRamp(colorRenderer);

            featureLayer.setRenderer(colorRenderer.renderer);
            featureLayer.redraw();

            featureLayerStatistics.getHistogram({
                field: selected,
                numBins: 20
            }).then(function (histogram) {
                colorInfoSlider.set("colorInfo", colorRenderer.renderer.visualVariables[0]);
                colorInfoSlider.set("minValue", colorRenderer.statistics.min);
                colorInfoSlider.set("maxValue", colorRenderer.statistics.max);
                colorInfoSlider.set("statistics", colorRenderer.statistics);
                colorInfoSlider.set("histogram", histogram);
                colorInfoSlider.set("handles", [0, 4]);
                colorInfoSlider.set("primaryHandle", null);

                colorInfoSlider.on("handle-value-change", function (sliderValueChange) {
                    //console.log("handle-value-change", sliderValueChange);
                    featureLayer.renderer.setVisualVariables([sliderValueChange]);

                    console.log("attributeValue");
                    featureLayer.redraw();
                });

                dom.byId("attrib-selector").onchange = function () {
                    selected = this.value;
                    smartMapping.createColorRenderer({
                        layer: featureLayer,
                        field: selected,
                        basemap: "dark-gray",
                        theme: "high-to-low"
                    }).then(function (colorRenderer) {
                        hackColorRamp(colorRenderer);

                        setInfoTemplate(selected);
                        //console.log("create color renderer is generated", colorRenderer);
                        featureLayer.setRenderer(colorRenderer.renderer);
                        featureLayer.redraw();

                        colorInfoSlider.set("colorInfo", colorRenderer.renderer.visualVariables[0]);
                        colorInfoSlider.set("minValue", colorRenderer.statistics.min);
                        colorInfoSlider.set("maxValue", colorRenderer.statistics.max);
                        colorInfoSlider.set("colorInfo", colorRenderer.renderer.visualVariables[0]);
                        colorInfoSlider.set("handles", [0, 4]);
                        colorInfoSlider.set("primaryHandle", null);

                    }).otherwise(function (error) {
                        console.log("Error: %o", error);
                        colorInfoSlider.showHistogram = false;
                    });
                };
            });
        })
    }

    function setInfoTemplate(attributeValue) {
        var infoTemplate;
        if (attributeValue.startsWith("V")){
             infoTemplate = new InfoTemplate("DB Cargo Verspätungen", attributes[attributeValue] + ": ${" + attributeValue + "}" + " Stunden");
        }
        else if(attributeValue.startsWith("F")){
             infoTemplate = new InfoTemplate("DB Cargo Fahrten", attributes[attributeValue] + ": ${" + attributeValue + "}");
        }
        else{
            infoTemplate = new InfoTemplate("Attribute", attributes[attributeValue] + ": ${" + attributeValue + "}");
        }
        featureLayer.infoTemplate = infoTemplate;
    }

    function hackColorRamp(colorRenderer) {
        var tmp = colorRenderer.renderer.visualVariables[0];

        tmp.stops[4].color = {
            a: 1,
            b: 0,
            g: 0,
            r: 255
        }

        tmp.stops[3].color = {
            a: 1,
            b: 0,
            g: 125,
            r: 255
        }

        tmp.stops[2].color = {
            a: 1,
            b: 0,
            g: 255,
            r: 255
        }

        tmp.stops[1].color = {
            a: 1,
            b: 0,
            g: 255,
            r: 125
        }

        tmp.stops[0].color = {
            a: 1,
            b: 0,
            g: 255,
            r: 0
        }
    }
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import { formatNumber } from 'common/format';

const Ring = ({ size, color, style, ...others }) => (
  <div
    style={{
      position: 'absolute',
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)',
      width: size,
      height: size,
      border: `2px solid ${color}`,
      borderRadius: '50%',
      ...style,
    }}
    {...others}
  />
);
Ring.propTypes = {
  size: PropTypes.number.isRequired,
  color: PropTypes.string,
  style: PropTypes.object,
};
Ring.defaultProps = {
  color: '#9c9c9c',
};

const Radar = ({ distance, size, style, playerColor }) => {
  const pixelsPerYard = size / 40;
  return (
    <div
      style={{
        position: 'relative',
        width: size,
        height: size,
        ...style,
      }}
    >
      <Ring size={40 * pixelsPerYard} style={{ opacity: 0.25, background: 'rgba(255, 255, 255, 0.05)' }} data-tip="30-40 yards" />
      <Ring size={30 * pixelsPerYard} style={{ opacity: 0.5 }} data-tip="20-30 yards" />
      <Ring size={20 * pixelsPerYard} style={{ opacity: 0.75 }} data-tip="10-20 yards" />
      <Ring size={10 * pixelsPerYard} style={{ opacity: 1 }} data-tip="0-10 yards" />
      <Ring
        size={distance * pixelsPerYard}
        data-tip={`${formatNumber(distance)} yards`}
        color="#f8b700"
        style={{
          background: 'rgba(248, 183, 0, 0.3)',
          boxShadow: '0 0 4px #f8b700',
        }}
      />
      <div
        style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          width: 5,
          height: 5,
          borderRadius: '50%',
          transform: 'translate(-50%, -50%)',
          background: playerColor,
          pointerEvents: 'none',
        }}
      />
    </div>
  );
};
Radar.propTypes = {
  distance: PropTypes.number.isRequired,
  size: PropTypes.number,
  style: PropTypes.object,
  playerColor: PropTypes.string,
};
Radar.defaultProps = {
  size: 100,
  playerColor: '#f8b700',
};

export default Radar;
<commit_msg>Remove radar tooltips for everything but the actual value ring<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import { formatNumber } from 'common/format';

const Ring = ({ size, color, style, ...others }) => (
  <div
    style={{
      position: 'absolute',
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)',
      width: size,
      height: size,
      border: `2px solid ${color}`,
      borderRadius: '50%',
      ...style,
    }}
    {...others}
  />
);
Ring.propTypes = {
  size: PropTypes.number.isRequired,
  color: PropTypes.string,
  style: PropTypes.object,
};
Ring.defaultProps = {
  color: '#9c9c9c',
};

const Radar = ({ distance, size, style, playerColor }) => {
  const pixelsPerYard = size / 40;
  return (
    <div
      style={{
        position: 'relative',
        width: size,
        height: size,
        ...style,
      }}
    >
      <Ring size={40 * pixelsPerYard} style={{ opacity: 0.25, background: 'rgba(255, 255, 255, 0.05)' }} />
      <Ring size={30 * pixelsPerYard} style={{ opacity: 0.5 }} />
      <Ring size={20 * pixelsPerYard} style={{ opacity: 0.75 }} />
      <Ring size={10 * pixelsPerYard} style={{ opacity: 1 }} />
      <Ring
        size={distance * pixelsPerYard}
        data-tip={`${formatNumber(distance)} yards`}
        color="#f8b700"
        style={{
          background: 'rgba(248, 183, 0, 0.3)',
          boxShadow: '0 0 4px #f8b700',
        }}
      />
      <div
        style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          width: 5,
          height: 5,
          borderRadius: '50%',
          transform: 'translate(-50%, -50%)',
          background: playerColor,
          pointerEvents: 'none',
        }}
      />
    </div>
  );
};
Radar.propTypes = {
  distance: PropTypes.number.isRequired,
  size: PropTypes.number,
  style: PropTypes.object,
  playerColor: PropTypes.string,
};
Radar.defaultProps = {
  size: 100,
  playerColor: '#f8b700',
};

export default Radar;
<|endoftext|>


<commit_before>(function(root) {

  window.URL = window.URL || window.webkitURL || window.mozURL;

  function disableSmoothRendering(ctx) {
    ctx.webkitImageSmoothingEnabled = false;
    ctx.mozImageSmoothingEnabled = false;
    ctx.imageSmoothingEnabled = false;
    return ctx;
  }

  function Pixelate(image, opts) {
    opts = opts || {};
    this.image = image;
    this.setAmount(opts.amount);

    var imageLoaded = function() {
      this.imageUrl = image.src;
      this.width = image.clientWidth;
      this.height = image.clientHeight;

      this.canvas = document.createElement('canvas');
      this.canvas.style.display = 'none';
      this.canvas.width = this.width;
      this.canvas.height = this.height;

      this.canvas.style.imageRendering = 'optimizeSpeed';
      this.canvas.style.imageRendering = '-webkit-crisp-edges';
      this.canvas.style.imageRendering = '-moz-crisp-edges';
      this.canvas.style.imageRendering = '-o-crisp-edges';
      this.canvas.style.imageRendering = 'crisp-edges';
      this.canvas.style.msInterpolationMode = 'nearest-neighbor';

      this.ctx = this.canvas.getContext('2d');
      this.ctx = disableSmoothRendering(this.ctx);

      this.image.parentNode.appendChild(this.canvas, this.image);
      this.image.onload = null;

      this.pixelImage = new Image();
      this.pixelImage.onload = function() {
        this.ready = true;
        this.render();
      }.bind(this);
      this.pixelImage.src = this.imageUrl;
    }.bind(this);

    if (this.image.complete) {
      imageLoaded();
    }

    this.image.onload = imageLoaded;

    return this;
  }

  Pixelate.prototype.setAmount = function(amount) {
    this.amount = 1 - (amount || 0);
    return this;
  };

  Pixelate.prototype.setWidth = function(width) {
    var height = (this.height / this.width) * width;
    this.width = width;
    this.height = height;
    this.canvas.width = this.width;
    this.canvas.height = this.height;

    this.ctx = disableSmoothRendering(this.ctx);
    return this;
  };

  Pixelate.prototype.render = function() {
    if (!this.ready) return this;
    var w = this.width * (this.amount <= 0 ? 0.01 : this.amount);
    var h = this.height * (this.amount <= 0 ? 0.01 : this.amount);
    // render smaller image
    this.ctx.drawImage(this.pixelImage, 0, 0, w, h);
    // stretch the smaller image
    this.ctx.drawImage(this.canvas, 0, 0, w, h, 0, 0, this.width, this.height);
    this.image.src = this.canvas.toDataURL('image/png');
    return this;
  };

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = Pixelate;
    }
    exports.pixelate = Pixelate;
  } else if (typeof define === 'function' && define.amd) {
    define([], function() {
      return Pixelate;
    });
  } else {
    root.Pixelate = Pixelate;
  }

})(this);
<commit_msg>css text<commit_after>(function(root) {

  window.URL = window.URL || window.webkitURL || window.mozURL;

  function disableSmoothRendering(ctx) {
    ctx.webkitImageSmoothingEnabled = false;
    ctx.mozImageSmoothingEnabled = false;
    ctx.msImageSmoothingEnabled = false;
    ctx.imageSmoothingEnabled = false;
    return ctx;
  }

  function Pixelate(image, opts) {
    opts = opts || {};
    this.image = image;
    this.setAmount(opts.amount);

    var imageLoaded = function() {
      this.imageUrl = image.src;
      this.width = image.clientWidth;
      this.height = image.clientHeight;

      this.canvas = document.createElement('canvas');
      this.canvas.style.display = 'none';
      this.canvas.width = this.width;
      this.canvas.height = this.height;

      this.canvas.style.cssText = 'image-rendering: optimizeSpeed;' + // FireFox < 6.0
                         'image-rendering: -moz-crisp-edges;' + // FireFox
                         'image-rendering: -o-crisp-edges;' +  // Opera
                         'image-rendering: -webkit-crisp-edges;' + // Chrome
                         'image-rendering: crisp-edges;' + // Chrome
                         'image-rendering: -webkit-optimize-contrast;' + // Safari
                         'image-rendering: pixelated; ' + // Future browsers
                         '-ms-interpolation-mode: nearest-neighbor;'; // IE

      this.ctx = this.canvas.getContext('2d');
      this.ctx = disableSmoothRendering(this.ctx);

      this.image.parentNode.appendChild(this.canvas, this.image);
      this.image.onload = null;

      this.pixelImage = new Image();
      this.pixelImage.onload = function() {
        this.ready = true;
        this.render();
      }.bind(this);
      this.pixelImage.src = this.imageUrl;
    }.bind(this);

    if (this.image.complete) {
      imageLoaded();
    }

    this.image.onload = imageLoaded;

    return this;
  }

  Pixelate.prototype.setAmount = function(amount) {
    this.amount = 1 - (amount || 0);
    return this;
  };

  Pixelate.prototype.setWidth = function(width) {
    var height = (this.height / this.width) * width;
    this.width = width;
    this.height = height;
    this.canvas.width = this.width;
    this.canvas.height = this.height;

    this.ctx = disableSmoothRendering(this.ctx);
    return this;
  };

  Pixelate.prototype.render = function() {
    if (!this.ready) return this;
    var w = this.width * (this.amount <= 0 ? 0.01 : this.amount);
    var h = this.height * (this.amount <= 0 ? 0.01 : this.amount);
    // render smaller image
    this.ctx.drawImage(this.pixelImage, 0, 0, w, h);
    // stretch the smaller image
    this.ctx.drawImage(this.canvas, 0, 0, w, h, 0, 0, this.width, this.height);
    this.image.src = this.canvas.toDataURL('image/png');
    return this;
  };

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = Pixelate;
    }
    exports.pixelate = Pixelate;
  } else if (typeof define === 'function' && define.amd) {
    define([], function() {
      return Pixelate;
    });
  } else {
    root.Pixelate = Pixelate;
  }

})(this);
<|endoftext|>


<commit_before>import angular from 'angular'
import register from './utils/register'
import hrRes from 'angular-hy-res'
import formly from 'angular-formly'
import formlyBootstrap from 'angular-formly-templates-bootstrap'
import angularAnimate from 'angular-animate'
import 'ng-promise-status'
import './directives/progressBar/progressBar'

import applicationDirective from './directives/application/application'
import applicationHeaderDirective from './directives/applicationHeader/applicationHeader'
import pollsList from './directives/pollsList/pollsList'
import pollsService from './services/pollsService'
import pollDirective from './directives/poll/poll'
import sirenActionDirective from './directives/sirenAction/sirenAction'

angular.module('pollsClient', [
    'hrSiren',
    'hrLinkHeader',
    hrRes,
    formly,
    formlyBootstrap,
    angularAnimate,
    'ngPromiseStatus',
    'isteven-omni-bar'
])
  .constant('apiLocation', 'https://polls.apiblueprint.org/')
  //.constant('apiLocation', 'http://private-851d-pollshypermedia.apiary-mock.com/')

register('pollsClient')
  .directive('application', applicationDirective)
  .directive('pollsList', pollsList)
  .directive('applicationHeader', applicationHeaderDirective)
  .directive('poll', pollDirective)
  .directive('sirenAction', sirenActionDirective)
  .service('pollsService', pollsService)
<commit_msg>Disable debug informations<commit_after>import angular from 'angular'
import register from './utils/register'
import hrRes from 'angular-hy-res'
import formly from 'angular-formly'
import formlyBootstrap from 'angular-formly-templates-bootstrap'
import angularAnimate from 'angular-animate'
import 'ng-promise-status'
import './directives/progressBar/progressBar'

import applicationDirective from './directives/application/application'
import applicationHeaderDirective from './directives/applicationHeader/applicationHeader'
import pollsList from './directives/pollsList/pollsList'
import pollsService from './services/pollsService'
import pollDirective from './directives/poll/poll'
import sirenActionDirective from './directives/sirenAction/sirenAction'

angular.module('pollsClient', [
    'hrSiren',
    'hrLinkHeader',
    hrRes,
    formly,
    formlyBootstrap,
    angularAnimate,
    'ngPromiseStatus',
    'isteven-omni-bar'
])
  .constant('apiLocation', 'https://polls.apiblueprint.org/')
  //.constant('apiLocation', 'http://private-851d-pollshypermedia.apiary-mock.com/')
  .config(['$compileProvider', function ($compileProvider) {
  // disable debug info
  $compileProvider.debugInfoEnabled(false);
}]);

register('pollsClient')
  .directive('application', applicationDirective)
  .directive('pollsList', pollsList)
  .directive('applicationHeader', applicationHeaderDirective)
  .directive('poll', pollDirective)
  .directive('sirenAction', sirenActionDirective)
  .service('pollsService', pollsService)
<|endoftext|>


<commit_before>export * from './js/Runtime.js';
export * from './js/core/Arc.js';
export * from './js/core/Host.js';
export * from './js/core/Decorator.js';
export * from './js/recipe/Chef.js';
export * from './js/isolation/ses.js';
export * as utils from './js/utils/utils.js';
export {logFactory} from './js/utils/utils.js';
<commit_msg>remove arcs.js<commit_after><|endoftext|>


<commit_before>var remote = require('remote');
var BrowserWindow = remote.require('browser-window');
var Vue = require('vue');
var settings = require('../app/settings');
var Client = require('../app/client');
var Timeline = require('../app/timeline');
var Parser = require('../app/parser');
var accessTokenKey = '';
var accessTokenSecret = '';
var client = '';

var auth = JSON.parse(localStorage.getItem('auth'));
accessTokenKey = auth.accessTokenKey;
accessTokenSecret = auth.accessTokenSecret;
console.log(auth);
client = new Client(settings.TWITTER_CONSUMER_KEY,
                    settings.TWITTER_CONSUMER_SECRET,
                    accessTokenKey,
                    accessTokenSecret);
console.log(client);
var twitterClient = client.getClient();

var timeline = new Timeline(twitterClient);
var parser = new Parser();<commit_msg>コードを簡略化<commit_after>var remote = require('remote');
var BrowserWindow = remote.require('browser-window');
var Vue = require('vue');
var settings = require('../app/settings');
var Client = require('../app/client');
var Timeline = require('../app/timeline');
var Parser = require('../app/parser');

var auth = JSON.parse(localStorage.getItem('auth'));

var client = new Client(settings.TWITTER_CONSUMER_KEY,
                    settings.TWITTER_CONSUMER_SECRET,
                    auth.accessTokenKey,
                    auth.accessTokenSecret);

var twitterClient = client.getClient();

var timeline = new Timeline(twitterClient);
var parser = new Parser();<|endoftext|>