<commit_before>module.exports = function(grunt){

    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        postcss: {
            options: {
                map: {
                    inline: false,
                    annotation: 'build/css'
                },

                processors: [
                    require('postcss-import')(),
                    require("postcss-cssnext")({
                        browsers: ['last 3 versions', 'Firefox ESR', 'Firefox 28']
                    }),
                    require('cssnano')()
                ]
            },
            css: {
                expand: true,
                cwd: 'src/templates/css/',
                src  : 'project.css',
                dest : 'build/css/'
            },
            thirdParty: {
                expand: true,
                cwd: 'src/templates/css/third-party',
                src  : '*.css',
                dest : 'build/css/third-party/'
            }
        },

        svgmin: {
            img:
            {
                files: [{
                    expand: true,
                    cwd: 'src/templates/img/',
                    src: '*.svg',
                    dest: 'build/static/img/'

                }]
            },
            icons:
            {
                files: [{
                    expand: true,
                    cwd: 'src/templates/img/icons',
                    src: '*.svg',
                    dest: 'build/img/icons/'
                }]
            }
        },

        modernizr: {
            dist: {
                 // Path to save out the built file
                'dest' : 'build/js/modernizr-custom.js',
                'options' : [
                    'setClasses',
                    'addTest',
                    'html5printshiv',
                    'testProp',
                    'fnBind'
                ],
                'uglify': true,
                'classPrefix': 'mzr_'
            }
        },

        webfont: {
            icons: {
                src: 'build/img/icons/*.svg',
                dest: 'build/fonts',
                destCss: 'build/css/',
                options: {
                    engine: 'node',
                    font: '<%= pkg.name %>-icons',
                    hashes: true,
                    syntax: 'bootstrap',
                    template: 'src/templates/img/icons/icons-tmpl.css',
                    templateOptions: {
                        htmlDemoTemplate: 'src/templates/img/icons/demoicons-tmpl.html',
                        destHtml: 'src/docs'
                    }
                }
            }
        },

        nunjucks: {
            options: {
                paths : 'src/'
            },
            template: {
                files:[{
                    expand: true,
                    flatten: true,
                    cwd: 'src/templates',
                    src: '*.html',
                    dest: 'build/',
                    ext: '.html'
                }]
            },
            docs: {
                files:[{
                    expand: true,
                    flatten: true,
                    cwd: 'src/docs',
                    src: '*.html',
                    dest: 'docs/',
                    ext: '.html'
                }]
            }

        },

        watch: {
            options: {
                livereload: true,
            },
            src_template_html : {
                    files : 'src/templates/**/*.html',
                    tasks : ['nunjucks:template']
                },
                src_template_css : {
                    files: 'src/templates/css/**/*.css',
                    tasks : ['postcss']
                },
                src_template_js: {
                    files: 'build/js/*.js'
                },
            src_docs_html : {
                files : 'src/docs/**/*',
                tasks : ['nunjucks:docs']
            },
            src_docs_css_js : {
                files : ['docs/assets/doc.css', 'docs/assets/doc.js']
            }
        },

        clean: {
            html : ['build/*.html'],
            css: ['build/css/*'],
            icons: ['build/img/icons/*.svg'],
            iconsfont: ['build/fonts/*-icons.*']
        }

    });

    // Load plugins
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-svgmin');
    grunt.loadNpmTasks('grunt-webfont');
    grunt.loadNpmTasks('grunt-nunjucks-2-html');
    grunt.loadNpmTasks('grunt-postcss');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-modernizr');

    // Custom tasks -- Run plugins
    grunt.registerTask('default', ['watch']);
    grunt.registerTask('buildhtml', ['clean:html','nunjucks:template']);
    grunt.registerTask('buildcss', ['clean:css', 'postcss']);
    grunt.registerTask('buildicons', ['svgmin:icons','webfont:icons']);
    grunt.registerTask('builddocs', ['nunjucks:docs']);
    grunt.registerTask('build', ['buildcss', 'buildhtml', 'modernizr', 'buildicons', 'builddocs']);
    grunt.registerTask('init', ['build']);
};<commit_msg>gruntfile: add task for BrowserSync and remove livereload<commit_after>module.exports = function(grunt){

    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        postcss: {
            options: {
                map: {
                    inline: false,
                    annotation: 'build/css'
                },

                processors: [
                    require('postcss-import')(),
                    require("postcss-cssnext")({
                        browsers: ['last 3 versions', 'Firefox ESR', 'Firefox 28']
                    }),
                    require('cssnano')()
                ]
            },
            css: {
                expand: true,
                cwd: 'src/templates/css/',
                src  : 'project.css',
                dest : 'build/css/'
            },
            thirdParty: {
                expand: true,
                cwd: 'src/templates/css/third-party',
                src  : '*.css',
                dest : 'build/css/third-party/'
            }
        },

        svgmin: {
            img:
            {
                files: [{
                    expand: true,
                    cwd: 'src/templates/img/',
                    src: '*.svg',
                    dest: 'build/static/img/'

                }]
            },
            icons:
            {
                files: [{
                    expand: true,
                    cwd: 'src/templates/img/icons',
                    src: '*.svg',
                    dest: 'build/img/icons/'
                }]
            }
        },

        modernizr: {
            dist: {
                 // Path to save out the built file
                'dest' : 'build/js/modernizr-custom.js',
                'options' : [
                    'setClasses',
                    'addTest',
                    'html5printshiv',
                    'testProp',
                    'fnBind'
                ],
                'uglify': true,
                'classPrefix': 'mzr_'
            }
        },

        webfont: {
            icons: {
                src: 'build/img/icons/*.svg',
                dest: 'build/fonts',
                destCss: 'build/css/',
                options: {
                    engine: 'node',
                    font: '<%= pkg.name %>-icons',
                    hashes: true,
                    syntax: 'bootstrap',
                    template: 'src/templates/img/icons/icons-tmpl.css',
                    templateOptions: {
                        htmlDemoTemplate: 'src/templates/img/icons/demoicons-tmpl.html',
                        destHtml: 'src/docs'
                    }
                }
            }
        },

        nunjucks: {
            options: {
                paths : 'src/'
            },
            template: {
                files:[{
                    expand: true,
                    flatten: true,
                    cwd: 'src/templates',
                    src: '*.html',
                    dest: 'build/',
                    ext: '.html'
                }]
            },
            docs: {
                files:[{
                    expand: true,
                    flatten: true,
                    cwd: 'src/docs',
                    src: '*.html',
                    dest: 'docs/',
                    ext: '.html'
                }]
            }

        },

        watch: {
            src_template_html : {
                    files : 'src/templates/**/*.html',
                    tasks : ['nunjucks:template']
                },
                src_template_css : {
                    files: 'src/templates/css/**/*.css',
                    tasks : ['postcss']
                },
                src_template_js: {
                    files: 'build/js/*.js'
                },
            src_docs_html : {
                files : 'src/docs/**/*',
                tasks : ['nunjucks:docs']
            }
        },

        browserSync: {
            bsFiles: {
                src : 'build/**/*'
            },
            options: {
                watchTask: true,
                server: './build'
            }
        },

        clean: {
            html : ['build/*.html'],
            css: ['build/css/*'],
            icons: ['build/img/icons/*.svg'],
            iconsfont: ['build/fonts/*-icons.*']
        }

    });

    // Load plugins
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-svgmin');
    grunt.loadNpmTasks('grunt-webfont');
    grunt.loadNpmTasks('grunt-nunjucks-2-html');
    grunt.loadNpmTasks('grunt-postcss');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-modernizr');
    grunt.loadNpmTasks('grunt-browser-sync');

    // Custom tasks -- Run plugins
    grunt.registerTask('default', ['browserSync','watch']);
    grunt.registerTask('buildhtml', ['clean:html','nunjucks:template']);
    grunt.registerTask('buildcss', ['clean:css', 'postcss']);
    grunt.registerTask('buildicons', ['svgmin:icons','webfont:icons']);
    grunt.registerTask('builddocs', ['nunjucks:docs']);
    grunt.registerTask('build', ['buildcss', 'buildhtml', 'modernizr', 'buildicons', 'builddocs']);
    grunt.registerTask('init', ['build']);
};<|endoftext|>


<commit_before>var request = require('request'),
    fs = require('fs'),
    auth = require('./auth'),
    edgerc = require('./edgerc'),
    helpers = require('./helpers'),
    logger = require('./logger');

var EdgeGrid = function(client_token, client_secret, access_token, host) {
  // accepting an object containing a path to .edgerc and a config group
  if (typeof arguments[0] === 'object') {
    this._setConfigFromObj(arguments[0]);
  } else {
    this._setConfigFromStrings(client_token, client_secret, access_token, host);
  }
};

EdgeGrid.prototype.auth = function(req) {
  req = helpers.extend(req, {
    "method": "GET",
    "headers": {
      "Content-Type": "application/json"
    },
     "body": {}
  });

  this.request = auth.generate_auth(req, this.config.client_token, this.config.client_secret, this.config.access_token, this.config.host);
};

EdgeGrid.prototype.send = function(callback) {
  request(this.request, function(error, response, body) {
    if (error) { throw new Error(error); }

    callback(body, response);
  });
};

