<commit_before>imagespace.views.LayoutUserDataView = imagespace.View.extend({
    events: {
        'click .im-search-by-size': function () {
            this.searchBySizeWidget = new imagespace.views.SearchBySizeWidget({
                el: $('#g-dialog-container'),
                parentView: this
            });
            this.searchBySizeWidget.render();
        },

        'click .im-blur': function () {
            $('#blur-style').text('img.im-blur { -webkit-filter: blur(10px); filter blur(10px) }');
        },

        'click .im-unblur-hover': function () {
            $('#blur-style').text(
                'img.im-blur { -webkit-filter: blur(10px); filter: blur(10px) }'
                + '\nimg.im-blur:hover { -webkit-filter: blur(0px); filter: blur(0px) }');
        },

        'click .im-unblur': function () {
            $('#blur-style').text('');
        },

        'click .im-search-by-serial-number': function () {
            this.searchBySerialNumberWidget = new imagespace.views.SearchBySerialNumberWidget({
                el: $('#g-dialog-container'),
                parentView: this
            });
            this.searchBySerialNumberWidget.render();
        },

        'change #im-files': function () {
            var files = $('#im-files')[0].files;
            _.each(files, function (file) {
                this.upload(file);
            }, this);
        },

        'click #im-upload': function () {
            $('#im-files').click();
        },

        'dragenter #im-upload': function (e) {
            e.stopPropagation();
            e.preventDefault();
            e.originalEvent.dataTransfer.dropEffect = 'copy';
            d3.select('#im-upload')
                .classed('btn-success', true)
                .classed('btn-primary', false);
        },

        'dragleave #im-upload': function (e) {
            e.stopPropagation();
            e.preventDefault();
            d3.select('#im-upload')
                .classed('btn-success', false)
                .classed('btn-primary', true);
        },

        'dragover #im-upload': function (e) {
            e.preventDefault();
        },

        'drop #im-upload': function (e) {
            var files = e.originalEvent.dataTransfer.files;
            e.stopPropagation();
            e.preventDefault();
            if (files.length === 0) {
                this.loadUrl(e.originalEvent.dataTransfer.getData('URL'));
            } else {
                _.each(files, function (file) {
                    this.upload(file);
                }, this);
            }
        },

        'click .im-details': function (event) {
            var id = $(event.currentTarget).attr('im-id'),
                image = this.imageIdMap[id];
            this.imageDetailWidget = new imagespace.views.ImageDetailWidget({
                el: $('#g-dialog-container'),
                image: image,
                parentView: this
            });
            this.imageDetailWidget.render();
        },

        'click .im-remove': function (event) {
            var id = $(event.currentTarget).attr('im-id'),
                image = this.imageIdMap[id],
                item = new girder.models.ItemModel({
                    _id: image.item_id
                });

            if (image.item_id) {
                item.once('g:deleted', function () {
                    this.render();
                }, this).destroy();
            }
        },

        'click .im-find-similar': function (event) {
            var id = $(event.currentTarget).attr('im-id'),
                image = this.imageIdMap[id];
            $('.alert-info').html('Finding similar images ').removeClass('hidden');
            $('.btn-lg').addClass('disabled');
            $(event.currentTarget).parent().find('.im-find-similar')
                .html('');
            if (image.histogram) {
                this.findSimilarImages(image);
            } else {
                girder.restRequest({
                    path: 'imagefeatures',
                    data: {
                        url: image.imageUrl
                    },
                    method: 'POST'
                }).done(_.bind(function (features) {
                    image.histogram = features.histogram;
                    this.findSimilarImages(image);
                }, this));
            }
        },

        'mouseover .im-image-area': function (event) {
            $(event.currentTarget).find('.im-caption-content').removeClass('hidden');
        },

        'mouseout .im-image-area': function (event) {
            $(event.currentTarget).find('.im-caption-content').addClass('hidden');
        }
    },

    initialize: function (settings) {
        this.imagePathRoot = '/data/roxyimages/';
        // this.imagePathRoot = '/data/xdata/syria/syria_instagram_images/';
        this.resLimit = 30;
        this.imageIdMap = {};
        girder.cancelRestRequests('fetch');
        this.render();
    },

    updateUserData: function (done) {
        girder.restRequest({
            path: 'folder?text=Private'
        }).done(_.bind(function (folders) {
            var privateFolder = null;
            folders.forEach(function (folder) {
                if (folder.parentId === girder.currentUser.id) {
                    privateFolder = folder;
                }
            });
            if (privateFolder) {
                console.log(privateFolder);
                girder.restRequest({
                    path: 'item?limit=100&offset=0&sort=created&sortdir=-1&folderId=' + privateFolder._id
                }).done(_.bind(function (items) {
                    imagespace.userData.images = [];
                    console.log(items);
                    items.forEach(_.bind(function (item) {
                        if (item.meta && item.meta.item_id) {
                            imagespace.userData.images.push(item.meta);
                            this.imageIdMap[item.meta.id] = item.meta;
                        }
                    }, this));
                    done();
                }, this));
            }
        }, this));
    },

    render: function () {
        this.updateUserData(_.bind(function () {
            this.$el.html(imagespace.templates.userData({
                userData: imagespace.userData,
                showText: true
            }));
        }, this));
        return this;
    },

    findSimilarImages: function (image) {
        girder.restRequest({
            path: 'imagesearch',
            data: {
                url: image.imageUrl,
                histogram: JSON.stringify(image.histogram || []),
                limit: this.resLimit
            }
        }).done(_.bind(function (results) {
            var query = '(', count = 0;
            results.forEach(_.bind(function (result, index) {
                var parts = result.id.split('/'),
                    file = parts[parts.length - 1];
                if (file.length < 30) {
                    return;
                }
                if (result.id.indexOf('cmuImages') !== -1) {
                    file = 'cmuImages/' + file;
                }
		file = this.imagePathRoot + file;
                if (count < this.resLimit) {
                    query += 'id:"' + file + '" ';
                    count += 1;
                }
            }, this));
            query += ')';
            imagespace.router.navigate('search/' + encodeURIComponent(query), {trigger: true});

            $('.btn-lg').removeClass('disabled');
            $('.im-find-similar').html('');

            $('.alert-info').addClass('hidden');
            $('.alert-success').text('Search complete.').removeClass('hidden');
            setTimeout(function () {
                $('.alert-success').addClass('hidden')
            }, 5000);
        }, this));
    },

    upload: function (file) {
        var reader = new FileReader();

        $('#im-upload')
            .addClass('btn-info disabled')
            .removeClass('btn-default')
            .html(' Processing ...');

        reader.onload = _.bind(function (e) {
            var data = new Uint8Array(e.target.result);
            girder.restRequest({
                path: 'imagefeatures',
                data: data,
                method: 'POST',
                processData: false,
                contentType: 'application/octet-stream'
            }).done(_.bind(function (image) {
                var dataURLReader = new FileReader();

                dataURLReader.onloadend = _.bind(function () {
                    image.imageUrl = dataURLReader.result;
                    imagespace.userData.images.unshift(image);
                    if (girder.currentUser) {
                        girder.restRequest({
                            path: 'folder?text=Private'
                        }).done(_.bind(function (folders) {
                            var privateFolder = null;
                            folders.forEach(function (folder) {
                                if (folder.parentId === girder.currentUser.id) {
                                    privateFolder = folder;
                                }
                            })
                            if (privateFolder) {
                                this.girderUpload(this.dataURLToBlob(dataURLReader.result), file.name, privateFolder._id, null, _.bind(function (fileObject) {
                                    var location = window.location, item;
                                    image.imageUrl = location.protocol + '//' + location.host + location.pathname + '/girder/api/v1/file/' + fileObject.id + '/download?token=' + girder.cookie.find('girderToken');

                                    console.log('fileObject');
                                    console.log(fileObject);

                                    item = new girder.models.ItemModel({_id: fileObject.attributes.itemId});
                                    image.item_id = fileObject.attributes.itemId;
                                    item._sendMetadata(image, _.bind(function () {
                                        this.render();
                                    }, this));
                                }, this));
                            }
                        }, this));
                    }
                }, this);

                dataURLReader.readAsDataURL(file);
                image.id = file.name;
            }, this));
        }, this);

        reader.readAsArrayBuffer(file);
    },

    addUserImage: function (image) {
        image.source_query = window.location.href;

        girder.restRequest({
            path: 'folder?text=Private'
        }).done(_.bind(function (folders) {
            var privateFolder = null;
            folders.forEach(function (folder) {
                if (folder.parentId === girder.currentUser.id) {
                    privateFolder = folder;
                }
            })
            if (privateFolder) {
                var item = new girder.models.ItemModel({
                    name: image.id,
                    folderId: privateFolder._id
                });

                item.once('g:saved', _.bind(function () {
                    console.log(item);
                    image.item_id = item.attributes._id;
                    console.log(image);
                    item._sendMetadata(image, _.bind(function () {
                        this.render();
                    }, this), function (error) {
                        // TODO report error
                    })
                }, this)).once('g:error', function (error) {
                    console.log(error);
                }, this).save();
            }
        }, this));
    },

    loadUrl: function (url) {
        $('#im-upload')
            .addClass('btn-info disabled')
            .removeClass('btn-default')
            .html(' Processing ...');

        girder.restRequest({
            path: 'imagefeatures',
            data: {
                url: url
            },
            method: 'POST'
        }).done(_.bind(function (image) {
            image.imageUrl = url;
            image.id = url;

            this.addUserImage(image);
        }, this));
    },

    girderUpload: function (data, name, folderId, itemToOverwrite, success, error) {
        success = success || function () {};
        error = error || function () {};

        var file, bindEvents = function (file) {
            file.on('g:upload.complete', function () {
                success(file);
            }).on('g:upload.error', function () {
            }).on('g:upload.error g:upload.errorStarting', function () {
                error(file);
            });
            return file;
        };

        if (itemToOverwrite) {
            // We have the dataset's itemid, but we need its fileid.
            var files = new girder.collections.FileCollection();
            files.altUrl = 'item/' + itemToOverwrite + '/files';

            files.on('g:changed', function () {
                file = bindEvents(files.models[0]);
                file.updateContents(data);
            }).fetch();
        } else {
            var folder = new girder.models.FolderModel({_id: folderId});
            file = bindEvents(new girder.models.FileModel());
            file.uploadToFolder(folder, data, name);
        }

        return file;
    },

    dataURLToBlob: function (dataURL) {
        var BASE64_MARKER = ';base64,';
        if (dataURL.indexOf(BASE64_MARKER) == -1) {
            var parts = dataURL.split(','),
                contentType = parts[0].split(':')[1],
                raw = decodeURIComponent(parts[1]);

            return new Blob([raw], {type: contentType});
        }

        var parts = dataURL.split(BASE64_MARKER),
            contentType = parts[0].split(':')[1],
            raw = window.atob(parts[1]),
            rawLength = raw.length,
            uInt8Array = new Uint8Array(rawLength);

        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], {type: contentType});
    }

});
<commit_msg>Fix css rule<commit_after>imagespace.views.LayoutUserDataView = imagespace.View.extend({
    events: {
        'click .im-search-by-size': function () {
            this.searchBySizeWidget = new imagespace.views.SearchBySizeWidget({
                el: $('#g-dialog-container'),
                parentView: this
            });
            this.searchBySizeWidget.render();
        },

        'click .im-blur': function () {
            $('#blur-style').text('img.im-blur { -webkit-filter: blur(10px); filter: blur(10px) }');
        },

        'click .im-unblur-hover': function () {
            $('#blur-style').text(
                'img.im-blur { -webkit-filter: blur(10px); filter: blur(10px) }'
                + '\nimg.im-blur:hover { -webkit-filter: blur(0px); filter: blur(0px) }');
        },

        'click .im-unblur': function () {
            $('#blur-style').text('');
        },

        'click .im-search-by-serial-number': function () {
            this.searchBySerialNumberWidget = new imagespace.views.SearchBySerialNumberWidget({
                el: $('#g-dialog-container'),
                parentView: this
            });
            this.searchBySerialNumberWidget.render();
        },

        'change #im-files': function () {
            var files = $('#im-files')[0].files;
            _.each(files, function (file) {
                this.upload(file);
            }, this);
        },

        'click #im-upload': function () {
            $('#im-files').click();
        },

        'dragenter #im-upload': function (e) {
            e.stopPropagation();
            e.preventDefault();
            e.originalEvent.dataTransfer.dropEffect = 'copy';
            d3.select('#im-upload')
                .classed('btn-success', true)
                .classed('btn-primary', false);
        },

        'dragleave #im-upload': function (e) {
            e.stopPropagation();
            e.preventDefault();
            d3.select('#im-upload')
                .classed('btn-success', false)
                .classed('btn-primary', true);
        },

        'dragover #im-upload': function (e) {
            e.preventDefault();
        },

        'drop #im-upload': function (e) {
            var files = e.originalEvent.dataTransfer.files;
            e.stopPropagation();
            e.preventDefault();
            if (files.length === 0) {
                this.loadUrl(e.originalEvent.dataTransfer.getData('URL'));
            } else {
                _.each(files, function (file) {
                    this.upload(file);
                }, this);
            }
        },

        'click .im-details': function (event) {
            var id = $(event.currentTarget).attr('im-id'),
                image = this.imageIdMap[id];
            this.imageDetailWidget = new imagespace.views.ImageDetailWidget({
                el: $('#g-dialog-container'),
                image: image,
                parentView: this
            });
            this.imageDetailWidget.render();
        },

        'click .im-remove': function (event) {
            var id = $(event.currentTarget).attr('im-id'),
                image = this.imageIdMap[id],
                item = new girder.models.ItemModel({
                    _id: image.item_id
                });

            if (image.item_id) {
                item.once('g:deleted', function () {
                    this.render();
                }, this).destroy();
            }
        },

        'click .im-find-similar': function (event) {
            var id = $(event.currentTarget).attr('im-id'),
                image = this.imageIdMap[id];
            $('.alert-info').html('Finding similar images ').removeClass('hidden');
            $('.btn-lg').addClass('disabled');
            $(event.currentTarget).parent().find('.im-find-similar')
                .html('');
            if (image.histogram) {
                this.findSimilarImages(image);
            } else {
                girder.restRequest({
                    path: 'imagefeatures',
                    data: {
                        url: image.imageUrl
                    },
                    method: 'POST'
                }).done(_.bind(function (features) {
                    image.histogram = features.histogram;
                    this.findSimilarImages(image);
                }, this));
            }
        },

        'mouseover .im-image-area': function (event) {
            $(event.currentTarget).find('.im-caption-content').removeClass('hidden');
        },

        'mouseout .im-image-area': function (event) {
            $(event.currentTarget).find('.im-caption-content').addClass('hidden');
        }
    },

    initialize: function (settings) {
        this.imagePathRoot = '/data/roxyimages/';
        // this.imagePathRoot = '/data/xdata/syria/syria_instagram_images/';
        this.resLimit = 30;
        this.imageIdMap = {};
        girder.cancelRestRequests('fetch');
        this.render();
    },

    updateUserData: function (done) {
        girder.restRequest({
            path: 'folder?text=Private'
        }).done(_.bind(function (folders) {
            var privateFolder = null;
            folders.forEach(function (folder) {
                if (folder.parentId === girder.currentUser.id) {
                    privateFolder = folder;
                }
            });
            if (privateFolder) {
                console.log(privateFolder);
                girder.restRequest({
                    path: 'item?limit=100&offset=0&sort=created&sortdir=-1&folderId=' + privateFolder._id
                }).done(_.bind(function (items) {
                    imagespace.userData.images = [];
                    console.log(items);
                    items.forEach(_.bind(function (item) {
                        if (item.meta && item.meta.item_id) {
                            imagespace.userData.images.push(item.meta);
                            this.imageIdMap[item.meta.id] = item.meta;
                        }
                    }, this));
                    done();
                }, this));
            }
        }, this));
    },

    render: function () {
        this.updateUserData(_.bind(function () {
            this.$el.html(imagespace.templates.userData({
                userData: imagespace.userData,
                showText: true
            }));
        }, this));
        return this;
    },

    findSimilarImages: function (image) {
        girder.restRequest({
            path: 'imagesearch',
            data: {
                url: image.imageUrl,
                histogram: JSON.stringify(image.histogram || []),
                limit: this.resLimit
            }
        }).done(_.bind(function (results) {
            var query = '(', count = 0;
            results.forEach(_.bind(function (result, index) {
                var parts = result.id.split('/'),
                    file = parts[parts.length - 1];
                if (file.length < 30) {
                    return;
                }
                if (result.id.indexOf('cmuImages') !== -1) {
                    file = 'cmuImages/' + file;
                }
		file = this.imagePathRoot + file;
                if (count < this.resLimit) {
                    query += 'id:"' + file + '" ';
                    count += 1;
                }
            }, this));
            query += ')';
            imagespace.router.navigate('search/' + encodeURIComponent(query), {trigger: true});

            $('.btn-lg').removeClass('disabled');
            $('.im-find-similar').html('');

            $('.alert-info').addClass('hidden');
            $('.alert-success').text('Search complete.').removeClass('hidden');
            setTimeout(function () {
                $('.alert-success').addClass('hidden')
            }, 5000);
        }, this));
    },

    upload: function (file) {
        var reader = new FileReader();

        $('#im-upload')
            .addClass('btn-info disabled')
            .removeClass('btn-default')
            .html(' Processing ...');

        reader.onload = _.bind(function (e) {
            var data = new Uint8Array(e.target.result);
            girder.restRequest({
                path: 'imagefeatures',
                data: data,
                method: 'POST',
                processData: false,
                contentType: 'application/octet-stream'
            }).done(_.bind(function (image) {
                var dataURLReader = new FileReader();

                dataURLReader.onloadend = _.bind(function () {
                    image.imageUrl = dataURLReader.result;
                    imagespace.userData.images.unshift(image);
                    if (girder.currentUser) {
                        girder.restRequest({
                            path: 'folder?text=Private'
                        }).done(_.bind(function (folders) {
                            var privateFolder = null;
                            folders.forEach(function (folder) {
                                if (folder.parentId === girder.currentUser.id) {
                                    privateFolder = folder;
                                }
                            })
                            if (privateFolder) {
                                this.girderUpload(this.dataURLToBlob(dataURLReader.result), file.name, privateFolder._id, null, _.bind(function (fileObject) {
                                    var location = window.location, item;
                                    image.imageUrl = location.protocol + '//' + location.host + location.pathname + '/girder/api/v1/file/' + fileObject.id + '/download?token=' + girder.cookie.find('girderToken');

                                    console.log('fileObject');
                                    console.log(fileObject);

                                    item = new girder.models.ItemModel({_id: fileObject.attributes.itemId});
                                    image.item_id = fileObject.attributes.itemId;
                                    item._sendMetadata(image, _.bind(function () {
                                        this.render();
                                    }, this));
                                }, this));
                            }
                        }, this));
                    }
                }, this);

                dataURLReader.readAsDataURL(file);
                image.id = file.name;
            }, this));
        }, this);

        reader.readAsArrayBuffer(file);
    },

    addUserImage: function (image) {
        image.source_query = window.location.href;

        girder.restRequest({
            path: 'folder?text=Private'
        }).done(_.bind(function (folders) {
            var privateFolder = null;
            folders.forEach(function (folder) {
                if (folder.parentId === girder.currentUser.id) {
                    privateFolder = folder;
                }
            })
            if (privateFolder) {
                var item = new girder.models.ItemModel({
                    name: image.id,
                    folderId: privateFolder._id
                });

                item.once('g:saved', _.bind(function () {
                    console.log(item);
                    image.item_id = item.attributes._id;
                    console.log(image);
                    item._sendMetadata(image, _.bind(function () {
                        this.render();
                    }, this), function (error) {
                        // TODO report error
                    })
                }, this)).once('g:error', function (error) {
                    console.log(error);
                }, this).save();
            }
        }, this));
    },

    loadUrl: function (url) {
        $('#im-upload')
            .addClass('btn-info disabled')
            .removeClass('btn-default')
            .html(' Processing ...');

        girder.restRequest({
            path: 'imagefeatures',
            data: {
                url: url
            },
            method: 'POST'
        }).done(_.bind(function (image) {
            image.imageUrl = url;
            image.id = url;

            this.addUserImage(image);
        }, this));
    },

    girderUpload: function (data, name, folderId, itemToOverwrite, success, error) {
        success = success || function () {};
        error = error || function () {};

        var file, bindEvents = function (file) {
            file.on('g:upload.complete', function () {
                success(file);
            }).on('g:upload.error', function () {
            }).on('g:upload.error g:upload.errorStarting', function () {
                error(file);
            });
            return file;
        };

        if (itemToOverwrite) {
            // We have the dataset's itemid, but we need its fileid.
            var files = new girder.collections.FileCollection();
            files.altUrl = 'item/' + itemToOverwrite + '/files';

            files.on('g:changed', function () {
                file = bindEvents(files.models[0]);
                file.updateContents(data);
            }).fetch();
        } else {
            var folder = new girder.models.FolderModel({_id: folderId});
            file = bindEvents(new girder.models.FileModel());
            file.uploadToFolder(folder, data, name);
        }

        return file;
    },

    dataURLToBlob: function (dataURL) {
        var BASE64_MARKER = ';base64,';
        if (dataURL.indexOf(BASE64_MARKER) == -1) {
            var parts = dataURL.split(','),
                contentType = parts[0].split(':')[1],
                raw = decodeURIComponent(parts[1]);

            return new Blob([raw], {type: contentType});
        }

        var parts = dataURL.split(BASE64_MARKER),
            contentType = parts[0].split(':')[1],
            raw = window.atob(parts[1]),
            rawLength = raw.length,
            uInt8Array = new Uint8Array(rawLength);

        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], {type: contentType});
    }

});
<|endoftext|>


