<commit_before>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const ngcWebpack = require('ngc-webpack');
const WebpackBrowserPlugin = require('webpack-browser-plugin');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  isProd = options.env === 'production';
  return {

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
    //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {

      'polyfills': './src/polyfills.browser.ts',
      'main':      AOT ? './src/main.browser.aot.ts' :
                  './src/main.browser.ts'

    },

    /*
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {

      /*
       * An array of extensions that should be used to resolve modules.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: ['.ts', '.js', '.json', '.styl', '.pug'],

      // An array of directory names to be resolved to the current directory
      modules: [helpers.root('src'), helpers.root('node_modules')],

    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      rules: [

        /*
         * Typescript loader support for .ts
         *
         * Component Template/Style integration using `angular2-template-loader`
         * Angular 2 lazy loading (async routes) via `ng-router-loader`
         *
         * `ng-router-loader` expects vanilla JavaScript code, not TypeScript code. This is why the
         * order of the loader matter.
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         * See: https://github.com/shlomiassaf/ng-router-loader
         */
        {
          test: /\.ts$/,
          use: [
            {
              loader: '@angularclass/hmr-loader',
              options: {
                pretty: !isProd,
                prod: isProd
              }
            },
            { // MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION OUTPUT.
              loader: 'ng-router-loader',
              options: {
                loader: 'async-import',
                genDir: 'compiled',
                aot: AOT
              }
            },
            {
              loader: 'awesome-typescript-loader',
              options: {
                configFileName: 'tsconfig.webpack.json'
              }
            },
            {
              loader: 'angular2-template-loader'
            }
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /*
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          use: 'json-loader'
        },

        /*
         * to string and css loader support for *.css files (from Angular components)
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          use: ['to-string-loader', 'css-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /*
         * to string and sass loader support for *.scss files (from Angular components)
         * Returns compiled css content as string
         *
         */
        {
          test: /\.scss$/,
          use: ['to-string-loader', 'css-loader', 'sass-loader'],
          exclude: [helpers.root('src', 'styles')]
        },
        {
          test: /\.styl$/,
          use: ['to-string-loader', 'css-loader', 'stylus-loader']
        },
        {
          test: /\.(pug|jade)$/,
          use: ['pug-ng-html-loader']
        },
        /* Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          use: 'raw-loader',
          exclude: [helpers.root('src/index.html')]
        },

        /*
         * File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        /* File loader for supporting fonts, for example, in CSS files.
        */
        {
          test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
          use: 'file-loader'
        }

      ],

    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      new WebpackBrowserPlugin({
       browser: 'c:\Program Files (x86)\dartium-win-ia32-stable-1.22.1.0\chrome.exe',
       port: 3001,
       url: 'http://localhost'
      }),

      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new CheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new CommonsChunkPlugin({
        name: 'polyfills',
        chunks: ['polyfills']
      }),
      // This enables tree shaking of the vendor modules
      new CommonsChunkPlugin({
        name: 'vendor',
        chunks: ['main'],
        minChunks: module => /node_modules/.test(module.resource)
      }),
      // Specify the correct order the scripts will be injected in
      new CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
        helpers.root('src'), // location of your src
        {
          // your Angular Async Route paths relative to this root directory
        }
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
      new CopyWebpackPlugin([
        { from: 'src/assets', to: 'assets' },
        { from: 'src/meta'}
      ]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.html',
        title: METADATA.title,
        chunksSortMode: 'dependency',
        metadata: METADATA,
        inject: 'head'
      }),

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin: HtmlElementsPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({}),

      // Fix Angular 2
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)async/,
        helpers.root('node_modules/@angular/core/src/facade/async.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)collection/,
        helpers.root('node_modules/@angular/core/src/facade/collection.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)errors/,
        helpers.root('node_modules/@angular/core/src/facade/errors.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)lang/,
        helpers.root('node_modules/@angular/core/src/facade/lang.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)math/,
        helpers.root('node_modules/@angular/core/src/facade/math.js')
      ),

      new ngcWebpack.NgcWebpackPlugin({
        disabled: !AOT,
        tsConfig: helpers.root('tsconfig.webpack.json'),
        resourceOverride: helpers.root('config/resource-override.js')
      })

    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  };
}
<commit_msg>removed WebpackBrowserPlugin, wasn't working and was causing an issue with AOT<commit_after>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const ngcWebpack = require('ngc-webpack');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  isProd = options.env === 'production';
  return {

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
    //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {

      'polyfills': './src/polyfills.browser.ts',
      'main':      AOT ? './src/main.browser.aot.ts' :
                  './src/main.browser.ts'

    },

    /*
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {

      /*
       * An array of extensions that should be used to resolve modules.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: ['.ts', '.js', '.json', '.styl', '.pug'],

      // An array of directory names to be resolved to the current directory
      modules: [helpers.root('src'), helpers.root('node_modules')],

    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      rules: [

        /*
         * Typescript loader support for .ts
         *
         * Component Template/Style integration using `angular2-template-loader`
         * Angular 2 lazy loading (async routes) via `ng-router-loader`
         *
         * `ng-router-loader` expects vanilla JavaScript code, not TypeScript code. This is why the
         * order of the loader matter.
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         * See: https://github.com/shlomiassaf/ng-router-loader
         */
        {
          test: /\.ts$/,
          use: [
            {
              loader: '@angularclass/hmr-loader',
              options: {
                pretty: !isProd,
                prod: isProd
              }
            },
            { // MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION OUTPUT.
              loader: 'ng-router-loader',
              options: {
                loader: 'async-import',
                genDir: 'compiled',
                aot: AOT
              }
            },
            {
              loader: 'awesome-typescript-loader',
              options: {
                configFileName: 'tsconfig.webpack.json'
              }
            },
            {
              loader: 'angular2-template-loader'
            }
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /*
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          use: 'json-loader'
        },

        /*
         * to string and css loader support for *.css files (from Angular components)
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          use: ['to-string-loader', 'css-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /*
         * to string and sass loader support for *.scss files (from Angular components)
         * Returns compiled css content as string
         *
         */
        {
          test: /\.scss$/,
          use: ['to-string-loader', 'css-loader', 'sass-loader'],
          exclude: [helpers.root('src', 'styles')]
        },
        {
          test: /\.styl$/,
          use: ['to-string-loader', 'css-loader', 'stylus-loader']
        },
        {
          test: /\.(pug|jade)$/,
          use: ['pug-ng-html-loader']
        },
        /* Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          use: 'raw-loader',
          exclude: [helpers.root('src/index.html')]
        },

        /*
         * File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        /* File loader for supporting fonts, for example, in CSS files.
        */
        {
          test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
          use: 'file-loader'
        }

      ],

    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [

      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new CheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new CommonsChunkPlugin({
        name: 'polyfills',
        chunks: ['polyfills']
      }),
      // This enables tree shaking of the vendor modules
      new CommonsChunkPlugin({
        name: 'vendor',
        chunks: ['main'],
        minChunks: module => /node_modules/.test(module.resource)
      }),
      // Specify the correct order the scripts will be injected in
      new CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
        helpers.root('src'), // location of your src
        {
          // your Angular Async Route paths relative to this root directory
        }
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
      new CopyWebpackPlugin([
        { from: 'src/assets', to: 'assets' },
        { from: 'src/meta'}
      ]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.html',
        title: METADATA.title,
        chunksSortMode: 'dependency',
        metadata: METADATA,
        inject: 'head'
      }),

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin: HtmlElementsPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({}),

      // Fix Angular 2
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)async/,
        helpers.root('node_modules/@angular/core/src/facade/async.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)collection/,
        helpers.root('node_modules/@angular/core/src/facade/collection.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)errors/,
        helpers.root('node_modules/@angular/core/src/facade/errors.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)lang/,
        helpers.root('node_modules/@angular/core/src/facade/lang.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)math/,
        helpers.root('node_modules/@angular/core/src/facade/math.js')
      ),

      new ngcWebpack.NgcWebpackPlugin({
        disabled: !AOT,
        tsConfig: helpers.root('tsconfig.webpack.json'),
        resourceOverride: helpers.root('config/resource-override.js')
      })

    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  };
}
<|endoftext|>


<commit_before>(function($) {
//$.entwine('ss', function($) {

	$('.field').entwine({

		getFormField: function() {
			return this.find('[name='+this.getFieldName()+']');
		},

		getFieldName: function() {
			return this.attr('id');
		},

		getFieldValue: function() {
			return this.getFormField().val();
		},

		evaluateEqualTo: function(val) {
			return this.getFieldValue() === val;
		},

		evaluateNotEqualTo: function(val) {
			return this.getFieldValue() !== val;
		},

		evaluateLessThan: function(val) {
			num = parseFloat(val);
			return this.getFieldValue() < num;
		},

		evaluateGreaterThan: function(val) {
			num = parseFloat(val);
			return parseFloat(this.getFieldValue()) > num;
		},

		evaluateLessThan: function(val) {
			num = parseFloat(val);
			return parseFloat(this.getFieldValue()) < num;
		},

		evaluateContains: function(val) {
			return this.getFieldValue().match(val) !== null;
		},

		evaluateStartsWith: function(val) {
			return this.getFieldValue().match(new RegExp('^'+val)) !== null;
		},

		evaluateEndsWith: function(val) {
			return this.getFieldValue().match(new RegExp(val+'$')) !== null;
		},

		evaluateEmpty: function() {
			return $.trim(this.getFieldValue()).length === 0;
		},

		evaluateNotEmpty: function() {
			return !this.evaluateEmpty();
		},

		evaluateBetween: function(minmax) {
			v = parseFloat(this.getFieldValue());
			parts = minmax.split("-");
			if(parts.length === 2) {
				return v > parseFloat(parts[0]) && v < parseFloat(parts[1]);
			}
			return false;
		},

		evaluateChecked: function() {
			return this.getFormField().is(":checked");
		}

	});

	$('.field.display-logic').entwine({
		onmatch: function () {
			masters = this.getMasters();
			for(m in masters) {
				this.closest('form').find('#'+masters[m]).addClass("display-logic-master");
			}
		},

		getLogic: function() {
			return $.trim(this.find('.display-logic-eval').text());
		},

		parseLogic: function() {
			js = this.getLogic();
			result = eval(js);
			return result;
		},

		getMasters: function() {
			return this.data('display-logic-masters').split(",");
		}

	});

	$('.field.optionset').entwine({

		getFormField: function() {
			f = this._super().filter(":checked");
			return f;
		}

	});

	$('.field.optionset.checkboxset').entwine({

		evaluateHasCheckedOption: function(val) {
			this.find(':checkbox').filter(':checked').each(function() {
				return $(this).val() === val || $(this).getLabel() === val;
			})
		},

		evaluateHasCheckedAtLeast: function(num) {
			return this.find(':checked').length >= num;
		},

		evaluateHasCheckedLessThan: function(num) {
			return this.find(':checked').length <= num;
		}
	});

	$('.field input[type=checkbox]').entwine({
		getLabel: function() {
			return this.closest('form').find('label[for='+this.attr('id')+']');
		}
	})

	$('.field.display-logic.display-logic-display').entwine({
		testLogic: function() {
			this.toggle(this.parseLogic());
		}
	});

	$('.field.display-logic.display-logic-hide').entwine({
		testLogic: function() {
			this.toggle(!this.parseLogic());
		}
	});

	$('.field.display-logic-master :text, .field.display-logic-master select').entwine({
		onmatch: function() {
			this.closest(".field").notify();
		},

		onchange: function() {
			this.closest(".field").notify();
		}
	});

	$('.field.display-logic-master :checkbox, .field.display-logic-master :radio').entwine({
		onmatch: function() {
			this.closest(".field").notify();
		},

		onclick: function() {
			this.closest(".field").notify();
		}
	});

	$('.field.display-logic-master').entwine({
		Listeners: null,

		notify: function() {
			$.each(this.getListeners(), function() {
				$(this).testLogic();
			});
		},

		getListeners: function() {
			if(l = this._super()) {
				return l;
			}
			var self = this;
			var listeners = [];
			this.closest("form").find('.display-logic').each(function() {
				masters = $(this).getMasters();
				for(m in  masters) {
					if(masters[m] == self.attr('id')) {
						listeners.push($(this));
						break;
					}
				}
			});
			this.setListeners(listeners);
			return this.getListeners();
		}
	});

	$('.field.display-logic-master.checkboxset').entwine({

	})

	$('.field.display-logic *').entwine({
		getHolder: function() {
			return this.closest('.display-logic');
		}
	});

//})
})(jQuery);<commit_msg>allow hidden inputs<commit_after>(function($) {
//$.entwine('ss', function($) {

	$('.field').entwine({

		getFormField: function() {
			return this.find('[name='+this.getFieldName()+']');
		},

		getFieldName: function() {
			return this.attr('id');
		},

		getFieldValue: function() {
			return this.getFormField().val();
		},

		evaluateEqualTo: function(val) {
			return this.getFieldValue() === val;
		},

		evaluateNotEqualTo: function(val) {
			return this.getFieldValue() !== val;
		},

		evaluateLessThan: function(val) {
			num = parseFloat(val);
			return this.getFieldValue() < num;
		},

		evaluateGreaterThan: function(val) {
			num = parseFloat(val);
			return parseFloat(this.getFieldValue()) > num;
		},

		evaluateLessThan: function(val) {
			num = parseFloat(val);
			return parseFloat(this.getFieldValue()) < num;
		},

		evaluateContains: function(val) {
			return this.getFieldValue().match(val) !== null;
		},

		evaluateStartsWith: function(val) {
			return this.getFieldValue().match(new RegExp('^'+val)) !== null;
		},

		evaluateEndsWith: function(val) {
			return this.getFieldValue().match(new RegExp(val+'$')) !== null;
		},

		evaluateEmpty: function() {
			return $.trim(this.getFieldValue()).length === 0;
		},

		evaluateNotEmpty: function() {
			return !this.evaluateEmpty();
		},

		evaluateBetween: function(minmax) {
			v = parseFloat(this.getFieldValue());
			parts = minmax.split("-");
			if(parts.length === 2) {
				return v > parseFloat(parts[0]) && v < parseFloat(parts[1]);
			}
			return false;
		},

		evaluateChecked: function() {
			return this.getFormField().is(":checked");
		}

	});

	$('.field.display-logic').entwine({
		onmatch: function () {
			masters = this.getMasters();
			for(m in masters) {
				this.closest('form').find('#'+masters[m]).addClass("display-logic-master");
			}
		},

		getLogic: function() {
			return $.trim(this.find('.display-logic-eval').text());
		},

		parseLogic: function() {
			js = this.getLogic();
			result = eval(js);
			return result;
		},

		getMasters: function() {
			return this.data('display-logic-masters').split(",");
		}

	});

	$('.field.optionset').entwine({

		getFormField: function() {
			f = this._super().filter(":checked");
			return f;
		}

	});

	$('.field.optionset.checkboxset').entwine({

		evaluateHasCheckedOption: function(val) {
			this.find(':checkbox').filter(':checked').each(function() {
				return $(this).val() === val || $(this).getLabel() === val;
			})
		},

		evaluateHasCheckedAtLeast: function(num) {
			return this.find(':checked').length >= num;
		},

		evaluateHasCheckedLessThan: function(num) {
			return this.find(':checked').length <= num;
		}
	});

	$('.field input[type=checkbox]').entwine({
		getLabel: function() {
			return this.closest('form').find('label[for='+this.attr('id')+']');
		}
	})

	$('.field.display-logic.display-logic-display').entwine({
		testLogic: function() {
			this.toggle(this.parseLogic());
		}
	});

	$('.field.display-logic.display-logic-hide').entwine({
		testLogic: function() {
			this.toggle(!this.parseLogic());
		}
	});

	$('.field.display-logic-master :text, .field.display-logic-master :hidden, .field.display-logic-master select').entwine({
		onmatch: function() {
			this.closest(".field").notify();
		},

		onchange: function() {
			this.closest(".field").notify();
		}
	});

	$('.field.display-logic-master :checkbox, .field.display-logic-master :radio').entwine({
		onmatch: function() {
			this.closest(".field").notify();
		},

		onclick: function() {
			this.closest(".field").notify();
		}
	});

	$('.field.display-logic-master').entwine({
		Listeners: null,

		notify: function() {
			$.each(this.getListeners(), function() {
				$(this).testLogic();
			});
		},

		getListeners: function() {
			if(l = this._super()) {
				return l;
			}
			var self = this;
			var listeners = [];
			this.closest("form").find('.display-logic').each(function() {
				masters = $(this).getMasters();
				for(m in  masters) {
					if(masters[m] == self.attr('id')) {
						listeners.push($(this));
						break;
					}
				}
			});
			this.setListeners(listeners);
			return this.getListeners();
		}
	});

	$('.field.display-logic-master.checkboxset').entwine({

	})

	$('.field.display-logic *').entwine({
		getHolder: function() {
			return this.closest('.display-logic');
		}
	});

//})
})(jQuery);<|endoftext|>


<commit_before>require('dotenv').config({ silent: true });

process.env.BROWSERSLIST_CONFIG = 'browserslist';

const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const packageJSON = require('../package.json');

const rootPath = process.cwd();
const envVariables = process.env;

const webpackConfig = {
entry: [
    'whatwg-fetch',
    path.join(rootPath, 'app/src/util/assignPolyfill.js'),
    path.join(rootPath, 'app/src/index.jsx')
  ],

  output: {
    path: path.join(rootPath, 'dist/'),
    filename: '[name]-[hash].js',
    publicPath: envVariables.PUBLIC_PATH,
  },

  plugins: [
    new ExtractTextPlugin('styles.css', {
      allChunks: true
    }),
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      inject: 'body',
      filename: 'index.html',
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      PUBLIC_PATH: JSON.stringify(envVariables.PUBLIC_PATH || ''),
      GOOGLE_API_KEY: JSON.stringify(envVariables.GOOGLE_API_KEY),
      ENVIRONMENT: JSON.stringify(envVariables.NODE_ENV || 'development'),
      VERSION: JSON.stringify(packageJSON.version),
      MAP_URL: JSON.stringify(envVariables.MAP_URL),
      V2_API_ENDPOINT: JSON.stringify(envVariables.V2_API_ENDPOINT),
      BLOG_URL: JSON.stringify(envVariables.BLOG_URL),
      SITE_URL: JSON.stringify(envVariables.SITE_URL),
      REQUIRE_MAP_LOGIN: envVariables.REQUIRE_MAP_LOGIN,
      DEFAULT_WORKSPACE: JSON.stringify(envVariables.DEFAULT_WORKSPACE),
      LOCAL_WORKSPACE: JSON.stringify(envVariables.LOCAL_WORKSPACE),
      GA_TRACKING_CODE: JSON.stringify(envVariables.GA_TRACKING_CODE),
      DISABLE_WELCOME_MODAL: envVariables.DISABLE_WELCOME_MODAL === 'true',
      WELCOME_MODAL_COOKIE_KEY: JSON.stringify(envVariables.WELCOME_MODAL_COOKIE_KEY),
      COMPLETE_MAP_RENDER: envVariables.COMPLETE_MAP_RENDER === 'true',
      TIMEBAR_DATA_URL: JSON.stringify(envVariables.TIMEBAR_DATA_URL),
      SHARE_BASE_URL: JSON.stringify(envVariables.SHARE_BASE_URL),
      SHOW_BANNER: envVariables.SHOW_BANNER === 'true'
    })
  ],

  resolve: {
    root: `${process.cwd()}/app`,
    alias: {
      assets: 'assets',
      actions: 'src/actions',
      components: 'src/components',
      constants: 'src/constants.js',
      containers: 'src/containers',
      lib: 'src/lib',
      middleware: 'src/middleware',
      reducers: 'src/reducers',
      styles: 'styles',
      util: 'src/util'
    },
    extensions: ['', '.js', '.jsx']
  },

  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel'
      },
      {
        test: /\.(jpe?g|png|gif|svg|ico)$/i,
        loaders: [
          'file?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack'
        ]
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!resolve-url!postcss-loader!sass?sourceMap')
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader!postcss-loader'
      },
      {
        test: /manifest.json$/,
        loader: 'file?hash=sha512&digest=hex&name=[hash].[ext]'
      },
      {
        test: /\.json$/,
        exclude: /manifest.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.html$/,
        loader: 'html?interpolate',
      }
    ]
  },

  imageWebpackLoader: {
    optimizationLevel: (envVariables.NODE_ENV === 'development' ? 0 : 7),
    bypassOnDebug: true,
    interlaced: false
  },
  postcss() {
    return [autoprefixer];
  }
};

