<commit_before>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var fs = require('fs');

// var nm = path.join(global.workingPath, '/node_modules/');
// var dirs = fs.readdirSync(nm)
//   .filter(function(el) { return ['react-shower'].indexOf(el) < 0 })
//   .map(function(el) { return path.join(nm, el) });

const showerThemeRegEx = /shower-[^\/]+\/styles\/[^\/]+\.css/;

module.exports = function(options) {
  var entry, jsLoaders, plugins, cssLoaders;

  // If production is true
  if (options.prod) {
    // Entry
    entry = [
      path.resolve(__dirname, 'js/app.js') // Start with js/app.js...
    ];
    cssLoaders = ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader');
    // Plugins
    plugins = [// Plugins for Webpack
      new webpack.optimize.UglifyJsPlugin({ // Optimize the JavaScript...
        compress: {
          warnings: false // ...but do not show warnings in the console (there is a lot of them)
        }
      }),
      new HtmlWebpackPlugin({
        template: path.join(__dirname, 'index.html'), // Move the index.html file...
        minify: { // Minifying it while it is parsed
          removeComments: true,
          collapseWhitespace: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeStyleLinkTypeAttributes: true,
          keepClosingSlash: true,
          minifyJS: true,
          minifyCSS: true,
          minifyURLs: true
        },
        inject: true // inject all files that are generated by webpack, e.g. bundle.js, main.css with the correct HTML tags
      }),
      new ExtractTextPlugin("css/main.css"),
      new webpack.DefinePlugin({
        "process.env": {
          NODE_ENV: JSON.stringify("production")
        }
      })
    ];

  // If app is in development
  } else {
    // Entry
    entry = [
      "webpack-dev-server/client?http://localhost:3000", // Needed for hot reloading
      "webpack/hot/only-dev-server", // See above
      path.resolve(__dirname, 'js/app.js') // Start with js/app.js...
    ];
    cssLoaders = 'style-loader!css-loader!postcss-loader';
    // Only plugin is the hot module replacement plugin
    plugins = [
      new webpack.HotModuleReplacementPlugin(), // Make hot loading work
      new HtmlWebpackPlugin({
        template: path.join(__dirname, 'index.html'), // Move the index.html file
        inject: true // inject all files that are generated by webpack, e.g. bundle.js, main.css with the correct HTML tags
      }),
      new webpack.ContextReplacementPlugin(/style-theme/, path.join(process.cwd(), "node_modules"), true, showerThemeRegEx)
    ]
  }

  return {
    entry: entry,
    output: { // Compile into js/build.js
      path: path.resolve(process.cwd(), 'build'),
      filename: "js/bundle.js"
    },
    resolve: {
      modulesDirectories: [
        process.cwd(),
        path.resolve(__dirname, "js"),
        __dirname,
        path.join(process.cwd(), "node_modules")
      ]
    },
    module: {
      loaders: [{
          test: /\.js$/,
          loader: 'babel',
          include: [
            path.join(__dirname, "js"),
            path.join(process.cwd(), "presentation.js")
          ],
          query: {
            "plugins": [
              "syntax-class-properties",
              "transform-class-properties"
            ],
            "presets": ["es2015", "react", "stage-2"]
          }
        }, {
          test: /\.css$/,
          loader: cssLoaders,
          exclude: [
            path.join(process.cwd(), '/node_modules/')
          ],
        }, {
          test: showerThemeRegEx,
          loader: "style/useable!css",
        }, {
          test: /\.jpe?g$|\.gif$|\.png|\.woff$|\.woff2$|\.eot$|\.ttf$|\.svg$/i,
          loader: "url-loader?limit=10000"
        },
        {
          test:/\.json$/,
          loader: "json-loader"
        }, {
          loader: "raw-loader",
          include: [path.join(process.cwd(), "code")]
        }
      ]
    },
    plugins: plugins,
    postcss: function() {
      return [
        require('postcss-import')({ // Import all the css files...
          glob: true,
          onImport: function (files) {
              files.forEach(this.addDependency); // ...and add dependecies from the main.css files to the other css files...
          }.bind(this) // ...so they get hot–reloaded when something changes...
        }),
        require('postcss-simple-vars')(), // ...then replace the variables...
        require('postcss-focus')(), // ...add a :focus to ever :hover...
        require('autoprefixer')({ // ...and add vendor prefixes...
          browsers: ['last 2 versions', 'IE > 8'] // ...supporting the last 2 major browser versions and IE 8 and up...
        }),
        require('postcss-reporter')({ // This plugin makes sure we get warnings in the console
          clearMessages: true
        })
      ];
    },
    target: "web", // Make web variables accessible to webpack, e.g. window
    stats: false, // Don't show stats in the console
    progress: true
  }
}
<commit_msg>sync webpack config for prod<commit_after>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var fs = require('fs');

const showerThemeRegEx = /shower-[^\/]+\/styles\/[^\/]+\.css/;

module.exports = function(options) {
  var entry, jsLoaders, plugins, cssLoaders;

  // If production is true
  if (options.prod) {
    // Entry
    entry = [
      path.resolve(__dirname, 'js/app.js') // Start with js/app.js...
    ];
    cssLoaders = ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader');
    // Plugins
    plugins = [// Plugins for Webpack
      new webpack.optimize.UglifyJsPlugin({ // Optimize the JavaScript...
        compress: {
          warnings: false // ...but do not show warnings in the console (there is a lot of them)
        }
      }),
      new HtmlWebpackPlugin({
        template: path.join(__dirname, 'index.html'), // Move the index.html file...
        minify: { // Minifying it while it is parsed
          removeComments: true,
          collapseWhitespace: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeStyleLinkTypeAttributes: true,
          keepClosingSlash: true,
          minifyJS: true,
          minifyCSS: true,
          minifyURLs: true
        },
        inject: true // inject all files that are generated by webpack, e.g. bundle.js, main.css with the correct HTML tags
      }),
      new ExtractTextPlugin("css/main.css"),
      new webpack.DefinePlugin({
        "process.env": {
          NODE_ENV: JSON.stringify("production")
        }
      }),
      new webpack.ContextReplacementPlugin(/style-theme/, path.join(process.cwd(), "node_modules"), true, showerThemeRegEx)
    ];

  // If app is in development
  } else {
    // Entry
    entry = [
      "webpack-dev-server/client?http://localhost:3000", // Needed for hot reloading
      "webpack/hot/only-dev-server", // See above
      path.resolve(__dirname, 'js/app.js') // Start with js/app.js...
    ];
    cssLoaders = 'style-loader!css-loader!postcss-loader';
    // Only plugin is the hot module replacement plugin
    plugins = [
      new webpack.HotModuleReplacementPlugin(), // Make hot loading work
      new HtmlWebpackPlugin({
        template: path.join(__dirname, 'index.html'), // Move the index.html file
        inject: true // inject all files that are generated by webpack, e.g. bundle.js, main.css with the correct HTML tags
      }),
      new webpack.ContextReplacementPlugin(/style-theme/, path.join(process.cwd(), "node_modules"), true, showerThemeRegEx)
    ]
  }

  return {
    entry: entry,
    output: { // Compile into js/build.js
      path: path.resolve(process.cwd(), 'build'),
      filename: "js/bundle.js"
    },
    resolve: {
      modulesDirectories: [
        process.cwd(),
        path.resolve(__dirname, "js"),
        __dirname,
        path.join(process.cwd(), "node_modules")
      ]
    },
    module: {
      loaders: [{
          test: /\.js$/,
          loader: 'babel',
          include: [
            path.join(__dirname, "js"),
            path.join(process.cwd(), "presentation.js")
          ],
          query: {
            "plugins": [
              "syntax-class-properties",
              "transform-class-properties"
            ],
            "presets": ["es2015", "react", "stage-2"]
          }
        }, {
          test: /\.css$/,
          loader: cssLoaders,
          exclude: [
            path.join(process.cwd(), '/node_modules/')
          ],
        }, {
          test: showerThemeRegEx,
          loader: "style/useable!css",
        }, {
          test: /\.jpe?g$|\.gif$|\.png|\.woff$|\.woff2$|\.eot$|\.ttf$|\.svg$/i,
          loader: "url-loader?limit=10000"
        },
        {
          test:/\.json$/,
          loader: "json-loader"
        }, {
          loader: "raw-loader",
          include: [path.join(process.cwd(), "code")]
        }
      ]
    },
    plugins: plugins,
    postcss: function() {
      return [
        require('postcss-import')({ // Import all the css files...
          glob: true,
          onImport: function (files) {
              files.forEach(this.addDependency); // ...and add dependecies from the main.css files to the other css files...
          }.bind(this) // ...so they get hot–reloaded when something changes...
        }),
        require('postcss-simple-vars')(), // ...then replace the variables...
        require('postcss-focus')(), // ...add a :focus to ever :hover...
        require('autoprefixer')({ // ...and add vendor prefixes...
          browsers: ['last 2 versions', 'IE > 8'] // ...supporting the last 2 major browser versions and IE 8 and up...
        }),
        require('postcss-reporter')({ // This plugin makes sure we get warnings in the console
          clearMessages: true
        })
      ];
    },
    target: "web", // Make web variables accessible to webpack, e.g. window
    stats: false, // Don't show stats in the console
    progress: true
  }
}
<|endoftext|>


<commit_before>import VueRx from 'vue-rx';
import { Observable, Subject } from 'rxjs';
import './sass.scss';

Vue.use(VueRx, { Subject });

// general components
Vue.component('toggle-button', {
    props: ['onText', 'offText'],
    template:'#toggleButtonTemplate',
    data(){
        return {
            name: "Play",
            isOn: false
        };
    },
    mounted(){
        this.name = this.onText;
    },
    methods:
    {
        buttonclicked: function(value)
        {
            this.isOn = !this.isOn;
            this.name = this.isOn ? this.onText : this.offText;
            this.$emit('buttonclicked', this.isOn);
        },
        setState: function(value)
        {
            this.isOn = value;
            this.name = this.isOn ? this.onText : this.offText;
        }
    }
});
Vue.component('drop-down-element', {
    props: ['name', 'dropdowncontent'],
    template:'#dropDownTemplate',
    data() {
        return {
            selectedOption: ""
        };
    },
    // this is used to init the dropdown (so it is not empty on UI bootup)
    mounted(){
        if(this.dropdowncontent === undefined || this.dropdowncontent.length === 0)
        {
            return;
        }
        this.selectedOption = this.dropdowncontent[0].title;
    },
    methods:
    {
        selectionchanged: function(value)
        {
            this.$emit('selectionchanged', value);
        },
        setSelection: function(value)
        {
            this.selectedOption = value;
        }
    }
});
Vue.component('radio-button-list-element', {
    props: ['name', 'radiobuttoncontent'],
    data() {
        return {
            radio: ""
        };
    },
    updated: function() {
        this.$emit('selectionchanged', this.radio);
    },
    methods:
    {
        setSelection: function(value)
        {
            this.radio = value;
        }
    },
    template:'#radioButtonListTemplate'
});
Vue.component('check-box-element', {
    props: ['name', 'checkboxcontent'],
    data() {
        return {
            checkboxGroup: []
        };
    },
    template:'#checkBoxTemplate'
});
Vue.component('slider-element', {
    props: ['name'],
    data() {
        return {
            value: 1
        };
    },
    updated : function()
    {
        this.$emit('valuechanged', this.value);
    },
    methods:
    {
        setValue(value)
        {
            this.value = value;
        }
    },
    template:'#sliderTemplate'
});
Vue.component('color-picker-element', {
    props: ['name'],
    data() {
        return {
            color: '#1CA085'
        };
    },
    methods:
    {
        colorchanged: function(value)
        {
            this.$emit('colorchanged', value);
        },
        setColor(value)
        {
            this.color = value;
        }
    },
    template:'#colorPickerTemplate'
});
Vue.component('dual-label-list-element', {
  props: ['name', 'items'],
  template:'#dualLabelListTemplate'
});
Vue.component('dual-label-element', {
  props: ['name', 'value'],
  template:'#dualLabelTemplate'
});