<commit_before>

/**
 * Yo, the single page dependency management script created by pocketninja for his own amusement
 *
 * @module Yo
 * @returns {object} public functions
 */
var Yo = function() {
  // Yo.loadedState.tooltip.{
  //    loaded: boolean
  //    loadedFunc: function
  //    dependedBy: [string],
  //    dependencies: [string]
  // }

  /**
   * container of the namespace object provided by the user with Yo.init()
   * @private
   * @var {object} ns
   */
  var ns;
  var scriptRoot = 'modules';

  /**
   * After creating Yo you need to provide it with your main namespace to any level within it. Like "company" or "company.cool.scripts"
   *
   * @method init
   * @param {object} data - initial data object.
   * @param {object} data.namespace - users main script namespace.
   *
   * @example
   * Yo.init({
   *   namespace: your.script.name.space,
   *   scriptRoot: 'cheese'
   * });
   */
  var init = function(data){
    ns = data.namespace || Yo;
    Yo.loadedState = {};
    if(data.scriptRoot) {
      scriptRoot = data.scriptRoot;
    }
    ns[scriptRoot] = {};
  };

  var isTypeOf = function(str, obj) {
    return '[object ' + str + ']' === Object.prototype.toString.call(obj);
  };

  var argumentChecker = function(args, argSequence) {
    if(args.length === argSequence.length) {
      var i, val;
      for (i = 0; i < args.length; i++) {
        val = args[i];
        if (!isTypeOf(argSequence[i], val)) {
          console.log('Error with value comparison: ' + val + ', EXPECTED: ' + argSequence[i]);
          return false;
        }
      }

      return true;
    }
    else {
      return false;
    }
  };

  var arrayClone = function(arr) {
    return arr.slice(0);
  };

  var extend = function() {
    for(var i=1; i < arguments.length; i++) {
      for(var key in arguments[i]) {
        if(arguments[i].hasOwnProperty(key)) {
          arguments[0][key] = arguments[i][key];
        }
      }
    }
    return arguments[0];
  };

  /**
   * For adding new scripts with their own dependencies
   *
   * @method add
   * @param {string} scriptName Script name
   * @param {array} [scriptDependencies=undefined] Script list of dependencies
   * @param {function} scriptCallback Script module callback
   *
   * @example
   * Yo.add('WidgetName', ['dependency1', 'dependency2', 'etc'], function() {
   *   // your code in here
   *   return {}
   * });
   */
  var add = function() {

    var scriptName;
    var scriptDependencies = [];
    var scriptCallback;
    var hasNoDependencies = true;

    /**
     * Gets either and object or false
     *
     * @method add
     * @param {string} _nsStr Script namespace or name
     * @param {object} _nsObject Namespace object
     *
     * @returns {object || boolean} functions
     *
     */
    var nsGet = function(_nsStr, _nsObject, _getObjectRoot) {
      var keyArr = _nsStr.split('.');
      var currentObj = _nsObject;
      _getObjectRoot = _getObjectRoot || false;

      for(var i = 0; i < keyArr.length; i++) {
        if (!currentObj[keyArr[i]]) {
          return false;
        }
        if(_getObjectRoot && (i === keyArr.length - 1)) {
          return currentObj;
        }
        currentObj = currentObj[keyArr[i]];
      }

      return currentObj;
    };

    /**
     * Set new branches to your namespace tree
     * WIll run through the object tree creating
     * everything that doesn't exist.
     *
     * @method add
     * @param {string} _nsStr Script namespace or name
     * @param {object} _nsObject Namespace object
     *
     * @returns {object} Section of the object param
     *
     */
    var nsSet = function(_nsStr, _nsObject, _getObjectRoot) {
      var keyArr = _nsStr.split('.');
      var currentObj = _nsObject;
      _getObjectRoot = _getObjectRoot || false;

      if (keyArr.length < 2) {
        if(!currentObj[_nsStr]) {
          currentObj[_nsStr] = {};
        }
        if(_getObjectRoot) {
          return _nsObject;
        }
        return currentObj[_nsStr];
      }
      else {
        for(var i = 0; i < keyArr.length; i++) {
          if (!currentObj[keyArr[i]]) {
            currentObj[keyArr[i]] = {};
          }
          if(_getObjectRoot && (i === keyArr.length - 1)) {
            return currentObj;
          }
          currentObj = currentObj[keyArr[i]];
        }
      }

      return currentObj;
    };

    var getLoadedState = function(_script) {
      return nsGet(_script, Yo.loadedState);
    };

    var setLoadedState = function(_script, _data) {
      extend(nsSet(_script, Yo.loadedState), _data);
    };

    var activateScript = function(_script) {
      var nsLocation = nsSet(_script, ns[scriptRoot], true);
      if(getLoadedState(_script).loaded) {
        nsLocation[_script] = getLoadedState(_script).loadedFunc();
      }
    };

    var getScript = function(_script) {
      return nsSet(_script, ns[scriptRoot]);
    };

    var createOrEditLoadedState = function(_data, _script) {
      _script = _script || scriptName;

      setLoadedState(_script, extend({
        loaded: false,
        loadedFunc: function(){},
        dependedBy: [],
        dependencies: []
      }, nsSet(_script, Yo.loadedState) || {}, _data));
    };

    /**
     * Callback added to loadState[scriptName].loadedFunc which is run once all of it's dependencies have loaded
     *
     * @function pushFunction
     * @private
     */
    var pushFunction = function() {
      createOrEditLoadedState({
        loaded: true,
        loadedFunc: function() { console.log(scriptName + ' called and already loaded'); }
      });
      return scriptCallback.apply(null, scriptDependencies.map(function(_scriptName) {
        return getScript(_scriptName);
      }));
    };

    var checkDependedBy = function() {
      var dependedBy = getLoadedState(scriptName).dependedBy;

      dependedBy.forEach(function(otherScript) {
        for(var i = 0; i < dependedBy.length; i++) {
          if (getLoadedState(otherScript).dependencies[i] === scriptName) {
            getLoadedState(otherScript).dependencies.splice(i, 1);
            dependedBy.splice(i, 1);
            break;
          }
        }

        if (getLoadedState(otherScript).dependencies.length < 1) {
          getLoadedState(otherScript).loaded = true;
          activateScript(otherScript);
        }
      });
    };

    var checkDependencies = function() {
      var allDependenciesLoaded = true;
      var scriptDependents = getLoadedState(scriptName).dependencies;
      var dependencyScriptName;

      var looper = function() {
        for(var i = 0; i < scriptDependents.length; i++) {
          dependencyScriptName = scriptDependents[i];
          // If script name loadState doesn't
          // exist then create one
          if(!nsGet(dependencyScriptName, Yo.loadedState)) {
            createOrEditLoadedState({}, dependencyScriptName);
          }

          if(!getLoadedState(dependencyScriptName).loaded) {
            getLoadedState(dependencyScriptName).dependedBy.push(scriptName);
            allDependenciesLoaded = false;
          }
          else {
            scriptDependents.splice(i, 1);
            looper();
            break;
          }
        }
      };

      looper();

      if(allDependenciesLoaded) {
        getLoadedState(scriptName).loaded = true;
      }
    };

    if(argumentChecker(arguments, ['String', 'Array', 'Function'])) {
      scriptName = arguments[0].toLowerCase();
      scriptDependencies = arguments[1];
      scriptCallback = arguments[2];
      hasNoDependencies = scriptDependencies.length < 1;
    }
    else if(argumentChecker(arguments, ['String', 'Function'])) {
      scriptName = arguments[0].toLowerCase();
      scriptCallback = arguments[1];
    }
    else {
      console.log('incorrect params added', arguments);
      return false;
    }

    console.log('YO.ADD: ' + scriptName);

    if (hasNoDependencies) {
      createOrEditLoadedState({
        loaded: true,
        loadedFunc: scriptCallback
      });
      activateScript(scriptName);
      checkDependedBy();
    }
    else {
      createOrEditLoadedState({
        loadedFunc: pushFunction,
        dependencies: arrayClone(scriptDependencies)
      });
      checkDependencies();
      activateScript(scriptName);
      checkDependedBy();
    }
  };

  return {
    init: init,
    add: add,
    isTypeOf: isTypeOf,
    argumentChecker: argumentChecker,
    arrayClone: arrayClone,
    extend: extend
  }
}();<commit_msg>Finally finished it.  Maybe, so now you can namespace your scripts<commit_after>