// Environment configuration
if (envVariables.NODE_ENV === 'production') {
  webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false,
      dead_code: true,
      drop_debugger: true,
      drop_console: true
    },
    comments: false
  }));
  webpackConfig.devtool = 'source-map';
} else {
  webpackConfig.devtool = 'eval-source-map';
}

module.exports = webpackConfig;
<commit_msg>Fixes broken indentation<commit_after>require('dotenv').config({ silent: true });

process.env.BROWSERSLIST_CONFIG = 'browserslist';

const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const packageJSON = require('../package.json');

const rootPath = process.cwd();
const envVariables = process.env;

const webpackConfig = {
  entry: [
    'whatwg-fetch',
    path.join(rootPath, 'app/src/util/assignPolyfill.js'),
    path.join(rootPath, 'app/src/index.jsx')
  ],

  output: {
    path: path.join(rootPath, 'dist/'),
    filename: '[name]-[hash].js',
    publicPath: envVariables.PUBLIC_PATH,
  },

  plugins: [
    new ExtractTextPlugin('styles.css', {
      allChunks: true
    }),
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      inject: 'body',
      filename: 'index.html',
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      PUBLIC_PATH: JSON.stringify(envVariables.PUBLIC_PATH || ''),
      GOOGLE_API_KEY: JSON.stringify(envVariables.GOOGLE_API_KEY),
      ENVIRONMENT: JSON.stringify(envVariables.NODE_ENV || 'development'),
      VERSION: JSON.stringify(packageJSON.version),
      MAP_URL: JSON.stringify(envVariables.MAP_URL),
      V2_API_ENDPOINT: JSON.stringify(envVariables.V2_API_ENDPOINT),
      BLOG_URL: JSON.stringify(envVariables.BLOG_URL),
      SITE_URL: JSON.stringify(envVariables.SITE_URL),
      REQUIRE_MAP_LOGIN: envVariables.REQUIRE_MAP_LOGIN,
      DEFAULT_WORKSPACE: JSON.stringify(envVariables.DEFAULT_WORKSPACE),
      LOCAL_WORKSPACE: JSON.stringify(envVariables.LOCAL_WORKSPACE),
      GA_TRACKING_CODE: JSON.stringify(envVariables.GA_TRACKING_CODE),
      DISABLE_WELCOME_MODAL: envVariables.DISABLE_WELCOME_MODAL === 'true',
      WELCOME_MODAL_COOKIE_KEY: JSON.stringify(envVariables.WELCOME_MODAL_COOKIE_KEY),
      COMPLETE_MAP_RENDER: envVariables.COMPLETE_MAP_RENDER === 'true',
      TIMEBAR_DATA_URL: JSON.stringify(envVariables.TIMEBAR_DATA_URL),
      SHARE_BASE_URL: JSON.stringify(envVariables.SHARE_BASE_URL),
      SHOW_BANNER: envVariables.SHOW_BANNER === 'true'
    })
  ],

  resolve: {
    root: `${process.cwd()}/app`,
    alias: {
      assets: 'assets',
      actions: 'src/actions',
      components: 'src/components',
      constants: 'src/constants.js',
      containers: 'src/containers',
      lib: 'src/lib',
      middleware: 'src/middleware',
      reducers: 'src/reducers',
      styles: 'styles',
      util: 'src/util'
    },
    extensions: ['', '.js', '.jsx']
  },

  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel'
      },
      {
        test: /\.(jpe?g|png|gif|svg|ico)$/i,
        loaders: [
          'file?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack'
        ]
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!resolve-url!postcss-loader!sass?sourceMap')
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader!postcss-loader'
      },
      {
        test: /manifest.json$/,
        loader: 'file?hash=sha512&digest=hex&name=[hash].[ext]'
      },
      {
        test: /\.json$/,
        exclude: /manifest.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.html$/,
        loader: 'html?interpolate',
      }
    ]
  },

  imageWebpackLoader: {
    optimizationLevel: (envVariables.NODE_ENV === 'development' ? 0 : 7),
    bypassOnDebug: true,
    interlaced: false
  },
  postcss() {
    return [autoprefixer];
  }
};