// create components for menu tabs
Vue.component('tab-models', {
    props: ["materialvariants", "models", "flavors", "scenes", "cameras"],
    template:'#modelsTemplate',
    methods:
    {
        modelchanged: function(value) {
            this.$emit('modelchanged', value);
        },
        flavourchanged: function(value) {
            this.$emit('flavourchanged', value);
        },
        scenechanged: function(value) {
            this.$emit('scenechanged', value);
        },
        camerachanged: function(value) {
            this.$emit('camerachanged', value);
        },
        variantchanged: function(value) {
            this.$emit('variantchanged', value);
        },
        setSelectedModel: function(value) {
            this.$refs.models.setSelection(value);
        },
        setSelectedScene: function(value) {
            this.$refs.scenes.setSelection(value);
        }
    }
});
Vue.component('tab-display', {
    props: ["environments", "colorpicker"],
    template:'#displayTemplate',
    data() {
        return {
            environmentvisibility: true,
            punctuallights: true,
            ibl: true,
            environmentRotations: [{title: "+Z"}, {title: "-X"}, {title: "-Z"}, {title: "+X"}]
        };
    },
    methods:
    {
        environmentvisibilitychanged: function(value) {
            this.$emit('environmentvisibilitychanged', value)
        },
        punctuallightschanged: function(value) {
            this.$emit('punctuallightschanged', value)
        },
        iblchanged: function(value) {
            this.$emit('iblchanged', value)
        },
        environmentchanged: function(value) {
            this.$emit('environmentchanged', value)
        },
        environmentrotationchanged: function(value) {
            this.$emit('environmentrotationchanged', value);
        },
        addenvironment: function(value) {
            this.$emit('addenvironment', value)
        },
        colorchanged: function(value) {
            this.$emit('colorchanged', value)
        },
        setSelectedClearColor: function (value) {
            this.$refs.colorpicker.setColor(value);
        }
    }
});
Vue.component('tab-animation', {
    props: ["animations"],
    template:'#animationTemplate',
    methods:
    {
        animationplayclicked: function(value) {
            this.$emit('animationplayclicked', value)
        },
        setAnimationState: function(value) {
            this.$refs.animations.setState(value);
        }
    }
});
Vue.component('tab-xmp', {
  props: ["xmp"],
  template:'#xmpTemplate',
  data() {
    return {
    };
  },
});
Vue.component('tab-advanced-controls', {
    props: ["debugchannels", "tonemaps", "statistics", "exposure"],
    template:'#advancedControlsTemplate',
    data() {
        return {
            skinning: true,
            morphing: true,
        };
    },
    methods:
    {
        exposurechanged: function(value) {
            this.$emit('exposurechanged', value)
        },
        skinningchanged: function(value) {
            this.$emit('skinningchanged', value)
        },
        morphingchanged: function(value) {
            this.$emit('morphingchanged', value)
        },
        debugchannelchanged: function(value) {
            this.$emit('debugchannelchanged', value)
        },
        tonemapchanged: function(value) {
            this.$emit('tonemapchanged', value);
        }
    }
});

const app = new Vue({
    domStreams: ['modelChanged$', 'flavourChanged$', 'sceneChanged$', 'cameraChanged$',
                'environmentChanged$', 'debugchannelChanged$', 'tonemapChanged$', 'skinningChanged$',
                'environmentVisibilityChanged$', 'punctualLightsChanged$', 'iblChanged$', 'morphingChanged$',
                'addEnvironment$', 'colorChanged$', 'environmentRotationChanged$', 'animationPlayChanged$',
                'variantChanged$', 'exposureChanged$'],
    data() {
        return {
            fullheight: true,
            right: true,
            models: [{title: "Avocado"}],
            flavors: [],
            scenes: [{title: "0"}, {title: "1"}],
            cameras: [{title: "User Camera"}],
            materialVariants: [{title: "mat var yellow"}, {title: "mat var red"}, {title: "mat var blue"}],
            environments: [{title: "Doge"}, {title: "Helipad"}, {title: "Footprint Court"}],
            animations: [{title: "cool animation"}, {title: "even cooler"}, {title: "not cool"}, {title: "Do not click!"}],
            tonemaps: [{title: "Linear"}],
            debugchannels: [{title: "None"}],
            xmp: [{title: "xmp"}],
            statistics: []
        };
    },
    methods:
    {
        setSelectedModel: function(value)
        {
            this.$refs.models.setSelectedModel(value);
        },
        setSelectedScene: function(value)
        {
            this.$refs.scenes.setSelectedScene(value);
        },
        setSelectedClearColor: function(value)
        {
            this.$refs.colorpicker.setSelectedClearColor(value);
        },
        setAnimationState: function(value)
        {
            this.$refs.animations.setAnimationState(value);
        }
    }
}).$mount('#app');

export { app };
<commit_msg>ui should display None as default<commit_after>import VueRx from 'vue-rx';
import { Observable, Subject } from 'rxjs';
import './sass.scss';

Vue.use(VueRx, { Subject });

// general components
Vue.component('toggle-button', {
    props: ['onText', 'offText'],
    template:'#toggleButtonTemplate',
    data(){
        return {
            name: "Play",
            isOn: false
        };
    },
    mounted(){
        this.name = this.onText;
    },
    methods:
    {
        buttonclicked: function(value)
        {
            this.isOn = !this.isOn;
            this.name = this.isOn ? this.onText : this.offText;
            this.$emit('buttonclicked', this.isOn);
        },
        setState: function(value)
        {
            this.isOn = value;
            this.name = this.isOn ? this.onText : this.offText;
        }
    }
});
Vue.component('drop-down-element', {
    props: ['name', 'dropdowncontent'],
    template:'#dropDownTemplate',
    data() {
        return {
            selectedOption: ""
        };
    },
    // this is used to init the dropdown (so it is not empty on UI bootup)
    mounted(){
        if(this.dropdowncontent === undefined || this.dropdowncontent.length === 0)
        {
            return;
        }
        this.selectedOption = this.dropdowncontent[0].title;
    },
    methods:
    {
        selectionchanged: function(value)
        {
            this.$emit('selectionchanged', value);
        },
        setSelection: function(value)
        {
            this.selectedOption = value;
        }
    }
});
Vue.component('radio-button-list-element', {
    props: ['name', 'radiobuttoncontent'],
    data() {
        return {
            radio: ""
        };
    },
    updated: function() {
        this.$emit('selectionchanged', this.radio);
    },
    methods:
    {
        setSelection: function(value)
        {
            this.radio = value;
        }
    },
    template:'#radioButtonListTemplate'
});
Vue.component('check-box-element', {
    props: ['name', 'checkboxcontent'],
    data() {
        return {
            checkboxGroup: []
        };
    },
    template:'#checkBoxTemplate'
});
Vue.component('slider-element', {
    props: ['name'],
    data() {
        return {
            value: 1
        };
    },
    updated : function()
    {
        this.$emit('valuechanged', this.value);
    },
    methods:
    {
        setValue(value)
        {
            this.value = value;
        }
    },
    template:'#sliderTemplate'
});
Vue.component('color-picker-element', {
    props: ['name'],
    data() {
        return {
            color: '#1CA085'
        };
    },
    methods:
    {
        colorchanged: function(value)
        {
            this.$emit('colorchanged', value);
        },
        setColor(value)
        {
            this.color = value;
        }
    },
    template:'#colorPickerTemplate'
});
Vue.component('dual-label-list-element', {
  props: ['name', 'items'],
  template:'#dualLabelListTemplate'
});
Vue.component('dual-label-element', {
  props: ['name', 'value'],
  template:'#dualLabelTemplate'
});

// create components for menu tabs
Vue.component('tab-models', {
    props: ["materialvariants", "models", "flavors", "scenes", "cameras"],
    template:'#modelsTemplate',
    methods:
    {
        modelchanged: function(value) {
            this.$emit('modelchanged', value);
        },
        flavourchanged: function(value) {
            this.$emit('flavourchanged', value);
        },
        scenechanged: function(value) {
            this.$emit('scenechanged', value);
        },
        camerachanged: function(value) {
            this.$emit('camerachanged', value);
        },
        variantchanged: function(value) {
            this.$emit('variantchanged', value);
        },
        setSelectedModel: function(value) {
            this.$refs.models.setSelection(value);
        },
        setSelectedScene: function(value) {
            this.$refs.scenes.setSelection(value);
        }
    }
});
Vue.component('tab-display', {
    props: ["environments", "colorpicker"],
    template:'#displayTemplate',
    data() {
        return {
            environmentvisibility: true,
            punctuallights: true,
            ibl: true,
            environmentRotations: [{title: "+Z"}, {title: "-X"}, {title: "-Z"}, {title: "+X"}]
        };
    },
    methods:
    {
        environmentvisibilitychanged: function(value) {
            this.$emit('environmentvisibilitychanged', value)
        },
        punctuallightschanged: function(value) {
            this.$emit('punctuallightschanged', value)
        },
        iblchanged: function(value) {
            this.$emit('iblchanged', value)
        },
        environmentchanged: function(value) {
            this.$emit('environmentchanged', value)
        },
        environmentrotationchanged: function(value) {
            this.$emit('environmentrotationchanged', value);
        },
        addenvironment: function(value) {
            this.$emit('addenvironment', value)
        },
        colorchanged: function(value) {
            this.$emit('colorchanged', value)
        },
        setSelectedClearColor: function (value) {
            this.$refs.colorpicker.setColor(value);
        }
    }
});
Vue.component('tab-animation', {
    props: ["animations"],
    template:'#animationTemplate',
    methods:
    {
        animationplayclicked: function(value) {
            this.$emit('animationplayclicked', value)
        },
        setAnimationState: function(value) {
            this.$refs.animations.setState(value);
        }
    }
});
Vue.component('tab-xmp', {
  props: ["xmp"],
  template:'#xmpTemplate',
  data() {
    return {
    };
  },
});
Vue.component('tab-advanced-controls', {
    props: ["debugchannels", "tonemaps", "statistics", "exposure"],
    template:'#advancedControlsTemplate',
    data() {
        return {
            skinning: true,
            morphing: true,
        };
    },
    methods:
    {
        exposurechanged: function(value) {
            this.$emit('exposurechanged', value)
        },
        skinningchanged: function(value) {
            this.$emit('skinningchanged', value)
        },
        morphingchanged: function(value) {
            this.$emit('morphingchanged', value)
        },
        debugchannelchanged: function(value) {
            this.$emit('debugchannelchanged', value)
        },
        tonemapchanged: function(value) {
            this.$emit('tonemapchanged', value);
        }
    }
});