/**
 * Yo, the single page dependency management script created by pocketninja for his own amusement
 *
 * @module Yo
 * @returns {object} public functions
 */
var Yo = function() {
  // Yo.loadedState.tooltip.{
  //    loaded: boolean
  //    loadedFunc: function
  //    dependedBy: [string],
  //    dependencies: [string]
  // }

  /**
   * container of the namespace object provided by the user with Yo.init()
   * @private
   * @var {object} ns
   */
  var ns;
  var scriptRoot = 'modules';

  /**
   * After creating Yo you need to provide it with your main namespace to any level within it. Like "company" or "company.cool.scripts"
   *
   * @method init
   * @param {object} data - initial data object.
   * @param {object} data.namespace - users main script namespace.
   *
   * @example
   * Yo.init({
   *   namespace: your.script.name.space,
   *   scriptRoot: 'cheese'
   * });
   */
  var init = function(data){
    ns = data.namespace || Yo;
    Yo.loadedState = {};
    if(data.scriptRoot) {
      scriptRoot = data.scriptRoot;
    }
    ns[scriptRoot] = {};
  };

  var isTypeOf = function(str, obj) {
    return '[object ' + str + ']' === Object.prototype.toString.call(obj);
  };

  var argumentChecker = function(args, argSequence) {
    if(args.length === argSequence.length) {
      var i, val;
      for (i = 0; i < args.length; i++) {
        val = args[i];
        if (!isTypeOf(argSequence[i], val)) {
          console.log('Error with value comparison: ' + val + ', EXPECTED: ' + argSequence[i]);
          return false;
        }
      }

      return true;
    }
    else {
      return false;
    }
  };

  var arrayClone = function(arr) {
    return arr.slice(0);
  };

  var extend = function() {
    for(var i=1; i < arguments.length; i++) {
      for(var key in arguments[i]) {
        if(arguments[i].hasOwnProperty(key)) {
          arguments[0][key] = arguments[i][key];
        }
      }
    }
    return arguments[0];
  };

  /**
   * For adding new scripts with their own dependencies
   *
   * @method add
   * @param {string} scriptName Script name
   * @param {array} [scriptDependencies=undefined] Script list of dependencies
   * @param {function} scriptCallback Script module callback
   *
   * @example
   * Yo.add('WidgetName', ['dependency1', 'dependency2', 'etc'], function() {
   *   // your code in here
   *   return {}
   * });
   */
  var add = function() {

    var scriptName;
    var scriptDependencies = [];
    var scriptCallback;
    var hasNoDependencies = true;

    /**
     * Gets either and object or false
     *
     * @method add
     * @param {string} _nsStr Script namespace or name
     * @param {object} _nsObject Namespace object
     *
     * @returns {object || boolean} functions
     *
     */
    var nsGet = function(_nsStr, _nsObject, _getObjectRoot) {
      var keyArr = _nsStr.split('.');
      var currentObj = _nsObject;
      _getObjectRoot = _getObjectRoot || false;

      for(var i = 0; i < keyArr.length; i++) {
        if (!currentObj[keyArr[i]]) {
          return false;
        }
        if(_getObjectRoot && (i === keyArr.length - 1)) {
          return currentObj;
        }
        currentObj = currentObj[keyArr[i]];
      }

      return currentObj;
    };

    /**
     * Set new branches to your namespace tree
     * WIll run through the object tree creating
     * everything that doesn't exist.
     *
     * @method add
     * @param {string} _nsStr Script namespace or name
     * @param {object} _nsObject Namespace object
     *
     * @returns {object} Section of the object param
     *
     */
    var nsSet = function(_nsStr, _nsObject, _getObjectRoot) {
      var keyArr = _nsStr.split('.');
      var currentObj = _nsObject;
      _getObjectRoot = _getObjectRoot || false;

      if (keyArr.length < 2) {
        if(!currentObj[_nsStr]) {
          currentObj[_nsStr] = {};
        }
        if(_getObjectRoot) {
          return _nsObject;
        }
        return currentObj[_nsStr];
      }
      else {
        for(var i = 0; i < keyArr.length; i++) {
          if (!currentObj[keyArr[i]]) {
            currentObj[keyArr[i]] = {};
          }
          if(_getObjectRoot && (i === keyArr.length - 1)) {
            return currentObj;
          }
          currentObj = currentObj[keyArr[i]];
        }
      }

      return currentObj;
    };

    var getLoadedState = function(_script) {
      return nsGet(_script, Yo.loadedState);
    };

    var setLoadedState = function(_script, _data) {
      extend(nsSet(_script, Yo.loadedState), _data);
    };

    var activateScript = function(_script) {
      var nsLocation = nsSet(_script, ns[scriptRoot], true);
      var lastNameSpace = _script.split('.');
      lastNameSpace = lastNameSpace[lastNameSpace.length - 1];

      if(getLoadedState(_script).loaded) {
        nsLocation[lastNameSpace] = getLoadedState(_script).loadedFunc();
      }
    };

    var getScript = function(_script) {
      return nsSet(_script, ns[scriptRoot]);
    };

    var createOrEditLoadedState = function(_data, _script) {
      _script = _script || scriptName;

      setLoadedState(_script, extend({
        loaded: false,
        loadedFunc: function(){},
        dependedBy: [],
        dependencies: []
      }, nsSet(_script, Yo.loadedState) || {}, _data));
    };

    /**
     * Callback added to loadState[scriptName].loadedFunc which is run once all of it's dependencies have loaded
     *
     * @function pushFunction
     * @private
     */
    var pushFunction = function() {
      createOrEditLoadedState({
        loaded: true,
        loadedFunc: function() { console.log(scriptName + ' called and already loaded'); }
      });
      return scriptCallback.apply(null, scriptDependencies.map(function(_scriptName) {
        return getScript(_scriptName);
      }));
    };

    var checkDependedBy = function() {
      var dependedBy = getLoadedState(scriptName).dependedBy;

      dependedBy.forEach(function(otherScript) {
        for(var i = 0; i < dependedBy.length; i++) {
          if (getLoadedState(otherScript).dependencies[i] === scriptName) {
            getLoadedState(otherScript).dependencies.splice(i, 1);
            dependedBy.splice(i, 1);
            break;
          }
        }

        if (getLoadedState(otherScript).dependencies.length < 1) {
          getLoadedState(otherScript).loaded = true;
          activateScript(otherScript);
        }
      });
    };

    var checkDependencies = function() {
      var allDependenciesLoaded = true;
      var scriptDependents = getLoadedState(scriptName).dependencies;
      var dependencyScriptName;

      var looper = function() {
        for(var i = 0; i < scriptDependents.length; i++) {
          dependencyScriptName = scriptDependents[i];
          // If script name loadState doesn't
          // exist then create one
          if(!nsGet(dependencyScriptName, Yo.loadedState)) {
            createOrEditLoadedState({}, dependencyScriptName);
          }

          if(!getLoadedState(dependencyScriptName).loaded) {
            getLoadedState(dependencyScriptName).dependedBy.push(scriptName);
            allDependenciesLoaded = false;
          }
          else {
            scriptDependents.splice(i, 1);
            looper();
            break;
          }
        }
      };

      looper();

      if(allDependenciesLoaded) {
        getLoadedState(scriptName).loaded = true;
      }
    };

    if(argumentChecker(arguments, ['String', 'Array', 'Function'])) {
      scriptName = arguments[0].toLowerCase();
      scriptDependencies = arguments[1];
      scriptCallback = arguments[2];
      hasNoDependencies = scriptDependencies.length < 1;
    }
    else if(argumentChecker(arguments, ['String', 'Function'])) {
      scriptName = arguments[0].toLowerCase();
      scriptCallback = arguments[1];
    }
    else {
      console.log('incorrect params added', arguments);
      return false;
    }

    console.log('YO.ADD: ' + scriptName);

    if (hasNoDependencies) {
      createOrEditLoadedState({
        loaded: true,
        loadedFunc: scriptCallback
      });
      activateScript(scriptName);
      checkDependedBy();
    }
    else {
      createOrEditLoadedState({
        loadedFunc: pushFunction,
        dependencies: arrayClone(scriptDependencies)
      });
      checkDependencies();
      activateScript(scriptName);
      checkDependedBy();
    }
  };

  return {
    init: init,
    add: add,
    isTypeOf: isTypeOf,
    argumentChecker: argumentChecker,
    arrayClone: arrayClone,
    extend: extend
  }
}();<|endoftext|>