// Environment configuration
if (envVariables.NODE_ENV === 'production') {
  webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false,
      dead_code: true,
      drop_debugger: true,
      drop_console: true
    },
    comments: false
  }));
  webpackConfig.devtool = 'source-map';
} else {
  webpackConfig.devtool = 'eval-source-map';
}

module.exports = webpackConfig;
<|endoftext|>


<commit_before>// Chunked File library
describe("library2", function() {
	var tickExtra, tickEmpty, tickMerged;
	var extraValue, testValue;

	before(function(done) {
		var asnycOk = false, asnycOk2 = false;
		var sameTick1 = true;
		require.ensure(["./extra"], function(require) {
			asnycOk = true;
			tickExtra = sameTick1;
			var sameTick2 = true;
			require.ensure([], function(require) {
				asnycOk2 = true;
				extraValue = require("./extra");
				tickEmpty = sameTick2;
				require.ensure(["./test.js"], function(require) {
					tickMerged = sameTick2;
					testValue = require("./test.js");
					done();
				});
			});
			sameTick2 = false;
		});
		sameTick1 = false;
	});

	it("should load stuff with require.ensure asynchron", function() {
		should.exist(tickExtra);
		tickExtra.should.be.eql(false);
	});

	it("should load not include stuff from parent, remove empty chunks and apply a post loader", function() {
		should.exist(tickEmpty);
		tickEmpty.should.be.eql(true);
		extraValue.should.be.eql("Lib2 extra2 with post loader");
	});

	it("should merge chunks if maxChunks specified", function() {
		should.exist(tickEmpty);
		tickEmpty.should.be.eql(true);
		testValue.should.be.eql("test module");
	});

	it("should load require.amd from options", function() {
		require.amd.should.have.property("fromOptions").be.eql(true);
	});

	it("should run empty AMD require", function() {
		var emptyRequire = false;
		require([], function() {
			emptyRequire = true;
		});
		emptyRequire.should.be.eql(true);
	});

	it("should provide free variables", function() {
		s3().should.be.eql("submodule3");
	});

	it("should define values", function() {
		CONST_UNDEFINED.should.be.eql(undefined);
		CONST_NULL.should.be.eql(null);
		CONST_TRUE.should.be.eql(true);
		CONST_FALSE.should.be.eql(false);
		CONST_FUNCTION().should.be.eql("ok");
		CONST_NUMBER.should.be.eql(123);
		CONST_NUMBER_EXPR.should.be.eql(123);

		var o = CONST_OBJECT;
		CONST_OBJECT.A.should.be.eql(1);
		o.A.should.be.eql(1);
		CONST_OBJECT.B.should.be.eql("B");
		o.B.should.be.eql("B");
		CONST_OBJECT.C().should.be.eql("C");
		o.C().should.be.eql("C");

		if(CONST_FALSE) require("fail");
		if(!CONST_TRUE) require("fail");
		if(!CONST_NUMBER) require("fail");
		if(!CONST_NUMBER_EXPR) require("fail");
		if(typeof CONST_FALSE !== "boolean") require("fail");
		if(typeof CONST_FUNCTION !== "function") require("fail");
		if(typeof CONST_OBJECT !== "object") require("fail");
		if(!CONST_OBJECT.A) require("fail");
		if(typeof CONST_OBJECT.A !== "number") require("fail");
	});
});
exports.ok = true;