EdgeGrid.prototype._setConfigFromObj = function(obj) {
  if (!obj.path) {
    if (!process.env.EDGEGRID_ENV === 'test') {
      logger.error('No .edgerc path');
    }

    throw new Error('No edgerc path');
  }

  this.config = edgerc(obj.path, obj.group);
};

EdgeGrid.prototype._setConfigFromStrings = function(client_token, client_secret, access_token, host) {
  if (!validatedArgs([client_token, client_secret, access_token, host])) {
    throw new Error('Insufficient Akamai credentials');
  }

  this.config = {
    client_token: client_token,
    client_secret: client_secret,
    access_token: access_token,
    host: host.indexOf('https://') > -1 ? host : 'https://' + host
  };
};

function validatedArgs(args) {
  var expected = [
        'client_token', 'client_secret', 'access_token', 'host'
      ],
      valid = true,
      i;

  expected.forEach(function(arg, i) {
    if (!args[i]) {
      if (process.env.EDGEGRID_ENV !== 'test' ) {
        logger.error('No defined ' + arg);
      }

      valid = false;
    }
  });

  return valid;
}

module.exports = EdgeGrid;
<commit_msg>default req object adheres to coding convention<commit_after>var request = require('request'),
    fs = require('fs'),
    auth = require('./auth'),
    edgerc = require('./edgerc'),
    helpers = require('./helpers'),
    logger = require('./logger');

var EdgeGrid = function(client_token, client_secret, access_token, host) {
  // accepting an object containing a path to .edgerc and a config group
  if (typeof arguments[0] === 'object') {
    this._setConfigFromObj(arguments[0]);
  } else {
    this._setConfigFromStrings(client_token, client_secret, access_token, host);
  }
};

EdgeGrid.prototype.auth = function(req) {
  req = helpers.extend(req, {
    method: 'GET',
    headers: {
      'Content-Type': "application/json"
    },
     body: {}
  });

  this.request = auth.generate_auth(req, this.config.client_token, this.config.client_secret, this.config.access_token, this.config.host);
};

EdgeGrid.prototype.send = function(callback) {
  request(this.request, function(error, response, body) {
    if (error) { throw new Error(error); }

    callback(body, response);
  });
};

EdgeGrid.prototype._setConfigFromObj = function(obj) {
  if (!obj.path) {
    if (!process.env.EDGEGRID_ENV === 'test') {
      logger.error('No .edgerc path');
    }

    throw new Error('No edgerc path');
  }

  this.config = edgerc(obj.path, obj.group);
};

EdgeGrid.prototype._setConfigFromStrings = function(client_token, client_secret, access_token, host) {
  if (!validatedArgs([client_token, client_secret, access_token, host])) {
    throw new Error('Insufficient Akamai credentials');
  }

  this.config = {
    client_token: client_token,
    client_secret: client_secret,
    access_token: access_token,
    host: host.indexOf('https://') > -1 ? host : 'https://' + host
  };
};

function validatedArgs(args) {
  var expected = [
        'client_token', 'client_secret', 'access_token', 'host'
      ],
      valid = true,
      i;

  expected.forEach(function(arg, i) {
    if (!args[i]) {
      if (process.env.EDGEGRID_ENV !== 'test' ) {
        logger.error('No defined ' + arg);
      }

      valid = false;
    }
  });

  return valid;
}

module.exports = EdgeGrid;
<|endoftext|>