<commit_before>$(document).ready(function () {
  /* --Variables------------------------------------------------------------- */

  var faqsContainer = $('#faqs-list')
  var jsonPath = 'data/faqs.json'

  /* --Functions------------------------------------------------------------- */

  function expandLinked () {
    var url = document.location.toString()
    var hash = url.split('#')[1]

    if (typeof hash !== 'undefined') {
      var title = '#' + hash
      var panel = title + '_c'

      // collapse the expanded panel
      var allPanels = $('#accordion .accordion-collapse')

      allPanels.removeClass('in')
      allPanels.find('.accordion-toggle').addClass('collapsed')

      // expand the requested panel, change the title
      $(panel).addClass('in')
      $(title).find('.accordion-toggle').removeClass('collapsed')

      location.href = title
    }
  }

  function printList () {
    /* -- Open JSON file, parse the contents, loop through & print markup -- */

    $.ajaxSetup({
      cache: false
    })

    $.getJSON(jsonPath, function (data) {
      $.each(data, function (key, value) {
        /* -- Assign returned data -- */
        var id = value.id
        var question = value.question
        var answer = value.answer

        var entry = ''
        entry += '
' +
                    '
' +
                        '' + question +
                        '' +
                    '
' +
                 '
' +
                 '
' +
                    '
' +
                        '
' + answer + '
' +
                    '
' +
                 '
'

        /* -- Add it to the list! -- */
        faqsContainer.append(entry)
      })

      expandLinked()
    })
  }

  /* --Calls----------------------------------------------------------------- */

  printList()
})
<commit_msg>Remove obsolete jquery-faqs.js<commit_after><|endoftext|>