// it should not fail if comment in last line<commit_msg>fixed wrong tests<commit_after>// Chunked File library
describe("library2", function() {
	var tickExtra, tickEmpty, tickMerged;
	var extraValue, testValue;

	before(function(done) {
		var asnycOk = false, asnycOk2 = false;
		var sameTick1 = true;
		require.ensure(["./extra"], function(require) {
			asnycOk = true;
			tickExtra = sameTick1;
			var sameTick2 = true;
			require.ensure([], function(require) {
				asnycOk2 = true;
				extraValue = require("./extra");
				tickEmpty = sameTick2;
				require.ensure(["./test.js"], function(require) {
					tickMerged = sameTick2;
					testValue = require("./test.js");
					done();
				});
			});
			sameTick2 = false;
		});
		sameTick1 = false;
	});

	it("should load stuff with require.ensure asynchron", function() {
		should.exist(tickExtra);
		tickExtra.should.be.eql(false);
	});

	it("should load not include stuff from parent, remove empty chunks and apply a post loader", function() {
		should.exist(tickEmpty);
		tickEmpty.should.be.eql(true);
		extraValue.should.be.eql("Lib2 extra2 with post loader");
	});

	it("should merge chunks if maxChunks specified", function() {
		should.exist(tickEmpty);
		tickEmpty.should.be.eql(true);
		testValue.should.be.eql("test module");
	});

	it("should load require.amd from options", function() {
		require.amd.should.have.property("fromOptions").be.eql(true);
	});

	it("should run empty AMD require", function() {
		var emptyRequire = false;
		require([], function() {
			emptyRequire = true;
		});
		emptyRequire.should.be.eql(true);
	});

	it("should provide free variables", function() {
		s3().should.be.eql("submodule3");
	});

	it("should define values", function() {
		(CONST_UNDEFINED === undefined).should.be.eql(true);
		(CONST_NULL === null).should.be.eql(true);
		CONST_TRUE.should.be.eql(true);
		CONST_FALSE.should.be.eql(false);
		CONST_FUNCTION().should.be.eql("ok");
		CONST_NUMBER.should.be.eql(123);
		CONST_NUMBER_EXPR.should.be.eql(123);

		var o = CONST_OBJECT;
		CONST_OBJECT.A.should.be.eql(1);
		o.A.should.be.eql(1);
		CONST_OBJECT.B.should.be.eql("B");
		o.B.should.be.eql("B");
		CONST_OBJECT.C().should.be.eql("C");
		o.C().should.be.eql("C");

		if(CONST_FALSE) require("fail");
		if(!CONST_TRUE) require("fail");
		if(!CONST_NUMBER) require("fail");
		if(!CONST_NUMBER_EXPR) require("fail");
		if(typeof CONST_FALSE !== "boolean") require("fail");
		if(typeof CONST_FUNCTION !== "function") require("fail");
		if(typeof CONST_OBJECT !== "object") require("fail");
		if(!CONST_OBJECT.A) require("fail");
		if(typeof CONST_OBJECT.A !== "number") require("fail");
	});
});
exports.ok = true;

// it should not fail if comment in last line<|endoftext|>


<commit_before>var fs = require('fs');

var db = require('../db/content-provider');
var timelineUtils = require('../utils/timeline-utils');

var generateTimelineCommits = function(outputFilename) {
    db.loadDatabase({}, function() {
        var commits = db.getCollection('commits');
        var githubCommits = timelineUtils.getCommitsPerDay(commits, 'github');
        var bitbucketCommits = timelineUtils.getCommitsPerDay(commits, 'bitbucket');
        var allCommits = githubCommits.concat(bitbucketCommits);

        var sortedCommitsByDate = allCommits.sort(function(first, second) {
            return new Date(first.date) - new Date(second.date);
        });

        var jsonData = sortedCommitsByDate.reduce(function(acc, item) {
            var currentDate = item.date;
            if (acc[currentDate] != null) {
                acc[currentDate] += item.num_commits;
            } else {
                acc[currentDate] = item.num_commits;
            }

            return acc;
        }, {});

        fs.writeFileSync(outputFilename, JSON.stringify(jsonData));
    });
}

module.exports = {
    generateTimelineCommits: generateTimelineCommits
};
<commit_msg>remove spacing<commit_after>var fs = require('fs');
var db = require('../db/content-provider');
var timelineUtils = require('../utils/timeline-utils');

var generateTimelineCommits = function(outputFilename) {
    db.loadDatabase({}, function() {
        var commits = db.getCollection('commits');
        var githubCommits = timelineUtils.getCommitsPerDay(commits, 'github');
        var bitbucketCommits = timelineUtils.getCommitsPerDay(commits, 'bitbucket');
        var allCommits = githubCommits.concat(bitbucketCommits);

        var sortedCommitsByDate = allCommits.sort(function(first, second) {
            return new Date(first.date) - new Date(second.date);
        });

        var jsonData = sortedCommitsByDate.reduce(function(acc, item) {
            var currentDate = item.date;
            if (acc[currentDate] != null) {
                acc[currentDate] += item.num_commits;
            } else {
                acc[currentDate] = item.num_commits;
            }

            return acc;
        }, {});

        fs.writeFileSync(outputFilename, JSON.stringify(jsonData));
    });
}