<commit_before>module.exports = function (grunt) {
    "use strict";
    /*eslint-env node*/

    require("time-grunt")(grunt);

    // Since the tasks are split using load-grunt-config, I need a global object containing the configuration
    global.configuration = {
        pkg: grunt.file.readJSON("./package.json")
    };

    require("load-grunt-config")(grunt);
    grunt.task.loadTasks("grunt/tasks");

};
<commit_msg>Minimal grunt file (no extra files)<commit_after>module.exports = function (grunt) {
    "use strict";
    /*eslint-env node*/

    // This will measure the time spent in each task
    require("time-grunt")(grunt);

    // This will configure each task individually
    grunt.initConfig({
        pkg: grunt.file.readJSON("package.json"),

        eslint: {
            target: [
                "grunt/**/*.js",
                "src/**/*.js",
                "test/**/*.js"
            ]
        },

        mochaTest: {
            source: {
                options: {
                    reporter: "spec",
                    quiet: false,
                    require: [
                        function () {
                            global.assert = require("assert");
                        },
                        "test/host/node.js"
                    ]
                },
                src: "test/*.js"
            }
        }

    });

    // Load the packages that adds features to grunt
    [
        "grunt-eslint",
        "grunt-mocha-test"
    ].forEach(function (packageName) {
        grunt.loadNpmTasks(packageName);
    });

    // Default task
    grunt.registerTask("default", [
        "eslint",
        "mochaTest"
    ]);

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jshint: {
      files: [
        'Gruntfile.js',
        'package.json',
        'bower.json',
        'server.js',
        'public/app/**/*.js',
        'public/languages/**/*.json',
        'app/**/*.js'
      ],
      options: {
        undef: true,
        // unused: true,
        curly: true,
        latedef: true,
        browser: true,
        devel: true,
        globals: {
          $: true,
          jQuery: true,
          module: true,
          angular: true,
          moment: true,
          markdown: true,
          jsPDF: true,
          jwt_decode: true,
          ga: true,
          require: true,
          process: true,
          __dirname: true,
          exports: true,
          res: true,
          Promise: true
        }
      }
    },
    clean: ['dist/'],
    copy: {
      dist: {
        expand: true,
        cwd: 'public/',
        src: [
          'assets/data/**/*.json',
          'assets/data/**/*.js',
          'assets/languages/**/*.json',
          'assets/libs/**/*.js',
          'assets/libs/**/*.css',
          'assets/libs/**/*.map',
          'assets/libs/**/*.svg',
          'assets/libs/**/*.woff',
          'assets/libs/**/*.eot',
          'assets/libs/**/*.ttf',
          'assets/libs/**/*.ttf',
          'app/**/*.html'
        ],
        dest: 'dist/'
      },
      fonts: {
        expand: true,
        flatten: true,
        cwd: 'public/',
        src: [
          'assets/libs/**/*.svg',
          'assets/libs/**/*.woff',
          'assets/libs/**/*.eot',
          'assets/libs/**/*.ttf',
        ],
        dest: 'dist/assets/fonts/'
      }
    },
    concat: {
      js: {
        options: {
          separator: ';'
        },
        src: [
          'public/assets/libs/jquery/dist/jquery.js',
          'public/assets/libs/angular/angular.min.js',
          'public/assets/libs/angular-ui-router/release/angular-ui-router.min.js',
          'public/assets/libs/angular-animate/angular-animate.min.js',
          'public/assets/libs/angular-sanitize/angular-sanitize.min.js',
          'public/assets/libs/angular-cookies/angular-cookies.min.js',
          'public/assets/libs/angular-localization/angular-localization.min.js',
          'public/assets/libs/ngInfiniteScroll/build/ng-infinite-scroll.min.js',
          'public/assets/libs/jspdf/dist/jspdf.min.js',
          'public/assets/libs/markdown/lib/markdown.js',
          'public/assets/libs/moment/min/moment.min.js',
          'public/assets/libs/angular-bootstrap/ui-bootstrap.min.js',
          'public/assets/libs/angular-bootstrap/ui-bootstrap-tpls.min.js',
          'public/assets/libs/bootstrap/dist/js/bootstrap.min.js',
          'public/assets/libs/jvectormap/jquery.jvectormap.min.js',
          'public/assets/libs/jwt-decode/build/jwt-decode.min.js',
          'public/app/app-module.js',
          'public/app/*.js',
          'public/app/**/*.js'
        ],
        dest: 'dist/assets/js/<%= pkg.name %>.js'
      },
      css: {
        options: {
          separator: ' '
        },
        src: [
          'public/assets/libs/bootstrap/dist/css/bootstrap.min.css',
          'public/assets/libs/components-font-awesome/css/font-awesome.min.css',
          'public/app/app-style.css',
          'public/app/**/*.css'
        ],
        dest: 'dist/assets/css/<%= pkg.name %>.css'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        mangle: false
      },
      dist: {
        files: {
          'dist/assets/js/<%= pkg.name %>.min.js': ['<%= concat.js.dest %>']
        }
      }
    },
    cssmin: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        options: {
          ignore: []
        },
        files: {
          'dist/assets/css/<%= pkg.name %>.min.css': ['<%= concat.css.dest %>']
        }
      }
    },
    imagemin: {
      dynamic: {
        options: {
          optimizationLevel: 4,
        },
        files: [{
          expand: true,
          cwd: 'public/assets/images/',
          src: ['**/*.{png,jpg,gif}'],
          dest: 'dist/assets/images/'
        }]
      }
    },
    processhtml: {
      dist: {
        files: {
          'dist/index.html': ['public/index.html']
        }
      }
    },
    pagespeed: {
      options: {
        nokey: true
      },
      desktop: {
        options: {
          url: "http://ianlamb.com",
          locale: "en_CA",
          strategy: "desktop",
          threshold: 80
        }
      },
      mobile: {
        options: {
          url: "http://ianlamb.com",
          locale: "en_CA",
          strategy: "mobile",
          threshold: 60
        }
      }
    },
    watch: {
      all: {
        files: [
          'public/app/**/*.html',
          'public/app/**/*.js',
          'public/app/**/*.css',
          'public/assets/languages/**/*.json',
          'public/assets/images/**/*.jpg',
          'public/assets/images/**/*.png',
          'public/assets/images/**/*.gif'
        ],
        options: {
          livereload: true,
        },
      },
    },
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-imagemin');
  grunt.loadNpmTasks('grunt-processhtml');
  grunt.loadNpmTasks('grunt-pagespeed');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('test', ['jshint']);
  grunt.registerTask('default', ['jshint', 'copy', 'concat', 'uglify', 'cssmin', 'processhtml']);
  grunt.registerTask('full', ['jshint', 'clean', 'copy', 'concat', 'uglify', 'cssmin', 'imagemin', 'processhtml']);

};
<commit_msg>fix grunt copy for maps<commit_after>module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jshint: {
      files: [
        'Gruntfile.js',
        'package.json',
        'bower.json',
        'server.js',
        'public/app/**/*.js',
        'public/languages/**/*.json',
        'app/**/*.js'
      ],
      options: {
        undef: true,
        // unused: true,
        curly: true,
        latedef: true,
        browser: true,
        devel: true,
        globals: {
          $: true,
          jQuery: true,
          module: true,
          angular: true,
          moment: true,
          markdown: true,
          jsPDF: true,
          jwt_decode: true,
          ga: true,
          require: true,
          process: true,
          __dirname: true,
          exports: true,
          res: true,
          Promise: true
        }
      }
    },
    clean: ['dist/'],
    copy: {
      dist: {
        expand: true,
        cwd: 'public/',
        src: [
          'assets/maps/**/*.json',
          'assets/maps/**/*.js',
          'assets/languages/**/*.json',
          'assets/libs/**/*.js',
          'assets/libs/**/*.css',
          'assets/libs/**/*.map',
          'assets/libs/**/*.svg',
          'assets/libs/**/*.woff',
          'assets/libs/**/*.eot',
          'assets/libs/**/*.ttf',
          'assets/libs/**/*.ttf',
          'app/**/*.html'
        ],
        dest: 'dist/'
      },
      fonts: {
        expand: true,
        flatten: true,
        cwd: 'public/',
        src: [
          'assets/libs/**/*.svg',
          'assets/libs/**/*.woff',
          'assets/libs/**/*.eot',
          'assets/libs/**/*.ttf',
        ],
        dest: 'dist/assets/fonts/'
      }
    },
    concat: {
      js: {
        options: {
          separator: ';'
        },
        src: [
          'public/assets/libs/jquery/dist/jquery.js',
          'public/assets/libs/angular/angular.min.js',
          'public/assets/libs/angular-ui-router/release/angular-ui-router.min.js',
          'public/assets/libs/angular-animate/angular-animate.min.js',
          'public/assets/libs/angular-sanitize/angular-sanitize.min.js',
          'public/assets/libs/angular-cookies/angular-cookies.min.js',
          'public/assets/libs/angular-localization/angular-localization.min.js',
          'public/assets/libs/ngInfiniteScroll/build/ng-infinite-scroll.min.js',
          'public/assets/libs/jspdf/dist/jspdf.min.js',
          'public/assets/libs/markdown/lib/markdown.js',
          'public/assets/libs/moment/min/moment.min.js',
          'public/assets/libs/angular-bootstrap/ui-bootstrap.min.js',
          'public/assets/libs/angular-bootstrap/ui-bootstrap-tpls.min.js',
          'public/assets/libs/bootstrap/dist/js/bootstrap.min.js',
          'public/assets/libs/jvectormap/jquery.jvectormap.min.js',
          'public/assets/libs/jwt-decode/build/jwt-decode.min.js',
          'public/app/app-module.js',
          'public/app/*.js',
          'public/app/**/*.js'
        ],
        dest: 'dist/assets/js/<%= pkg.name %>.js'
      },
      css: {
        options: {
          separator: ' '
        },
        src: [
          'public/assets/libs/bootstrap/dist/css/bootstrap.min.css',
          'public/assets/libs/components-font-awesome/css/font-awesome.min.css',
          'public/app/app-style.css',
          'public/app/**/*.css'
        ],
        dest: 'dist/assets/css/<%= pkg.name %>.css'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        mangle: false
      },
      dist: {
        files: {
          'dist/assets/js/<%= pkg.name %>.min.js': ['<%= concat.js.dest %>']
        }
      }
    },
    cssmin: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        options: {
          ignore: []
        },
        files: {
          'dist/assets/css/<%= pkg.name %>.min.css': ['<%= concat.css.dest %>']
        }
      }
    },
    imagemin: {
      dynamic: {
        options: {
          optimizationLevel: 4,
        },
        files: [{
          expand: true,
          cwd: 'public/assets/images/',
          src: ['**/*.{png,jpg,gif}'],
          dest: 'dist/assets/images/'
        }]
      }
    },
    processhtml: {
      dist: {
        files: {
          'dist/index.html': ['public/index.html']
        }
      }
    },
    pagespeed: {
      options: {
        nokey: true
      },
      desktop: {
        options: {
          url: "http://ianlamb.com",
          locale: "en_CA",
          strategy: "desktop",
          threshold: 80
        }
      },
      mobile: {
        options: {
          url: "http://ianlamb.com",
          locale: "en_CA",
          strategy: "mobile",
          threshold: 60
        }
      }
    },
    watch: {
      all: {
        files: [
          'public/app/**/*.html',
          'public/app/**/*.js',
          'public/app/**/*.css',
          'public/assets/languages/**/*.json',
          'public/assets/images/**/*.jpg',
          'public/assets/images/**/*.png',
          'public/assets/images/**/*.gif'
        ],
        options: {
          livereload: true,
        },
      },
    },
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-imagemin');
  grunt.loadNpmTasks('grunt-processhtml');
  grunt.loadNpmTasks('grunt-pagespeed');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('test', ['jshint']);
  grunt.registerTask('default', ['jshint', 'copy', 'concat', 'uglify', 'cssmin', 'processhtml']);
  grunt.registerTask('full', ['jshint', 'clean', 'copy', 'concat', 'uglify', 'cssmin', 'imagemin', 'processhtml']);

};
<|endoftext|>


<commit_before>let _           = require('lodash');
let debug       = require('debug')('purge-cache');
let API         = require('taskcluster-lib-api');
let taskcluster = require('taskcluster-client');

// Common schema prefix
let SCHEMA_PREFIX_CONST = 'http://schemas.taskcluster.net/purge-cache/v1/';

// Common patterns URL parameters
const GENERIC_ID_PATTERN = /^[a-zA-Z0-9-_]{1,22}$/;

/** API end-point for version v1/ */
let api = new API({
  title:        'Purge Cache API Documentation',
  context: [
    'cfg',              // A typed-env-config instance
    'publisher',        // A pulse-publisher instance
    'CachePurge',      // A data.CachePurge instance
    'cachePurgeCache', // An Promise for cacheing cachepurge responses
  ],
  params: {
    provisionerId:    GENERIC_ID_PATTERN,
    workerType:       GENERIC_ID_PATTERN,
  },
  description: [
    'The purge-cache service, typically available at',
    '`purge-cache.taskcluster.net`, is responsible for publishing a pulse',
    'message for workers, so they can purge cache upon request.',
    '',
    'This document describes the API end-point for publishing the pulse',
    'message. This is mainly intended to be used by tools.',
  ].join('\n'),
});

// Export API
module.exports = api;

/** Define tasks */
api.declare({
  method:     'post',
  route:      '/purge-cache/:provisionerId/:workerType',
  name:       'purgeCache',
  scopes:     'purge-cache:<provisionerId>/<workerType>:<cacheName>',
  input:      SCHEMA_PREFIX_CONST + 'purge-cache-request.json#',
  title:      'Purge Worker Cache',
  description: [
    'Publish a purge-cache message to purge caches named `cacheName` with',
    '`provisionerId` and `workerType` in the routing-key. Workers should',
    'be listening for this message and purge caches when they see it.',
  ].join('\n'),
}, async function(req, res) {
  let {provisionerId, workerType} = req.params;
  let {cacheName} = req.body;

  debug(`Processing request for ${provisionerId}/${workerType}/${cacheName}.`);

  await req.authorize({provisionerId, workerType, cacheName});

  // Publish message
  await this.publisher.purgeCache({provisionerId, workerType, cacheName});

  try {
    await this.CachePurge.create({
      workerType,
      provisionerId,
      cacheName,
      before: new Date(),
      expires: taskcluster.fromNow('1 day'),
    });
  } catch (err) {
    if (err.code !== 'EntityAlreadyExists') {
      throw err;
    }
    let cb = await this.CachePurge.load({
      workerType,
      provisionerId,
      cacheName,
    });

    await cb.modify(cachePurge => {
      cachePurge.before = new Date();
      cachePurge.expires = taskcluster.fromNow('1 day');
    });
  }

  // Return 204
  res.status(204).send();
});