const app = new Vue({
    domStreams: ['modelChanged$', 'flavourChanged$', 'sceneChanged$', 'cameraChanged$',
                'environmentChanged$', 'debugchannelChanged$', 'tonemapChanged$', 'skinningChanged$',
                'environmentVisibilityChanged$', 'punctualLightsChanged$', 'iblChanged$', 'morphingChanged$',
                'addEnvironment$', 'colorChanged$', 'environmentRotationChanged$', 'animationPlayChanged$',
                'variantChanged$', 'exposureChanged$'],
    data() {
        return {
            fullheight: true,
            right: true,
            models: [{title: "Avocado"}],
            flavors: [],
            scenes: [{title: "0"}, {title: "1"}],
            cameras: [{title: "User Camera"}],
            materialVariants: [{title: "mat var yellow"}, {title: "mat var red"}, {title: "mat var blue"}],
            environments: [{title: "Doge"}, {title: "Helipad"}, {title: "Footprint Court"}],
            animations: [{title: "cool animation"}, {title: "even cooler"}, {title: "not cool"}, {title: "Do not click!"}],
            tonemaps: [{title: "None"}],
            debugchannels: [{title: "None"}],
            xmp: [{title: "xmp"}],
            statistics: []
        };
    },
    methods:
    {
        setSelectedModel: function(value)
        {
            this.$refs.models.setSelectedModel(value);
        },
        setSelectedScene: function(value)
        {
            this.$refs.scenes.setSelectedScene(value);
        },
        setSelectedClearColor: function(value)
        {
            this.$refs.colorpicker.setSelectedClearColor(value);
        },
        setAnimationState: function(value)
        {
            this.$refs.animations.setAnimationState(value);
        }
    }
}).$mount('#app');

export { app };
<|endoftext|>


<commit_before>$('body').append(
    '

' +
    '

'
);
<commit_msg>Update tmp/bower_components/lodash/vendor/backbone/test/setup/dom-setup.js<commit_after><|endoftext|>


<commit_before>const { mongoose } = require('./../config/mongoose');
const User = require('../model/user');

let exportedMethods = {
    getAllUsers() {
        return User.find({}).toArray();
    },
    getUserById(id) {
        return User.find({ _id: id }).then((user) => {
            if (!user) throw "No such user found";
            return user;
        });
    },
    addUser(newUser, password) {
        return User.register(newUser, password, function(err, user) {
            if (err) {
                // handle the error
            }
            return user;
        });
    },
    updateUser(user, id) {
        return User.findOneAndUpdate({
            _id: id
        }, {
            $set: user
        }, {
            new: true
        }).then((user) => {
            if (!todo) {
                return;
            }
            return todo;
        }).catch((error) => {
            return error;
        });
    },
    deleteUser(id) {

    }
};

module.exports = { exportedMethods };<commit_msg>Removed passport mongoose<commit_after>const { mongoose } = require('./../config/mongoose');
const User = require('../model/user');

let exportedMethods = {
    getAllUsers() {
        return User.find({}).toArray();
    },
    getUserById(id) {
        return User.find({ _id: id }).then((user) => {
            if (!user) throw "No such user found";
            return user;
        });
    },
    // addUser(newUser, password) {
    //     return User.register(newUser, password, function(err, user) {
    //         if (err) {
    //             // handle the error
    //         }
    //         return user;
    //     });
    // },
    addUser(newUser) {
        return User.save(newUser).then((doc) => {
            return doc;
        }).catch((error) => {
            return error;
        });
    },
    updateUser(user, id) {
        return User.findOneAndUpdate({
            _id: id
        }, {
            $set: user
        }, {
            new: true
        }).then((user) => {
            if (!todo) {
                return;
            }
            return todo;
        }).catch((error) => {
            return error;
        });
    },
    deleteUser(id) {

    }
};

module.exports = { exportedMethods };<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var Future = require("fibers/future");
var _ = require("underscore");
var switchFunctions = [];
var pollingInterval = 500;

// Set this environment variable to a truthy value to force the use of
// fs.watchFile instead of pathwatcher.watch.
var canUsePathwatcher = !process.env.METEOR_WATCH_FORCE_POLLING;

// The pathwatcher library does not work on all platforms and file systems
// (notably, network file systems), so we have to do a little feature
// detection to see if we can use it.

// We optimistically watch files using pathwatcher.watch until one of the
// directories tested fails to support file system events. When that
// happens, we switch all previously created pathwatcher watches to use
// fs.watchFile, and set canUsePathwatcher to false so that all future
// watches will use fs.watchFile as well.

// There is some theoretical risk of missing file system events from
// pathwatcher watches created before we discover that we can't use
// pathwatcher.watch, but the window of time where that can happen is
// small enough (500ms) that developers are highly unlikely to care.

exports.testDirectory = function(dir) {
  if (! canUsePathwatcher) {
    // No need to test this directory if we've already decided we can't
    // use pathwatcher.watch.
    return;
  }

  var canaryFile = path.join(
    dir, "canary$" + Math.random().toString(36).slice(2)
  );

  fs.unlink(canaryFile, function(ignoredError) {
    function cleanUp(arg) {
      if (watcher) {
        watcher.close();
        watcher = null;
        fs.unlink(canaryFile, function(ignoredError) {});
      }
    }

    function fallBack() {
      // Disallow future uses of pathwatcher.watch.
      canUsePathwatcher = false;

      // Convert any pathwatcher watchers we previously created to
      // fs.watchFile watchers.
      _.each(switchFunctions.splice(0), function(switchToPolling) {
        switchToPolling();
      });

      require("./console.js").Console.debug(
        "Falling back to fs.watchFile instead of pathwatcher.watch..."
      );
    }

    // Watch the candidate directory using pathwatcher.watch.
    var watcher = require("pathwatcher").watch(dir, cleanUp);

    // Create a new file to trigger a change event (hopefully). It's fine
    // if other events sneak in while we're waiting, since all we care
    // about is whether pathwatcher.watch works.
    fs.writeFile(canaryFile, "ok", function(err) {
      if (err) {
        cleanUp();
        throw err;
      }
    });

    // Set a time limit of 500ms for the change event.
    setTimeout(function() {
      if (watcher) {
        cleanUp();
        fallBack();
      }
    }, 500);
  });
};

exports.watch = function(absPath, callback) {
  if (canUsePathwatcher) {
    // In principle, all this logic for watching files should continue to
    // work perfectly if we substitute fs.watch for pathwatcher.watch, but
    // that will probably have to wait until we upgrade Node to v0.11.x,
    // so that fs.watch is more reliable.
    var watcher = require("pathwatcher").watch(absPath, callback);

    var closed = false;
    var switched = false;

    switchFunctions.push(function switchToPolling() {
      if (! switched && ! closed) {
        switched = true;
        watcher.close();

        // Re-watch the file using fs.watchFile instead.
        fs.watchFile(absPath, {
          interval: pollingInterval
        }, callback);
      }
    });

    return {
      close: function close() {
        if (! closed) {
          closed = true;
          if (switched) {
            fs.unwatchFile(absPath, callback);
          } else {
            watcher.close();
          }
        }
      }
    };
  }

  fs.watchFile(absPath, {
    interval: pollingInterval
  }, callback);

  return {
    close: function close() {
      fs.unwatchFile(absPath, callback);
    }
  };
};
<commit_msg>Avoid pathwatcher.watch failures in testDirectory.<commit_after>var fs = require("fs");
var path = require("path");
var Future = require("fibers/future");
var _ = require("underscore");
var switchFunctions = [];
var pollingInterval = 500;

// Set this environment variable to a truthy value to force the use of
// fs.watchFile instead of pathwatcher.watch.
var canUsePathwatcher = !process.env.METEOR_WATCH_FORCE_POLLING;

// The pathwatcher library does not work on all platforms and file systems
// (notably, network file systems), so we have to do a little feature
// detection to see if we can use it.

// We optimistically watch files using pathwatcher.watch until one of the
// directories tested fails to support file system events. When that
// happens, we switch all previously created pathwatcher watches to use
// fs.watchFile, and set canUsePathwatcher to false so that all future
// watches will use fs.watchFile as well.

// There is some theoretical risk of missing file system events from
// pathwatcher watches created before we discover that we can't use
// pathwatcher.watch, but the window of time where that can happen is
// small enough (500ms) that developers are highly unlikely to care.

exports.testDirectory = function(dir) {
  if (! canUsePathwatcher) {
    // No need to test this directory if we've already decided we can't
    // use pathwatcher.watch.
    return;
  }

  var canaryFile = path.join(
    dir, "canary$" + Math.random().toString(36).slice(2)
  );

  // Make sure the test directory exists.
  require("./files.js").mkdir_p(dir);

  fs.unlink(canaryFile, function(ignoredError) {
    function cleanUp(arg) {
      if (watcher) {
        watcher.close();
        watcher = null;
        fs.unlink(canaryFile, function(ignoredError) {});
      }
    }

    function fallBack() {
      // Disallow future uses of pathwatcher.watch.
      canUsePathwatcher = false;

      // Convert any pathwatcher watchers we previously created to
      // fs.watchFile watchers.
      _.each(switchFunctions.splice(0), function(switchToPolling) {
        switchToPolling();
      });

      require("./console.js").Console.debug(
        "Falling back to fs.watchFile instead of pathwatcher.watch..."
      );
    }

    // Watch the candidate directory using pathwatcher.watch.
    var pathwatcher = require("pathwatcher");
    try {
      var watcher = pathwatcher.watch(dir, cleanUp);
    } catch (err) {
      // If the directory did not exist, do not treat this failure as
      // evidence against pathwatcher.watch, but simply return and leave
      // canUsePathwatcher set to true.
      if (err instanceof TypeError &&
          err.message === "Unable to watch path") {
        return;
      }
      throw err;
    }

    // Create a new file to trigger a change event (hopefully). It's fine
    // if other events sneak in while we're waiting, since all we care
    // about is whether pathwatcher.watch works.
    fs.writeFile(canaryFile, "ok", function(err) {
      if (err) {
        cleanUp();
        throw err;
      }
    });

    // Set a time limit of 500ms for the change event.
    setTimeout(function() {
      if (watcher) {
        cleanUp();
        fallBack();
      }
    }, 500);
  });
};