module.exports = {
    generateTimelineCommits: generateTimelineCommits
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Pavel Aksonov
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
import React, {Component, Animated, PropTypes, StyleSheet, ScrollView, View, Text, NavigationExperimental} from "react-native";
const {
    AnimatedView: NavigationAnimatedView,
    Card: NavigationCard,
    RootContainer: NavigationRootContainer,
    Header: NavigationHeader,
    } = NavigationExperimental;
import Actions from "./Actions";
import getInitialState from "./State";
import Reducer from "./Reducer";
import TabBar from "./TabBar";
import NavBar from "./NavBar";

export default class DefaultRenderer extends Component {
    constructor(props) {
        super(props);
        this._renderCard = this._renderCard.bind(this);
        this._renderScene = this._renderScene.bind(this);
        this._renderHeader = this._renderHeader.bind(this);
    }

    getChildContext() {
        return {
            navigationState: this.props.navigationState,
        };
    }

    render() {
        const navigationState = this.props.navigationState;
        if (!navigationState) {
            return null;
        }
        let Component = navigationState.component;
        if (navigationState.tabs && !Component){
            Component = TabBar;
        }
        if (Component) {
            return (
                <View style={[{flex: 1}, navigationState.sceneStyle]}>
                    <Component {...navigationState} navigationState={navigationState} />
                </View>
            )
        }

        const selected = navigationState.children[navigationState.index];
        //return <DefaultRenderer key={selected.key} navigationState={selected}/>

        let applyAnimation = selected.applyAnimation || navigationState.applyAnimation;
        let style = selected.style || navigationState.style;
        let direction = selected.direction || navigationState.direction || "horizontal";

        let optionals = {};
        if (applyAnimation) {
            optionals.applyAnimation = applyAnimation;
        } else {
            let duration = selected.duration;
            if (duration === null || duration === undefined) duration = navigationState.duration;
            if (duration !== null && duration !== undefined) {
                optionals.applyAnimation = function (pos, navState) {
                    Animated.timing(pos, {toValue: navState.index, duration}).start();
                };
            }
        }

        return (
            <NavigationAnimatedView
                navigationState={navigationState}
                style={[styles.animatedView, style]}
                renderOverlay={this._renderHeader}
                direction={direction}
                renderScene={this._renderCard}
                {...optionals}
            />
        );
    }

    _renderHeader(/*NavigationSceneRendererProps*/ props) {
        return <NavBar
                {...props}
                getTitle={state => state.title}
            />;
    }

    _renderCard(/*NavigationSceneRendererProps*/ props) {
        const { key, direction, panHandlers, getSceneStyle } = props.scene.navigationState;
        const style = getSceneStyle ? getSceneStyle(props) : null;
        return (
            <NavigationCard
                {...props}
                key={'card_' + key}
                direction={direction || 'horizontal'}
                panHandlers={panHandlers}
                renderScene={this._renderScene}
                style={style}
            />
        );
    }

    _renderScene(/*NavigationSceneRendererProps*/ props) {
        return <DefaultRenderer key={props.scene.navigationState.key} navigationState={props.scene.navigationState}/>
    }

}

DefaultRenderer.childContextTypes = {
    navigationState: PropTypes.any,
};

const styles = StyleSheet.create({
    animatedView: {
        flex: 1,
        backgroundColor:"transparent"
    },
});

<commit_msg>Bug fix: childContextTypes not defined when DefaultRenderer is exported<commit_after>/**
 * Copyright (c) 2015-present, Pavel Aksonov
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */
import React, {Component, Animated, PropTypes, StyleSheet, ScrollView, View, Text, NavigationExperimental} from "react-native";
const {
    AnimatedView: NavigationAnimatedView,
    Card: NavigationCard,
    RootContainer: NavigationRootContainer,
    Header: NavigationHeader,
    } = NavigationExperimental;
import Actions from "./Actions";
import getInitialState from "./State";
import Reducer from "./Reducer";
import TabBar from "./TabBar";
import NavBar from "./NavBar";

export default class DefaultRenderer extends Component {
    constructor(props) {
        super(props);
        this._renderCard = this._renderCard.bind(this);
        this._renderScene = this._renderScene.bind(this);
        this._renderHeader = this._renderHeader.bind(this);
    }

    static childContextTypes = {
        navigationState: PropTypes.any,
    };

    getChildContext() {
        return {
            navigationState: this.props.navigationState,
        };
    }

    render() {
        const navigationState = this.props.navigationState;
        if (!navigationState) {
            return null;
        }
        let Component = navigationState.component;
        if (navigationState.tabs && !Component){
            Component = TabBar;
        }
        if (Component) {
            return (
                <View style={[{flex: 1}, navigationState.sceneStyle]}>
                    <Component {...navigationState} navigationState={navigationState} />
                </View>
            )
        }

        const selected = navigationState.children[navigationState.index];
        //return <DefaultRenderer key={selected.key} navigationState={selected}/>

        let applyAnimation = selected.applyAnimation || navigationState.applyAnimation;
        let style = selected.style || navigationState.style;
        let direction = selected.direction || navigationState.direction || "horizontal";

        let optionals = {};
        if (applyAnimation) {
            optionals.applyAnimation = applyAnimation;
        } else {
            let duration = selected.duration;
            if (duration === null || duration === undefined) duration = navigationState.duration;
            if (duration !== null && duration !== undefined) {
                optionals.applyAnimation = function (pos, navState) {
                    Animated.timing(pos, {toValue: navState.index, duration}).start();
                };
            }
        }

        return (
            <NavigationAnimatedView
                navigationState={navigationState}
                style={[styles.animatedView, style]}
                renderOverlay={this._renderHeader}
                direction={direction}
                renderScene={this._renderCard}
                {...optionals}
            />
        );
    }

    _renderHeader(/*NavigationSceneRendererProps*/ props) {
        return <NavBar
                {...props}
                getTitle={state => state.title}
            />;
    }

    _renderCard(/*NavigationSceneRendererProps*/ props) {
        const { key, direction, panHandlers, getSceneStyle } = props.scene.navigationState;
        const style = getSceneStyle ? getSceneStyle(props) : null;
        return (
            <NavigationCard
                {...props}
                key={'card_' + key}
                direction={direction || 'horizontal'}
                panHandlers={panHandlers}
                renderScene={this._renderScene}
                style={style}
            />
        );
    }

    _renderScene(/*NavigationSceneRendererProps*/ props) {
        return <DefaultRenderer key={props.scene.navigationState.key} navigationState={props.scene.navigationState}/>
    }

}

const styles = StyleSheet.create({
    animatedView: {
        flex: 1,
        backgroundColor:"transparent"
    },
});
<|endoftext|>


<commit_before>const fixtures = require('../../fixtures')
const selectors = require('../../../../selectors')
const userActions = require('../../support/user-actions')

const { contacts } = require('../../../../../src/lib/urls')

describe('Contacts', () => {
  const data = {
    name: 'NewAddress',
    lastName: 'Contact',
    jobTitle: 'Coffee machine operator',
    countryCode: '44',
    phone: '0778877778800',
    email: 'company.contact@dit.com',
    address1: 'Rua Candido Portinari',
    address2: 'Numero 521',
    city: 'Campinas',
    country: 'Brazil',
  }

  it.skip('should create a primary contact with a different address to the companies address', () => {
    const company = fixtures.company.create.defaultCompany('contact testing')
    cy.loadFixture([company])

    cy.visit(contacts.create(company.pk))
    userActions.contacts.createWithNewAddress(data)

    cy.get(selectors.contactCreate.details)
      .should('contain', 'Coffee machine operator')
      .and('contain', '(44) 0778877778800')
      .and('contain', 'company.contact@dit.com')
      .and('contain', 'Rua Candido Portinari, Numero 521, Campinas, Brazil')
  })

  it.skip('Should show a warning message when adding contact with duplicate email', () => {
    const EMAIL = 'andy.pipkin@andyandlou.co.uk'
    const company = fixtures.company.create.defaultCompany('contact testing')
    cy.loadFixture([company])
    cy.visit(contacts.create(company.pk))

    cy.checkRadioGroup(
      'Is the contact’s address the same as the company address?',
      'Yes'
    )
    cy.checkRadioGroup('Is this person a primary contact?', 'Yes')
    cy.typeIntoInputs({
      'First name': 'Andy',
      'Last name': 'Pipkin',
      'Job title': 'On dole',
      'Telephone country code': '1234',
      'Telephone number': '56789',
      Email: EMAIL,
    })

    cy.clickSubmitButton('Add contact')
    cy.contains('You have successfully added a new contact Andy Pipkin')

    cy.visit(contacts.create(company.pk))

    cy.checkRadioGroup(
      'Is the contact’s address the same as the company address?',
      'Yes'
    )
    cy.checkRadioGroup('Is this person a primary contact?', 'Yes')
    cy.typeIntoInputs({
      'First name': 'Lou',
      'Last name': 'Todd',
      'Job title': 'Carer',
      'Telephone country code': '4567',
      'Telephone number': '987654321',
      Email: EMAIL,
    })

    cy.clickSubmitButton('Add contact')

    cy.contains('You have successfully added a new contact').should('not.exist')
    cy.contains(
      `The email ${EMAIL} already exists at contact testing. ` +
        "To continue adding this contact select 'Add contact'. " +
        "To return to the previous screen, select 'Cancel'."
    )

    cy.clickSubmitButton('Add contact')
    cy.contains('You have successfully added a new contact Lou Todd')
  })
})
<commit_msg>Randomise contact email<commit_after>const fixtures = require('../../fixtures')
const selectors = require('../../../../selectors')
const userActions = require('../../support/user-actions')

const { contacts } = require('../../../../../src/lib/urls')

describe('Contacts', () => {
  const CONTACT_EMAIL = `${Math.random().toString(36).substring(2, 15)}@dit.com`

  const data = {
    name: 'NewAddress',
    lastName: 'Contact',
    jobTitle: 'Coffee machine operator',
    countryCode: '44',
    phone: '0778877778800',
    email: CONTACT_EMAIL,
    address1: 'Rua Candido Portinari',
    address2: 'Numero 521',
    city: 'Campinas',
    country: 'Brazil',
  }

  it('should create a primary contact with a different address to the companies address', () => {
    const company = fixtures.company.create.defaultCompany('contact testing')
    cy.loadFixture([company])

    cy.visit(contacts.create(company.pk))
    userActions.contacts.createWithNewAddress(data)

    cy.get(selectors.contactCreate.details)
      .should('contain', 'Coffee machine operator')
      .and('contain', '(44) 0778877778800')
      .and('contain', CONTACT_EMAIL)
      .and('contain', 'Rua Candido Portinari, Numero 521, Campinas, Brazil')
  })

  it('Should show a warning message when adding contact with duplicate email', () => {
    const EMAIL = 'andy.pipkin@andyandlou.co.uk'
    const company = fixtures.company.create.defaultCompany('contact testing')
    cy.loadFixture([company])
    cy.visit(contacts.create(company.pk))

    cy.checkRadioGroup(
      'Is the contact’s address the same as the company address?',
      'Yes'
    )
    cy.checkRadioGroup('Is this person a primary contact?', 'Yes')
    cy.typeIntoInputs({
      'First name': 'Andy',
      'Last name': 'Pipkin',
      'Job title': 'On dole',
      'Telephone country code': '1234',
      'Telephone number': '56789',
      Email: EMAIL,
    })

    cy.clickSubmitButton('Add contact')
    cy.contains('You have successfully added a new contact Andy Pipkin')

    cy.visit(contacts.create(company.pk))

    cy.checkRadioGroup(
      'Is the contact’s address the same as the company address?',
      'Yes'
    )
    cy.checkRadioGroup('Is this person a primary contact?', 'Yes')
    cy.typeIntoInputs({
      'First name': 'Lou',
      'Last name': 'Todd',
      'Job title': 'Carer',
      'Telephone country code': '4567',
      'Telephone number': '987654321',
      Email: EMAIL,
    })

    cy.clickSubmitButton('Add contact')

    cy.contains('You have successfully added a new contact').should('not.exist')
    cy.contains(
      `The email ${EMAIL} already exists at contact testing. ` +
        "To continue adding this contact select 'Add contact'. " +
        "To return to the previous screen, select 'Cancel'."
    )

    cy.clickSubmitButton('Add contact')
    cy.contains('You have successfully added a new contact Lou Todd')
  })
})
<|endoftext|>


<commit_before>'use strict';

module.exports = function () {
    this.World = require('../support/world.js').World;

    this.Given(/^я нахожусь на экране "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.Then(/^система отобразит экран "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.Then(/^система отобразит модальное окно "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.ModalView.header(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.When(/^я закрою текущее модальное окно$/, function () {
        var selector = this.selectors.XPATH.ModalView.closeButton();
        var xpath = this.by.xpath(selector);
        var that = this;

        return this.driver.findElements(xpath)
            .then(function (elements) {
                var lastModalViewCloseButton = that._.last(elements);
                return lastModalViewCloseButton.click();
            });
    });

    this.Then(/^система отобразит окно-сообщение "([^"]*)"$/, function (message) {
        var selector = this.selectors.XPATH.ModalView.message();
        var xpath = this.by.xpath(selector);
        var that = this;

        message = message.replace(/''/g, '"');

        // TODO: Выполнять без setTimeout
        return this.driver.findElement(xpath).then(function (messageBox) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    messageBox.getText().then(function (text) {
                        text = that.helpers.ignoreNumbers(text.trim(), message);
                        try {
                            that.assert.equal(text, message);
                            resolve();
                        } catch (err) {
                            reject(err);
                        }
                    });
                }, 500);
            });
        });
    });

    this.When(/^я нажму в окне-сообщении на кнопку "([^"]*)"$/, function (buttonText) {
        var selector = this.selectors.XPATH.ModalView.messageBoxButton(buttonText);
        var xpath = this.by.xpath(selector);

        return this.driver.findElement(xpath)
            .then(function (button) {
                button.click();
                return new Promise(function (resolve) {
                    setTimeout(resolve, 1000);
                });
            });
    });
};<commit_msg>fix text format (integration tests)<commit_after>'use strict';