api.declare({
  method:   'get',
  route:    '/purge-cache/list',
  query: {
    continuationToken: /./,
    limit: /^[0-9]+$/,
  },
  name:     'allPurgeRequests',
  output:   SCHEMA_PREFIX_CONST + 'all-purge-cache-request-list.json#',
  title:    'All Open Purge Requests',
  description: [
    'This is useful mostly for administors to view',
    'the set of open purge requests. It should not',
    'be used by workers. They should use the purgeRequests',
    'endpoint that is specific to their workerType and',
    'provisionerId.',
  ].join('\n'),
}, async function(req, res) {
  let continuation = req.query.continuationToken || null;
  let limit = parseInt(req.query.limit || 1000, 10);
  let openRequests = await this.CachePurge.scan({}, {continuation, limit});
  return res.reply({
    continuationToken: openRequests.continuation || '',
    requests: _.map(openRequests.entries, entry => {
      return {
        provisionerId: entry.provisionerId,
        workerType: entry.workerType,
        cacheName: entry.cacheName,
        before: entry.before.toJSON(),
      };
    }),
  });
});

api.declare({
  method:   'get',
  route:    '/purge-cache/:provisionerId/:workerType',
  query: {
    since: dt => Date.parse(dt) ? null : 'Invalid Date',
  },
  name:     'purgeRequests',
  output:   SCHEMA_PREFIX_CONST + 'purge-cache-request-list.json#',
  title:    'Open Purge Requests for a provisionerId/workerType pair',
  description: [
    'List of caches that need to be purged if they are from before',
    'a certain time. This is safe to be used in automation from',
    'workers.',
  ].join('\n'),
}, async function(req, res) {

  let {provisionerId, workerType} = req.params;
  let cacheKey = `${provisionerId}/${workerType}`;
  let cacheHit = false;
  let since = new Date(req.query.since || 0);

  this.cachePurgeCache[cacheKey] = Promise.resolve(this.cachePurgeCache[cacheKey]).then(async cacheCache => {
    if (cacheCache && Date.now() - cacheCache.touched < this.cfg.app.cacheTime * 1000) {
      cacheHit = true;
      return cacheCache;
    }
    return Promise.resolve({reqs: await this.CachePurge.query({provisionerId, workerType}), touched: Date.now()});
  });

  let {reqs: openRequests} = await this.cachePurgeCache[cacheKey];
  return res.reply({
    cacheHit,
    requests: _.reduce(openRequests.entries, (l, entry) => {
      if (entry.before >= since) {
        l.push({
          provisionerId: entry.provisionerId,
          workerType: entry.workerType,
          cacheName: entry.cacheName,
          before: entry.before.toJSON(),
        });
      }
      return l;
    }, []),
  });
});
<commit_msg>Bug 1237310 - Added stability levels to API methods<commit_after>let _           = require('lodash');
let debug       = require('debug')('purge-cache');
let API         = require('taskcluster-lib-api');
let taskcluster = require('taskcluster-client');

// Common schema prefix
let SCHEMA_PREFIX_CONST = 'http://schemas.taskcluster.net/purge-cache/v1/';

// Common patterns URL parameters
const GENERIC_ID_PATTERN = /^[a-zA-Z0-9-_]{1,22}$/;

/** API end-point for version v1/ */
let api = new API({
  title:        'Purge Cache API Documentation',
  context: [
    'cfg',              // A typed-env-config instance
    'publisher',        // A pulse-publisher instance
    'CachePurge',      // A data.CachePurge instance
    'cachePurgeCache', // An Promise for cacheing cachepurge responses
  ],
  params: {
    provisionerId:    GENERIC_ID_PATTERN,
    workerType:       GENERIC_ID_PATTERN,
  },
  description: [
    'The purge-cache service, typically available at',
    '`purge-cache.taskcluster.net`, is responsible for publishing a pulse',
    'message for workers, so they can purge cache upon request.',
    '',
    'This document describes the API end-point for publishing the pulse',
    'message. This is mainly intended to be used by tools.',
  ].join('\n'),
});

// Export API
module.exports = api;

/** Define tasks */
api.declare({
  method:     'post',
  route:      '/purge-cache/:provisionerId/:workerType',
  name:       'purgeCache',
  scopes:     'purge-cache:<provisionerId>/<workerType>:<cacheName>',
  input:      SCHEMA_PREFIX_CONST + 'purge-cache-request.json#',
  title:      'Purge Worker Cache',
  stability:  API.stability.stable,
  description: [
    'Publish a purge-cache message to purge caches named `cacheName` with',
    '`provisionerId` and `workerType` in the routing-key. Workers should',
    'be listening for this message and purge caches when they see it.',
  ].join('\n'),
}, async function(req, res) {
  let {provisionerId, workerType} = req.params;
  let {cacheName} = req.body;

  debug(`Processing request for ${provisionerId}/${workerType}/${cacheName}.`);

  await req.authorize({provisionerId, workerType, cacheName});

  // Publish message
  await this.publisher.purgeCache({provisionerId, workerType, cacheName});

  try {
    await this.CachePurge.create({
      workerType,
      provisionerId,
      cacheName,
      before: new Date(),
      expires: taskcluster.fromNow('1 day'),
    });
  } catch (err) {
    if (err.code !== 'EntityAlreadyExists') {
      throw err;
    }
    let cb = await this.CachePurge.load({
      workerType,
      provisionerId,
      cacheName,
    });

    await cb.modify(cachePurge => {
      cachePurge.before = new Date();
      cachePurge.expires = taskcluster.fromNow('1 day');
    });
  }

  // Return 204
  res.status(204).send();
});

api.declare({
  method:   'get',
  route:    '/purge-cache/list',
  query: {
    continuationToken: /./,
    limit: /^[0-9]+$/,
  },
  name:     'allPurgeRequests',
  output:   SCHEMA_PREFIX_CONST + 'all-purge-cache-request-list.json#',
  title:    'All Open Purge Requests',
  stability:  API.stability.stable,
  description: [
    'This is useful mostly for administors to view',
    'the set of open purge requests. It should not',
    'be used by workers. They should use the purgeRequests',
    'endpoint that is specific to their workerType and',
    'provisionerId.',
  ].join('\n'),
}, async function(req, res) {
  let continuation = req.query.continuationToken || null;
  let limit = parseInt(req.query.limit || 1000, 10);
  let openRequests = await this.CachePurge.scan({}, {continuation, limit});
  return res.reply({
    continuationToken: openRequests.continuation || '',
    requests: _.map(openRequests.entries, entry => {
      return {
        provisionerId: entry.provisionerId,
        workerType: entry.workerType,
        cacheName: entry.cacheName,
        before: entry.before.toJSON(),
      };
    }),
  });
});

api.declare({
  method:   'get',
  route:    '/purge-cache/:provisionerId/:workerType',
  query: {
    since: dt => Date.parse(dt) ? null : 'Invalid Date',
  },
  name:     'purgeRequests',
  output:   SCHEMA_PREFIX_CONST + 'purge-cache-request-list.json#',
  title:    'Open Purge Requests for a provisionerId/workerType pair',
  stability:  API.stability.stable,
  description: [
    'List of caches that need to be purged if they are from before',
    'a certain time. This is safe to be used in automation from',
    'workers.',
  ].join('\n'),
}, async function(req, res) {

  let {provisionerId, workerType} = req.params;
  let cacheKey = `${provisionerId}/${workerType}`;
  let cacheHit = false;
  let since = new Date(req.query.since || 0);

  this.cachePurgeCache[cacheKey] = Promise.resolve(this.cachePurgeCache[cacheKey]).then(async cacheCache => {
    if (cacheCache && Date.now() - cacheCache.touched < this.cfg.app.cacheTime * 1000) {
      cacheHit = true;
      return cacheCache;
    }
    return Promise.resolve({reqs: await this.CachePurge.query({provisionerId, workerType}), touched: Date.now()});
  });

  let {reqs: openRequests} = await this.cachePurgeCache[cacheKey];
  return res.reply({
    cacheHit,
    requests: _.reduce(openRequests.entries, (l, entry) => {
      if (entry.before >= since) {
        l.push({
          provisionerId: entry.provisionerId,
          workerType: entry.workerType,
          cacheName: entry.cacheName,
          before: entry.before.toJSON(),
        });
      }
      return l;
    }, []),
  });
});
<|endoftext|>