exports.watch = function(absPath, callback) {
  if (canUsePathwatcher) {
    // In principle, all this logic for watching files should continue to
    // work perfectly if we substitute fs.watch for pathwatcher.watch, but
    // that will probably have to wait until we upgrade Node to v0.11.x,
    // so that fs.watch is more reliable.
    var watcher = require("pathwatcher").watch(absPath, callback);

    var closed = false;
    var switched = false;

    switchFunctions.push(function switchToPolling() {
      if (! switched && ! closed) {
        switched = true;
        watcher.close();

        // Re-watch the file using fs.watchFile instead.
        fs.watchFile(absPath, {
          interval: pollingInterval
        }, callback);
      }
    });

    return {
      close: function close() {
        if (! closed) {
          closed = true;
          if (switched) {
            fs.unwatchFile(absPath, callback);
          } else {
            watcher.close();
          }
        }
      }
    };
  }

  fs.watchFile(absPath, {
    interval: pollingInterval
  }, callback);

  return {
    close: function close() {
      fs.unwatchFile(absPath, callback);
    }
  };
};
<|endoftext|>


<commit_before>
// @require ../picker.js

(function ( $, _, Svelto, Widgets, Factory, EmojiData ) {

  /* CONFIG */

  let config = {
    name: 'emojipickerPopover',
    templates: {
      base: _.template ( '<div>' )
    },
    options: {
      classes: {
        popover: 'popover'
      },
      callbacks: {
        beforeopen: _.noop,
        open: _.noop,
        beforeclose: _.noop,
        close: _.noop
      }
    }
  };

  /* EMOJIPICKER POPOVER */

  class EmojipickerPopover extends Widgets.Widget {

    /* SPECIAL */

    _variables () {

      this._initiated = false;

    }

    /* CLOSE */

    ___close () {

      this._on ( true, 'popover:close', this.__close );

    }

    __close () {

      this.$element.detach ();

      this._reset ();

    }

    /* UTILITIES */

    _isEmpty () {

      return this.$element.is ( ':empty' );

    }

    /* API */

    toggle ( anchor ) {

      if ( this.isLocked () ) {

        if ( !this._isEmpty () ) {

          this.unlock ();

        } else {

          return this.open ( anchor ); //FIXME: What is this for??? (it actually gets called, if an error gets thrown the first time)

        }

      } else {

        if ( this._isEmpty () ) {

          this.lock ();

          EmojiData.get ().then ( data => {

            Widgets.Emojipicker.config.options.data = data;

            this.$element = $.widget.new ( Widgets.Emojipicker ).$element.addClass ( this.options.classes.popover );

            this.toggle ( anchor );

          });

          return;

        }

      }

      if ( !this.$element.isAttached () ) {

        this.$layout.append ( this.$element );

      }

      if ( !this._initiated ) {

        this.$element.popover ({
          callbacks: {
            beforeopen: () => this._trigger ( 'beforeopen' ),
            open: () => this._trigger ( 'open' ),
            beforeclose: () => this._trigger ( 'beforeclose' ),
            close: () => this._trigger ( 'close' )
          }
        });

        this._initiated = true;

      }

      this.$element.popover ( 'toggle', undefined, anchor );

      this.___close ();

    }

  }

  /* FACTORY */

  Factory.make ( EmojipickerPopover, config );

}( Svelto.$, Svelto._, Svelto, Svelto.Widgets, Svelto.Factory, Svelto.EmojiData ));
<commit_msg>EmojiPickerPopover: fixed<commit_after>
// @require ../picker.js

(function ( $, _, Svelto, Widgets, Factory, EmojiData ) {

  /* CONFIG */

  let config = {
    name: 'emojipickerPopover',
    options: {
      classes: {
        popover: 'popover'
      },
      callbacks: {
        beforeopen: _.noop,
        open: _.noop,
        beforeclose: _.noop,
        close: _.noop
      }
    }
  };

  /* EMOJIPICKER POPOVER */

  class EmojipickerPopover extends Widgets.Widget {

    /* SPECIAL */

    _variables () {

      this._initiated = false;

    }

    /* CLOSE */

    ___close () {

      this._on ( true, 'popover:close', this.__close );

    }

    __close () {

      this.$element.detach ();

      this._reset ();

    }

    /* API */

    toggle ( anchor ) {

      if ( this.isLocked () ) {

        if ( this.element ) {

          this.unlock ();

        } else {

          return this.open ( anchor ); //FIXME: What is this for??? (it actually gets called, if an error gets thrown the first time)

        }

      } else {

        if ( !this.element ) {

          this.lock ();

          EmojiData.get ().then ( data => {

            Widgets.Emojipicker.config.options.data = data;

            this.$element = $.widget.new ( Widgets.Emojipicker ).$element.addClass ( this.options.classes.popover );
            this.element = this.$element[0];

            this.toggle ( anchor );

          });

          return;

        }

      }

      if ( !this.$element.isAttached () ) {

        this.$layout.append ( this.$element );

      }

      if ( !this._initiated ) {

        this.$element.popover ({
          callbacks: {
            beforeopen: () => this._trigger ( 'beforeopen' ),
            open: () => this._trigger ( 'open' ),
            beforeclose: () => this._trigger ( 'beforeclose' ),
            close: () => this._trigger ( 'close' )
          }
        });

        this._initiated = true;

      }

      this.$element.popover ( 'toggle', undefined, anchor );

      this.___close ();

    }

  }

  /* FACTORY */

  Factory.make ( EmojipickerPopover, config );

}( Svelto.$, Svelto._, Svelto, Svelto.Widgets, Svelto.Factory, Svelto.EmojiData ));
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var express = require('express')
  , http = require('http')
  , stylus = require('stylus')
  , nib = require('nib')
  , sio = require('../../node_modules/socket.io')
  , azure = require('../../node_modules/azure')
  , SbStore = require('../../lib/sbstore');

/**
 * App.
 */

var app = express();

// Pick up port, topic, & subscription names from command line / environment

var topic = process.argv[2] || process.env['SB_CHAT_TOPIC'] || 'chat';
var subscription = process.argv[3] || process.env['SB_CHAT_SUBSCRIPTION'] || 'chatA';
var port = process.argv[4] || process.env['SB_CHAT_PORT'] || 3000;

/**
 * App configuration.
 */

app.configure(function () {
  app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }));
  app.use(express.static(__dirname + '/public'));
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  function compile (str, path) {
    return stylus(str)
      .set('filename', path)
      .use(nib());
  };
});

/**
 * App routes.
 */

app.get('/', function (req, res) {
  res.render('index', { layout: false });
});

/**
 * App listen.
 */

var server = http.createServer(app);

server.listen(port, function () {
  var addr = server.address();
  console.log('   app listening on http://' + addr.address + ':' + addr.port);
});

/**
 * Socket.IO server (single process only)
 */

var io = sio.listen(server)
  , nicknames = {};

/**
 * Set up socket.io to use service bus store
 */

io.configure(function () {
  io.set('store', new SbStore({
    topic: topic,
    subscription: subscription,
    serviceBusService: azure.createServiceBusService()
  }));
});

io.sockets.on('connection', function (socket) {
  socket.on('user message', function (msg) {
    socket.broadcast.emit('user message', socket.nickname, msg);
  });

  socket.on('nickname', function (nick, fn) {
    if (nicknames[nick]) {
      fn(true);
    } else {
      fn(false);
      nicknames[nick] = socket.nickname = nick;
      socket.broadcast.emit('announcement', nick + ' connected');
      io.sockets.emit('nicknames', nicknames);
    }
  });

  socket.on('disconnect', function () {
    if (!socket.nickname) return;

    delete nicknames[socket.nickname];
    socket.broadcast.emit('announcement', socket.nickname + ' disconnected');
    socket.broadcast.emit('nicknames', nicknames);
  });
});
<commit_msg>Forced xhr polling in the sample, websocket doesn't work in iisnode yet<commit_after>/**
 * Module dependencies.
 */

var express = require('express')
  , http = require('http')
  , stylus = require('stylus')
  , nib = require('nib')
  , sio = require('../../node_modules/socket.io')
  , azure = require('../../node_modules/azure')
  , SbStore = require('../../lib/sbstore');

/**
 * App.
 */

var app = express();

// Pick up port, topic, & subscription names from command line / environment

var topic = process.argv[2] || process.env['SB_CHAT_TOPIC'] || 'chat';
var subscription = process.argv[3] || process.env['SB_CHAT_SUBSCRIPTION'] || 'chatA';
var port = process.argv[4] || process.env['SB_CHAT_PORT'] || 3000;

/**
 * App configuration.
 */

app.configure(function () {
  app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }));
  app.use(express.static(__dirname + '/public'));
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  function compile (str, path) {
    return stylus(str)
      .set('filename', path)
      .use(nib());
  };
});

/**
 * App routes.
 */

app.get('/', function (req, res) {
  res.render('index', { layout: false });
});

/**
 * App listen.
 */

var server = http.createServer(app);

server.listen(port, function () {
  var addr = server.address();
  console.log('   app listening on http://' + addr.address + ':' + addr.port);
});

/**
 * Socket.IO server (single process only)
 */

var io = sio.listen(server)
  , nicknames = {};

/**
 * Set up socket.io to use service bus store
 */

io.configure(function () {
  io.set('store', new SbStore({
    topic: topic,
    subscription: subscription,
    serviceBusService: azure.createServiceBusService()
  }));

  io.set('transports', ['xhr-polling']);
});

io.sockets.on('connection', function (socket) {
  socket.on('user message', function (msg) {
    socket.broadcast.emit('user message', socket.nickname, msg);
  });

  socket.on('nickname', function (nick, fn) {
    if (nicknames[nick]) {
      fn(true);
    } else {
      fn(false);
      nicknames[nick] = socket.nickname = nick;
      socket.broadcast.emit('announcement', nick + ' connected');
      io.sockets.emit('nicknames', nicknames);
    }
  });

  socket.on('disconnect', function () {
    if (!socket.nickname) return;

    delete nicknames[socket.nickname];
    socket.broadcast.emit('announcement', socket.nickname + ' disconnected');
    socket.broadcast.emit('nicknames', nicknames);
  });
});
<|endoftext|>