<commit_before>angular
	.module('ngSharepoint')
	.factory('SelectQuery', ['$q', '$sp', 'Query', 'WhereQuery', function($q, $sp, WhereQuery, Query) {
        var SelectQuery = function(fields) {
            this.__values = fields;
            this.__where = null;
            this.__limit = null;
            this.__queries.where = [];
            this.__queries.limit = [];
            return this;
        };
        SelectQuery.prototype = new Query();
        SelectQuery.prototype.from = function(list) {
        	this.__list = list;
        	return this;
        };
        SelectQuery.prototype.where = function(field) {
            this.__where = new WhereQuery(this, field);
            return this.__where;
        };
        SelectQuery.prototype.limit = function(amount) {
            this.__limit = amount;
            return this;
        };
        SelectQuery.prototype.__execute = function() {
            var query = this;
            return $q(function(resolve, reject) {
                var clientContext = $sp.getContext();
                var camlQuery = new SP.CamlQuery();
                var caml = ['<View>'];
                if (query.__where !== null) {
                    query.__where.push(caml);
                }
                caml.push('<ViewFields>');
                query.__values.forEach(function(field) {
                    caml.push('<FieldRef Name="' + field + '"/>');
                });
                caml.push('</ViewFields>');
                if (query.__limit !== null) {
                    caml.push('<RowLimit>' + query.__limit + '</RowLimit>');
                }
                caml.push('</View>');
                camlQuery.set_viewXml(caml.join(''));
                var items = query.__list.getItems(camlQuery);
                clientContext.load(items);
                clientContext.executeQueryAsync(
                    function(sender, args) {
                        var result = [];
                        var itemIterator = items.getEnumerator();
                        while (itemIterator.moveNext()) {
                           var item = itemIterator.get_current();
                           result.push(query.unpackItem(item));
                        }
                        resolve(result);
                    },
                    function(sender, args) {
                        reject(args);
                    }
                );
            });
        };
		return (SelectQuery);
	}]);<commit_msg>Fixed mixed up dependency injection<commit_after>angular
	.module('ngSharepoint')
	.factory('SelectQuery', ['$q', '$sp', 'Query', 'WhereQuery', function($q, $sp, Query, WhereQuery) {
        var SelectQuery = function(fields) {
            this.__values = fields;
            this.__where = null;
            this.__limit = null;
            this.__queries.where = [];
            this.__queries.limit = [];
            return this;
        };
        SelectQuery.prototype = new Query();
        SelectQuery.prototype.from = function(list) {
        	this.__list = list;
        	return this;
        };
        SelectQuery.prototype.where = function(field) {
            this.__where = new WhereQuery(this, field);
            return this.__where;
        };
        SelectQuery.prototype.limit = function(amount) {
            this.__limit = amount;
            return this;
        };
        SelectQuery.prototype.__execute = function() {
            var query = this;
            return $q(function(resolve, reject) {
                var clientContext = $sp.getContext();
                var camlQuery = new SP.CamlQuery();
                var caml = ['<View>'];
                if (query.__where !== null) {
                    query.__where.push(caml);
                }
                caml.push('<ViewFields>');
                query.__values.forEach(function(field) {
                    caml.push('<FieldRef Name="' + field + '"/>');
                });
                caml.push('</ViewFields>');
                if (query.__limit !== null) {
                    caml.push('<RowLimit>' + query.__limit + '</RowLimit>');
                }
                caml.push('</View>');
                camlQuery.set_viewXml(caml.join(''));
                var items = query.__list.getItems(camlQuery);
                clientContext.load(items);
                clientContext.executeQueryAsync(
                    function(sender, args) {
                        var result = [];
                        var itemIterator = items.getEnumerator();
                        while (itemIterator.moveNext()) {
                           var item = itemIterator.get_current();
                           result.push(query.unpackItem(item));
                        }
                        resolve(result);
                    },
                    function(sender, args) {
                        reject(args);
                    }
                );
            });
        };
		return (SelectQuery);
	}]);<|endoftext|>


<commit_before>import React from 'react';
import compose from 'recompose/compose';
import { themr } from 'react-css-themr';
import markdown from 'markdown-in-js';
import Carusel from './Carusel';
import contentStyles from './content.sass';

const Data = () => markdown`
**Pbl** allows you to make fast and easy deployment of your
Docker powered applications and services on your server.
Any directory that contains a Dockerfile can be deployed with one command \`pbl\`

Every time you deploy a project, **pbl** (by default) will provide you
immediately with a new unique URL. Until build process will be finished,
full-featured view-only terminal with all the build
process output will be available at provided URL.

If build process was finished successfully the app
itself will be available at same URL,
otherwise terminal with build process output and error will be available.

*More information available [here](https://github.com/istarkov/pbl)*
`;

export const content = ({ theme }) => (

      <Data />

    <Carusel />

);

export const contentHOC = compose(
  themr('content', contentStyles)
);

export default contentHOC(content);
<commit_msg>edit readme<commit_after>import React from 'react';
import compose from 'recompose/compose';
import { themr } from 'react-css-themr';
import markdown from 'markdown-in-js';
import Carusel from './Carusel';
import contentStyles from './content.sass';

const Data = () => markdown`
**Pbl** gives users the ability to make fast and easy deployment of their
Docker powered applications and services onto their server.
Any directory that contains a Dockerfile can be deployed with just one command: \`pbl\`

Every time a user deploys a project, **pbl** (by default), will immediately
provide a new unique URL. While the build process runs,
a full-featured, view-only terminal with all the build
process output will be available at the provided URL.

If the build process concludes successfully, the app
itself will be available at the same URL,
otherwise the terminal with the build process output and error(s) will remain available.

*More information available [here](https://github.com/istarkov/pbl)*
`;

export const content = ({ theme }) => (

      <Data />

    <Carusel />

);

export const contentHOC = compose(
  themr('content', contentStyles)
);

export default contentHOC(content);
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

importScript("Dimension.js");
importScript("qb/ESQuery.js");

if (!Mozilla) var Mozilla = {"name": "Mozilla", "edges": []};

(function () {

  Dimension.addEdges(true, Mozilla, [
    {
      "name": "Quantum",
      "esfilter": {"match_all": {}},
      "edges": [
        {
          "name": "Project", "index": "bugs", "isFacet": true,
          "partitions": [
            // {
            //   "name": "Photon",
            //   "start_date": "Jan 1, 2017",
            //   "targetDate": "Nov 28, 2017",
            //   "dateMarks": [],
            //   "style": {"color": "#ff7f0e"},
            //   "esfilter": {"prefix": {"status_whiteboard.tokenized": "photon"}}
            // },
            {
              "name": "QF",
              "start_date": "Jan 1, 2017",
              "targetDate": "Nov 28, 2017",
              "dateMarks": [],
              "style": {"color": "#ff7f0e"},
              "esfilter": {"prefix": {"status_whiteboard.tokenized": "qf"}}
            }
          ]
        },

        {"name": "Nominations", "index": "bugs", "esfilter": {"term": {"status_whiteboard.tokenized": "qf"}}},
        {"name": "AllNominations", "index": "bugs", "esfilter": {"terms": {"status_whiteboard.tokenized": ["qf:investigate:p1", "qf", "qf:investigate"]}}},
        {"name": "Blockers", "index": "bugs", "esfilter": {"term": {"status_whiteboard.tokenized": "qf:p1"}}},
        {"name": "Regressions", "index": "bugs", "esfilter": {"term": {"keywords": "regression"}}},
        {"name": "Unassigned", "index": "bugs", "esfilter": {"term": {"assigned_to": "nobody@mozilla.org"}}},

        //AN UNFORTUNATE DISTINCTION BETWEEN DIMENSIONS (ABOVE, THAT OVERLAP), AND PARTITIONS THAT DO NOT OVERLAP
        {
          "name": "State", "index": "bugs", "isFacet": true,
          "partitions": [
            {
              "name": "Nominated", "esfilter": {
              "and": [
                {"term": {"status_whiteboard.tokenized": "qf"}},
                {"not": {"term": {"keywords": "regression"}}}
              ]
            }
            },
            {
              "name": "Blocker", "esfilter": {
              "and": [
                {"term": {"status_whiteboard.tokenized": "qf:p1"}},
                {"not": {"term": {"keywords": "regression"}}}
              ]
            }
            },
            {"name": "Regression", "esfilter": {"term": {"keywords": "regression"}}}
          ]
        },

        {
          "name": "Component",
          "field": "component",
          "type": "set",
          "esfilter": ESQuery.TrueFilter,
          "index": "bugs",
          "limit": 200,
          "end": function (p) {
            return p.name;
          }
        },

        {
          "name": "Team",
          "isFacet": true,
          "esfilter": {"match_all": {}},
          "partitions": [
            {
              "name": "DevTools",
              "manager": "Patrick Brosset",
              "style": {"color": "#FAA43A"},
              "esfilter": {
                "and": [
                  {
                    "or": [
                      {"prefix": {"component": "dev"}}, // Component: Anything starting with "Developer Tools"
                      {"term": {"component": "gecko profiler"}}
                    ]
                  }
                ]
              }
            },
            {
              "name": "DOM",
              "manager": "Andrew Overholt",
              "style": {"color": "#4D4D4D"},
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {"not": {"prefix": {"component": "dom: css"}}},
                  {
                    "or": [
                      {"prefix": {"component": "dom"}},  // Lawrence, Nov 11, 2014: Anything starting with "DOM", "Document Navigation", "IPC", "XBL", "XForms"
                      {"prefix": {"component": "document"}},
                      {"prefix": {"component": "ipc"}},
                      {"prefix": {"component": "xbl"}},
                      {"prefix": {"component": "xform"}},
                      {
                        "terms": {
                          "component": [
                            "html: parser",
                            "html: form submission",
                            "keyboard: navigation",
                            "serializers",
                            "xbl",
                            "xml",
                            "xpconnect",
                            "xslt"
                          ]
                        }
                      }
                    ]
                  }
                ]
              }
            },
            {
              "name": "Layout",
              "manager": "Jet Villegas",
              "style": {"color": "#B2912F"},
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {
                    "or": [
                      {"prefix": {"component": "dom: css"}},
                      {"prefix": {"component": "css parsing"}},  // Component: "CSS Parsing and Computation", starts with "HTML", starts with "Image", starts with "Layout", "Selection"
                      {"prefix": {"component": "html"}},
                      {"prefix": {"component": "image"}},
                      {"prefix": {"component": "layout"}},
                      {"prefix": {"component": "selection"}},
                      {"terms": {"component": ["svg"]}}
                    ]
                  }
                ]
              }
            },
            {
              "name": "Graphics",
              "manager": "Milan Sreckovic",
              "style": {"color": "#B276B2"},
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {
                    "or": [
                      {"prefix": {"component": "canvas"}},  // Anything starting with "Canvas", "Graphics", "Panning and Zooming", "SVG"
                      {"prefix": {"component": "graphics"}},
                      {"prefix": {"component": "panning"}},
                      {"prefix": {"component": "svg"}},
                      {"prefix": {"component": "gfx: color"}},
                      {"terms": {"component": ["color management", "imagelib", "panning and zooming"]}}
                    ]
                  }
                ]
              }
            },
            {
              "name": "Javascript",
              "manager": "Shuyu Guo",
              "style": {"color": "#F17CB0"},
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {
                    "or": [
                      {"prefix": {"component": "javascript"}},  //starts with "JavaScript" or "js", "MFBT", "Nanojit"
                      {"prefix": {"component": "js"}},
                      {"prefix": {"component": "mfbt"}},
                      {"prefix": {"component": "nanojit"}}
                    ]
                  }
                ]
              }
            },
            {
              "name": "Networking",
              "manager": "Patrick McManus",
              "style": {"color": "#DECF3F"},
              "description": "Network",
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {"prefix": {"component": "network"}}  // Product: Core, Component: starts with "Networking"
                ]
              }
            },
            {
              "name": "WebExtensions",
              "manager": "Andy McKay",
              "style": {"color": "#757EBA"},
              "esfilter": {
                "and": [
                  {"prefix": {"component": "webextensions"}}
                ]
              }
            },
            {
              "name": "Runtime",
              "manager": "Selena Deckelmann",
              "style": {"color": "#757EBA"},
              "esfilter": {
                "and": [
                  {"prefix": {"product": "core"}}
                ]
              }
            },
            {
              "name": "Front End",
              "manager": "Justin Dolske",
              "style": {"color": "#757EBA"},
              "esfilter": {
                "or": [
                  {"prefix": {"product": "toolkit"}},
                  {"prefix": {"product": "firefox"}}
                ]
              }
            },
            {
              "name": "Webtools",
              "manager": "",
              "style": {"color": "#757EBA"},
              "esfilter": {
                "and": [
                  {"prefix": {"product": "webtools"}}
                ]
              }
            },
            {
              "name": "Other",
              "manager": "",
              "style": {"color": "#CCCCCC"},
              "esfilter": {"match_all": {}} // Any tracked bug not in one of the product/component combinations above.
            }
          ]
        }
      ]
    }

  ]);
})();