module.exports = function () {
    this.World = require('../support/world.js').World;

    this.Given(/^я нахожусь на экране "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.Then(/^система отобразит экран "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.Then(/^система отобразит модальное окно "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.ModalView.header(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.When(/^я закрою текущее модальное окно$/, function () {
        var selector = this.selectors.XPATH.ModalView.closeButton();
        var xpath = this.by.xpath(selector);
        var that = this;

        return this.driver.findElements(xpath)
            .then(function (elements) {
                var lastModalViewCloseButton = that._.last(elements);
                return lastModalViewCloseButton.click();
            });
    });

    this.Then(/^система отобразит окно-сообщение "([^"]*)"$/, function (message) {
        var selector = this.selectors.XPATH.ModalView.message();
        var xpath = this.by.xpath(selector);
        var that = this;

        message = message.replace(/''/g, '"');

        // TODO: Выполнять без setTimeout
        return this.driver.findElement(xpath).then(function (messageBox) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    messageBox.getText().then(function (text) {
                        message = that.helpers.ignoreNumbers(text.trim(), message);
                        try {
                            that.assert.equal(text, message);
                            resolve();
                        } catch (err) {
                            reject(err);
                        }
                    });
                }, 500);
            });
        });
    });

    this.When(/^я нажму в окне-сообщении на кнопку "([^"]*)"$/, function (buttonText) {
        var selector = this.selectors.XPATH.ModalView.messageBoxButton(buttonText);
        var xpath = this.by.xpath(selector);

        return this.driver.findElement(xpath)
            .then(function (button) {
                button.click();
                return new Promise(function (resolve) {
                    setTimeout(resolve, 1000);
                });
            });
    });
};<|endoftext|>


<commit_before>Contacts.Index = new Class({
	toString: 'Index',
	extend: F.Component,

	construct: function(options) {
		// Overwrite defaults directly into options
		_.extend(options, {
			template: this.Template,
			component: this
		});

		/*
		Since we use this as an event listener, don't forget to bind it, rascala!
		Also, since we're going to use handleSearch as a keyup listener, make sure
		it doesn't fire constantly by throttling it
		*/
		this.handleSearch = _.throttle(this.handleSearch.bind(this), 100);

		// Create a view for our search/list display
		this.view = new this.View(options).render();

		/*
			Item list
			This component will display the list of items
		*/
		this.addComponent(new this.ListComponent({
			el: this.view.$('.list'),
			Collection: this.Collection,
			visible: true
		}), 'list');

		// Hide the search field when the list is done rendering the first time only
		this.list.view.on('renderComplete', _.once(this.hideSearch.bind(this)));

		// Bubble the itemSelected event of our list upward
		this.bubble('list', 'itemSelected');
	},

	// Our template and view should go in the prototype so they can be overridden
	Template: Contacts.Templates.Index,

	View: F.View.extend({
		events: {
			'submit .search': 'handleSearch',		// Search when the user hits enter
			'keyup .searchField': 'handleSearch',	// Filter as the user types
			'click .clearButton': 'clearSearch',	// Clear the search when X is clicked
			'click .new': 'newContact'				// Create a new contact when + is clicked
		}
	}),

	// Put the component we'll use in our prototype so it can be overridden
	ListComponent: Contacts.List,

	newContact: function() {
		// Tell our parent to switch to the contact editor component with a blank contact
		this.trigger('newContact');
	},

	show: function() {
		var wasVisible = this.visible;

		this.inherited(arguments);

		// Hide the search field on show
		if (!wasVisible)
			this.hideSearch();
	},

	hideSearch: function() {
		// Scroll down so search disappears
		this.view.$('.scrollContainer').animate({
			scrollTop: 16*3
		}, 250);
	},

	search: function(query) {
		// Update the hash
		Contacts.router.navigate('search/'+query, { trigger: false });

		// Set the input field text in case this came from the router
		// Only do this if the value is different to avoid selection issues
		if (this.view.$('input').val() != query)
			this.view.$('input').val(query);

		// Show the clear search button
		this.view.$('.clearButton').show();

		// Send the query to the server
		this.list.load({
			query: query
		});
	},

	clearSearch: function() {
		// Clear the value of the filter field
		this.view.$('input').val('');

		// Clears fetch parameters before fetching
		this.list.load();

		// Remove the clear button
		this.view.$('.clearButton').hide();
	},

	handleSearch: function(evt) {
		// Get the search term from the form
		var query = this.view.$('input').val();

		if (query.length) {
			// NOTE: Search won't find newly added entries or modified entries in this faked API example
			// Perform the fetch on the collection with the query term
			this.search(query);
		}
		else {
			// Clear the search; will fetch collection without params
			this.clearSearch();
		}

		return false;
	}
});
<commit_msg>Fixed show/hide of search field when search loaded from hash<commit_after>Contacts.Index = new Class({
	toString: 'Index',
	extend: F.Component,

	construct: function(options) {
		// Overwrite defaults directly into options
		_.extend(options, {
			template: this.Template,
			component: this
		});

		/*
		Since we use this as an event listener, don't forget to bind it, rascala!
		Also, since we're going to use handleSearch as a keyup listener, make sure
		it doesn't fire constantly by throttling it
		*/
		this.handleSearch = _.throttle(this.handleSearch.bind(this), 100);

		// Create a view for our search/list display
		this.view = new this.View(options).render();

		/*
			Item list
			This component will display the list of items
		*/
		this.addComponent(new this.ListComponent({
			el: this.view.$('.list'),
			Collection: this.Collection,
			visible: true
		}), 'list');

		// Hide the search field when the list is done rendering the first time only, if it's blank
		// It won't be blank if the search was loaded from the hash
		this.list.view.on('renderComplete', _.once(function() {
			if (this.view.$('input').val() == '')
				this.hideSearch();
		}.bind(this)));

		// Hide the search field when we show the view
		this.on('component:shown', function() {
			// Defer this so we give the router a chance to set the input field's value
			_.defer(function() {
				if (this.view.$('input').val() == '')
					this.hideSearch();
			}.bind(this));
		});

		// Bubble the itemSelected event of our list upward
		this.bubble('list', 'itemSelected');
	},

	// Our template and view should go in the prototype so they can be overridden
	Template: Contacts.Templates.Index,

	View: F.View.extend({
		events: {
			'submit .search': 'handleSearch',		// Search when the user hits enter
			'keyup .searchField': 'handleSearch',	// Filter as the user types
			'click .clearButton': 'clearSearch',	// Clear the search when X is clicked
			'click .new': 'newContact'				// Create a new contact when + is clicked
		}
	}),

	// Put the component we'll use in our prototype so it can be overridden
	ListComponent: Contacts.List,

	newContact: function() {
		// Tell our parent to switch to the contact editor component with a blank contact
		this.trigger('newContact');
	},

	hideSearch: function() {
		// Scroll down so search disappears
		this.view.$('.scrollContainer').animate({
			scrollTop: 16*3
		}, 250);
	},

	search: function(query) {
		// Update the hash
		Contacts.router.navigate('search/'+query, { trigger: false });

		// Set the input field text in case this came from the router
		// Only do this if the value is different to avoid selection issues
		if (this.view.$('input').val() != query)
			this.view.$('input').val(query);

		// Show the clear search button
		this.view.$('.clearButton').show();

		// Send the query to the server
		this.list.load({
			query: query
		});
	},

	clearSearch: function() {
		// Clear the value of the filter field
		this.view.$('input').val('');

		// Clear the search from the hash
		Contacts.router.navigate('', { trigger: true });

		// Clears fetch parameters before fetching
		this.list.load();

		// Remove the clear button
		this.view.$('.clearButton').hide();
	},

	handleSearch: function(evt) {
		// Get the search term from the form
		var query = this.view.$('input').val();

		if (query.length) {
			// NOTE: Search won't find newly added entries or modified entries in this faked API example
			// Perform the fetch on the collection with the query term
			this.search(query);
		}
		else {
			// Clear the search; will fetch collection without params
			this.clearSearch();
		}

		return false;
	}
});
<|endoftext|>