<commit_before>// Gruntfile.js
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    watch: {
      sass: {
        files: "scss/**/*.scss",
        tasks: ["build"]
      },
      jshint: {
        files: "js/*.js",
        tasks: ["jshint"]
      },
      eslint: {
        files: "js/*.js",
        tasks: ["eslint"]
      },
      jekyll: {
        files: ["docs/**/*.*", "scss/**/**/*.scss"],
        tasks: ["docs-build"]
      }
    },
    pure_grids: {
      responsive: {
        dest: 'scss/modules/_grid-units.scss',
        options: {
          units: [5,12,24],
          mediaQueries: {
              sm: 'screen and (min-width: 32em)', //512px
              md: 'screen and (min-width: 48em)', //768px
              lg: 'screen and (min-width: 64em)', //1024px
              xl: 'screen and (min-width: 75em)'  //1200px
          },
          selectorPrefix: '.unit-'
        }
      }
    },
    sass: {
      options: {
        outputStyle: "expanded",
        sourceMap: true,
        indentedSyntax: true,
        sassDir: 'scss',
        cssDir: 'dist/ui'
      },
      dev: {
        files: [{
          expand: true,
          cwd: "scss/",
          src: ["*.scss"],
          dest: "dist/ui/",
          ext: ".css"
        }]
      },
      dist: {
        options: {
          sourceMap: false
        },
        files: [{
          expand: true,
          cwd: "scss/",
          src: ["*.scss"],
          dest: "dist/ui/",
          ext: ".css"
        }]
      },
      docs: {
        files: {
          "docs/css/main.css": "docs/_sass/main.scss"
        }
      },
      docsDist: {
        options: {
          sourceMap: false
        },
        files: {
          "docs/css/main.css": "docs/_sass/main.scss"
        }
      }
    },
    postcss: {
      options: {
        processors: [
          require('autoprefixer')({ browsers: ['last 2 version'] })
        ],
        map: {
          inline: false,
        }
      },
      dist: {
        options: {
          processors: [ require('cssnano')() ],
          map: false
        },
        src: 'dist/css/*.css'
      },
      dev: {
        src: 'dist/css/*.css'
      },
      docs: {
        src: 'docs/css/*.css'
      },
      docsDist: {
        options: {
          processors: [ require('cssnano')() ],
          map: false
        },
        src: 'docs/css/*.css'
      }
    },
    jekyll: {
      dev: {
        options: {
          src: "./docs",
          config: './docs/_config-dev.yml',
          dest: "./dist/docs"
        }
      },
      dist: {
        options: {
          src: "./docs",
          config: './docs/_config.yml',
          dest: "./dist/docs"
        }
      }
    },
    jshint: {
      options: {
        globals: {
          jQuery: true
        },
        immed: true,
        indent: 2,
        latedef: true,
        newcap: true,
        multistr: true
      },
      all: ['js/*.js', 'test/*.js']
    },
    eslint: {
    options: {
        configFile: '.eslintrc.json',
        reset: true
      },
      target: ['js/*.js']
    }
  });

  grunt.loadNpmTasks("grunt-contrib-watch");
  grunt.loadNpmTasks("grunt-contrib-jshint");
  grunt.loadNpmTasks("grunt-jekyll");
  grunt.loadNpmTasks("grunt-postcss");
  grunt.loadNpmTasks("grunt-sass");
  grunt.loadNpmTasks("grunt-pure-grids");
  grunt.loadNpmTasks("grunt-eslint");
  grunt.loadNpmTasks("eslint");

  // Build WFP UI Docs
  grunt.registerTask("docs-build", ["sass:docs", "postcss:docs", "jekyll:dev"]);
  grunt.registerTask("docs-dist", ["sass:docsDist", "postcss:docsDist", "jekyll:dist"]);
  // Build WFP UI
  grunt.registerTask("build", ["jshint", "pure_grids", "sass:dev", "postcss:dev"]);
  // Build a dist-ready WFP UI
  grunt.registerTask("dist", ["sass:dist", "postcss:dist"]);
  grunt.registerTask("default", ["dist"]);
};
<commit_msg>Remove 'eslint' from grunt<commit_after>// Gruntfile.js
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    watch: {
      sass: {
        files: "scss/**/*.scss",
        tasks: ["build"]
      },
      jshint: {
        files: "js/*.js",
        tasks: ["jshint"]
      },
      eslint: {
        files: "js/*.js",
        tasks: ["eslint"]
      },
      jekyll: {
        files: ["docs/**/*.*", "scss/**/**/*.scss"],
        tasks: ["docs-build"]
      }
    },
    pure_grids: {
      responsive: {
        dest: 'scss/modules/_grid-units.scss',
        options: {
          units: [5,12,24],
          mediaQueries: {
              sm: 'screen and (min-width: 32em)', //512px
              md: 'screen and (min-width: 48em)', //768px
              lg: 'screen and (min-width: 64em)', //1024px
              xl: 'screen and (min-width: 75em)'  //1200px
          },
          selectorPrefix: '.unit-'
        }
      }
    },
    sass: {
      options: {
        outputStyle: "expanded",
        sourceMap: true,
        indentedSyntax: true,
        sassDir: 'scss',
        cssDir: 'dist/ui'
      },
      dev: {
        files: [{
          expand: true,
          cwd: "scss/",
          src: ["*.scss"],
          dest: "dist/ui/",
          ext: ".css"
        }]
      },
      dist: {
        options: {
          sourceMap: false
        },
        files: [{
          expand: true,
          cwd: "scss/",
          src: ["*.scss"],
          dest: "dist/ui/",
          ext: ".css"
        }]
      },
      docs: {
        files: {
          "docs/css/main.css": "docs/_sass/main.scss"
        }
      },
      docsDist: {
        options: {
          sourceMap: false
        },
        files: {
          "docs/css/main.css": "docs/_sass/main.scss"
        }
      }
    },
    postcss: {
      options: {
        processors: [
          require('autoprefixer')({ browsers: ['last 2 version'] })
        ],
        map: {
          inline: false,
        }
      },
      dist: {
        options: {
          processors: [ require('cssnano')() ],
          map: false
        },
        src: 'dist/css/*.css'
      },
      dev: {
        src: 'dist/css/*.css'
      },
      docs: {
        src: 'docs/css/*.css'
      },
      docsDist: {
        options: {
          processors: [ require('cssnano')() ],
          map: false
        },
        src: 'docs/css/*.css'
      }
    },
    jekyll: {
      dev: {
        options: {
          src: "./docs",
          config: './docs/_config-dev.yml',
          dest: "./dist/docs"
        }
      },
      dist: {
        options: {
          src: "./docs",
          config: './docs/_config.yml',
          dest: "./dist/docs"
        }
      }
    },
    jshint: {
      options: {
        globals: {
          jQuery: true
        },
        immed: true,
        indent: 2,
        latedef: true,
        newcap: true,
        multistr: true
      },
      all: ['js/*.js', 'test/*.js']
    },
    eslint: {
    options: {
        configFile: '.eslintrc.json',
        reset: true
      },
      target: ['js/*.js']
    }
  });

  grunt.loadNpmTasks("grunt-contrib-watch");
  grunt.loadNpmTasks("grunt-contrib-jshint");
  grunt.loadNpmTasks("grunt-jekyll");
  grunt.loadNpmTasks("grunt-postcss");
  grunt.loadNpmTasks("grunt-sass");
  grunt.loadNpmTasks("grunt-pure-grids");
  grunt.loadNpmTasks("grunt-eslint");

  // Build WFP UI Docs
  grunt.registerTask("docs-build", ["sass:docs", "postcss:docs", "jekyll:dev"]);
  grunt.registerTask("docs-dist", ["sass:docsDist", "postcss:docsDist", "jekyll:dist"]);
  // Build WFP UI
  grunt.registerTask("build", ["jshint", "pure_grids", "sass:dev", "postcss:dev"]);
  // Build a dist-ready WFP UI
  grunt.registerTask("dist", ["sass:dist", "postcss:dist"]);
  grunt.registerTask("default", ["dist"]);
};
<|endoftext|>


<commit_before>var fs     = require('./file');
var logger = require('./log');

exports = module.exports = {
  /**
   * Main API function, running the whole thing
   * @param {String} source - Source folder
   * @param {String} destination - Destination folder
   * @example
   * documentize('examples/sass', 'examples/dist')
   */
  documentize: function (source, destination) {
    fs.folder.refresh(destination)
      .then(function () {
        logger.log('Folder `' + destination + '` successfully generated.');
        return fs.getData(source);
      })
      .then(function (data) {
        logger.log('Folder `' + source + '` successfully parsed.');
        return fs.generate(data, destination + '/index.html');
      })
      .then(function () {
        logger.log('Documentation for folder `' + source + '` successfully generated.');
        return fs.dumpAssets(destination);
      })
      .then(function () {
        logger.log('Process over. Everything okay!');
      })
      .fail(function (err) {
        console.log(err);
      });
  },

  /**
   * Parse a folder and returns a promise yielding an array of documented items
   * @param {String} source - Source folder
   * @example
   * sassdoc.parse('examples/sass')
   * @return {Q.promise}
   */
  parse: function (source) {
    return fs.getData(source);
  }

};
<commit_msg>Changed a console.log into a console.error<commit_after>var fs     = require('./file');
var logger = require('./log');