<commit_msg>change manager name<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

importScript("Dimension.js");
importScript("qb/ESQuery.js");

if (!Mozilla) var Mozilla = {"name": "Mozilla", "edges": []};

(function () {

  Dimension.addEdges(true, Mozilla, [
    {
      "name": "Quantum",
      "esfilter": {"match_all": {}},
      "edges": [
        {
          "name": "Project", "index": "bugs", "isFacet": true,
          "partitions": [
            // {
            //   "name": "Photon",
            //   "start_date": "Jan 1, 2017",
            //   "targetDate": "Nov 28, 2017",
            //   "dateMarks": [],
            //   "style": {"color": "#ff7f0e"},
            //   "esfilter": {"prefix": {"status_whiteboard.tokenized": "photon"}}
            // },
            {
              "name": "QF",
              "start_date": "Jan 1, 2017",
              "targetDate": "Nov 28, 2017",
              "dateMarks": [],
              "style": {"color": "#ff7f0e"},
              "esfilter": {"prefix": {"status_whiteboard.tokenized": "qf"}}
            }
          ]
        },

        {"name": "Nominations", "index": "bugs", "esfilter": {"term": {"status_whiteboard.tokenized": "qf"}}},
        {"name": "AllNominations", "index": "bugs", "esfilter": {"terms": {"status_whiteboard.tokenized": ["qf:investigate:p1", "qf", "qf:investigate"]}}},
        {"name": "Blockers", "index": "bugs", "esfilter": {"term": {"status_whiteboard.tokenized": "qf:p1"}}},
        {"name": "Regressions", "index": "bugs", "esfilter": {"term": {"keywords": "regression"}}},
        {"name": "Unassigned", "index": "bugs", "esfilter": {"term": {"assigned_to": "nobody@mozilla.org"}}},

        //AN UNFORTUNATE DISTINCTION BETWEEN DIMENSIONS (ABOVE, THAT OVERLAP), AND PARTITIONS THAT DO NOT OVERLAP
        {
          "name": "State", "index": "bugs", "isFacet": true,
          "partitions": [
            {
              "name": "Nominated", "esfilter": {
              "and": [
                {"term": {"status_whiteboard.tokenized": "qf"}},
                {"not": {"term": {"keywords": "regression"}}}
              ]
            }
            },
            {
              "name": "Blocker", "esfilter": {
              "and": [
                {"term": {"status_whiteboard.tokenized": "qf:p1"}},
                {"not": {"term": {"keywords": "regression"}}}
              ]
            }
            },
            {"name": "Regression", "esfilter": {"term": {"keywords": "regression"}}}
          ]
        },

        {
          "name": "Component",
          "field": "component",
          "type": "set",
          "esfilter": ESQuery.TrueFilter,
          "index": "bugs",
          "limit": 200,
          "end": function (p) {
            return p.name;
          }
        },

        {
          "name": "Team",
          "isFacet": true,
          "esfilter": {"match_all": {}},
          "partitions": [
            {
              "name": "DevTools",
              "manager": "Patrick Brosset",
              "style": {"color": "#FAA43A"},
              "esfilter": {
                "and": [
                  {
                    "or": [
                      {"prefix": {"component": "dev"}}, // Component: Anything starting with "Developer Tools"
                      {"term": {"component": "gecko profiler"}}
                    ]
                  }
                ]
              }
            },
            {
              "name": "DOM",
              "manager": "Andrew Overholt",
              "style": {"color": "#4D4D4D"},
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {"not": {"prefix": {"component": "dom: css"}}},
                  {
                    "or": [
                      {"prefix": {"component": "dom"}},  // Lawrence, Nov 11, 2014: Anything starting with "DOM", "Document Navigation", "IPC", "XBL", "XForms"
                      {"prefix": {"component": "document"}},
                      {"prefix": {"component": "ipc"}},
                      {"prefix": {"component": "xbl"}},
                      {"prefix": {"component": "xform"}},
                      {
                        "terms": {
                          "component": [
                            "html: parser",
                            "html: form submission",
                            "keyboard: navigation",
                            "serializers",
                            "xbl",
                            "xml",
                            "xpconnect",
                            "xslt"
                          ]
                        }
                      }
                    ]
                  }
                ]
              }
            },
            {
              "name": "Layout",
              "manager": "Jet Villegas",
              "style": {"color": "#B2912F"},
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {
                    "or": [
                      {"prefix": {"component": "dom: css"}},
                      {"prefix": {"component": "css parsing"}},  // Component: "CSS Parsing and Computation", starts with "HTML", starts with "Image", starts with "Layout", "Selection"
                      {"prefix": {"component": "html"}},
                      {"prefix": {"component": "image"}},
                      {"prefix": {"component": "layout"}},
                      {"prefix": {"component": "selection"}},
                      {"terms": {"component": ["svg"]}}
                    ]
                  }
                ]
              }
            },
            {
              "name": "Graphics",
              "manager": "Milan Sreckovic",
              "style": {"color": "#B276B2"},
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {
                    "or": [
                      {"prefix": {"component": "canvas"}},  // Anything starting with "Canvas", "Graphics", "Panning and Zooming", "SVG"
                      {"prefix": {"component": "graphics"}},
                      {"prefix": {"component": "panning"}},
                      {"prefix": {"component": "svg"}},
                      {"prefix": {"component": "gfx: color"}},
                      {"terms": {"component": ["color management", "imagelib", "panning and zooming"]}}
                    ]
                  }
                ]
              }
            },
            {
              "name": "Javascript",
              "manager": "Naveed Ihsanullah",
              "style": {"color": "#F17CB0"},
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {
                    "or": [
                      {"prefix": {"component": "javascript"}},  //starts with "JavaScript" or "js", "MFBT", "Nanojit"
                      {"prefix": {"component": "js"}},
                      {"prefix": {"component": "mfbt"}},
                      {"prefix": {"component": "nanojit"}}
                    ]
                  }
                ]
              }
            },
            {
              "name": "Networking",
              "manager": "Patrick McManus",
              "style": {"color": "#DECF3F"},
              "description": "Network",
              "esfilter": {
                "and": [
                  {"term": {"product": "core"}},
                  {"prefix": {"component": "network"}}  // Product: Core, Component: starts with "Networking"
                ]
              }
            },
            {
              "name": "WebExtensions",
              "manager": "Andy McKay",
              "style": {"color": "#757EBA"},
              "esfilter": {
                "and": [
                  {"prefix": {"component": "webextensions"}}
                ]
              }
            },
            {
              "name": "Runtime",
              "manager": "Selena Deckelmann",
              "style": {"color": "#757EBA"},
              "esfilter": {
                "and": [
                  {"prefix": {"product": "core"}}
                ]
              }
            },
            {
              "name": "Front End",
              "manager": "Justin Dolske",
              "style": {"color": "#757EBA"},
              "esfilter": {
                "or": [
                  {"prefix": {"product": "toolkit"}},
                  {"prefix": {"product": "firefox"}}
                ]
              }
            },
            {
              "name": "Webtools",
              "manager": "",
              "style": {"color": "#757EBA"},
              "esfilter": {
                "and": [
                  {"prefix": {"product": "webtools"}}
                ]
              }
            },
            {
              "name": "Other",
              "manager": "",
              "style": {"color": "#CCCCCC"},
              "esfilter": {"match_all": {}} // Any tracked bug not in one of the product/component combinations above.
            }
          ]
        }
      ]
    }

  ]);
})();