<commit_before>/**
 * Created by anonymous on 28/12/15 14:35.
 */

(function() {
    'use strict';

    angular
        .module('jwtAuth')
        .factory('phonesService', phonesService);

    phonesService.$inject = [];

    /* @ngInject */
    function phonesService() {
        var service = {
            phone     : phone(),
            flComplete: flComplete()
        };

        return service;

        ////////////////

        function phone() {
            var ph = {
                ct: {
                    options: {
                        pk          : 'id',
                        refreshBtn  : true,
                        addRecord   : addRecord,
                        actionsCol  : true,
                        editRecord  : editRecord,
                        deleteRecord: deleteRecord,
                        deleteRows  : deleteRows,
                        cols        : [
                            {field: 'age', title: 'ID'},
                            {field: 'name', title: 'Name'},
                            {field: 'snippet', title: 'Description', sortable: false}
                        ],
                        filters     : [
                            {field: 'age', title: 'ID', condition: 'eq'},
                            {field: 'name', title: 'Name', condition: 'like_b', options: {insensitive: true}},
                            {
                                field    : 'snippet',
                                title    : 'Description',
                                condition: 'like_b',
                                options  : {insensitive: true}
                            }
                        ],
                        pagesizes   : [5, 10, 20],
                        debug       : true,
                        displayField: displayField
                    }
                },

                fl: {
                    options: {
                        listURL           : 'desserts.json',
                        method            : 'GET',
                        urlencoded        : true,
                        pagesize          : 5,
                        orderby           : [
                            {field: 'name', type: 'asc'}
                        ],
                        sortOnClient      : true,
                        paginationOnClient: true,
                        searchOnClient    : true
                        // Enable log
                        //,log: {id: 'phonesService', err: true, debug: true}
                    }
                }
            };

            return ph;
        }

        function flComplete($e, $args) {
            angular.forEach(phone().fl.records, function(record) {
                if (record.id === 'dell-venue') {
                    record.readonly = true;
                    return;
                }
            });
        }

        function addRecord() {
            alert('add record');
        }

        function editRecord(record) {
            alert('edit record');
        }

        function deleteRecord(record) {
            alert('delete record');
        }

        function deleteRows(selection) {
            alert(selection.length + ' records selected');
        }

        function displayField(scope, element, attrs) {
            // Add a link on field "name" to each record
            if (attrs['field'] == 'name') {
                if (attrs['value'] == 'Dell Venue') {
                    element.html('' + attrs['value'] + '');
                }
                else {
                    element.html('' + attrs['value'] + '');
                }

                return;
            }

            element.html(attrs['value']);
        }
    }

})();

<commit_msg>Modified phones.service<commit_after>/**
 * Created by anonymous on 28/12/15 14:35.
 */

(function() {
    'use strict';

    angular
        .module('jwtAuth')
        .factory('phonesService', phonesService);

    phonesService.$inject = [];

    /* @ngInject */
    function phonesService() {
        var service = {
            phone     : phone(),
            flComplete: flComplete()
        };

        return service;

        ////////////////

        function phone() {
            var ph = {
                ct: {
                    options: {
                        pk          : 'id',
                        refreshBtn  : true,
                        addRecord   : addRecord,
                        actionsCol  : true,
                        editRecord  : editRecord,
                        deleteRecord: deleteRecord,
                        deleteRows  : deleteRows,
                        cols        : [
                            {field: 'age', title: 'ID'},
                            {field: 'name', title: 'Name'},
                            {field: 'snippet', title: 'Description', sortable: false}
                        ],
                        filters     : [
                            {field: 'age', title: 'ID', condition: 'eq'},
                            {field: 'name', title: 'Name', condition: 'like_b', options: {insensitive: true}},
                            {
                                field    : 'snippet',
                                title    : 'Description',
                                condition: 'like_b',
                                options  : {insensitive: true}
                            }
                        ],
                        pagesizes   : [5, 10, 20],
                        debug       : true,
                        displayField: displayField
                    }
                },

                fl: {
                    options: {
                        listURL           : 'desserts.json',
                        method            : 'GET',
                        urlencoded        : true,
                        pagesize          : 5,
                        orderby           : [
                            {field: 'name', type: 'asc'}
                        ],
                        sortOnClient      : true,
                        paginationOnClient: true,
                        searchOnClient    : true
                        // Enable log
                        ,log: {id: 'phonesService', err: true, debug: true}
                    }
                }
            };

            return ph;
        }

        function flComplete($e, $args) {
            angular.forEach(phone().fl.records, function(record) {
                if (record.id === 'dell-venue') {
                    record.readonly = true;
                    return;
                }
            });
        }

        function addRecord() {
            alert('add record');
        }

        function editRecord(record) {
            alert('edit record');
        }

        function deleteRecord(record) {
            alert('delete record');
        }

        function deleteRows(selection) {
            alert(selection.length + ' records selected');
        }

        function displayField(scope, element, attrs) {
            // Add a link on field "name" to each record
            if (attrs['field'] == 'name') {
                if (attrs['value'] == 'Dell Venue') {
                    element.html('' + attrs['value'] + '');
                }
                else {
                    element.html('' + attrs['value'] + '');
                }

                return;
            }

            element.html(attrs['value']);
        }
    }

})();

<|endoftext|>


<commit_before>/**
    * @ngdoc service
    * @name umbraco.resources.elementTypeResource
    * @description Loads in data for element types
    **/
function elementTypeResource($q, $http, umbRequestHelper) {

    return {

        getAll: function () {

            return umbRequestHelper.resourcePromise(
                $http.get(
                    umbRequestHelper.getApiUrl(
                        "elementTypeApiBaseUrl",
                        "GetAll")),
                "Failed to retrieve element types");

        }

    };
}

angular.module("umbraco.resources").factory("elementTypeResource", elementTypeResource);
<commit_msg>Updated ngDocs for elementTypeResource<commit_after>/**
    * @ngdoc service
    * @name umbraco.resources.elementTypeResource
    * @description Loads in data for element types
    **/