<commit_before>
module.exports = function (all, defaults) {
  var methods = function () {}

  function enchainAll(all) {
    if(Array.isArray(all))
      return all.forEach(enchainAll)

    for(var k in all)
      methods[k] = enchain(all[k])
  }

  function enchain (fun) {
    return function () {
      var args = [].slice.call(arguments)
      this._chain.push(fun.apply(null, args))
      return this
    }
  }

  enchainAll(all)

  return function () {
    function go () {
      var chain = go._chain
      var pipeline = chain.shift()
      while(chain.length)
        pipeline = chain.shift()(pipeline)
      return pipeline
    }
    go._chain = []
    go.__proto__ = methods

    defaults.apply(go, arguments)

    return go
  }
}
<commit_msg>less indirection<commit_after>
module.exports = function (all, defaults) {
  var methods = function () {}

  function enchainAll(all) {
    if(Array.isArray(all))
      return all.forEach(enchainAll)

    for(var k in all)
      methods[k] = enchain(all[k])
  }

  function enchain (fun) {
    return function () {
      var stream = fun.apply(null, arguments)
      if(!this._stream)
        this._stream = stream
      else
        this._stream = this._stream.pipe(stream)
      return this
    }
  }

  enchainAll(all)

  return function () {
    function go (read) {
      return go._stream.call(read)
    }
    go._chain = []
    go._stream
    go.__proto__ = methods

    defaults.apply(go, arguments)

    return go
  }
}
<|endoftext|>


<commit_before>
require.paths.unshift('lib')
require('express')
require('express/plugins')

configure(function(){
  use(MethodOverride)
  use(ContentLength)
  use(CommonLogger)
  use(Cookie)
  use(Session)
  set('root', dirname(__filename))
  enable('cache static files')
  //enable('cache view contents')
})

var messages = []

get('/', function(){
  this.redirect('/chat')
})

get('/chat', function(){
  this.render('chat.haml.html', {
    locals: {
      title: 'Chat',
      messages: messages,
      name: this.session.name
    }
  })
})

post('/chat', function(){
  this.session.name = this.param('name')
  messages
    .push(escape(this.param('name')) + ': ' + escape(this.param('message'))
    .replace(/(http:\/\/[^\s]+)/g, '$1')
    .replace(/:\)/g, ''))
  this.halt(200)
})

get('/chat/messages', function(){
  var self = this,
      previousLength = messages.length,
      timer = setInterval(function(){
    if (messages.length > previousLength)
      self.contentType('json'),
      previousLength = messages.length,
      self.halt(200, JSON.encode(messages)),
      clearInterval(timer)
  }, 100)
})

get('/public/*', function(file){
  this.sendfile(dirname(__filename) + '/public/' + file)
})

get('/*.css', function(file){
  this.render(file + '.sass.css', { layout: false })
})

get('/error/view', function(){
  this.render('does.not.exist')
})

get('/error', function(){
  throw new Error('oh noes!')
})

get('/simple', function(){
  return 'Hello :)'
})

get('/favicon.ico', function(){
  this.halt()
})

run()<commit_msg>Session options in chat sample app<commit_after>
require.paths.unshift('lib')
require('express')
require('express/plugins')

configure(function(){
  var fiveMinutes = 300000,
      oneMinute = 60000
  use(MethodOverride)
  use(ContentLength)
  use(CommonLogger)
  use(Cookie)
  use(Session, { lifetime: fiveMinutes, reapInterval: oneMinute })
  set('root', dirname(__filename))
  enable('cache static files')
  //enable('cache view contents')
})

var messages = []

get('/', function(){
  this.redirect('/chat')
})

get('/chat', function(){
  this.render('chat.haml.html', {
    locals: {
      title: 'Chat',
      messages: messages,
      name: this.session.name
    }
  })
})

post('/chat', function(){
  this.session.name = this.param('name')
  messages
    .push(escape(this.param('name')) + ': ' + escape(this.param('message'))
    .replace(/(http:\/\/[^\s]+)/g, '$1')
    .replace(/:\)/g, ''))
  this.halt(200)
})

get('/chat/messages', function(){
  var self = this,
      previousLength = messages.length,
      timer = setInterval(function(){
    if (messages.length > previousLength)
      self.contentType('json'),
      previousLength = messages.length,
      self.halt(200, JSON.encode(messages)),
      clearInterval(timer)
  }, 100)
})

get('/public/*', function(file){
  this.sendfile(dirname(__filename) + '/public/' + file)
})

get('/*.css', function(file){
  this.render(file + '.sass.css', { layout: false })
})

get('/error/view', function(){
  this.render('does.not.exist')
})

get('/error', function(){
  throw new Error('oh noes!')
})

get('/simple', function(){
  return 'Hello :)'
})

get('/favicon.ico', function(){
  this.halt()
})

run()<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Bruce Schubert.
 * The MIT License
 * http://www.opensource.org/licenses/mit-license
 */

/*global define*/

/**
 * Explorer singleton and constants.
 *
 * @param {Constants} constants singleton
 * @param {Log} log singleton
 * @param {Settings} settings singleton
 * @param {WorldWind} ww
 *
 * @returns {Explorer}
 *
 * @author Bruce Schubert
 */
define(['jquery',
        'knockout',
        'model/Constants',
        'model/util/Log',
        'model/markers/MarkerManager',
        'model/util/Settings',
        'worldwind'],
    function ($,
              ko,
              constants,
              log,
              MarkerManager,
              settings) {
        "use strict";
        /**
         * This is the top-level Explorer singleton.
         * @exports Explorer
         * @global
         */
        var Explorer = {
            /**
             * The Explorer version number.
             * @constant
             */
            VERSION: "0.1.0",
            /**
             * Prepares the singleton Explorer object for use.
             * @param {Globe} globe
             */
            initialize: function (globe) {
                var self = this;

                this.globe = globe;
                this.wwd = globe.wwd;
                this.markerManager = new MarkerManager(globe);

                // Configure the objects used to animate the globe when performing "go to" operations
                this.goToAnimator = new WorldWind.GoToAnimator(this.wwd);
                this.isAnimating = false;

                // Internal. Intentionally not documented.
                this.updateTimeout = null;
                this.updateInterval = 50;

                // Setup to update each time the World Window is repainted.
                this.wwd.redrawCallbacks.push(function () {
                    self.handleRedraw();
                });

                // Setup an interval to update the current time
                this.autoUpdateTimeEnabled = ko.observable(true);
                this.dateTimeInterval = window.setInterval(function () {
                    if (self.autoUpdateTimeEnabled()) {
                        self.globe.updateDateTime(new Date());
                    }
                }, 30000);  // Update every 30 seconds

                // Setup to track the cursor position relative to the World Window's canvas. Listen to touch events in order
                // to recognize and ignore simulated mouse events in mobile browsers.
                window.addEventListener("mousemove", function (event) {
                    self.handleMouseEvent(event);
                });
                window.addEventListener("touchstart", function (event) {
                    self.handleTouchEvent(event);
                });

            },

            /**
             *
             * @param {Number} latitude
             * @param {Number} longitude
             * @param {Object} params
             */
            identifyFeaturesAtLatLon: function (latitude, longitude, params) {
                var arg = params || {};

                if (!latitude || !longitude || isNaN(latitude) || isNaN(longitude)) {
                    log.error("Explorer", "identifyFeaturesAtLatLon", "Invalid Latitude and/or Longitude.");
                    return;
                }
                //geoMacResource.identifyPoint(latitude, longitude, arg.layerId, function (json) {
                //
                //});

            },
            /**
             * Centers the globe on the given lat/lon via animation.
             * @param {Number} latitude
             * @param {Number} longitude
             * @param {Number} eyeAltitude
             */
            lookAtLatLon: function (latitude, longitude, eyeAltitude) {
                if (!latitude || !longitude || isNaN(latitude) || isNaN(longitude)) {
                    log.error("Explorer", "lookAtLatLon", "Invalid Latitude and/or Longitude.");
                    return;
                }
                // TODO: Make AGL and MSL elevations a function of the model
                // TODO: Eye Position a property of the model
                //
                var self = this,
                    eyeAltMsl = this.globe.viewpoint().eye.altitude,
                    eyePosGrdElev = this.globe.terrainProvider.elevationAtLatLon(this.globe.viewpoint().eye.latitude, this.globe.viewpoint().eye.longitude),
                    tgtPosElev = this.globe.terrainProvider.elevationAtLatLon(latitude, longitude),
                    eyeAltAgl = eyeAltitude || Math.max(eyeAltMsl - eyePosGrdElev, 100),
                    tgtEyeAltMsl = Math.max(tgtPosElev + eyeAltAgl, 100);

                // HACK: Force the view to nadir to avoid bug where navigator looks at target at 0 MSL.
                // This will establish the crosshairs on the target.
                this.wwd.navigator.range = eyeAltMsl;
                this.wwd.navigator.tilt = 0;
                this.wwd.redraw();

                this.globe.goto(latitude, longitude, tgtEyeAltMsl, function () {
                    self.updateSpatialData();
                });
            },
            /**
             * Returns the terrain at the reticule.
             * @returns {Terrain} Explorer.model.viewpoint.target}
             */
            getTargetTerrain: function () {
                return this.globe.viewpoint().target;
            },
            /**
             * Restores all the persistant data from a previous session.
             * This method must be called after World Wind has finished
             * updating. See the use Pace.on("done",...) in WmtClient.
             */
            restoreSession: function () {
                log.info('Explorer', 'restoreSession', 'Restoring the model and view.');
                this.markerManager.restoreMarkers();
                this.restoreSessionView();
                // Update all time sensitive objects
                this.globe.updateDateTime(new Date());

                // Force a refresh now that everything is setup.
                this.globe.redraw();
            },
            // Internal method
            restoreSessionView: function () {
                settings.restoreSessionSettings(this);
            },
            /**
             * Saves the current session to the persistent store.
             * See the call to window.onUnload(...) in WmtClient.
             */
            saveSession: function () {
                log.info('Explorer', 'saveSession', 'Saving the model and view.');
                this.saveSessionView();
                this.markerManager.saveMarkers();
            },
            // Internal method.
            saveSessionView: function () {
                settings.saveSessionSettings(this);
            },
            /**
             * Updates the view model with current globe viewpoint.
             */
            updateSpatialData: function () {
                var wwd = this.wwd,
                    mousePoint = this.mousePoint,
                    centerPoint = new WorldWind.Vec2(wwd.canvas.width / 2, wwd.canvas.height / 2);

                // Use the mouse point when we've received at least one mouse event. Otherwise assume that we're
                // on a touch device and use the center of the World Window's canvas.
                if (!mousePoint) {
                    this.globe.updateMousePosition(centerPoint);
                } else if (wwd.viewport.containsPoint(mousePoint)) {
                    this.globe.updateMousePosition(mousePoint);
                }
                // Update the viewpoint
                if (!this.isAnimating) {
                    this.globe.updateEyePosition();
                }
            },
            /**
             * handleRedraw updates the spatial view models.
             */
            handleRedraw: function () {
                var self = this;
                if (self.updateTimeout) {
                    return; // we've already scheduled an update; ignore redundant redraw events
                }
                self.updateTimeout = window.setTimeout(function () {
                    // Update the geospatial view models
                    self.updateSpatialData();
                    self.updateTimeout = null;
                }, self.updateInterval);
            },
            handleMouseEvent: function (event) {
                if (this.isTouchDevice) {
                    return; // ignore simulated mouse events in mobile browsers
                }
                this.mousePoint = this.wwd.canvasCoordinates(event.clientX, event.clientY);
                this.wwd.redraw();
            },
            //noinspection JSUnusedLocalSymbols
            handleTouchEvent: function () {
                this.isTouchDevice = true; // suppress simulated mouse events in mobile browsers
                this.mousePoint = null;
            }
        };
        /**
         * Holds configuration parameters for WWE. Applications may modify these parameters prior to creating
         * their first Explorer objects. Configuration properties are:
         *

         *
startupLatitude: Initial "look at" latitude. Default is Ventura, CA.
         *
startupLongitude: Initial "look at" longitude. Default is Venura, CA.
         *
startupLongitude: Initial altitude/eye position. Default 0.
         *
startupHeading: Initial view heading. Default 0.
         *
startupTilt: Initial view tilt. Default 0.
         *
startupRoll: Initial view roll. Default 0.
         *
viewControlOrientation: horizontal or vertical. Default vertical.
         *
showPanControl: Show pan (left/right/up/down) controls. Default false.
         *
showExaggerationControl: Show vertical exaggeration controls. Default false.
         *

         */
        Explorer.configuration = {
            imageryDetailHint: (window.screen.width < 768 ? -0.1 : (window.screen.width < 1024 ? 0.0 : (window.screen.width < 1280 ? 0.1 : 0.2))),
            markerLabels: constants.MARKER_LABEL_NAME,
            startupLatitude: 34.29,
            startupLongitude: -119.29,
            startupAltitude: 1000000,
            startupHeading: 0,
            startupTilt: 0,
            startupRoll: 0,
            showPanControl: true,
            showExaggerationControl: true,
            showFieldOfViewControl: false,
            terrainSampleRadius: 30,
            viewControlOrientation: "vertical"
        };

        return Explorer;
    }
);<commit_msg>Updated Explorer to initialize the WeatherScoutManager. - Invokes the save and restore functions of the WeatherScoutManager. - Re: issue #26.<commit_after>/*
 * Copyright (c) 2016 Bruce Schubert.
 * The MIT License
 * http://www.opensource.org/licenses/mit-license
 */