<|endoftext|>


<commit_before>// import libraries
var qm = require('qminer.js');
var loader = require('qminer-data-loader');
var la = qm.la;
var analytics = qm.analytics;
var fs = qm.fs;

var base = new qm.Base({
	mode: "createClean",
	schema: [
	    {
	        "name": "People",
	        "fields": [
	            { "name": "Name", "type": "string", "primary": true },
	            { "name": "Gender", "type": "string", "shortstring": true }
	        ],
	        "joins": [
	            { "name": "ActedIn", "type": "index", "store": "Movies", "inverse" : "Actor" },
	            { "name": "Directed", "type": "index", "store": "Movies", "inverse" : "Director" }
	        ],
	        "keys": [
	            { "field": "Gender", "type": "value" }
	        ]
	    },
	    {
	        "name": "Movies",
	        "fields": [
	            { "name": "Title", "type": "string" },
	            { "name": "Plot", "type": "string", "store" : "cache" },
	            { "name": "Year", "type": "int" },
	            { "name": "Rating", "type": "float" },
	            { "name": "Genres", "type": "string_v", "codebook" : true }
	        ],
	        "joins": [
	            { "name": "Actor", "type": "index", "store": "People", "inverse" : "ActedIn" },
	            { "name": "Director", "type": "field", "store": "People", "inverse" : "Directed" }
	        ],
	        "keys": [
	            { "field": "Title", "type": "value" },
	            { "field": "Title", "name": "TitleTxt", "type": "text", "vocabulary" : "voc_01" },
	            { "field": "Plot", "type": "text", "vocabulary" : "voc_01" },
	            { "field": "Genres", "type": "value" }
	        ]
	    }
	]
});

// We are, we start by loading in the dataset.
console.log("Movies", "Loading and indexing input data");
loader.loadMoviesDataset(base.store("Movies"));
// Prepare shortcuts to set of all people and all movies
var people = base.store("People").allRecords;
var movies = base.store("Movies").allRecords;
console.log("Loaded " + movies.length + " movies and " + people.length + " people.");

// Declare the features we will use to detect movie genres
var genreFeatures = [
    { type: "constant", source: "Movies" },
    { type: "text", source: "Movies", field: "Title" },
    { type: "text", source: "Movies", field: "Plot" },
    { type: "multinomial", source: { store: "Movies", join: "Actor" }, field: "Name" },
    { type: "multinomial", source: { store: "Movies", join: "Director" }, field: "Name" }
];
// Create and initialize feature matrix
var genreFeatureSpace = new qm.FeatureSpace(base, genreFeatures);
genreFeatureSpace.updateRecords(movies);
var genreFeatureMatrix = genreFeatureSpace.extractSparseMatrix(movies);
console.log("Dimensionality of feature space: " + genreFeatureSpace.dim);
// Create and initialize label matrix for training
var labelFeatures = [{ type: "multinomial", source: "Movies", field: "Genres" }]
var genreLabelSpace = new qm.FeatureSpace(base, labelFeatures);
genreLabelSpace.updateRecords(movies);
var genreLabelMatrix = genreLabelSpace.extractMatrix(movies);
console.log("Dimensionality of label space: " + genreLabelSpace.dims);
// We will use one-vs-all model for gener classification
var genreModel = new analytics.OneVsAll({
	model: analytics.SVC,
	modelParam: { c: 10, algorithm: "LIBSVM" },
	cats: genreLabelMatrix.rows,
	verbose: true
});
// Create a model for the Genres field, using all the movies as training set.
console.log("Training genre models");
genreModel.fit(genreFeatureMatrix, genreLabelMatrix);

// Declare the features we will use to predict movie rating
var ratingFeatures = [
    { type: "constant", source: "Movies" },
    { type: "text", source: "Movies", field: "Title" },
    { type: "text", source: "Movies", field: "Plot" },
    { type: "multinomial", source: "Movies", field: "Genres" },
    { type: "multinomial", source: { store: "Movies", join: "Actor" }, field: "Name" },
    { type: "multinomial", source: { store: "Movies", join: "Director" }, field: "Name" }
];
// Create and initialize feature matrix
var ratingFeatureSpace = new qm.FeatureSpace(base, ratingFeatures);
// Create and initialize vector with target ratings
ratingFeatureSpace.updateRecords(movies);
var ratingFeatureMatrix = ratingFeatureSpace.extractSparseMatrix(movies);
// Create and initialize vector with ratings for trainings
var ratingVector = movies.getVector("Rating");
// We will use regression model for predicting ratings
var ratingModel = new analytics.SVR();
// Train regression
ratingModel.fit(ratingFeatureMatrix, ratingVector);

// Test de-serialized models on two new movies
var newHorrorMovie = base.store("Movies").newRecord({
    "Title":"Unnatural Selection",
    "Plot":"When corpses are found with internal organs missing, Liz Shaw and P.R.O.B.E. " +
           "investigate a defunct government project from the 1970s that aimed to predict " +
           "the course of human evolution. But was the creature it produced really destroyed," +
           "or has it resurfaced twenty years on?",
    "Year":1996.000000,
    "Rating":6.200000,
    "Genres":["Horror", "Sci-Fi"],
    "Director":{"Name":"Baggs Bill", "Gender":"Unknown"},
    "Actor":[
        {"Name":"Beevers Geoffrey", "Gender":"Male"},
        {"Name":"Bradshaw Stephen (I)", "Gender":"Male"},
        {"Name":"Brooks Keith (III)", "Gender":"Male"},
        {"Name":"Gatiss Mark", "Gender":"Male"},
        {"Name":"Kay Charles", "Gender":"Male"},
        {"Name":"Kirk Alexander (I)", "Gender":"Male"},
        {"Name":"Moore Mark (II)", "Gender":"Male"},
        {"Name":"Murphy George A.", "Gender":"Male"},
        {"Name":"Mykaj Gabriel", "Gender":"Male"},
        {"Name":"Rigby Jonathan", "Gender":"Male"},
        {"Name":"Wolfe Simon (I)", "Gender":"Male"},
        {"Name":"Jameson Louise", "Gender":"Female"},
        {"Name":"John Caroline", "Gender":"Female"},
        {"Name":"Merrick Patricia", "Gender":"Female"},
        {"Name":"Randall Zoe", "Gender":"Female"},
        {"Name":"Rayner Kathryn", "Gender":"Female"}
    ]
});
// apply genre model
var newHorrorMovieGenreVector = genreFeatureSpace.extractSparseVector(newHorrorMovie);
console.log("Top genre: " + genreLabelSpace.getFeature(genreModel.predict(newHorrorMovieGenreVector)));
// apply rating model
var newHorrorMovieRatingVector = ratingFeatureSpace.extractSparseVector(newHorrorMovie);
console.log("Predicted rating: " + ratingModel.predict(newHorrorMovieRatingVector).toFixed(1));
console.log("True rating:      " + newHorrorMovie.Rating);

var newComedyMovie = base.store("Movies").newRecord({
    "Title":"Die Feuerzangenbowle",
    "Plot":"Hans Pfeiffer and some of his friends are drinking \"Feuerzangenbowle\". Talking " +
           "about their school-time they discover that Hans never was at a regular school and " +
           "so, as they think, missed an important part of his youth. They decide to send him " +
           "back to school to do all the things he never could do before.",
    "Year":1944.000000,
    "Rating":7.800000,
    "Genres":["Comedy"],
    "Director":{"Name":"Weiss Helmut", "Gender":"Unknown"},
    "Actor":[
        {"Name":"Biegel Erwin", "Gender":"Male"},
        {"Name":"Etlinger Karl", "Gender":"Male"},
        {"Name":"Florath Albert", "Gender":"Male"},
        {"Name":"Gutz Lutz", "Gender":"Male"},
        {"Name":"Gulstorff Max", "Gender":"Male"},
        {"Name":"Hasse Clemens", "Gender":"Male"},
        {"Name":"Henckels Paul", "Gender":"Male"},
        {"Name":"Leibelt Hans", "Gender":"Male"},
        {"Name":"Platen Karl", "Gender":"Male"},
        {"Name":"Ponto Erich", "Gender":"Male"},
        {"Name":"Richter Hans (I)", "Gender":"Male"},
        {"Name":"Ruhmann Heinz", "Gender":"Male"},
        {"Name":"Schippel Rudi", "Gender":"Male"},
        {"Name":"Schnell Georg H.", "Gender":"Male"},
        {"Name":"Vogel Egon (I)", "Gender":"Male"},
        {"Name":"Vogelsang Georg", "Gender":"Male"},
        {"Name":"Wenck Ewald", "Gender":"Male"},
        {"Name":"Werner Walter", "Gender":"Male"},
        {"Name":"Himboldt Karin", "Gender":"Female"},
        {"Name":"Litto Maria", "Gender":"Female"},
        {"Name":"Schun Margarete", "Gender":"Female"},
        {"Name":"Sessak Hilde", "Gender":"Female"},
        {"Name":"Wangel Hedwig", "Gender":"Female"},
        {"Name":"Wurtz Anneliese", "Gender":"Female"}
    ]
});
// apply genre model
var newComedyMovieGenreVector = genreFeatureSpace.extractSparseVector(newComedyMovie);
console.log("Top genre: " + genreLabelSpace.getFeature(genreModel.predict(newComedyMovieGenreVector)));
// apply rating model
var newComedyMovieRatingVector = ratingFeatureSpace.extractSparseVector(newComedyMovie);
console.log("Predicted rating: " + ratingModel.predict(newComedyMovieRatingVector).toFixed(1));
console.log("True rating:      " + newComedyMovie.Rating);
var search = base.search({$from : 'Movies', Plot: 'Die'});
console.log(search)
<commit_msg>Fixed require in moves example<commit_after>// import libraries
var qm = require('qminer');
var loader = require('qminer-data-loader');
var la = qm.la;
var analytics = qm.analytics;
var fs = qm.fs;