exports = module.exports = {
  /**
   * Main API function, running the whole thing
   * @param {String} source - Source folder
   * @param {String} destination - Destination folder
   * @example
   * documentize('examples/sass', 'examples/dist')
   */
  documentize: function (source, destination) {
    fs.folder.refresh(destination)
      .then(function () {
        logger.log('Folder `' + destination + '` successfully generated.');
        return fs.getData(source);
      })
      .then(function (data) {
        logger.log('Folder `' + source + '` successfully parsed.');
        return fs.generate(data, destination + '/index.html');
      })
      .then(function () {
        logger.log('Documentation for folder `' + source + '` successfully generated.');
        return fs.dumpAssets(destination);
      })
      .then(function () {
        logger.log('Process over. Everything okay!');
      })
      .fail(function (err) {
        console.error(err);
      });
  },

  /**
   * Parse a folder and returns a promise yielding an array of documented items
   * @param {String} source - Source folder
   * @example
   * sassdoc.parse('examples/sass')
   * @return {Q.promise}
   */
  parse: function (source) {
    return fs.getData(source);
  }

};
<|endoftext|>


<commit_before>module.exports = function(grunt) { // Grunt wrapper - Do grunt-related things in here

  grunt.initConfig({ // Initialize our configuration object
    pkg: grunt.file.readJSON('package.json'), // Read project settings from package.json

    //Set a path for the app folder.
    // The benifit of doing this is that when it comes time to start plugging in a cms we can just alter this to point to a new folder, for example the wordpress theme folder.
    path: 'app',

    copy: {
      snippets: {
      // This copies snippets from the src/snippets folder to the app/modules folder.
      // All snippets are added you just need to uncomment the ones you have included in your markup.
        files: {
          // '<%= path %>/modules/menu-d-float.php': ['src/snippets/menu-d-float.php'],
          // '<%= path %>/modules/menu-d-sticky.php': ['src/snippets/menu-d-sticky.php'],
          // '<%= path %>/modules/menu-m-flyout.php': ['src/snippets/menu-m-flyout.php'],
          // '<%= path %>/modules/holding-page-head.php': ['src/snippets/holding-page-head.php'],
          // '<%= path %>/modules/google-map.php': ['src/snippets/google-map.php'],
        }
      },

      modules: {
        // This copies the modules from the src folder to the app folder
        files: [
          {
            expand: true,
            cwd: 'src/modules/',
            src: ['*.php'],
            dest: '<%= path %>/modules/'
          }
        ]
      },

      includes: {
        // This copies the includes from the src folder to the app folder
        files: [
          {
            expand: true,
            cwd: 'src/includes/',
            src: ['*.php'],
            dest: '<%= path %>/includes/'
          }
        ]
      },

      pages: {
        // This copies the includes from the src folder to the app folder
        files: [
          {
            expand: true,
            cwd: 'src/pages/',
            src: ['*.php', '*.html', '.htaccess'],
            dest: '<%= path %>/'
          }
        ]
      },

      images: {
        // This copies the includes from the src folder to the app folder
        files: [
          {
            expand: true,
            cwd: 'src/images/',
            src: ['*.jpg', '*.png', '*.gif'],
            dest: '<%= path %>/images/'
          }
        ]
      },

      fontcopy:{
      //This task will find the relevant font files in the font folder and move them to the app folder.
        files: [
          {
            expand: true,
            cwd: 'src/fonts/',
            src: ['**/*.eot', '**/*.svg', '**/*.ttf', '**/*.woff'],
            dest: '<%= path %>/fonts/'
          }
        ]
      }
    },

    uglify: {
      // The base uglify task
      base: {
        options: {
          mangle: false,
          // If you want to add banners to your minified css uncomment the below. This currently is commented out in order to clean up commits in development.
          // banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
        },
        files: {
        '<%= path %>/js/custom.min.js': ['src/js/custom.js'],
        '<%= path %>/js/modernizer.min.js': ['src/js/modernizer.js']
        }
      },
      // The snippets uglify task for snippets with js files.
      // All snippets are added you just need to uncomment the ones you have included in your markup.
      snippets: {
        options: {
          mangle: false,
          // If you want to add banners to your minified css uncomment the below. This currently is commented out in order to clean up commits in development.
          // banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
        },
        files: {
        // '<%= path %>/js/google-map.min.js': ['src/snippets/google-map.js'],
        }
      }

    },

    jshint: {
      // The jshint task.
      files: [
      'src/js/custom.js', // Just watch the src js file not the minified one

      //The snippets
      // All snippets are listed below you just need to uncomment the ones you have included in order to have them tested when running "grunt test"

      //'src/snippets/google-map.js',
      ]
    },

    less: { // Configure the less task
      development: {
        options: {
          paths: ["src/less"],
        },
        files: {
          // target.css file: source.less file
          "src/css/style.css": "src/less/style.less"
        }
      }
    },

    autoprefixer: { // Configure the autoprefixer task
      options: {
        browsers: ['last 3 versions'] // More options available for this see https://github.com/ai/autoprefixer#browsers
      },
      files: {
        src: 'src/css/style.css',
        dest: 'src/css/style.css' // Put the autoprefixed version right back over its original
      },
    },

    cssmin: { // Now we can minify the auto-prefixed version of the code
      minify: {
        options: {
          // If you want to add banners to your minified css uncomment the below. This currently is commented out in order to clean up commits in development.
          // banner: '/* <%= pkg.name %>.css minified <%= grunt.template.today("dd-mm-yyyy") %> */' // Give it a nice banner
        },
        files: {
          '<%= path %>/css/style.min.css': ['src/css/style.css']
        }
      },
      fontmin: { //This task will find the stylesheet in the webkit folder, minify it and move it to the app folder
        files: [
          {
            expand: true,
            cwd: 'src/fonts/',
            src: ['**/*/stylesheet.css'],
            dest: '<%= path %>/fonts/',
            ext: '.min.css'
          }
        ]
      }
    },

    watch: {
    // Configure the watch task
    // You should adapt this to your specific needs on a per project basis
      snippets: {
        files: ['src/snippets/*.php'],
        tasks: ['copy:snippets'],
      },
      modules: {
        files: ['src/modules/*.php'],
        tasks: ['copy:modules'],
      },
      scripts: {
        files: ['<%= jshint.files %>'],
        tasks: ['jshint'],
      },
      uglify: {
        files: ['src/**/*.js'],
        tasks: ['uglify'],
      },
      css: {
        files: ['src/**/*.less'],
        tasks: ['less'],
      },
      cssmin: {
        files: ['src/css/style.css'],
        tasks: ['cssmin:minify'],
      },
      livereload: {
        // Here we watch the files the css task will compile to
        // These files are sent to the live reload server after css compiles to them
        options: { livereload: true },
        files: ['<%= path %>/**/*'],
      },
    }

  });

    // Load the tasks
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-autoprefixer');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-watch');

    // Register a test task for jshint. This can be run just by typing "grunt test" on the command line
    grunt.registerTask('test', ['jshint'])

    //Register a task for setting the snippets the first time
    grunt.registerTask('snippetload', ['copy:snippets', 'uglify:snippets'])

    //Register a task for setting the snippets the first time
    grunt.registerTask('moduleload', ['copy:modules'])

    //Register a task for setting up the webkit fonts when picking up the project
    grunt.registerTask('fontload', ['copy:fontcopy', 'cssmin:fontmin'])

    // And register the default task. This can be run just by typing "grunt" on the command line. This should be done before production.
    grunt.registerTask('default', ['copy:snippets', 'copy:modules', 'uglify', 'less', 'autoprefixer', 'cssmin']);

};<commit_msg>See #14. Add subtasks to the watch task. Reorder for ease of reading<commit_after>module.exports = function(grunt) { // Grunt wrapper - Do grunt-related things in here

  grunt.initConfig({ // Initialize our configuration object
    pkg: grunt.file.readJSON('package.json'), // Read project settings from package.json

    //Set a path for the app folder.
    // The benifit of doing this is that when it comes time to start plugging in a cms we can just alter this to point to a new folder, for example the wordpress theme folder.
    path: 'app',

    copy: {

      pages: {
        // This copies the pages from the src/pages folder to the app folder
        files: [
          {
            expand: true,
            cwd: 'src/pages/',
            src: ['*.php', '*.html', '.htaccess'],
            dest: '<%= path %>/'
          }
        ]
      },

      snippets: {
      // This copies snippets from the src/snippets folder to the app/modules folder.
      // All snippets are added you just need to uncomment the ones you have included in your markup.
        files: {
          // '<%= path %>/modules/menu-d-float.php': ['src/snippets/menu-d-float.php'],
          // '<%= path %>/modules/menu-d-sticky.php': ['src/snippets/menu-d-sticky.php'],
          // '<%= path %>/modules/menu-m-flyout.php': ['src/snippets/menu-m-flyout.php'],
          // '<%= path %>/modules/holding-page-head.php': ['src/snippets/holding-page-head.php'],
          // '<%= path %>/modules/google-map.php': ['src/snippets/google-map.php'],
        }
      },

      modules: {
        // This copies the modules from the src/modules folder to the app/modules folder
        files: [
          {
            expand: true,
            cwd: 'src/modules/',
            src: ['*.php'],
            dest: '<%= path %>/modules/'
          }
        ]
      },

      includes: {
        // This copies the includes from the src/includes folder to the app/includes folder
        files: [
          {
            expand: true,
            cwd: 'src/includes/',
            src: ['*.php'],
            dest: '<%= path %>/includes/'
          }
        ]
      },

      images: {
        // This copies the includes from the src/images folder to the app/images folder
        files: [
          {
            expand: true,
            cwd: 'src/images/',
            src: ['*.jpg', '*.png', '*.gif'],
            dest: '<%= path %>/images/'
          }
        ]
      },

      fontcopy:{
      //This task will find the relevant font files in the src/fonts folder and move them to the app/fonts folder.
        files: [
          {
            expand: true,
            cwd: 'src/fonts/',
            src: ['**/*.eot', '**/*.svg', '**/*.ttf', '**/*.woff'],
            dest: '<%= path %>/fonts/'
          }
        ]
      }
    },

    uglify: {
      // The base uglify task
      base: {
        options: {
          mangle: false,
          // If you want to add banners to your minified css uncomment the below. This currently is commented out in order to clean up commits in development.
          // banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
        },
        files: {
        '<%= path %>/js/custom.min.js': ['src/js/custom.js'],
        '<%= path %>/js/modernizer.min.js': ['src/js/modernizer.js']
        }
      },
      // The snippets uglify task for snippets with js files.
      // All snippets are added you just need to uncomment the ones you have included in your markup.
      snippets: {
        options: {
          mangle: false,
          // If you want to add banners to your minified css uncomment the below. This currently is commented out in order to clean up commits in development.
          // banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
        },
        files: {
        // '<%= path %>/js/google-map.min.js': ['src/snippets/google-map.js'],
        }
      }

    },

    jshint: {
      // The jshint task.
      files: [
      'src/js/custom.js', // Just watch the src js file not the minified one

      //The snippets
      // All snippets are listed below you just need to uncomment the ones you have included in order to have them tested when running "grunt test"

      //'src/snippets/google-map.js',
      ]
    },

    less: { // Configure the less task
      development: {
        options: {
          paths: ["src/less"],
        },
        files: {
          // target.css file: source.less file
          "src/css/style.css": "src/less/style.less"
        }
      }
    },

    autoprefixer: { // Configure the autoprefixer task
      options: {
        browsers: ['last 3 versions'] // More options available for this see https://github.com/ai/autoprefixer#browsers
      },
      files: {
        src: 'src/css/style.css',
        dest: 'src/css/style.css' // Put the autoprefixed version right back over its original
      },
    },

    cssmin: { // Now we can minify the auto-prefixed version of the code
      minify: {
        options: {
          // If you want to add banners to your minified css uncomment the below. This currently is commented out in order to clean up commits in development.
          // banner: '/* <%= pkg.name %>.css minified <%= grunt.template.today("dd-mm-yyyy") %> */' // Give it a nice banner
        },
        files: {
          '<%= path %>/css/style.min.css': ['src/css/style.css']
        }
      },
      fontmin: { //This task will find the stylesheet in the webkit folder, minify it and move it to the app folder
        files: [
          {
            expand: true,
            cwd: 'src/fonts/',
            src: ['**/*/stylesheet.css'],
            dest: '<%= path %>/fonts/',
            ext: '.min.css'
          }
        ]
      }
    },

    watch: {
    // Configure the watch task
    // You should adapt this to your specific needs on a per project basis
      pages: {
        files: ['src/pages/*.php'],
        tasks: ['copy:pages'],
      },
      snippets: {
        files: ['src/snippets/*.php'],
        tasks: ['copy:snippets'],
      },
      modules: {
        files: ['src/modules/*.php'],
        tasks: ['copy:modules'],
      },
      includes: {
        files: ['src/includes/*.php'],
        tasks: ['copy:includes'],
      },
      images: {
        files: ['src/images/*'],
        tasks: ['copy:images'],
      },
      scripts: {
        files: ['<%= jshint.files %>'],
        tasks: ['jshint'],
      },
      uglify: {
        files: ['src/**/*.js'],
        tasks: ['uglify'],
      },
      css: {
        files: ['src/**/*.less'],
        tasks: ['less'],
      },
      cssmin: {
        files: ['src/css/style.css'],
        tasks: ['cssmin:minify'],
      },
      livereload: {
        // Here we watch the files the css task will compile to
        // These files are sent to the live reload server after css compiles to them
        options: { livereload: true },
        files: ['<%= path %>/**/*'],
      },
    }

  });

    // Load the tasks
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-autoprefixer');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-watch');

    // Register a test task for jshint. This can be run just by typing "grunt test" on the command line
    grunt.registerTask('test', ['jshint'])

    //Register a task for setting the snippets the first time
    grunt.registerTask('snippetload', ['copy:snippets', 'uglify:snippets'])

    //Register a task for setting the snippets the first time
    grunt.registerTask('moduleload', ['copy:modules'])

    //Register a task for setting up the webkit fonts when picking up the project
    grunt.registerTask('fontload', ['copy:fontcopy', 'cssmin:fontmin'])

    // And register the default task. This can be run just by typing "grunt" on the command line. This should be done before production.
    grunt.registerTask('default', ['copy:snippets', 'copy:modules', 'uglify', 'less', 'autoprefixer', 'cssmin']);

};<|endoftext|>