/*global define*/

/**
 * Explorer singleton and constants.
 *
 * @param {Constants} constants singleton
 * @param {Log} log singleton
 * @param {Settings} settings singleton
 * @param {WorldWind} ww
 *
 * @returns {Explorer}
 *
 * @author Bruce Schubert
 */
define(['jquery',
    'knockout',
    'model/Constants',
    'model/util/Log',
    'model/markers/MarkerManager',
    'model/util/Settings',
    'model/weather/WeatherScoutManager',
    'worldwind'],
    function (
        $,
        ko,
        constants,
        log,
        MarkerManager,
        settings,
        WeatherScoutManager) {
        "use strict";
        /**
         * This is the top-level Explorer singleton.
         * @exports Explorer
         * @global
         */
        var Explorer = {
            /**
             * The Explorer version number.
             * @constant
             */
            VERSION: "0.2.0",
            /**
             * Prepares the singleton Explorer object for use.
             * @param {Globe} globe
             */
            initialize: function (globe) {
                var self = this;

                this.globe = globe;
                this.wwd = globe.wwd;

                // Configure the manager of objects on the globe
                this.markerManager = new MarkerManager(globe);
                this.weatherManager = new WeatherScoutManager(globe);

                // Configure the objects used to animate the globe when performing "go to" operations
                this.goToAnimator = new WorldWind.GoToAnimator(this.wwd);
                this.isAnimating = false;

                // Internal. Intentionally not documented.
                this.updateTimeout = null;
                this.updateInterval = 50;

                // Setup to update each time the World Window is repainted.
                this.wwd.redrawCallbacks.push(function () {
                    self.handleRedraw();
                });

                // Setup an interval to update the current time
                this.autoUpdateTimeEnabled = ko.observable(true);
                this.dateTimeInterval = window.setInterval(function () {
                    if (self.autoUpdateTimeEnabled()) {
                        self.globe.updateDateTime(new Date());
                    }
                }, 30000);  // Update every 30 seconds

                // Setup to track the cursor position relative to the World Window's canvas. Listen to touch events in order
                // to recognize and ignore simulated mouse events in mobile browsers.
                window.addEventListener("mousemove", function (event) {
                    self.handleMouseEvent(event);
                });
                window.addEventListener("touchstart", function (event) {
                    self.handleTouchEvent(event);
                });

            },

            /**
             *
             * @param {Number} latitude
             * @param {Number} longitude
             * @param {Object} params
             */
            identifyFeaturesAtLatLon: function (latitude, longitude, params) {
                var arg = params || {};

                if (!latitude || !longitude || isNaN(latitude) || isNaN(longitude)) {
                    log.error("Explorer", "identifyFeaturesAtLatLon", "Invalid Latitude and/or Longitude.");
                    return;
                }
            },
            /**
             * Centers the globe on the given lat/lon via animation.
             * @param {Number} latitude
             * @param {Number} longitude
             * @param {Number} eyeAltitude
             */
            lookAtLatLon: function (latitude, longitude, eyeAltitude) {
                if (!latitude || !longitude || isNaN(latitude) || isNaN(longitude)) {
                    log.error("Explorer", "lookAtLatLon", "Invalid Latitude and/or Longitude.");
                    return;
                }
                // TODO: Make AGL and MSL elevations a function of the model
                // TODO: Eye Position a property of the model
                //
                var self = this,
                    eyeAltMsl = this.globe.viewpoint().eye.altitude,
                    eyePosGrdElev = this.globe.terrainProvider.elevationAtLatLon(this.globe.viewpoint().eye.latitude, this.globe.viewpoint().eye.longitude),
                    tgtPosElev = this.globe.terrainProvider.elevationAtLatLon(latitude, longitude),
                    eyeAltAgl = eyeAltitude || Math.max(eyeAltMsl - eyePosGrdElev, 100),
                    tgtEyeAltMsl = Math.max(tgtPosElev + eyeAltAgl, 100);

                // HACK: Force the view to nadir to avoid bug where navigator looks at target at 0 MSL.
                // This will establish the crosshairs on the target.
                this.wwd.navigator.range = eyeAltMsl;
                this.wwd.navigator.tilt = 0;
                this.wwd.redraw();

                this.globe.goto(latitude, longitude, tgtEyeAltMsl, function () {
                    self.updateSpatialData();
                });
            },
            /**
             * Returns the terrain at the reticule.
             * @returns {Terrain} Explorer.model.viewpoint.target}
             */
            getTargetTerrain: function () {
                return this.globe.viewpoint().target;
            },
            /**
             * Restores all the persistant data from a previous session.
             * This method must be called after World Wind has finished
             * updating. See the use Pace.on("done",...) in WmtClient.
             */
            restoreSession: function () {
                log.info('Explorer', 'restoreSession', 'Restoring the model and view.');
                this.markerManager.restoreMarkers();
                this.weatherManager.restoreScouts();
                this.restoreSessionView();
                // Update all time sensitive objects
                this.globe.updateDateTime(new Date());

                // Force a refresh now that everything is setup.
                this.globe.redraw();
            },
            // Internal method
            restoreSessionView: function () {
                settings.restoreSessionSettings(this);
            },
            /**
             * Saves the current session to the persistent store.
             * See the call to window.onUnload(...) in WmtClient.
             */
            saveSession: function () {
                log.info('Explorer', 'saveSession', 'Saving the model and view.');
                this.saveSessionView();
                this.markerManager.saveMarkers();
                this.weatherManager.saveScouts();
            },
            // Internal method.
            saveSessionView: function () {
                settings.saveSessionSettings(this);
            },
            /**
             * Updates the view model with current globe viewpoint.
             */
            updateSpatialData: function () {
                var wwd = this.wwd,
                    mousePoint = this.mousePoint,
                    centerPoint = new WorldWind.Vec2(wwd.canvas.width / 2, wwd.canvas.height / 2);

                // Use the mouse point when we've received at least one mouse event. Otherwise assume that we're
                // on a touch device and use the center of the World Window's canvas.
                if (!mousePoint) {
                    this.globe.updateMousePosition(centerPoint);
                } else if (wwd.viewport.containsPoint(mousePoint)) {
                    this.globe.updateMousePosition(mousePoint);
                }
                // Update the viewpoint
                if (!this.isAnimating) {
                    this.globe.updateEyePosition();
                }
            },
            /**
             * handleRedraw updates the spatial view models.
             */
            handleRedraw: function () {
                var self = this;
                if (self.updateTimeout) {
                    return; // we've already scheduled an update; ignore redundant redraw events
                }
                self.updateTimeout = window.setTimeout(function () {
                    // Update the geospatial view models
                    self.updateSpatialData();
                    self.updateTimeout = null;
                }, self.updateInterval);
            },
            handleMouseEvent: function (event) {
                if (this.isTouchDevice) {
                    return; // ignore simulated mouse events in mobile browsers
                }
                this.mousePoint = this.wwd.canvasCoordinates(event.clientX, event.clientY);
                this.wwd.redraw();
            },
            //noinspection JSUnusedLocalSymbols
            handleTouchEvent: function () {
                this.isTouchDevice = true; // suppress simulated mouse events in mobile browsers
                this.mousePoint = null;
            }
        };
        /**
         * Holds configuration parameters for WWE. Applications may modify these parameters prior to creating
         * their first Explorer objects. Configuration properties are:
         *

         *
startupLatitude: Initial "look at" latitude. Default is Ventura, CA.
         *
startupLongitude: Initial "look at" longitude. Default is Venura, CA.
         *
startupLongitude: Initial altitude/eye position. Default 0.
         *
startupHeading: Initial view heading. Default 0.
         *
startupTilt: Initial view tilt. Default 0.
         *
startupRoll: Initial view roll. Default 0.
         *
viewControlOrientation: horizontal or vertical. Default vertical.
         *
showPanControl: Show pan (left/right/up/down) controls. Default false.
         *
showExaggerationControl: Show vertical exaggeration controls. Default false.
         *

         */
        Explorer.configuration = {
            imageryDetailHint: (window.screen.width < 768 ? -0.1 : (window.screen.width < 1024 ? 0.0 : (window.screen.width < 1280 ? 0.1 : 0.2))),
            markerLabels: constants.MARKER_LABEL_NAME,
            startupLatitude: 34.29,
            startupLongitude: -119.29,
            startupAltitude: 1000000,
            startupHeading: 0,
            startupTilt: 0,
            startupRoll: 0,
            showPanControl: true,
            showExaggerationControl: true,
            showFieldOfViewControl: false,
            terrainSampleRadius: 30,
            viewControlOrientation: "vertical"
        };

        return Explorer;
    }
);<|endoftext|>