var base = new qm.Base({
	mode: "createClean",
	schema: [
	    {
	        "name": "People",
	        "fields": [
	            { "name": "Name", "type": "string", "primary": true },
	            { "name": "Gender", "type": "string", "shortstring": true }
	        ],
	        "joins": [
	            { "name": "ActedIn", "type": "index", "store": "Movies", "inverse" : "Actor" },
	            { "name": "Directed", "type": "index", "store": "Movies", "inverse" : "Director" }
	        ],
	        "keys": [
	            { "field": "Gender", "type": "value" }
	        ]
	    },
	    {
	        "name": "Movies",
	        "fields": [
	            { "name": "Title", "type": "string" },
	            { "name": "Plot", "type": "string", "store" : "cache" },
	            { "name": "Year", "type": "int" },
	            { "name": "Rating", "type": "float" },
	            { "name": "Genres", "type": "string_v", "codebook" : true }
	        ],
	        "joins": [
	            { "name": "Actor", "type": "index", "store": "People", "inverse" : "ActedIn" },
	            { "name": "Director", "type": "field", "store": "People", "inverse" : "Directed" }
	        ],
	        "keys": [
	            { "field": "Title", "type": "value" },
	            { "field": "Title", "name": "TitleTxt", "type": "text", "vocabulary" : "voc_01" },
	            { "field": "Plot", "type": "text", "vocabulary" : "voc_01" },
	            { "field": "Genres", "type": "value" }
	        ]
	    }
	]
});

// We are, we start by loading in the dataset.
console.log("Movies", "Loading and indexing input data");
loader.loadMoviesDataset(base.store("Movies"));
// Prepare shortcuts to set of all people and all movies
var people = base.store("People").allRecords;
var movies = base.store("Movies").allRecords;
console.log("Loaded " + movies.length + " movies and " + people.length + " people.");

// Declare the features we will use to detect movie genres
var genreFeatures = [
    { type: "constant", source: "Movies" },
    { type: "text", source: "Movies", field: "Title" },
    { type: "text", source: "Movies", field: "Plot" },
    { type: "multinomial", source: { store: "Movies", join: "Actor" }, field: "Name" },
    { type: "multinomial", source: { store: "Movies", join: "Director" }, field: "Name" }
];
// Create and initialize feature matrix
var genreFeatureSpace = new qm.FeatureSpace(base, genreFeatures);
genreFeatureSpace.updateRecords(movies);
var genreFeatureMatrix = genreFeatureSpace.extractSparseMatrix(movies);
console.log("Dimensionality of feature space: " + genreFeatureSpace.dim);
// Create and initialize label matrix for training
var labelFeatures = [{ type: "multinomial", source: "Movies", field: "Genres" }]
var genreLabelSpace = new qm.FeatureSpace(base, labelFeatures);
genreLabelSpace.updateRecords(movies);
var genreLabelMatrix = genreLabelSpace.extractMatrix(movies);
console.log("Dimensionality of label space: " + genreLabelSpace.dims);
// We will use one-vs-all model for gener classification
var genreModel = new analytics.OneVsAll({
	model: analytics.SVC,
	modelParam: { c: 10, algorithm: "LIBSVM" },
	cats: genreLabelMatrix.rows,
	verbose: true
});
// Create a model for the Genres field, using all the movies as training set.
console.log("Training genre models");
genreModel.fit(genreFeatureMatrix, genreLabelMatrix);

// Declare the features we will use to predict movie rating
var ratingFeatures = [
    { type: "constant", source: "Movies" },
    { type: "text", source: "Movies", field: "Title" },
    { type: "text", source: "Movies", field: "Plot" },
    { type: "multinomial", source: "Movies", field: "Genres" },
    { type: "multinomial", source: { store: "Movies", join: "Actor" }, field: "Name" },
    { type: "multinomial", source: { store: "Movies", join: "Director" }, field: "Name" }
];
// Create and initialize feature matrix
var ratingFeatureSpace = new qm.FeatureSpace(base, ratingFeatures);
// Create and initialize vector with target ratings
ratingFeatureSpace.updateRecords(movies);
var ratingFeatureMatrix = ratingFeatureSpace.extractSparseMatrix(movies);
// Create and initialize vector with ratings for trainings
var ratingVector = movies.getVector("Rating");
// We will use regression model for predicting ratings
var ratingModel = new analytics.SVR();
// Train regression
ratingModel.fit(ratingFeatureMatrix, ratingVector);

// Test de-serialized models on two new movies
var newHorrorMovie = base.store("Movies").newRecord({
    "Title":"Unnatural Selection",
    "Plot":"When corpses are found with internal organs missing, Liz Shaw and P.R.O.B.E. " +
           "investigate a defunct government project from the 1970s that aimed to predict " +
           "the course of human evolution. But was the creature it produced really destroyed," +
           "or has it resurfaced twenty years on?",
    "Year":1996.000000,
    "Rating":6.200000,
    "Genres":["Horror", "Sci-Fi"],
    "Director":{"Name":"Baggs Bill", "Gender":"Unknown"},
    "Actor":[
        {"Name":"Beevers Geoffrey", "Gender":"Male"},
        {"Name":"Bradshaw Stephen (I)", "Gender":"Male"},
        {"Name":"Brooks Keith (III)", "Gender":"Male"},
        {"Name":"Gatiss Mark", "Gender":"Male"},
        {"Name":"Kay Charles", "Gender":"Male"},
        {"Name":"Kirk Alexander (I)", "Gender":"Male"},
        {"Name":"Moore Mark (II)", "Gender":"Male"},
        {"Name":"Murphy George A.", "Gender":"Male"},
        {"Name":"Mykaj Gabriel", "Gender":"Male"},
        {"Name":"Rigby Jonathan", "Gender":"Male"},
        {"Name":"Wolfe Simon (I)", "Gender":"Male"},
        {"Name":"Jameson Louise", "Gender":"Female"},
        {"Name":"John Caroline", "Gender":"Female"},
        {"Name":"Merrick Patricia", "Gender":"Female"},
        {"Name":"Randall Zoe", "Gender":"Female"},
        {"Name":"Rayner Kathryn", "Gender":"Female"}
    ]
});
// apply genre model
var newHorrorMovieGenreVector = genreFeatureSpace.extractSparseVector(newHorrorMovie);
console.log("Top genre: " + genreLabelSpace.getFeature(genreModel.predict(newHorrorMovieGenreVector)));
// apply rating model
var newHorrorMovieRatingVector = ratingFeatureSpace.extractSparseVector(newHorrorMovie);
console.log("Predicted rating: " + ratingModel.predict(newHorrorMovieRatingVector).toFixed(1));
console.log("True rating:      " + newHorrorMovie.Rating);

var newComedyMovie = base.store("Movies").newRecord({
    "Title":"Die Feuerzangenbowle",
    "Plot":"Hans Pfeiffer and some of his friends are drinking \"Feuerzangenbowle\". Talking " +
           "about their school-time they discover that Hans never was at a regular school and " +
           "so, as they think, missed an important part of his youth. They decide to send him " +
           "back to school to do all the things he never could do before.",
    "Year":1944.000000,
    "Rating":7.800000,
    "Genres":["Comedy"],
    "Director":{"Name":"Weiss Helmut", "Gender":"Unknown"},
    "Actor":[
        {"Name":"Biegel Erwin", "Gender":"Male"},
        {"Name":"Etlinger Karl", "Gender":"Male"},
        {"Name":"Florath Albert", "Gender":"Male"},
        {"Name":"Gutz Lutz", "Gender":"Male"},
        {"Name":"Gulstorff Max", "Gender":"Male"},
        {"Name":"Hasse Clemens", "Gender":"Male"},
        {"Name":"Henckels Paul", "Gender":"Male"},
        {"Name":"Leibelt Hans", "Gender":"Male"},
        {"Name":"Platen Karl", "Gender":"Male"},
        {"Name":"Ponto Erich", "Gender":"Male"},
        {"Name":"Richter Hans (I)", "Gender":"Male"},
        {"Name":"Ruhmann Heinz", "Gender":"Male"},
        {"Name":"Schippel Rudi", "Gender":"Male"},
        {"Name":"Schnell Georg H.", "Gender":"Male"},
        {"Name":"Vogel Egon (I)", "Gender":"Male"},
        {"Name":"Vogelsang Georg", "Gender":"Male"},
        {"Name":"Wenck Ewald", "Gender":"Male"},
        {"Name":"Werner Walter", "Gender":"Male"},
        {"Name":"Himboldt Karin", "Gender":"Female"},
        {"Name":"Litto Maria", "Gender":"Female"},
        {"Name":"Schun Margarete", "Gender":"Female"},
        {"Name":"Sessak Hilde", "Gender":"Female"},
        {"Name":"Wangel Hedwig", "Gender":"Female"},
        {"Name":"Wurtz Anneliese", "Gender":"Female"}
    ]
});
// apply genre model
var newComedyMovieGenreVector = genreFeatureSpace.extractSparseVector(newComedyMovie);
console.log("Top genre: " + genreLabelSpace.getFeature(genreModel.predict(newComedyMovieGenreVector)));
// apply rating model
var newComedyMovieRatingVector = ratingFeatureSpace.extractSparseVector(newComedyMovie);
console.log("Predicted rating: " + ratingModel.predict(newComedyMovieRatingVector).toFixed(1));
console.log("True rating:      " + newComedyMovie.Rating);
var search = base.search({$from : 'Movies', Plot: 'Die'});
console.log(search)
<|endoftext|>