<commit_before>import Postgrest from 'mithril-postgrest';

const platformTokenMeta = document.querySelector('[name="common-platform-token"]');
const platformToken = platformTokenMeta.getAttribute('content');
const commonRequestHeader = { 'Platform-Code': platformToken };
const apiInit = (api, authUrl, globalHeader) => {
    api.init(catarseApiMeta.getAttribute('content'), { method: 'GET', url: authUrl }, globalHeader);
}

const catarse = new Postgrest();
const catarseApiMeta = document.querySelector('[name="api-host"]');
apiInit(catarse, '/api_token');

const commonPayment = new Postgrest();
const commonPaymentApiMeta = document.querySelector('[name="common-payment-api-host"]');
apiInit(commonPayment, '/api_token/common', commonRequestHeader);

const commonProject = new Postgrest();
const commonProjectApiMeta = document.querySelector('[name="common-project-api-host"]');
apiInit(commonProject, '/api_token/common', commonRequestHeader);

const commonAnalytics = new Postgrest();
const commonAnalyticsApiMeta = document.querySelector('[name="common-analytics-api-host"]');
apiInit(commonAnalytics, '/api_token/common', commonRequestHeader);

export { catarse, commonPayment, commonProject, commonAnalytics };
<commit_msg>apiInit should receive a apiMeta for every service<commit_after>import Postgrest from 'mithril-postgrest';

const platformTokenMeta = document.querySelector('[name="common-platform-token"]');
const platformToken = platformTokenMeta ? platformTokenMeta.getAttribute('content') : null;
const commonRequestHeader = { 'Platform-Code': platformToken };

const apiInit = (api, apiMeta, authUrl, globalHeader) => {
    api.init(apiMeta.getAttribute('content'), { method: 'GET', url: authUrl }, globalHeader);
}

const catarse = new Postgrest();
const catarseApiMeta = document.querySelector('[name="api-host"]');
apiInit(catarse, catarseApiMeta, '/api_token');

const commonPayment = new Postgrest();
const commonPaymentApiMeta = document.querySelector('[name="common-payment-api-host"]');
apiInit(commonPayment, commonPaymentApiMeta,'/api_token/common', commonRequestHeader);

const commonProject = new Postgrest();
const commonProjectApiMeta = document.querySelector('[name="common-project-api-host"]');
apiInit(commonProject, commonProjectApiMeta,'/api_token/common', commonRequestHeader);

const commonAnalytics = new Postgrest();
const commonAnalyticsApiMeta = document.querySelector('[name="common-analytics-api-host"]');
apiInit(commonAnalytics, commonAnalyticsApiMeta, '/api_token/common', commonRequestHeader);

export { catarse, commonPayment, commonProject, commonAnalytics };
<|endoftext|>


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