<commit_before>/**
 * @fileoverview sample file.
 */

goog.provide('my.app.Sample');

goog.require('goog.ui.Component');

/**
 * @param {goog.dom.DomHelper=} opt_domHelper
 * @constructor
 * @extends {goog.ui.Component}
 */
my.app.Sample = function(opt_domHelper) {
  goog.base(this, opt_domHelper);

  /**
   * @type {number}
   * @private
   */
  this.number_ = 0;
};
goog.inherits(my.app.Sample, goog.ui.Component);

/** @override */
my.app.Sample.prototype.enterDocument = function() {
  goog.base(this, 'enterDocument');
};

/** @override */
my.app.Sample.prototype.renderBefore = function(sibling) {
  goog.base(this, 'renderBefore', sibling);
};

/** @override */
my.app.Sample.prototype.disposeInternal = function() {
  goog.base(this, 'disposeInternal');
  delete this.number_;
};
<commit_msg>Fix whitespace.<commit_after>/**
 * @fileoverview sample file.
 */
goog.provide('my.app.Sample');

goog.require('goog.ui.Component');

/**
 * @param {goog.dom.DomHelper=} opt_domHelper
 * @constructor
 * @extends {goog.ui.Component}
 */
my.app.Sample = function(opt_domHelper) {
  goog.base(this, opt_domHelper);

  /**
   * @type {number}
   * @private
   */
  this.number_ = 0;
};
goog.inherits(my.app.Sample, goog.ui.Component);

/** @override */
my.app.Sample.prototype.enterDocument = function() {
  goog.base(this, 'enterDocument');
};

/** @override */
my.app.Sample.prototype.renderBefore = function(sibling) {
  goog.base(this, 'renderBefore', sibling);
};

/** @override */
my.app.Sample.prototype.disposeInternal = function() {
  goog.base(this, 'disposeInternal');
  delete this.number_;
};
<|endoftext|>


<commit_before>/*
 * Copyright 2006 The eFaps Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author:          tmo
 * Revision:        $Rev$
 * Last Changed:    $Date$
 * Last Changed By: $Author$
 */

importClass(java.io.File);
importClass(java.io.FileInputStream);

importClass(Packages.org.efaps.db.Checkin);
importClass(Packages.org.efaps.db.Insert);
importClass(Packages.org.efaps.db.Instance);
importClass(Packages.org.efaps.db.SearchQuery);

/**
 * The class represents images used e.g. for type icons or for user interfaces.
 */
function Image(_name)  {
  var query = new SearchQuery();
  query.setQueryTypes(Shell.getContext(), "Admin_UI_Image");
  query.addWhereExprEqValue(Shell.getContext(), "Name", _name);
  query.addSelect(Shell.getContext(), "OID");
  query.executeWithoutAccessCheck();

  if (query.next())  {
    var oid = query.get(Shell.getContext(), "OID");
    this.instance = new Instance(Shell.getContext(), oid);
  } else  {
    this.instance = null;
  }
  query.close();

  this.object = new EFapsInstance("Admin_UI_Image", _name);

  // add helper methods for getter and setter
  this._setAttrValue      = Abstract.prototype._setAttrValue;
  this._getAttrValue      = Abstract.prototype._getAttrValue;

  // add getter and setter methods
  this.getInstance        = Abstract.prototype.getInstance;
  this.getId              = Abstract.prototype.getId;
  this.getOid             = Abstract.prototype.getOid;
  this.getType            = Abstract.prototype.getType;
  this.getName            = Abstract.prototype.getName;
  this.getRevision        = Abstract.prototype.getRevision;
  this.setRevision        = Abstract.prototype.setRevision;
}

///////////////////////////////////////////////////////////////////////////////
// instance variables

/**
 * Prefix of script file names.
 */
Image.prototype.FILE_PREFIX = new Packages.java.lang.String("IMAGE_");

///////////////////////////////////////////////////////////////////////////////
// common methods

/**
 * Updates current image in eFaps with image of file. If the image in eFaps
 * does not exists, the image is created.
 *
 * @param _fileName (String)  name of the update file
 * @param _objName  (String)  name of the object
 */
Image.prototype.update = function(_fileName, _objName)  {
  if (this.getOid()==null || this.getOid()=="" || this.getOid()=="0")  {
    print("  - create");
    var insert = new Insert(Shell.getContext(), "Admin_UI_Image");
    insert.add(Shell.getContext(), "Name", _objName);
    insert.executeWithoutAccessCheck();
    this.instance = insert.getInstance();
  } else  {
    print("  - update");
  }
  this.checkin(_fileName);
}

/**
 * The file with the name '_fileName' is checked in the object. The file could
 * be accessable via the class patch or normal system path (method first
 * searches inside the classpath, than in the system path).
 *
 * @param _fileName name of the file to checkin
 */
Image.prototype.checkin = function(_fileName)  {
  var context = Packages.org.mozilla.javascript.Context.enter();
  var reader;
  try  {
    var stream = _eFapsClassLoader.getResourceAsStream(_fileName);
    if (stream==null)  {
      stream = new FileInputStream(new File(_fileName));
    }

    var checkin = new Checkin(Shell.getContext(), this.getInstance());
    checkin.execute(Shell.getContext(), _fileName, stream, stream.available());

    stream.close();
  } catch (e)  {
print(e);
    context.reportError(e.toString());
  } finally  {
    try  {reader.close();} catch(f) {}
  }
}

///////////////////////////////////////////////////////////////////////////////
// static functions

/**
 * One image file with the given name is imported.
 *
 * @param _fileName   file to import
 */
function importImage(_fileName)  {
  var file = new Packages.java.io.File(_fileName);
  var fileName = new Packages.java.lang.String(file.getName());
  if (fileName.startsWith(Image.prototype.FILE_PREFIX) && (fileName.endsWith(".gif") || fileName.endsWith(".png")))  {
    var objName = new String(fileName.substring(Image.prototype.FILE_PREFIX.length(), fileName.length()-4));
    print("Import Image '"+objName+"'");
    var imp = new Image(objName);
    imp.update(_fileName, objName);
  }
}

/**
 * A list of Image Definition files is imported.
 *
 * @param _fileList (Array) array with list of files
 */
function importImages(_fileList)  {
  print("");
  print("Import Images");
  print("~~~~~~~~~~~~~");
  for (indx in _fileList)  {
    importImage(_fileList[indx]);
  }
  print("");
}

/**
 * Creates all Images in the given path matching given match.
 *
 * @param _path   (String) path to write all images in
 * @param _match  (String) match for menu names
 */
function createScriptImages(_path, _match)  {
  var query = new SearchQuery();
  query.setQueryTypes(Shell.getContext(), "Admin_UI_Image");
  query.addWhereExprEqValue(Shell.getContext(), "Name", _match);
  query.addSelect(Shell.getContext(), "Name");

  query.executeWithoutAccessCheck();

  print("Create Images:");
  print("~~~~~~~~~~~~~~");
  while (query.next())  {
    var name = query.get(Shell.getContext(), "Name");
    print("  - '"+  name  +"'");
    var image = new Image(name);
    image.object.checkout("File", _path+"/"+name);
  }

  query.close();
}
<commit_msg>- javascript changed to use checkin of images without access management<commit_after>/*
 * Copyright 2006 The eFaps Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author:          tmo
 * Revision:        $Rev$
 * Last Changed:    $Date$
 * Last Changed By: $Author$
 */

importClass(java.io.File);
importClass(java.io.FileInputStream);

importClass(Packages.org.efaps.db.Checkin);
importClass(Packages.org.efaps.db.Insert);
importClass(Packages.org.efaps.db.Instance);
importClass(Packages.org.efaps.db.SearchQuery);

/**
 * The class represents images used e.g. for type icons or for user interfaces.
 */
function Image(_name)  {
  var query = new SearchQuery();
  query.setQueryTypes(Shell.getContext(), "Admin_UI_Image");
  query.addWhereExprEqValue(Shell.getContext(), "Name", _name);
  query.addSelect(Shell.getContext(), "OID");
  query.executeWithoutAccessCheck();

  if (query.next())  {
    var oid = query.get(Shell.getContext(), "OID");
    this.instance = new Instance(Shell.getContext(), oid);
  } else  {
    this.instance = null;
  }
  query.close();

  this.object = new EFapsInstance("Admin_UI_Image", _name);

  // add helper methods for getter and setter
  this._setAttrValue      = Abstract.prototype._setAttrValue;
  this._getAttrValue      = Abstract.prototype._getAttrValue;

  // add getter and setter methods
  this.getInstance        = Abstract.prototype.getInstance;
  this.getId              = Abstract.prototype.getId;
  this.getOid             = Abstract.prototype.getOid;
  this.getType            = Abstract.prototype.getType;
  this.getName            = Abstract.prototype.getName;
  this.getRevision        = Abstract.prototype.getRevision;
  this.setRevision        = Abstract.prototype.setRevision;
}

///////////////////////////////////////////////////////////////////////////////
// instance variables

/**
 * Prefix of script file names.
 */
Image.prototype.FILE_PREFIX = new Packages.java.lang.String("IMAGE_");

///////////////////////////////////////////////////////////////////////////////
// common methods

/**
 * Updates current image in eFaps with image of file. If the image in eFaps
 * does not exists, the image is created.
 *
 * @param _fileName (String)  name of the update file
 * @param _objName  (String)  name of the object
 */
Image.prototype.update = function(_fileName, _objName)  {
  if (this.getOid()==null || this.getOid()=="" || this.getOid()=="0")  {
    print("  - create");
    var insert = new Insert(Shell.getContext(), "Admin_UI_Image");
    insert.add(Shell.getContext(), "Name", _objName);
    insert.executeWithoutAccessCheck();
    this.instance = insert.getInstance();
  } else  {
    print("  - update");
  }
  this.checkin(_fileName);
}

/**
 * The file with the name '_fileName' is checked in the object. The file could
 * be accessable via the class patch or normal system path (method first
 * searches inside the classpath, than in the system path).
 *
 * @param _fileName name of the file to checkin
 */
Image.prototype.checkin = function(_fileName)  {
  var context = Packages.org.mozilla.javascript.Context.enter();
  var reader;
  try  {
    var stream = _eFapsClassLoader.getResourceAsStream(_fileName);
    if (stream==null)  {
      stream = new FileInputStream(new File(_fileName));
    }

    var checkin = new Checkin(this.getInstance());
    checkin.executeWithoutAccessCheck(_fileName, stream, stream.available());

    stream.close();
  } catch (e)  {
print(e);
    context.reportError(e.toString());
  } finally  {
    try  {reader.close();} catch(f) {}
  }
}