function elementTypeResource($q, $http, umbRequestHelper) {

    return {

        /**
        * @ngdoc method
        * @name umbraco.resources.elementTypeResource#getAll
        * @methodOf umbraco.resources.elementTypeResource
        *
        * @description
        * Gets a list of all element types
        *
        * ##usage
        * <pre>
        * elementTypeResource.getAll()
        *    .then(function() {
        *        alert('Found it!');
        *    });
        * </pre>
        *
        * @returns {Promise} resourcePromise object.
        *
        **/
        getAll: function () {

            return umbRequestHelper.resourcePromise(
                $http.get(
                    umbRequestHelper.getApiUrl(
                        "elementTypeApiBaseUrl",
                        "GetAll")),
                "Failed to retrieve element types");

        }

    };
}

angular.module("umbraco.resources").factory("elementTypeResource", elementTypeResource);
<|endoftext|>


<commit_before>var assert = require('assert');

module.exports = function parse(str) {
  var json = JSON.parse(str);
  assert(json.shift() === "MARKDOWN");
  var blocks = convertBlocks(json, 0);
  return ['text'].concat(blocks);
};

var convertBlocks = function(blocks, level) {
  var result = [];

  blocks.forEach(function(block) {
    var type = block.shift();
    switch (type) {

      case 'PARA':
      case 'PLAIN':
        result.push(['para', { 'level': level }].concat(convertInlines(block)));
        break;

      case 'H1':
      case 'H2':
      case 'H3':
      case 'H4':
      case 'H5':
      case 'H6':
        var headingLevel = parseInt(type.substr(1)) - 4;
        headingLevel = headingLevel > -1 ? -1 : headingLevel;
        result.push(['heading', { 'level': headingLevel }].concat(convertInlines(block)));
        break;

      case 'BULLETLIST':
        result = result.concat(convertList(block, level));
        break;

      case 'LIST':
      case 'HEADINGSECTION':
        result = result.concat(convertBlocks(block, level));
        break;

      default: // extract just text in the worst case
        result.push(['para', { 'level': level }].concat(convertInlines(block)));
    }
  });

  return result;
};

var convertList = function(items, level) {
  var result = [];

  items.forEach(function(item) {
    assert(item.shift() === 'LISTITEM');
    var blocks = convertBlocks(item, level+1);
    assert(blocks.length > 0);
    blocks[0][0] = 'bulleted';
    blocks[0][1].level = level;
    result = result.concat(blocks);
  });

  return result;
};

var convertInlines = function(inlines) {
  inlines = extractInlines(inlines);
  inlines = normalizeInlines(inlines);
  return inlines;
};

var extractInlines = function(inlines) {
  var result = [];

  inlines.forEach(function(inline) {
    if (! Array.isArray(inline)) // ignore objects, e.g. { "URL": "something" }
      return;

    var type = inline.shift();
    switch (type) {

      case 'STR':
        assert(inline.length === 1);
        result.push(['plain', inline[0]]);
        break;

      case 'SPACE':
        assert(inline.length === 1);
        result.push(['plain', ' ']);
        break;

      default: // extract just text in the worst case
        if (inline.length === 1 && typeof inline[0] == 'string')
          result.push(['plain', inline[0]]);
        else
          result = result.concat(extractInlines(inline));
    }
  });

  return result;
};

var normalizeInlines = function(inlines) {
  if (inlines.length === 0)
    return [];

  var result = [inlines.shift()];
  while (inlines.length > 0) {
    var current = inlines.shift();
    if (current[0] === 'break') {
      result.push(current);
      continue;
    }

    var last = result[result.length-1];
    if (last[0] == current[0] ||
        (current[0] === 'plain' && current[1] === ' ' &&
         inlines.length > 0 && last[0] === inlines[0][0] &&
         last[0] !== 'break')) {
      // append text
      assert(typeof last[1] === 'string');
      last[1] += current[1];
    } else {
     result.push(current);
    }
  }
  return result;
};
<commit_msg>[mmd] Return array of blocks from convertInlines().<commit_after>var assert = require('assert');

module.exports = function parse(str) {
  var json = JSON.parse(str);
  assert(json.shift() === "MARKDOWN");
  var blocks = convertBlocks(json, 0);
  return ['text'].concat(blocks);
};

var convertBlocks = function(blocks, level) {
  var result = [];

  blocks.forEach(function(block) {
    var type = block.shift();
    switch (type) {

      case 'PARA':
      case 'PLAIN':
        result = result.concat(convertInlines(block, level));
        break;

      case 'H1':
      case 'H2':
      case 'H3':
      case 'H4':
      case 'H5':
      case 'H6':
        var headingLevel = parseInt(type.substr(1)) - 4;
        headingLevel = headingLevel > -1 ? -1 : headingLevel;
        var convertedBlocks = convertInlines(block, level);
        assert(convertedBlocks.length > 0);
        convertedBlocks[0][0] = 'heading';
        convertedBlocks[0][1].level = headingLevel;
        result = result.concat(convertedBlocks);
        break;

      case 'BULLETLIST':
        result = result.concat(convertList(block, level));
        break;

      case 'LIST':
      case 'HEADINGSECTION':
        result = result.concat(convertBlocks(block, level));
        break;

      default: // extract just text in the worst case
        result = result.concat(convertInlines(block, level));
    }
  });

  return result;
};

var convertList = function(items, level) {
  var result = [];

  items.forEach(function(item) {
    assert(item.shift() === 'LISTITEM');
    var blocks = convertBlocks(item, level+1);
    assert(blocks.length > 0);
    blocks[0][0] = 'bulleted';
    blocks[0][1].level = level;
    result = result.concat(blocks);
  });

  return result;
};

var convertInlines = function(inlines, level) {
  inlines = extractInlines(inlines);
  inlines = normalizeInlines(inlines);
  return [['para', { 'level': level }].concat(inlines)];
};

var extractInlines = function(inlines) {
  var result = [];

  inlines.forEach(function(inline) {
    if (! Array.isArray(inline)) // ignore objects, e.g. { "URL": "something" }
      return;

    var type = inline.shift();
    switch (type) {

      case 'STR':
        assert(inline.length === 1);
        result.push(['plain', inline[0]]);
        break;

      case 'SPACE':
        assert(inline.length === 1);
        result.push(['plain', ' ']);
        break;

      default: // extract just text in the worst case
        if (inline.length === 1 && typeof inline[0] == 'string')
          result.push(['plain', inline[0]]);
        else
          result = result.concat(extractInlines(inline));
    }
  });

  return result;
};

var normalizeInlines = function(inlines) {
  if (inlines.length === 0)
    return [];

  var result = [inlines.shift()];
  while (inlines.length > 0) {
    var current = inlines.shift();
    if (current[0] === 'break') {
      result.push(current);
      continue;
    }

    var last = result[result.length-1];
    if (last[0] == current[0] ||
        (current[0] === 'plain' && current[1] === ' ' &&
         inlines.length > 0 && last[0] === inlines[0][0] &&
         last[0] !== 'break')) {
      // append text
      assert(typeof last[1] === 'string');
      last[1] += current[1];
    } else {
     result.push(current);
    }
  }
  return result;
};
<|endoftext|>


<commit_before>/**
 * @fileoverview Rule for disallowing require() outside of the top-level module context
 * @author Jamund Ferguson
 * @copyright 2015 Jamund Ferguson. All rights reserved.
 */

"use strict";

var ACCEPTABLE_PARENTS = [
    "AssignmentExpression",
    "VariableDeclarator",
    "MemberExpression",
    "ExpressionStatement",
    "CallExpression",
    "ConditionalExpression",
    "Program",
    "VariableDeclaration"
];

module.exports = function(context) {
    return {
        "CallExpression": function(node) {
            if (node.callee.name === "require") {
                var isGoodRequire = context.getAncestors().every(function(parent) {
                    return ACCEPTABLE_PARENTS.indexOf(parent.type) > -1;
                });
                if (!isGoodRequire) {
                    context.report(node, "Unexpected require().");
                }
            }
        }
    };
};

<commit_msg>Fix: Add schema to `global-require` rule (fixes #3923)<commit_after>/**
 * @fileoverview Rule for disallowing require() outside of the top-level module context
 * @author Jamund Ferguson
 * @copyright 2015 Jamund Ferguson. All rights reserved.
 */

"use strict";

var ACCEPTABLE_PARENTS = [
    "AssignmentExpression",
    "VariableDeclarator",
    "MemberExpression",
    "ExpressionStatement",
    "CallExpression",
    "ConditionalExpression",
    "Program",
    "VariableDeclaration"
];

module.exports = function(context) {
    return {
        "CallExpression": function(node) {
            if (node.callee.name === "require") {
                var isGoodRequire = context.getAncestors().every(function(parent) {
                    return ACCEPTABLE_PARENTS.indexOf(parent.type) > -1;
                });
                if (!isGoodRequire) {
                    context.report(node, "Unexpected require().");
                }
            }
        }
    };
};

module.exports.schema = [];
<|endoftext|>