define(function(require) {
  /*
    DEPENDENCIES
   */

//  require('foundation.slider');
  var Locale = require('utils/locale');
  var Tips = require('utils/tips');
  var WizardFields = require('utils/wizard-fields');
  var UserInputs = require('utils/user-inputs');
  var Config = require('sunstone-config');

  /*
    TEMPLATES
   */

  var TemplateHTML = require('hbs!./capacity-inputs/html');

  /*
    CONSTRUCTOR
   */

  return {
    'html': _html,
    'setup': _setup,
    'setCallback': _setCallback,
    'fill': _fill,
    'retrieve': _retrieve,
    'retrieveChanges': _retrieveChanges
  };

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML();
  }

  function _setup(context) {
    if (Config.isFeatureEnabled("instantiate_hide_cpu")){
      $(".cpu_input_wrapper", context).hide();
    }

    Tips.setup(context);
  }

  /**
   * Fills the capacity inputs
   * @param  {Object} context  JQuery selector
   * @param  {Object} template VM or VMTemplate object
   */
  function _fill(context, element) {
    var fields = $('[wizard_field]', context);

    fields.each(function() {
      var field_name = $(this).attr('wizard_field');
      $(this).data("original_value", element.TEMPLATE[field_name]);
    });

    var userInputs;

    if (element.USER_TEMPLATE != undefined){
      userInputs = element.USER_TEMPLATE.USER_INPUTS;
    } else {
      userInputs = element.TEMPLATE.USER_INPUTS;
    }

    var attr;
    var input;

    if (userInputs != undefined && userInputs.CPU != undefined){
      attr = UserInputs.parse("CPU", userInputs.CPU);
    } else {
      attr = UserInputs.parse("CPU", "O|number-float|||");
    }

    if (element.TEMPLATE.CPU != undefined){
      attr.initial = element.TEMPLATE.CPU;
    } else {
      attr.mandatory = true;
    }

    attr.step = 0.01;

    if(attr.min == undefined){
      attr.min = 0.01;
    }

    input = UserInputs.attributeInput(attr);

    if (attr.type != "range-float"){
      $("div.cpu_input_wrapper", context).addClass("medium-6");
    }

    $("div.cpu_input", context).html(input);

    if (userInputs != undefined && userInputs.VCPU != undefined){
      attr = UserInputs.parse("VCPU", userInputs.VCPU);
    } else {
      attr = UserInputs.parse("VCPU", "O|number|||");
    }

    if (element.TEMPLATE.VCPU != undefined){
      attr.initial = element.TEMPLATE.VCPU;
    }

    if(attr.min == undefined){
      attr.min = 1;
    }

    input = UserInputs.attributeInput(attr);

    if (attr.type != "range"){
      $("div.vcpu_input_wrapper", context).addClass("medium-6");
    }

    $("div.vcpu_input", context).html(input);

    if (Config.isFeatureEnabled("instantiate_cpu_factor")){
      $("div.cpu_input input", context).prop("disabled", true);
      $("div.vcpu_input input", context).on("change", function(){
        var vcpuValue = $("div.vcpu_input input", context).val();
        $("div.cpu_input input", context).val(vcpuValue * Config.scaleFactor);
      });
    } else {
        $("div.vcpu_input input", context).on("change", function(){
        var vcpuValue = $("div.vcpu_input input", context).val();
        $("div.cpu_input input", context).val(vcpuValue);
      });
    }

    if (userInputs != undefined && userInputs.MEMORY != undefined){
      attr = UserInputs.parse("MEMORY", userInputs.MEMORY);
    } else {
      attr = UserInputs.parse("MEMORY", "O|number|||");
    }

    if (element.TEMPLATE.MEMORY != undefined){
      attr.initial = element.TEMPLATE.MEMORY;
    } else {
      attr.mandatory = true;
    }

    if(attr.min == undefined){
      attr.min = 1;
    }

    if (attr.type != "range"){
      $("div.memory_input_wrapper", context).addClass("large-6").addClass("medium-8");
    }

    UserInputs.insertAttributeInputMB(attr, $("div.memory_input", context));

    if (Config.isFeatureEnabled("instantiate_hide_cpu")){
      $(".vcpu_input input", context).prop("required", true);
    }
  }

  /**
   * Sets a callback that will be called when the input values change
   * @param {Object}   context  jQuery selector
   * @param {Function} callback will be called as callback( retrieve(context) )
   */
  function _setCallback(context, callback) {
    context.on("change", function(){
      callback( _retrieve(context) );
    });

    callback( _retrieve(context) );
  }

  /**
   * Retrieves the input values
   * @param  {Object} context  JQuery selector
   * @return {Object}         If the input is not empty, returns:
   *                                  - CPU
   *                                  - MEMORY
   *                                  - VCPU
   */
  function _retrieve(context) {
    var values = WizardFields.retrieve(context);

    return values;
  }

  /**
   * Retrieves the input values, but only if the value has changed from the
   * original set in fill()
   * @param  {Object} context  JQuery selector
   * @return {Object}         If the input has changed, returns:
   *                                  - CPU
   *                                  - MEMORY
   *                                  - VCPU
   */
  function _retrieveChanges(context) {
    var templateJSON = WizardFields.retrieve(context);

    var fields = $('[wizard_field]', context);

    fields.each(function() {
      var field_name = $(this).attr('wizard_field');
      if (templateJSON[field_name] == $(this).data("original_value")){
        delete templateJSON[field_name];
      }
    });

    return templateJSON;
  }
});
<commit_msg>B #5529: Unable to set CPU first, it always get values from vCPU (#558)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

//  require('foundation.slider');
  var Locale = require('utils/locale');
  var Tips = require('utils/tips');
  var WizardFields = require('utils/wizard-fields');
  var UserInputs = require('utils/user-inputs');
  var Config = require('sunstone-config');

  /*
    TEMPLATES
   */

  var TemplateHTML = require('hbs!./capacity-inputs/html');

  /*
    CONSTRUCTOR
   */

  return {
    'html': _html,
    'setup': _setup,
    'setCallback': _setCallback,
    'fill': _fill,
    'retrieve': _retrieve,
    'retrieveChanges': _retrieveChanges
  };

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML();
  }

  function _setup(context) {
    if (Config.isFeatureEnabled("instantiate_hide_cpu")){
      $(".cpu_input_wrapper", context).hide();
    }

    Tips.setup(context);
  }

  /**
   * Fills the capacity inputs
   * @param  {Object} context  JQuery selector
   * @param  {Object} template VM or VMTemplate object
   */
  function _fill(context, element) {
    var fields = $('[wizard_field]', context);

    fields.each(function() {
      var field_name = $(this).attr('wizard_field');
      $(this).data("original_value", element.TEMPLATE[field_name]);
    });

    var userInputs;

    if (element.USER_TEMPLATE != undefined){
      userInputs = element.USER_TEMPLATE.USER_INPUTS;
    } else {
      userInputs = element.TEMPLATE.USER_INPUTS;
    }

    var attr;
    var input;

    if (userInputs != undefined && userInputs.CPU != undefined){
      attr = UserInputs.parse("CPU", userInputs.CPU);
    } else {
      attr = UserInputs.parse("CPU", "O|number-float|||");
    }

    if (element.TEMPLATE.CPU != undefined){
      attr.initial = element.TEMPLATE.CPU;
    } else {
      attr.mandatory = true;
    }

    attr.step = 0.01;

    if(attr.min == undefined){
      attr.min = 0.01;
    }

    input = UserInputs.attributeInput(attr);

    if (attr.type != "range-float"){
      $("div.cpu_input_wrapper", context).addClass("medium-6");
    }

    $("div.cpu_input", context).html(input);

    if (userInputs != undefined && userInputs.VCPU != undefined){
      attr = UserInputs.parse("VCPU", userInputs.VCPU);
    } else {
      attr = UserInputs.parse("VCPU", "O|number|||");
    }

    if (element.TEMPLATE.VCPU != undefined){
      attr.initial = element.TEMPLATE.VCPU;
    }

    if(attr.min == undefined){
      attr.min = 1;
    }

    input = UserInputs.attributeInput(attr);

    if (attr.type != "range"){
      $("div.vcpu_input_wrapper", context).addClass("medium-6");
    }

    $("div.vcpu_input", context).html(input);

    if (Config.isFeatureEnabled("instantiate_cpu_factor")){
      $("div.cpu_input input", context).prop("disabled", true);
      $("div.vcpu_input input", context).on("change", function(){
        var vcpuValue = $("div.vcpu_input input", context).val();
        $("div.cpu_input input", context).val(vcpuValue * Config.scaleFactor);
      });
    }

    if (userInputs != undefined && userInputs.MEMORY != undefined){
      attr = UserInputs.parse("MEMORY", userInputs.MEMORY);
    } else {
      attr = UserInputs.parse("MEMORY", "O|number|||");
    }

    if (element.TEMPLATE.MEMORY != undefined){
      attr.initial = element.TEMPLATE.MEMORY;
    } else {
      attr.mandatory = true;
    }

    if(attr.min == undefined){
      attr.min = 1;
    }

    if (attr.type != "range"){
      $("div.memory_input_wrapper", context).addClass("large-6").addClass("medium-8");
    }

    UserInputs.insertAttributeInputMB(attr, $("div.memory_input", context));

    if (Config.isFeatureEnabled("instantiate_hide_cpu")){
      $(".vcpu_input input", context).prop("required", true);
    }
  }

  /**
   * Sets a callback that will be called when the input values change
   * @param {Object}   context  jQuery selector
   * @param {Function} callback will be called as callback( retrieve(context) )
   */
  function _setCallback(context, callback) {
    context.on("change", function(){
      callback( _retrieve(context) );
    });

    callback( _retrieve(context) );
  }

  /**
   * Retrieves the input values
   * @param  {Object} context  JQuery selector
   * @return {Object}         If the input is not empty, returns:
   *                                  - CPU
   *                                  - MEMORY
   *                                  - VCPU
   */
  function _retrieve(context) {
    var values = WizardFields.retrieve(context);

    return values;
  }

  /**
   * Retrieves the input values, but only if the value has changed from the
   * original set in fill()
   * @param  {Object} context  JQuery selector
   * @return {Object}         If the input has changed, returns:
   *                                  - CPU
   *                                  - MEMORY
   *                                  - VCPU
   */
  function _retrieveChanges(context) {
    var templateJSON = WizardFields.retrieve(context);

    var fields = $('[wizard_field]', context);

    fields.each(function() {
      var field_name = $(this).attr('wizard_field');
      if (templateJSON[field_name] == $(this).data("original_value")){
        delete templateJSON[field_name];
      }
    });

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