///////////////////////////////////////////////////////////////////////////////
// static functions

/**
 * One image file with the given name is imported.
 *
 * @param _fileName   file to import
 */
function importImage(_fileName)  {
  var file = new Packages.java.io.File(_fileName);
  var fileName = new Packages.java.lang.String(file.getName());
  if (fileName.startsWith(Image.prototype.FILE_PREFIX) && (fileName.endsWith(".gif") || fileName.endsWith(".png")))  {
    var objName = new String(fileName.substring(Image.prototype.FILE_PREFIX.length(), fileName.length()-4));
    print("Import Image '"+objName+"'");
    var imp = new Image(objName);
    imp.update(_fileName, objName);
  }
}

/**
 * A list of Image Definition files is imported.
 *
 * @param _fileList (Array) array with list of files
 */
function importImages(_fileList)  {
  print("");
  print("Import Images");
  print("~~~~~~~~~~~~~");
  for (indx in _fileList)  {
    importImage(_fileList[indx]);
  }
  print("");
}

/**
 * Creates all Images in the given path matching given match.
 *
 * @param _path   (String) path to write all images in
 * @param _match  (String) match for menu names
 */
function createScriptImages(_path, _match)  {
  var query = new SearchQuery();
  query.setQueryTypes(Shell.getContext(), "Admin_UI_Image");
  query.addWhereExprEqValue(Shell.getContext(), "Name", _match);
  query.addSelect(Shell.getContext(), "Name");

  query.executeWithoutAccessCheck();

  print("Create Images:");
  print("~~~~~~~~~~~~~~");
  while (query.next())  {
    var name = query.get(Shell.getContext(), "Name");
    print("  - '"+  name  +"'");
    var image = new Image(name);
    image.object.checkout("File", _path+"/"+name);
  }

  query.close();
}
<|endoftext|>


<commit_before>var assert = chai.assert;
var expect = chai.expect;

describe("The Contact Service",function(){
	beforeEach(function(){

			module('AddressBook');
			module('ngMockE2E');

			inject(function(_contactService_,$injector){
				contactService = _contactService_;
				$httpBackend = $injector.get('$httpBackend');
				$httpBackend.whenGET('http://localhost:3000/contacts').passThrough();
				$httpBackend.expectGET('http://localhost:3000/contacts');

		})
	});

	it('should return an array of contacts asynchronously',function(){
			contactService.getContacts()
			.then(function(contacts){
				expect(contacts).to.be.an('array');
			});
	});

	describe("the validation helper",function(){

		it("should return null on no contact at all",function(){
			expect(contactService.isValidContact(undefined)).to.be.null;
		});

		it("should return false on a contact with no name",function(){
			var contact_with_no_name = {
				age:36,
				occupation:"Janitor",
				email:"janitor@planetexpress.com"
			};
			expect(contactService.isValidContact(contact_with_no_name)).to.be.false;
		});

		it("should return false on a contact with no email",function(){
			var contact_with_no_email = {
				name:"Scruffy",
				age:36,
				occupation:"Janitor",
			};
			assert.isFalse(contactService.isValidContact(contact_with_no_email));
		});

		it("should return true on a contact with no age, it is optional",function(){
			var contact_with_no_age = {
				name:"Scruffy",
				occupation:"Janitor",
				email:"janitor@planetexpress.com"
			};
			expect(contactService.isValidContact(contact_with_no_age)).to.be.true;
		});

		it("should return true on a contact with no occupation, because that is optional",function(){
			var contact_with_no_occupation = {
				name:"Scruffy",
				age:25,
				email:"janitor@planetexpress.com"
			};
			expect(contactService.isValidContact(contact_with_no_occupation)).to.be.true;
		});
	});

	describe("The Contacts",function(){
		beforeEach(function(){
				inject(function($injector){
					contactService = $injector.get('contactService');
				})
		})

		it('should have a name that is a string',	function(done){
			contactService.getContacts()
			.then(function(contacts){
				contacts.forEach(function(contact){
					expect(contact).to.have.property('name');
					expect(contact.name).to.be.a('string');
					done();
				});
			});
		});

		it('should have a numeric age property',function(done){
			contactService.getContacts()
			.then(function(contacts){
				contacts.forEach(function(contact){
					expect(contact).to.have.property('age');
					expect(contact.age).to.be.a('number');
					done();
				})
			})
		});
	})
});

describe("The validation service",function(){
	beforeEach(function(){
		module("AddressBook");
		inject(function(_validationService_){
			validationService = _validationService_;
		})
	})
	describe("the name validator",function(){
		it("should return false if the name is not a string.",function(){
			assert.notOk(validationService.validateName(0x0dedde))
			assert.notOk(validationService.validateName({}))
			assert.notOk(validationService.validateName([]))
		});

		it("should return false on names of less than two letters",function(){
			assert.isFalse(validationService.validateName('N'));
		});

		it("should return true on a string of two or more characters",function(){
			assert.ok(validationService.validateName('Eddard'));
			assert.ok(validationService.validateName('Roose Bolton'));
			assert.ok(validationService.validateName('Robert Baratheon, King of The Andals'));
		});
	})
})

describe("The Contact List Controller",function(){
	beforeEach(function(){

		module('AddressBook');
		module('ngMockE2E');

		inject(function($rootScope,$injector){
			/* Create a new scope that we can assign as the controllers scope. By keeping a reference to it, we can run tests. */
			$scope = $rootScope.$new();

			contactService = $injector.get("contactService");
			$httpBackend = $injector.get('$httpBackend');
			$controller = $injector.get("$controller");

			$httpBackend.whenGET('http://localhost:3000/contacts').passThrough();
			$httpBackend.expectGET('http://localhost:3000/contacts');
		})
	});

	it('should get a copy of the contact list on startup and store it in $scope',function(done){
		/* Create a new instance of the controller with the $controller service */
//		contactListController = $controller("ContactList",{$scope:$scope,contactService:contactService});
		contactService.getContacts()
			.then(function(contacts){
				expect(contacts).to.be.an('array');
				expect($scope.contacts).to.be.an('array');
				done();
			});

//		$httpBackend.flush();
	});
})
<commit_msg>fix all tests by going with non e2e mocks. e2e mocks are for backend use.<commit_after>var assert = chai.assert;
var expect = chai.expect;

describe("The Address Book App",function(){

	beforeEach(function(){

			module('AddressBook');
			module('ngMock');

			inject(function(_contactService_,$injector){
				contactService = _contactService_;
				$httpBackend = $injector.get('$httpBackend');
				$httpBackend.whenGET('http://localhost:3000/contacts').respond(200,[{
					"name":"Jon Snow",
					"age":15,
					"occupation":"Lord Commander of the Wall",
					"email":"jon@nightswatch.wl"
				}]);
				$httpBackend.expectGET('http://localhost:3000/contacts');

		})
	});

	describe("The Contact Service",function(){

		beforeEach(function(){
				inject(function($injector){
					contactService = $injector.get("contactService");
				})
		});

		it('should return an array of contacts asynchronously',function(done){
			contactService.getContacts()
			.then(function(contacts){
				expect(contacts).to.be.an('array');
				done();
			});
			setTimeout($httpBackend.flush);
		});

		describe("the validation helper",function(){

			it("should return null on no contact at all",function(){
				expect(contactService.isValidContact(undefined)).to.be.null;
			});

			it("should return false on a contact with no name",function(){
				var contact_with_no_name = {
					age:36,
					occupation:"Janitor",
					email:"janitor@planetexpress.com"
				};
				expect(contactService.isValidContact(contact_with_no_name)).to.be.false;
			});

			it("should return false on a contact with no email",function(){
				var contact_with_no_email = {
					name:"Scruffy",
					age:36,
					occupation:"Janitor",
				};
				assert.isFalse(contactService.isValidContact(contact_with_no_email));
			});

			it("should return true on a contact with no age, it is optional",function(){
				var contact_with_no_age = {
					name:"Scruffy",
					occupation:"Janitor",
					email:"janitor@planetexpress.com"
				};
				expect(contactService.isValidContact(contact_with_no_age)).to.be.true;
			});

			it("should return true on a contact with no occupation, because that is optional",function(){
				var contact_with_no_occupation = {
					name:"Scruffy",
					age:25,
					email:"janitor@planetexpress.com"
				};
				expect(contactService.isValidContact(contact_with_no_occupation)).to.be.true;
			});
		});

		describe("The Contacts",function(){
			beforeEach(function(){
					inject(function($injector){
						contactService = $injector.get('contactService');
					})
			})

			it('should have a name that is a string',	function(done){
				contactService.getContacts()
				.then(function(contacts){
					contacts.forEach(function(contact){
						expect(contact).to.have.property('name');
						expect(contact.name).to.be.a('string');
						done();
					});
				});
				setTimeout($httpBackend.flush);
			});

			it('should have a numeric age property',function(done){
				contactService.getContacts()
				.then(function(contacts){
					contacts.forEach(function(contact){
						expect(contact).to.have.property('age');
						expect(contact.age).to.be.a('number');
						done();
					});
				});
				setTimeout($httpBackend.flush);
			});
		})
	});

	describe("The validation service",function(){
		beforeEach(function(){
			inject(function($injector){
				validationService = $injector.get("validationService");
			})
		})
		describe("the name validator",function(){
			it("should return false if the name is not a string.",function(){
				assert.notOk(validationService.validateName(0x0dedde))
				assert.notOk(validationService.validateName({}))
				assert.notOk(validationService.validateName([]))
			});

			it("should return false on names of less than two letters",function(){
				assert.isFalse(validationService.validateName('N'));
			});

			it("should return true on a string of two or more characters",function(){
				assert.ok(validationService.validateName('Eddard'));
				assert.ok(validationService.validateName('Roose Bolton'));
				assert.ok(validationService.validateName('Robert Baratheon, King of The Andals'));
			});
		})
	})

	describe("The Contact List Controller",function(){
		beforeEach(function(){

			inject(function($rootScope,$injector){
				/* Create a new scope that we can assign as the controllers scope. By keeping a reference to it, we can run tests. */
				$scope = $rootScope.$new();

				contactService = $injector.get("contactService");
				$controller = $injector.get("$controller");
			})
		});

		it('should get a copy of the contact list on startup and store it in $scope',function(done){
			/* Create a new instance of the controller with the $controller service */
			contactListController = $controller("ContactList",{$scope:$scope,contactService:contactService});
			contactService.getContacts()
				.then(function(contacts){
					expect($scope.contacts).to.be.an('array');
					expect($scope.contacts).to.deep.equal(contacts);
					done();
				});

			setTimeout($httpBackend.flush);
		});
	})
})<|endoftext|>