<commit_before>var r = require('rethinkdb');
var Boom = require('boom');

exports.register = function(server, options, next) {
  server.route([
    {
      method: 'GET',
      path: '/messages/{id?}',
      config: {
        handler: function(req, reply) {
          if (req.params.id) {
            r.table('messages')
              .get(req.params.id)
              .run(req.server._rdbConn, function(err, result) {
                if (err) {
                  return reply(Boom.badImplementation(err));
                }
                return reply(result);
              });
          } else {
            r.table('messages')
            .run(req.server._rdbConn, function(err, result) {
              if (err) {
                return reply(Boom.badImplementation(err));
              }
              result.toArray(function(error, arrayResult) {
                if (error) {
                  return reply(Boom.badImplementation(error));
                }
                return reply(arrayResult);
              });
            });
          }
        }
      }
    },
    {
      method: 'POST',
      path: '/messages',
      config: {
        handler: function(req, reply) {
          var message = Object.assign(req.payload,
                                      {createdAt: new Date()});

          r.table('messages')
            .insert(message, {returnChanges: true})
            .run(req.server._rdbConn, function(err, result) {
              if (err) {
                return reply(Boom.badImplementation(err));
              }
              return reply(result.changes[0].new_val);
            });
        }
      }
    },
    {
      method: 'DELETE',
      path: '/messages/{id}',
      config: {
        handler: function(req, reply) {
          if (req.params.id) {
            r.table('messages')
              .get(req.params.id)
              .delete({returnChanges: true})
              .run(req.server._rdbConn, function(err, result) {
                if (err) {
                  return reply(Boom.badImplementation(err));
                }
                return reply(result);
              });
          } else {
            return reply(Boom.badImplementation());
          }
        }
      }
    }
  ]);

  next();
};

exports.register.attributes = {
  name: 'messages'
};
<commit_msg>404 on no documents found<commit_after>var r = require('rethinkdb');
var Boom = require('boom');

exports.register = function(server, options, next) {
  server.route([
    {
      method: 'GET',
      path: '/messages/{id?}',
      config: {
        handler: function(req, reply) {
          if (req.params.id) {
            r.table('messages')
              .get(req.params.id)
              .run(req.server._rdbConn, function(err, result) {
                if (err) {
                  return reply(Boom.badImplementation(err));
                }
                if (result) {
                  return reply(result);
                }
                return reply(Boom.notFound());
              });
          } else {
            r.table('messages')
              .run(req.server._rdbConn, function(err, result) {
                if (err) {
                  return reply(Boom.badImplementation(err));
                }
                result.toArray(function(error, arrayResult) {
                  if (error) {
                    return reply(Boom.badImplementation(error));
                  }
                  return reply(arrayResult);
                });
              });
          }
        }
      }
    },
    {
      method: 'POST',
      path: '/messages',
      config: {
        handler: function(req, reply) {
          var message = Object.assign(req.payload,
                                      {createdAt: new Date()});

          r.table('messages')
            .insert(message, {returnChanges: true})
            .run(req.server._rdbConn, function(err, result) {
              if (err) {
                return reply(Boom.badImplementation(err));
              }
              return reply(result.changes[0].new_val);
            });
        }
      }
    },
    {
      method: 'DELETE',
      path: '/messages/{id}',
      config: {
        handler: function(req, reply) {
          if (req.params.id) {
            r.table('messages')
              .get(req.params.id)
              .delete({returnChanges: true})
              .run(req.server._rdbConn, function(err, result) {
                if (err) {
                  return reply(Boom.badImplementation(err));
                }
                return reply(result);
              });
          } else {
            return reply(Boom.badImplementation());
          }
        }
      }
    }
  ]);

  next();
};

exports.register.attributes = {
  name: 'messages'
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var Game = require('../../models/game/game.model');
var User = require('../../models/user/user.model');
var verifyToken = require('../login/verifyToken');
var Rating = require('../../models/rating/rating.model');
var constants = require('../../config/constants.config');
var check = require('check-types');
var _ = require('lodash');

router.use(function (req, res, next) {
	next();
});

module.exports = function (app) {
	var validateGameQuery = function (req, res, next) {
		if (!req.body.title || !req.body.mainDescription) return res.status(422).json({message: constants.httpResponseMessages.unprocessableEntity});
		else next();
	};

	router.post('/games', verifyToken, validateGameQuery, function (req, res) {
		var game = new Game(_.extend(req.body, {owner: req.verified.id}));
		game.save(function (err) {
			if (err) {
				console.log(err);
				res.status(500);
				res.json({message: constants.httpResponseMessages.internalServerError});
				return;
			}
			game.populate('owner', 'username', function (err) {
				if (err) res.status(500).json({message: constants.httpResponseMessages.internalServerError});
				else return res.status(201).json(game);
			});
		});
	});

	var parseSearchQuery = function (req, res, next) {
		var query = {};
		if (req.query.title) query.title = {'$regex': req.query.title, '$options': 'i'};
		if (req.query.singles) query['pieces.singles'] = {'$lte': req.query.singles};
		if (req.query.doubles) query['pieces.doubles'] = {'$lte': req.query.doubles};
		if (req.query.triples) query['pieces.triples'] = {'$lte': req.query.triples};
		if (req.query.numberOfPlayers) query.numberOfPlayers = {'$lte': req.query.numberOfPlayers};
		if (req.query.owner) query.owner = req.query.owner;
		if (req.query.search) query['$text'] = {$search: req.query.search};
		req.query = query;
		next();
	};

	var populateOwnerField = function (req, res, next) {
		if (!req.query) {
			req.query = {};
			next();
		}
		if (req.query.owner) {
			User.findOne({username: req.query.owner}, '-password -__v', function (err, user) {
				if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
				if (user == null) return res.status(200).json({});
				else req.query.owner = user._id;
				next();
			});
		}
		else next();
	};

	router.route('/games').get(populateOwnerField, parseSearchQuery, function (req, res) {
		Game.find(req.query, '-__v', function (err, game) {
			if (err) res.status(500).json({mesage: constants.httpResponseMessages.internalServerError});
			else res.json(game);
		}).populate('owner', 'username');
	});

	router.route('/games/:game_id')
		.get(function (req, res) {
			Game.findById(req.params.game_id, function (err, game) {
				if (err) return res.send(constants.httpResponseMessages.internalServerError);
				if (game == null) return res.status(404).json({message: constants.httpResponseMessages.notFound});
				else return res.json(game);
			}).populate('owner', 'username');
		})
		.put(verifyToken, function (req, res) {
			Game.findById({_id: req.params.game_id}, function (err, game) { // TODO: Validate id before doing db call
				if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
				if (!game) return res.status(404).json({message: constants.httpResponseMessages.badRequest});
				if (req.body.title) game.title = req.body.title;
				if (req.body.mainDescription) game.mainDescription = req.body.mainDescription;
				game.save(function (err, game) {
					if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
					game.populate('owner', 'username', function (err) {
						if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
						return res.status(200).json(game);
					});
				});
			});
		})
		.delete(verifyToken, function (req, res) {
			Game.remove({
				_id: req.params.game_id
			}, function (err, game) {
				if (!game) {
					return res.status(404).json({message: constants.httpResponseMessages.notFound});
				}
				if (err) res.send(err);
				else res.status(204).json({message: constants.httpResponseMessages.deleted});
			});
		});

	router.route('/games/:game_id/ratings')
		.put(verifyToken, function (req, res) {
			if (!req.body.rating) {
				return res.status(400).json({message: constants.httpResponseMessages.badRequest});
			}
			Game.findById(req.params.game_id, function (err, game) {
				if (err) {
					return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
				}
				if (game === null) return res.status(404).json({message: constants.httpResponseMessages.notFound});
				var newRating;
				var newVoteCount;
				Rating.findOne({_userId: req.verified.id, _gameId: req.params.game_id}, function (err, rating) {
					if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
					if (rating !== null) {
						if (rating.rating === req.params.rating) {
							return res.status(409).json({message: constants.httpResponseMessages.conflict});
						}
						newRating = game.sumOfVotes;
						newRating -= rating.rating;
						newRating += req.body.rating;
						newVoteCount = game.numberOfVotes;
					}
					else {
						newRating = game.sumOfVotes + req.body.rating;
						newVoteCount = game.numberOfVotes;
						newVoteCount++;
					};
					Rating.findOneAndUpdate({_userId: req.verified.id, _gameId: req.params.game_id}, {rating: req.body.rating}, {upsert: true}, function (err) {
						if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
						Game.findOneAndUpdate({_id: req.params.game_id}, {numberOfVotes: newVoteCount, sumOfVotes: newRating}, {upsert: false}, function (err) {
							if (err) {
								return;
							}
							return res.status(204).json({message: constants.httpResponseMessages.ok});
						});
					});
				});
			});
		});
	return router;
};
<commit_msg>change description propertyname<commit_after>var express = require('express');
var router = express.Router();
var Game = require('../../models/game/game.model');
var User = require('../../models/user/user.model');
var verifyToken = require('../login/verifyToken');
var Rating = require('../../models/rating/rating.model');
var constants = require('../../config/constants.config');
var check = require('check-types');
var _ = require('lodash');

router.use(function (req, res, next) {
	next();
});

module.exports = function (app) {
	var validateGameQuery = function (req, res, next) {
		if (!req.body.title || !req.body.shortDescription) return res.status(422).json({message: constants.httpResponseMessages.unprocessableEntity});
		else next();
	};

	router.post('/games', verifyToken, validateGameQuery, function (req, res) {
		var game = new Game(_.extend(req.body, {owner: req.verified.id}));
		game.save(function (err) {
			if (err) {
				console.log(err);
				res.status(500);
				res.json({message: constants.httpResponseMessages.internalServerError});
				return;
			}
			game.populate('owner', 'username', function (err) {
				if (err) res.status(500).json({message: constants.httpResponseMessages.internalServerError});
				else return res.status(201).json(game);
			});
		});
	});

	var parseSearchQuery = function (req, res, next) {
		var query = {};
		if (req.query.title) query.title = {'$regex': req.query.title, '$options': 'i'};
		if (req.query.singles) query['pieces.singles'] = {'$lte': req.query.singles};
		if (req.query.doubles) query['pieces.doubles'] = {'$lte': req.query.doubles};
		if (req.query.triples) query['pieces.triples'] = {'$lte': req.query.triples};
		if (req.query.numberOfPlayers) query.numberOfPlayers = {'$lte': req.query.numberOfPlayers};
		if (req.query.owner) query.owner = req.query.owner;
		if (req.query.search) query['$text'] = {$search: req.query.search};
		req.query = query;
		next();
	};

	var populateOwnerField = function (req, res, next) {
		if (!req.query) {
			req.query = {};
			next();
		}
		if (req.query.owner) {
			User.findOne({username: req.query.owner}, '-password -__v', function (err, user) {
				if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
				if (user == null) return res.status(200).json({});
				else req.query.owner = user._id;
				next();
			});
		}
		else next();
	};

	router.route('/games').get(populateOwnerField, parseSearchQuery, function (req, res) {
		Game.find(req.query, '-__v', function (err, game) {
			if (err) res.status(500).json({mesage: constants.httpResponseMessages.internalServerError});
			else res.json(game);
		}).populate('owner', 'username');
	});

	router.route('/games/:game_id')
		.get(function (req, res) {
			Game.findById(req.params.game_id, function (err, game) {
				if (err) return res.send(constants.httpResponseMessages.internalServerError);
				if (game == null) return res.status(404).json({message: constants.httpResponseMessages.notFound});
				else return res.json(game);
			}).populate('owner', 'username');
		})
		.put(verifyToken, function (req, res) {
			Game.findById({_id: req.params.game_id}, function (err, game) { // TODO: Validate id before doing db call
				if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
				if (!game) return res.status(404).json({message: constants.httpResponseMessages.badRequest});
				if (req.body.title) game.title = req.body.title;
				if (req.body.mainDescription) game.mainDescription = req.body.mainDescription;
				game.save(function (err, game) {
					if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
					game.populate('owner', 'username', function (err) {
						if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
						return res.status(200).json(game);
					});
				});
			});
		})
		.delete(verifyToken, function (req, res) {
			Game.remove({
				_id: req.params.game_id
			}, function (err, game) {
				if (!game) {
					return res.status(404).json({message: constants.httpResponseMessages.notFound});
				}
				if (err) res.send(err);
				else res.status(204).json({message: constants.httpResponseMessages.deleted});
			});
		});

	router.route('/games/:game_id/ratings')
		.put(verifyToken, function (req, res) {
			if (!req.body.rating) {
				return res.status(400).json({message: constants.httpResponseMessages.badRequest});
			}
			Game.findById(req.params.game_id, function (err, game) {
				if (err) {
					return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
				}
				if (game === null) return res.status(404).json({message: constants.httpResponseMessages.notFound});
				var newRating;
				var newVoteCount;
				Rating.findOne({_userId: req.verified.id, _gameId: req.params.game_id}, function (err, rating) {
					if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
					if (rating !== null) {
						if (rating.rating === req.params.rating) {
							return res.status(409).json({message: constants.httpResponseMessages.conflict});
						}
						newRating = game.sumOfVotes;
						newRating -= rating.rating;
						newRating += req.body.rating;
						newVoteCount = game.numberOfVotes;
					}
					else {
						newRating = game.sumOfVotes + req.body.rating;
						newVoteCount = game.numberOfVotes;
						newVoteCount++;
					};
					Rating.findOneAndUpdate({_userId: req.verified.id, _gameId: req.params.game_id}, {rating: req.body.rating}, {upsert: true}, function (err) {
						if (err) return res.status(500).json({message: constants.httpResponseMessages.internalServerError});
						Game.findOneAndUpdate({_id: req.params.game_id}, {numberOfVotes: newVoteCount, sumOfVotes: newRating}, {upsert: false}, function (err) {
							if (err) {
								return;
							}
							return res.status(204).json({message: constants.httpResponseMessages.ok});
						});
					});
				});
			});
		});
	return router;
};
<|endoftext|>


<commit_before>/**
 * When using enketo-core in your own app, you'd want to replace
 * this build file with one of your own in your project root.
 */

/*jshint node:true*/
"use strict";

module.exports = function( grunt ) {
    var js;

    // Project configuration.
    grunt.initConfig( {
        pkg: grunt.file.readJSON( 'package.json' ),
        connect: {
            server: {
                options: {
                    port: 8080
                }
            },
            test: {
                options: {
                    port: 8000
                }
            }
        },
        jsbeautifier: {
            test: {
                src: [ "*.js", "src/js/*.js", "src/widget/*/*.js" ],
                options: {
                    config: "./.jsbeautifyrc",
                    mode: "VERIFY_ONLY"
                }
            },
            fix: {
                src: [ "src/js/*.js", "src/widget/*/*.js" ],
                options: {
                    config: "./.jsbeautifyrc"
                }
            }
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            all: [ '*.js', 'src/js/**/*.js', '!src/js/extern.js' ]
        },
        watch: {
            sass: {
                files: [ 'config.json', 'src/**/*.scss' ],
                tasks: [ 'style' ],
                options: {
                    spawn: false
                }
            },
            js: {
                files: [ '*.js', 'src/**/*.js', 'build/**/*.css' ],
                tasks: [ 'modernizr' ],
                options: {
                    spawn: false
                }
            }
        },
        jasmine: {
            test: {
                src: 'src/js/**/*.js',
                options: {
                    keepRunner: true,
                    specs: 'test/spec/*.js',
                    helpers: [ 'test/util/*.js', 'test/mock/*.js' ],
                    host: 'http://127.0.0.1:8000/',
                    template: require( 'grunt-template-jasmine-requirejs' ),
                    templateOptions: {
                        requireConfig: {
                            baseUrl: 'lib',
                            paths: {
                                'enketo-js': '../src/js',
                                'enketo-widget': '../src/widget',
                                'enketo-config': '../config.json',
                                text: 'text/text',
                                xpath: 'xpath/build/xpathjs_javarosa',
                                'jquery.xpath': 'jquery-xpath/jquery.xpath'
                            },
                            shim: {
                                'xpath': {
                                    exports: 'XPathJS'
                                },
                                'bootstrap': {
                                    deps: [ 'jquery' ],
                                    exports: 'jQuery.fn.bootstrap'
                                },
                                'widget/date/bootstrap3-datepicker/js/bootstrap-datepicker': {
                                    deps: [ 'jquery' ],
                                    exports: 'jQuery.fn.datepicker'
                                },
                                'widget/time/bootstrap3-timepicker/js/bootstrap-timepicker': {
                                    deps: [ 'jquery' ],
                                    exports: 'jQuery.fn.timepicker'
                                }
                            },
                            map: {
                                '*': {
                                    'enketo-js': '../src/js',
                                    'enketo-widget': '../src/widget'
                                }
                            }
                        }
                    }
                },
            }
        },
        prepWidgetSass: {
            writePath: 'src/sass/_widgets.scss',
            widgetConfigPath: 'config.json'
        },
        sass: {
            dist: {
                options: {
                    style: 'compressed',
                    noCache: true
                },
                files: [ {
                    expand: true,
                    cwd: 'src/sass',
                    src: [ '**/*.scss', '!**/_*.scss' ],
                    dest: 'build/css',
                    ext: '.css'
                } ]
            }
        },
        // this compiles all javascript to a single minified file
        requirejs: {
            compile: {
                options: {
                    name: '../app',
                    baseUrl: 'lib',
                    mainConfigFile: "app.js",
                    findNestedDependencies: true,
                    include: ( function() {
                        //add widgets js and widget config.json files
                        var widgets = grunt.file.readJSON( 'config.json' ).widgets;
                        widgets.forEach( function( widget, index, arr ) {
                            arr.push( 'text!' + widget.substr( 0, widget.lastIndexOf( '/' ) + 1 ) + 'config.json' );
                        } );
                        return [ 'require.js', 'enketo-js/Widget' ].concat( widgets );
                    } )(),
                    out: "build/js/combined.min.js",
                    optimize: "uglify2"
                }
            }
        },
        modernizr: {
            "devFile": "remote",
            "outputFile": "lib/Modernizr.js",
            "extra": {
                "shiv": false,
                "printshiv": true,
                "load": false,
                "mq": false,
                "cssclasses": true
            },
            "uglify": false,
            "parseFiles": true
        }
    } );

    grunt.loadNpmTasks( 'grunt-contrib-connect' );
    grunt.loadNpmTasks( 'grunt-jsbeautifier' );
    grunt.loadNpmTasks( 'grunt-contrib-jasmine' );
    grunt.loadNpmTasks( 'grunt-contrib-watch' );
    grunt.loadNpmTasks( 'grunt-contrib-jshint' );
    grunt.loadNpmTasks( 'grunt-contrib-sass' );
    grunt.loadNpmTasks( 'grunt-contrib-requirejs' );
    grunt.loadNpmTasks( "grunt-modernizr" );

    //maybe this can be turned into a npm module?
    grunt.registerTask( 'prepWidgetSass', 'Preparing _widgets.scss dynamically', function() {
        var widgetConfig, widgetFolderPath, widgetSassPath, widgetConfigPath,
            config = grunt.config( 'prepWidgetSass' ),
            widgets = grunt.file.readJSON( config.widgetConfigPath ).widgets,
            content = '// Dynamically created list of widget stylesheets to import based on the content\r\n' +
                '// based on the content of config.json\r\n\r\n';

        widgets.forEach( function( widget ) {
            if ( widget.indexOf( 'enketo-widget/' ) === 0 ) {
                //strip require.js module name
                widgetFolderPath = widget.substr( 0, widget.lastIndexOf( '/' ) + 1 );
                //replace widget require.js path shortcut with proper path relative to src/js
                widgetSassPath = widgetFolderPath.replace( /^enketo-widget\//, '../widget/' );
                //create path to widget config file
                widgetConfigPath = widgetFolderPath.replace( /^enketo-widget\//, 'src/widget/' ) + 'config.json';
                grunt.log.writeln( 'widget config path: ' + widgetConfigPath );
                //create path to widget stylesheet file
                widgetSassPath += grunt.file.readJSON( widgetConfigPath ).stylesheet;
            } else {
                grunt.log.error( [ 'Expected widget path "' + widget + '" in config.json to be preceded by "widget/".' ] );
            }
            //replace this by a function that parses config.json in each widget folder to get the 'stylesheet' variable
            content += '@import "' + widgetSassPath + '";\r\n';
        } );

        grunt.file.write( config.writePath, content );

    } );

    grunt.registerTask( 'compile', [ 'requirejs:compile' ] );
    grunt.registerTask( 'test', [ 'jsbeautifier:test', 'jshint', 'connect:test', 'compile', 'jasmine' ] );
    grunt.registerTask( 'style', [ 'prepWidgetSass', 'sass' ] );
    grunt.registerTask( 'server', [ 'connect:server:keepalive' ] );
    grunt.registerTask( 'default', [ 'jshint', 'prepWidgetSass', 'sass', 'test' ] );
};
<commit_msg>removed unneccesary ‘include’ item from js build<commit_after>/**
 * When using enketo-core in your own app, you'd want to replace
 * this build file with one of your own in your project root.
 */

/*jshint node:true*/
"use strict";

module.exports = function( grunt ) {
    var js;

    // Project configuration.
    grunt.initConfig( {
        pkg: grunt.file.readJSON( 'package.json' ),
        connect: {
            server: {
                options: {
                    port: 8080
                }
            },
            test: {
                options: {
                    port: 8000
                }
            }
        },
        jsbeautifier: {
            test: {
                src: [ "*.js", "src/js/*.js", "src/widget/*/*.js" ],
                options: {
                    config: "./.jsbeautifyrc",
                    mode: "VERIFY_ONLY"
                }
            },
            fix: {
                src: [ "src/js/*.js", "src/widget/*/*.js" ],
                options: {
                    config: "./.jsbeautifyrc"
                }
            }
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            all: [ '*.js', 'src/js/**/*.js', '!src/js/extern.js' ]
        },
        watch: {
            sass: {
                files: [ 'config.json', 'src/**/*.scss' ],
                tasks: [ 'style' ],
                options: {
                    spawn: false
                }
            },
            js: {
                files: [ '*.js', 'src/**/*.js', 'build/**/*.css' ],
                tasks: [ 'modernizr' ],
                options: {
                    spawn: false
                }
            }
        },
        jasmine: {
            test: {
                src: 'src/js/**/*.js',
                options: {
                    keepRunner: true,
                    specs: 'test/spec/*.js',
                    helpers: [ 'test/util/*.js', 'test/mock/*.js' ],
                    host: 'http://127.0.0.1:8000/',
                    template: require( 'grunt-template-jasmine-requirejs' ),
                    templateOptions: {
                        requireConfig: {
                            baseUrl: 'lib',
                            paths: {
                                'enketo-js': '../src/js',
                                'enketo-widget': '../src/widget',
                                'enketo-config': '../config.json',
                                text: 'text/text',
                                xpath: 'xpath/build/xpathjs_javarosa',
                                'jquery.xpath': 'jquery-xpath/jquery.xpath'
                            },
                            shim: {
                                'xpath': {
                                    exports: 'XPathJS'
                                },
                                'bootstrap': {
                                    deps: [ 'jquery' ],
                                    exports: 'jQuery.fn.bootstrap'
                                },
                                'widget/date/bootstrap3-datepicker/js/bootstrap-datepicker': {
                                    deps: [ 'jquery' ],
                                    exports: 'jQuery.fn.datepicker'
                                },
                                'widget/time/bootstrap3-timepicker/js/bootstrap-timepicker': {
                                    deps: [ 'jquery' ],
                                    exports: 'jQuery.fn.timepicker'
                                }
                            },
                            map: {
                                '*': {
                                    'enketo-js': '../src/js',
                                    'enketo-widget': '../src/widget'
                                }
                            }
                        }
                    }
                },
            }
        },
        prepWidgetSass: {
            writePath: 'src/sass/_widgets.scss',
            widgetConfigPath: 'config.json'
        },
        sass: {
            dist: {
                options: {
                    style: 'compressed',
                    noCache: true
                },
                files: [ {
                    expand: true,
                    cwd: 'src/sass',
                    src: [ '**/*.scss', '!**/_*.scss' ],
                    dest: 'build/css',
                    ext: '.css'
                } ]
            }
        },
        // this compiles all javascript to a single minified file
        requirejs: {
            compile: {
                options: {
                    name: '../app',
                    baseUrl: 'lib',
                    mainConfigFile: "app.js",
                    findNestedDependencies: true,
                    include: ( function() {
                        //add widgets js and widget config.json files
                        var widgets = grunt.file.readJSON( 'config.json' ).widgets;
                        widgets.forEach( function( widget, index, arr ) {
                            arr.push( 'text!' + widget.substr( 0, widget.lastIndexOf( '/' ) + 1 ) + 'config.json' );
                        } );
                        return [ 'require.js' ].concat( widgets );
                    } )(),
                    out: "build/js/combined.min.js",
                    optimize: "uglify2"
                }
            }
        },
        modernizr: {
            "devFile": "remote",
            "outputFile": "lib/Modernizr.js",
            "extra": {
                "shiv": false,
                "printshiv": true,
                "load": false,
                "mq": false,
                "cssclasses": true
            },
            "uglify": false,
            "parseFiles": true
        }
    } );

    grunt.loadNpmTasks( 'grunt-contrib-connect' );
    grunt.loadNpmTasks( 'grunt-jsbeautifier' );
    grunt.loadNpmTasks( 'grunt-contrib-jasmine' );
    grunt.loadNpmTasks( 'grunt-contrib-watch' );
    grunt.loadNpmTasks( 'grunt-contrib-jshint' );
    grunt.loadNpmTasks( 'grunt-contrib-sass' );
    grunt.loadNpmTasks( 'grunt-contrib-requirejs' );
    grunt.loadNpmTasks( "grunt-modernizr" );

    //maybe this can be turned into a npm module?
    grunt.registerTask( 'prepWidgetSass', 'Preparing _widgets.scss dynamically', function() {
        var widgetConfig, widgetFolderPath, widgetSassPath, widgetConfigPath,
            config = grunt.config( 'prepWidgetSass' ),
            widgets = grunt.file.readJSON( config.widgetConfigPath ).widgets,
            content = '// Dynamically created list of widget stylesheets to import based on the content\r\n' +
                '// based on the content of config.json\r\n\r\n';

        widgets.forEach( function( widget ) {
            if ( widget.indexOf( 'enketo-widget/' ) === 0 ) {
                //strip require.js module name
                widgetFolderPath = widget.substr( 0, widget.lastIndexOf( '/' ) + 1 );
                //replace widget require.js path shortcut with proper path relative to src/js
                widgetSassPath = widgetFolderPath.replace( /^enketo-widget\//, '../widget/' );
                //create path to widget config file
                widgetConfigPath = widgetFolderPath.replace( /^enketo-widget\//, 'src/widget/' ) + 'config.json';
                grunt.log.writeln( 'widget config path: ' + widgetConfigPath );
                //create path to widget stylesheet file
                widgetSassPath += grunt.file.readJSON( widgetConfigPath ).stylesheet;
            } else {
                grunt.log.error( [ 'Expected widget path "' + widget + '" in config.json to be preceded by "widget/".' ] );
            }
            //replace this by a function that parses config.json in each widget folder to get the 'stylesheet' variable
            content += '@import "' + widgetSassPath + '";\r\n';
        } );

        grunt.file.write( config.writePath, content );

    } );

    grunt.registerTask( 'compile', [ 'requirejs:compile' ] );
    grunt.registerTask( 'test', [ 'jsbeautifier:test', 'jshint', 'connect:test', 'compile', 'jasmine' ] );
    grunt.registerTask( 'style', [ 'prepWidgetSass', 'sass' ] );
    grunt.registerTask( 'server', [ 'connect:server:keepalive' ] );
    grunt.registerTask( 'default', [ 'jshint', 'prepWidgetSass', 'sass', 'test' ] );
};
<|endoftext|>


<commit_before>import React from 'react';
import { c } from 'ttag';
import { SubTitle, Alert, MozillaInfoPanel, ErrorButton, useModals, useUser, useSubscription } from 'react-components';

import DeleteAccountModal from './DeleteAccountModal';

const DeleteSection = () => {
    const [{ isMember }] = useUser();
    const [{ isManagedByMozilla } = {}] = useSubscription();
    const { createModal } = useModals();
    // TODO get clientType from config (proton-pack)

    if (isMember) {
        return null;
    }

    const subTitle = <SubTitle>{c('Title').t`Delete account`}</SubTitle>;

    if (isManagedByMozilla) {
        return (
            <>
                {subTitle}
                <MozillaInfoPanel />
            </>
        );
    }

    return (
        <>
            {subTitle}
            <Alert type="error">
                {c('Info')
                    .t`Deleting your account will permanently delete your emails, and you will lose your email address.`}
            </Alert>
            <ErrorButton id="deleteButton" onClick={() => createModal(<DeleteAccountModal />)}>
                {c('Action').t`Delete your account`}
            </ErrorButton>
        </>
    );
};

export default DeleteSection;
<commit_msg>Don't display delection section for vpn user having mailbox<commit_after>import React from 'react';
import { c } from 'ttag';
import {
    SubTitle,
    Alert,
    MozillaInfoPanel,
    ErrorButton,
    useModals,
    useUser,
    useSubscription,
    Loader,
    useAddresses,
    useConfig
} from 'react-components';
import { CLIENT_TYPES } from 'proton-shared/lib/constants';

import DeleteAccountModal from './DeleteAccountModal';

const { VPN } = CLIENT_TYPES;

const DeleteSection = () => {
    const [{ isMember }] = useUser();
    const [addresses, loading] = useAddresses();
    const [{ isManagedByMozilla } = {}] = useSubscription();
    const { createModal } = useModals();
    const { CLIENT_TYPE } = useConfig();

    if (loading) {
        return <Loader />;
    }

    // For ProtonVPN, if the user has PM mailbox, we don't display this section to avoid mistake
    if (CLIENT_TYPE === VPN && addresses.length) {
        return null;
    }

    if (isMember) {
        return null;
    }

    const subTitle = <SubTitle>{c('Title').t`Delete account`}</SubTitle>;

    if (isManagedByMozilla) {
        return (
            <>
                {subTitle}
                <MozillaInfoPanel />
            </>
        );
    }

    return (
        <>
            {subTitle}
            <Alert type="error">
                {c('Info')
                    .t`Deleting your account will permanently delete your emails, and you will lose your email address.`}
            </Alert>
            <ErrorButton id="deleteButton" onClick={() => createModal(<DeleteAccountModal />)}>
                {c('Action').t`Delete your account`}
            </ErrorButton>
        </>
    );
};

export default DeleteSection;
<|endoftext|>


<commit_before>var cursor = db.Nodes.find()
while (cursor.hasNext()) { var doc = cursor.next(); db.Nodes.update({_id: doc._id}, {$set: {last_modified : new Date(doc.last_modified)}}) }
var cursor = db.Nodes.find()
while (cursor.hasNext()) { var doc = cursor.next(); db.Nodes.update({_id: doc._id}, {$set: {created_on : new Date(doc.created_on)}}) }
<commit_msg>Update to fix_dates.js. I found that nodes without a last_modified date set when updated to the date format in mongo got set to a value that the golang mongo interpreter would fail on. The added code should fix those so that Shock will not throw an error anymore when trying to unmarshal those nodes.<commit_after>var cursor = db.Nodes.find()
while (cursor.hasNext()) { var doc = cursor.next(); db.Nodes.update({_id: doc._id}, {$set: {last_modified : new Date(doc.last_modified)}}) }
var cursor = db.Nodes.find()
while (cursor.hasNext()) { var doc = cursor.next(); db.Nodes.update({_id: doc._id}, {$set: {created_on : new Date(doc.created_on)}}) }
var cursor = db.Nodes.find({"last_modified": {"$lte": new ISODate("0000-00-00T00:00:00Z")}})
while (cursor.hasNext()) { var doc = cursor.next(); db.Nodes.update({_id: doc._id}, {$set: {last_modified : new ISODate("0000-00-00T00:00:00Z")}}) }
<|endoftext|>


<commit_before>import _ from 'lodash';

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

import Star from './Star'

export default class AirbnbRating extends React.Component {
  constructor() {
    super()

    this.state = {
      position: 5
    }
  }

  componentDidMount() {
    const { defaultRating } = this.props

    this.setState({ position: defaultRating })
  }

  renderStars(rating_array) {
    return _.map(rating_array, (star, index) => {
      return star
    })
  }

  starSelectedInPosition(position) {
    this.setState({ position: position })
  }

  displayReview() {
    const { position } = this.state

    switch (position) {
      case 1:
        return "Terrible"
      case 2:
        return "Bad"
      case 3:
        return "Okay"
      case 4:
        return "Good"
      case 5:
        return "Great"
      default:
        return "Great"
    }
  }

  render() {
    const { position } = this.state
    const { count, reviews } = this.props
    const rating_array = []

    _.times(count || 5, index => {
      rating_array.push(
        <Star
          key={index}
          position={index + 1}
          starSelectedInPosition={this.starSelectedInPosition.bind(this)}
          fill={position >= index + 1}
          {...this.props}
        />
      )
    })

    return (
      <View style={styles.ratingContainer}>
        <Text style={styles.reviewText}>
          {reviews ? reviews[position - 1] : this.displayReview()}
        </Text>
        <View style={styles.starContainer}>
          {this.renderStars(rating_array)}
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  ratingContainer: {
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
  reviewText: {
    fontSize: 25,
    fontWeight: 'bold',
    margin: 10,
    color: 'rgba(230, 196, 46, 1)'
  },
  starContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  }
});
<commit_msg>fixed default rating prop<commit_after>import _ from 'lodash';

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

import Star from './Star'

export default class AirbnbRating extends React.Component {
  constructor() {
    super()

    this.state = {
      position: 5
    }
  }

  componentDidMount() {
    const { defaultRating } = this.props

    this.setState({ position: defaultRating || 5 })
  }

  renderStars(rating_array) {
    return _.map(rating_array, (star, index) => {
      return star
    })
  }

  starSelectedInPosition(position) {
    this.setState({ position: position })
  }

  displayReview() {
    const { position } = this.state

    switch (position) {
      case 1:
        return "Terrible"
      case 2:
        return "Bad"
      case 3:
        return "Okay"
      case 4:
        return "Good"
      case 5:
        return "Great"
      default:
        return "Great"
    }
  }

  render() {
    const { position } = this.state
    const { count, reviews } = this.props
    const rating_array = []

    _.times(count || 5, index => {
      rating_array.push(
        <Star
          key={index}
          position={index + 1}
          starSelectedInPosition={this.starSelectedInPosition.bind(this)}
          fill={position >= index + 1}
          {...this.props}
        />
      )
    })

    return (
      <View style={styles.ratingContainer}>
        <Text style={styles.reviewText}>
          {reviews ? reviews[position - 1] : this.displayReview()}
        </Text>
        <View style={styles.starContainer}>
          {this.renderStars(rating_array)}
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  ratingContainer: {
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
  reviewText: {
    fontSize: 25,
    fontWeight: 'bold',
    margin: 10,
    color: 'rgba(230, 196, 46, 1)'
  },
  starContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  }
});
<|endoftext|>


<commit_before>"use strict";

module.exports = function (grunt) {
    var saucerSection;
    function killSaucerSection() {
        if (saucerSection) {
            saucerSection.kill();
            saucerSection = null;
        }
    }

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        env: {
            test: {
                NODE_ENV: 'test',
                CLEAR_DB: 'true'
            }
        },
        uglify: {
            'respoke-stats': {
                options: {
                    compress: true,
                    sourceMap: true,
                    sourceMapIncludeSources: true,
                    banner: '/*! Copyright (c) 2014, D.C.S. LLC. All Rights Reserved. Licensed Software. */'
                },
                files: {
                    'respoke-stats.min.js': 'plugins/respoke-stats/respoke-stats.js'
                }
            }
        },
        webpack: {
            all: require('./webpack.config')
        },
        stratos: {
            liftSails: true,
            sailsDir: '../../../collective/',
            sailsPort: 2001
        },
        saucerSection: {
            dir: '../../../saucer-section',
            port: 3000
        },
        mochaTest: {
            unit: {
                options: {
                    reporter: 'mocha-bamboo-reporter'
                },
                src: [
                    './spec/functional/*.spec.js'
                ]
            }
        },
        karma: {
            unit: {
                singleRun: true,
                configFile: './karma-unit.conf.js'
            },
            functional: {
                singleRun: true,
                configFile: './karma-functional.conf.js'
            }
        },
        watch: {
            scripts: {
                files: ['respoke/**/*.js','plugins/**/*.js'],
                tasks: ['dist']
            }
        },
    });

    grunt.loadNpmTasks('grunt-webpack');
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-stratos');
    grunt.loadNpmTasks('grunt-mocha-test');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-env');
    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.registerTask('dist', [
        'webpack',
        'uglify:respoke-stats'
    ]);

    grunt.registerTask('default', 'karma:devOrig');

    grunt.registerTask('unit', 'Run unit specs', [
        'dist',
        'karma:unit'
    ]);

    grunt.registerTask('start-saucer-section', 'Start saucer-section', function () {
        process.env.CONNECT_PORT = grunt.config('saucerSection.port');
        if (!grunt.file.isDir(grunt.config('saucerSection.dir'))) {
            throw grunt.util.error('saucer-section dir not available.  Please setup saucer-section.');
        }
        process.on('exit', function() {
            //ensure saucer-section child process is dead
             killSaucerSection();
        });
        saucerSection = grunt.util.spawn({
            grunt: true,
            args: ['default'],
            opts: {
                cwd: grunt.config('saucerSection.dir')
            }
        });
    });

    grunt.registerTask('stop-saucer-section', 'Start saucer-section', function () {
        killSaucerSection();
    });

    grunt.registerTask('functional', 'Run client-side functional tests', [
        'dist',
        'env:test',
        'start-saucer-section',
        'liftSails',
        'karma:functional',
        'lowerSails',
        'stop-saucer-section'
    ]);

    grunt.registerTask('ci', 'Run all tests', [
        'dist',
        'env:test',
        'start-saucer-section',
        'liftSails',
        'karma:unit',
        'karma:functional',
        'lowerSails',
        'stop-saucer-section'
    ]);
};
<commit_msg>load webhook-service when running transporter functional tests<commit_after>"use strict";

module.exports = function (grunt) {
    var saucerSection;
    var webhookService;

    function killSaucerSection() {
        if (saucerSection) {
            saucerSection.kill();
            saucerSection = null;
        }
    }

    function killWebhookService() {
        if (webhookService) {
            webhookService.kill();
            webhookService = null;
        }
    }

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        env: {
            test: {
                NODE_ENV: 'test',
                CLEAR_DB: 'true'
            }
        },
        uglify: {
            'respoke-stats': {
                options: {
                    compress: true,
                    sourceMap: true,
                    sourceMapIncludeSources: true,
                    banner: '/*! Copyright (c) 2014, D.C.S. LLC. All Rights Reserved. Licensed Software. */'
                },
                files: {
                    'respoke-stats.min.js': 'plugins/respoke-stats/respoke-stats.js'
                }
            }
        },
        webpack: {
            all: require('./webpack.config')
        },
        stratos: {
            liftSails: true,
            sailsDir: '../../../collective/',
            sailsPort: 2001
        },
        saucerSection: {
            dir: '../../../saucer-section',
            port: 3000
        },
        webhookService: {
            dir: '../../../webhook-service'
        },
        mochaTest: {
            unit: {
                options: {
                    reporter: 'mocha-bamboo-reporter'
                },
                src: [
                    './spec/functional/*.spec.js'
                ]
            }
        },
        karma: {
            unit: {
                singleRun: true,
                configFile: './karma-unit.conf.js'
            },
            functional: {
                singleRun: true,
                configFile: './karma-functional.conf.js'
            }
        },
        watch: {
            scripts: {
                files: ['respoke/**/*.js','plugins/**/*.js'],
                tasks: ['dist']
            }
        }
    });

    grunt.loadNpmTasks('grunt-webpack');
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-stratos');
    grunt.loadNpmTasks('grunt-mocha-test');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-env');
    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.registerTask('dist', [
        'webpack',
        'uglify:respoke-stats'
    ]);

    grunt.registerTask('default', 'karma:devOrig');

    grunt.registerTask('unit', 'Run unit specs', [
        'dist',
        'karma:unit'
    ]);

    grunt.registerTask('start-webhook-service', 'Start webhook-service', function () {
        if (!grunt.file.isDir(grunt.config('webhookService.dir'))) {
            throw grunt.util.error('webhook-service dir not available.  Please setup webhook-service.');
        }
        process.on('exit', function() {
            //ensure webhook-service child process is dead
            killWebhookService();
        });
        webhookService = grunt.util.spawn({
            cmd: 'node',
            args: ['app.js'],
            opts: {
                cwd: grunt.config('webhookService.dir')
            }
        });
    });

    grunt.registerTask('stop-webhook-service', 'Stop webhook-service', function () {
        killWebhookService();
    });

    grunt.registerTask('start-saucer-section', 'Start saucer-section', function () {
        process.env.CONNECT_PORT = grunt.config('saucerSection.port');
        if (!grunt.file.isDir(grunt.config('saucerSection.dir'))) {
            throw grunt.util.error('saucer-section dir not available.  Please setup saucer-section.');
        }
        process.on('exit', function() {
            //ensure saucer-section child process is dead
             killSaucerSection();
        });
        saucerSection = grunt.util.spawn({
            grunt: true,
            args: ['default'],
            opts: {
                cwd: grunt.config('saucerSection.dir')
            }
        });
    });

    grunt.registerTask('stop-saucer-section', 'Start saucer-section', function () {
        killSaucerSection();
    });

    grunt.registerTask('functional', 'Run client-side functional tests', [
        'dist',
        'env:test',
        'start-saucer-section',
        'start-webhook-service',
        'liftSails',
        'karma:functional',
        'lowerSails',
        'stop-saucer-section',
        'stop-webhook-service'
    ]);

    grunt.registerTask('ci', 'Run all tests', [
        'dist',
        'env:test',
        'start-saucer-section',
        'liftSails',
        'karma:unit',
        'karma:functional',
        'lowerSails',
        'stop-saucer-section'
    ]);
};
<|endoftext|>


<commit_before>'use strict';

(function() {

    angular
        .module('app')
        .controller('AddCreativityController', [
            '$scope',
            '$sce',
            '$timeout',
            '$mdDialog',
            'allDataService',
            'tokenService',
            '$state',
            'Upload',
            '$rootScope',
            'creativityCategories',
            'addItemService',
            '$mdBottomSheet',
            AddCreativityController
        ]);

    function AddCreativityController($scope, $sce, $timeout, $mdDialog, allDataService, tokenService, $state, Upload, $rootScope, creativityCategories, addItemService, $mdBottomSheet) {
        // 22 june
        $scope.publishable = false;
        $scope.compulsaryP = [1, 2, 17, 18, 19, 20, 21];
        $scope.onlyText = [1, 2];
        $scope.addMenu = true;
        $scope.publishFromDir = false;
        //
        // Functions
        $scope.showMenu = function() {
                if ($scope.addMenu) {
                    $scope.addMenu = false;
                } else {
                    $scope.addMenu = true;
                }
            };
            //
        var body = {};
        $scope.progress = 0;
        $scope.isOpen = false;
        $scope.selectedMode = 'md-scale';

        $rootScope.currentPageBackground = '#fff';
        $rootScope.title = "New Creativity";

        $scope.creativity = {};
        $scope.coverStatus = false;
        $scope.creativity.items = [];
        $scope.mediumEditor = "";
        $scope.trix = "";
        // body.mediaType = "text";
        // body.text = "";
        // $scope.creativity.items[0] = body;
        $scope.loading = false;
        $scope.title = "";

        //imagefilter varaibles
        $scope.filterVisible = false;
        //$scope.currentFilterId = 0;
        // $scope.filters = [
        //     { 'id': 0, 'type': 'Rotate', 'value': 0 },
        //     { 'id': 1, 'type': 'Greyscale', 'value': 0 },
        //     { 'id': 2, 'type': 'Opacity', 'value': 100 }
        // ];
        $scope.filter = {};
        $scope.filter.rotate = 0;
        $scope.filter.saturation = 100;
        $scope.filter.contrast = 100;
        $scope.filter.brightness = 100;

        $scope.css = {
            'transform': 'rotate(' + ($scope.filter.rotate) + 'deg)',
            'filter': 'saturate(' + ($scope.filter.saturation) + '%) brightness(' + ($scope.filter.brightness) + '%) contrast(' + ($scope.filter.contrast) + '%)'
        };
        $scope.$watch('filter', function(newValue, oldValue) {
            //console.log(newValue);
            $scope.css = {
                'transform': 'rotate(' + ($scope.filter.rotate) + 'deg)',
                'filter': 'saturate(' + ($scope.filter.saturation) + '%) brightness(' + ($scope.filter.brightness) + '%) contrast(' + ($scope.filter.contrast) + '%)'
            };
            $scope.creativity.items.css = JSON.stringify($scope.css);
            console.log(JSON.stringify($scope.creativity.items.css));
            console.log(JSON.parse($scope.creativity.items.css));
        }, true);

        $scope.filterToggle = function() {
            if ($scope.filterVisible)
                $scope.filterVisible = false;
            else
                $scope.filterVisible = true;
        };

        if (!localStorage.getItem('seenTutorial') || !parseInt(localStorage.getItem('tutorial'))) {
            localStorage.setItem('seenTutorial', true);
            localStorage.setItem('tutorial', 1);

            $mdDialog.show({
                controller: 'AddItemController',
                heading: 'Tutorial',
                templateUrl: 'app/views/partials/addBlogTutorial.html',
                parent: angular.element(document.body),
                locals: {
                    title: "tutorial"
                },
                clickOutsideToClose: true,
                escapeToClose: true

            }).then(function() {
                    localStorage.setItem('tutorial', parseInt(localStorage.getItem('tutorial')) + 1);
                }, function() {
                    localStorage.setItem('tutorial', parseInt(localStorage.getItem('tutorial')) + 1);
                }

            );

        } else if (parseInt(localStorage.getItem('tutorial')) < 4) {
            console.log('notlessthan3');

            $mdDialog.show({
                controller: 'AddItemController',
                heading: 'Tutorial',
                templateUrl: 'app/views/partials/addBlogTutorial.html',
                parent: angular.element(document.body),
                locals: {
                    title: "tutorial"
                },
                clickOutsideToClose: true,
                escapeToClose: true

            }).then(function() {
                    localStorage.setItem('tutorial', parseInt(localStorage.getItem('tutorial')) + 1);
                }, function() {
                    localStorage.setItem('tutorial', parseInt(localStorage.getItem('tutorial')) + 1);
                }

            );
        }
        $scope.url = "";
        $scope.media = {};
        $scope.media.embedUrl = "";
        $scope.media.mediaType = "";
        $scope.linkPreview = {};
        $scope.types = creativityCategories.types;
        $scope.items = creativityCategories.items;
        $scope.itemsMobile = creativityCategories.itemsMobile;

        $scope.contents = [

            // { 'title': 'Link', 'icon': 'link-variant' },
            // { 'title': 'Embed', 'icon': 'code-tags' },
            { 'title': 'Soundcloud', 'icon': 'soundcloud', 'style': '{fill: "#ff7700"}' },
            { 'title': 'Youtube', 'icon': 'youtube-play', 'style': '{fill: "#bb0000"}' },
            { 'title': 'Vimeo', 'icon': 'vimeo', 'style': '{fill: "#4EBBFF"}' }
        ];

        $scope.selectType = function(type) {
            $scope.progress = 1;
            $scope.creativity.type = type.id;
            $scope.categoryName = $scope.types[$scope.creativity.type - 1].title;
        };
        $scope.uploadFiles = function(files) {
            $rootScope.$emit("ImagesAdded");
            $scope.files = files;
            if (files && files.length) {
                $scope.progress = 2;
                angular.forEach(files, function(file) {
                    Upload.dataUrl(file, true).then(function(url) {
                        var media = {};
                        media.mediaType = 'image';
                        media.image = url;
                        $scope.creativity.items.push(media);
                    });
                });
                $scope.addMenu = false;
            }
        };

        function tutorialController($scope, $mdDialog) {
            $scope.hide = function() {
                $mdDialog.hide();
            };

            $scope.cancel = function() {
                $mdDialog.cancel();
            };
        }

        $scope.removeCover = function() {
            for (var i = $scope.creativity.items.length - 1; i >= 0; i--) {
                if ($scope.creativity.items[i].mediaType == 'cover') {

                    console.log(i);
                    $scope.creativity.items.splice(i, 1)
                    $scope.coverStatus = false;
                }
            }

        };

        $scope.uploadCover = function(file) {
            if (file) {
                $scope.coverStatus = true;
                Upload.dataUrl(file, true).then(function(url) {
                    var cover = {};
                    cover.mediaType = 'cover';
                    cover.image = url;
                    $scope.creativity.items.push(cover);
                });
                $scope.addMenu = false;

            }
        };
        $scope.error = '';
        $rootScope.$on("returnedItem", function(event, response, errorAdd) {
            $scope.error = errorAdd;
            $scope.returnedItem = response;
            $scope.progress = 2;
            $scope.creativity.items.push(response);
            console.log($scope.creativity.items);
            $scope.addMenu = false;
            if ($scope.returnedItem.mediaType == 'Soundcloud') {
                var widgetIframe = document.getElementById('sc-widget'),
                    widget = SC.Widget(widgetIframe),
                    newSoundUrl = $scope.embedUrlIframe;
                widget.bind(SC.Widget.Events.READY, function() {
                    // load new widget
                    widget.bind(SC.Widget.Events.FINISH, function() {
                        widget.load(newSoundUrl, {
                            show_artwork: false
                        });
                    });
                });
            }

        });
        $scope.isAllowed = function(allowed, id) {
            if (id != undefined) {
                return allowed.indexOf(id) !== -1;
            }
        }

        // $rootScope.$on("publishable", function(event, state) {
        //     // Set variable when confirmed from respective directives
        //     $scope.publishFromDir = state;
        //     console.log('$scope.publishFromDir ' + $scope.publishFromDir)
        // });
        $scope.checkPublish = function() {
            if ($scope.isAllowed($scope.compulsaryP, $scope.creativity.type)) {
                // If a category only text as compulsion we have to check weather min text is added or not
                $scope.textAdded = (($scope.mediumEditor || $scope.trix) && ($scope.mediumEditor.length > 20 || $scope.trix.length > 20));
                if ($scope.isAllowed($scope.onlyText, $scope.creativity.type)) {
                    // If a category has only text as compulsion it wont have publishFromDir
                    $scope.publishable = $scope.textAdded;
                } else {
                    $scope.publishable = $scope.textAdded && ($scope.websiteAdded || $scope.danceAdded || $scope.musicAdded || $scope.drawingAdded || $scope.UiUxAdded || $scope.poetryAdded);
                }
            } else {
                $scope.publishable = ($scope.websiteAdded || $scope.danceAdded || $scope.musicAdded || $scope.drawingAdded || $scope.UiUxAdded || $scope.poetryAdded);
            }
            var abc = (!($scope.title && $scope.publishable) || $scope.loading);
            return abc;
        }
        $scope.checkEditor = function() {
            console.log('checkEditor called');
            if ($scope.mediumEditor > $scope.trix) {
                // $scope.creativity.items[0].text = $scope.mediumEditor;
                addItemService.text($scope.mediumEditor);
                console.log($scope.creativity);
            } else if ($scope.mediumEditor < $scope.trix) {
                // $scope.creativity.items[0].text = $scope.trix;
                addItemService.text($scope.trix);
                console.log($scope.creativity);
            }
            // else {
            //     console.log('else');
            //     $scope.creativity.items[0].text = '';
            // }
        };

        $scope.publish = function() {
            console.log($scope.creativity);
            $scope.checkEditor();
            $scope.loading = true;
            $scope.image = {};
            $scope.creativity.tags = $scope.tags;
            $scope.creativity.title = $scope.title;
            console.log($scope.creativity);
            tokenService.post("addContent", $scope.creativity)
                .then(function(status) {
                    alert(status.message);
                    if (status.status) {

                        $state.go('home.dashboard');
                    }
                    $state.go('home.dashboard');
                }).catch(function(status) {
                    alert(status.message);
                    $state.go('home.dashboard');
                    if (status.status) {

                        $state.go('home.dashboard');
                    }
                });

        };

        // Add tags shit staeted
        $scope.readonly = false;
        $scope.removable = true;
        $scope.selectedItem = null;
        $scope.searchText = null;
        $scope.querySearch = querySearch;
        $scope.vegetables = loadVegetables();
        $scope.tags = [];

        /**
         * Return the proper object when the append is called.
         */
        function transformChip(chip) {
            // If it is an object, it's already a known chip
            if (angular.isObject(chip)) {
                return chip;
            }
            // Otherwise, create a new one
            return { name: chip };
        }

        /**
         * Search for vegetables.
         */
        function querySearch(query) {
            console.log('query funciton called');
            var results = query ? $scope.vegetables.filter(createFilterFor(query)) : [];
            return results;
        }
        var numberChips = [];
        var numberChips2 = [];
        var numberBuffer = '';
        $scope.autocompleteDemoRequireMatch = false;
        $scope.transformChip = transformChip;

        /**
         * Create filter function for a query string
         */
        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);

            return function filterFn(vegetable) {
                return (vegetable._lowername.indexOf(lowercaseQuery) === 0);
                // (vegetable._lowertype.indexOf(lowercaseQuery) === 0);
            };

        }

        function loadVegetables() {
            var veggies = [];

            return veggies.map(function(veg) {
                veg._lowername = veg.name.toLowerCase();
                return veg;
            });
        }
        $scope.skillsEdit = function() {
            $scope.readonly = !$scope.readonly;
            $scope.removable = !$scope.removable;
        }

        // Add tags shit ended
    }

})();
<commit_msg>Revert "Changed API endpoint"<commit_after>'use strict';

(function() {

    angular
        .module('app')
        .controller('AddCreativityController', [
            '$scope',
            '$sce',
            '$timeout',
            '$mdDialog',
            'allDataService',
            'tokenService',
            '$state',
            'Upload',
            '$rootScope',
            'creativityCategories',
            'addItemService',
            '$mdBottomSheet',
            AddCreativityController
        ]);

    function AddCreativityController($scope, $sce, $timeout, $mdDialog, allDataService, tokenService, $state, Upload, $rootScope, creativityCategories, addItemService, $mdBottomSheet) {
        // 22 june
        $scope.publishable = false;
        $scope.compulsaryP = [1, 2, 17, 18, 19, 20, 21];
        $scope.onlyText = [1, 2];
        $scope.addMenu = true;
        $scope.publishFromDir = false;
        //
        // Functions
        $scope.showMenu = function() {
                if ($scope.addMenu) {
                    $scope.addMenu = false;
                } else {
                    $scope.addMenu = true;
                }
            };
            //
        var body = {};
        $scope.progress = 0;
        $scope.isOpen = false;
        $scope.selectedMode = 'md-scale';

        $rootScope.currentPageBackground = '#fff';
        $rootScope.title = "New Creativity";

        $scope.creativity = {};
        $scope.coverStatus = false;
        $scope.creativity.items = [];
        $scope.mediumEditor = "";
        $scope.trix = "";
        body.mediaType = "text";
        body.text = "";
        $scope.creativity.items[0] = body;
        $scope.loading = false;
        $scope.title = "";

        //imagefilter varaibles
        $scope.filterVisible = false;
        //$scope.currentFilterId = 0;
        // $scope.filters = [
        //     { 'id': 0, 'type': 'Rotate', 'value': 0 },
        //     { 'id': 1, 'type': 'Greyscale', 'value': 0 },
        //     { 'id': 2, 'type': 'Opacity', 'value': 100 }
        // ];
        $scope.filter = {};
        $scope.filter.rotate = 0;
        $scope.filter.saturation = 100;
        $scope.filter.contrast = 100;
        $scope.filter.brightness = 100;

        $scope.css = {
            'transform': 'rotate(' + ($scope.filter.rotate) + 'deg)',
            'filter': 'saturate(' + ($scope.filter.saturation) + '%) brightness(' + ($scope.filter.brightness) + '%) contrast(' + ($scope.filter.contrast) + '%)'
        };
        $scope.$watch('filter', function(newValue, oldValue) {
            //console.log(newValue);
            $scope.css = {
                'transform': 'rotate(' + ($scope.filter.rotate) + 'deg)',
                'filter': 'saturate(' + ($scope.filter.saturation) + '%) brightness(' + ($scope.filter.brightness) + '%) contrast(' + ($scope.filter.contrast) + '%)'
            };
            $scope.creativity.items.css = JSON.stringify($scope.css);
            console.log(JSON.stringify($scope.creativity.items.css));
            console.log(JSON.parse($scope.creativity.items.css));
        }, true);

        $scope.filterToggle = function() {
            if ($scope.filterVisible)
                $scope.filterVisible = false;
            else
                $scope.filterVisible = true;
        };

        if (!localStorage.getItem('seenTutorial') || !parseInt(localStorage.getItem('tutorial'))) {
            localStorage.setItem('seenTutorial', true);
            localStorage.setItem('tutorial', 1);

            $mdDialog.show({
                controller: 'AddItemController',
                heading: 'Tutorial',
                templateUrl: 'app/views/partials/addBlogTutorial.html',
                parent: angular.element(document.body),
                locals: {
                    title: "tutorial"
                },
                clickOutsideToClose: true,
                escapeToClose: true

            }).then(function() {
                    localStorage.setItem('tutorial', parseInt(localStorage.getItem('tutorial')) + 1);
                }, function() {
                    localStorage.setItem('tutorial', parseInt(localStorage.getItem('tutorial')) + 1);
                }

            );

        } else if (parseInt(localStorage.getItem('tutorial')) < 4) {
            console.log('notlessthan3');

            $mdDialog.show({
                controller: 'AddItemController',
                heading: 'Tutorial',
                templateUrl: 'app/views/partials/addBlogTutorial.html',
                parent: angular.element(document.body),
                locals: {
                    title: "tutorial"
                },
                clickOutsideToClose: true,
                escapeToClose: true

            }).then(function() {
                    localStorage.setItem('tutorial', parseInt(localStorage.getItem('tutorial')) + 1);
                }, function() {
                    localStorage.setItem('tutorial', parseInt(localStorage.getItem('tutorial')) + 1);
                }

            );
        }
        $scope.url = "";
        $scope.media = {};
        $scope.media.embedUrl = "";
        $scope.media.mediaType = "";
        $scope.linkPreview = {};
        $scope.types = creativityCategories.types;
        $scope.items = creativityCategories.items;
        $scope.itemsMobile = creativityCategories.itemsMobile;

        $scope.contents = [

            // { 'title': 'Link', 'icon': 'link-variant' },
            // { 'title': 'Embed', 'icon': 'code-tags' },
            { 'title': 'Soundcloud', 'icon': 'soundcloud', 'style': '{fill: "#ff7700"}' },
            { 'title': 'Youtube', 'icon': 'youtube-play', 'style': '{fill: "#bb0000"}' },
            { 'title': 'Vimeo', 'icon': 'vimeo', 'style': '{fill: "#4EBBFF"}' }
        ];

        $scope.selectType = function(type) {
            $scope.progress = 1;
            $scope.creativity.type = type.id;
            $scope.categoryName = $scope.types[$scope.creativity.type - 1].title;
        };
        $scope.uploadFiles = function(files) {
            $rootScope.$emit("ImagesAdded");
            $scope.files = files;
            if (files && files.length) {
                $scope.progress = 2;
                angular.forEach(files, function(file) {
                    Upload.dataUrl(file, true).then(function(url) {
                        var media = {};
                        media.mediaType = 'image';
                        media.image = url;
                        $scope.creativity.items.push(media);
                    });
                });
                $scope.addMenu = false;
            }
        };

        function tutorialController($scope, $mdDialog) {
            $scope.hide = function() {
                $mdDialog.hide();
            };

            $scope.cancel = function() {
                $mdDialog.cancel();
            };
        }

        $scope.removeCover = function() {
            for (var i = $scope.creativity.items.length - 1; i >= 0; i--) {
                if ($scope.creativity.items[i].mediaType == 'cover') {

                    console.log(i);
                    $scope.creativity.items.splice(i, 1)
                    $scope.coverStatus = false;
                }
            }

        };

        $scope.uploadCover = function(file) {
            if (file) {
                $scope.coverStatus = true;
                Upload.dataUrl(file, true).then(function(url) {
                    var cover = {};
                    cover.mediaType = 'cover';
                    cover.image = url;
                    $scope.creativity.items.push(cover);
                });
                $scope.addMenu = false;

            }
        };
        $scope.error = '';
        $rootScope.$on("returnedItem", function(event, response, errorAdd) {
            $scope.error = errorAdd;
            $scope.returnedItem = response;
            $scope.progress = 2;
            $scope.creativity.items.push(response);
            console.log($scope.creativity.items);
            $scope.addMenu = false;
            if ($scope.returnedItem.mediaType == 'Soundcloud') {
                var widgetIframe = document.getElementById('sc-widget'),
                    widget = SC.Widget(widgetIframe),
                    newSoundUrl = $scope.embedUrlIframe;
                widget.bind(SC.Widget.Events.READY, function() {
                    // load new widget
                    widget.bind(SC.Widget.Events.FINISH, function() {
                        widget.load(newSoundUrl, {
                            show_artwork: false
                        });
                    });
                });
            }

        });
        $scope.isAllowed = function(allowed, id) {
            if (id != undefined) {
                return allowed.indexOf(id) !== -1;
            }
        }

        // $rootScope.$on("publishable", function(event, state) {
        //     // Set variable when confirmed from respective directives
        //     $scope.publishFromDir = state;
        //     console.log('$scope.publishFromDir ' + $scope.publishFromDir)
        // });
        $scope.checkPublish = function() {
            if ($scope.isAllowed($scope.compulsaryP, $scope.creativity.type)) {
                // If a category only text as compulsion we have to check weather min text is added or not
                $scope.textAdded = (($scope.mediumEditor || $scope.trix) && ($scope.mediumEditor.length > 20 || $scope.trix.length > 20));
                if ($scope.isAllowed($scope.onlyText, $scope.creativity.type)) {
                    // If a category has only text as compulsion it wont have publishFromDir
                    $scope.publishable = $scope.textAdded;
                } else {
                    $scope.publishable = $scope.textAdded && ($scope.websiteAdded || $scope.danceAdded || $scope.musicAdded || $scope.drawingAdded || $scope.UiUxAdded || $scope.poetryAdded);
                }
            } else {
                $scope.publishable = ($scope.websiteAdded || $scope.danceAdded || $scope.musicAdded || $scope.drawingAdded || $scope.UiUxAdded || $scope.poetryAdded);
            }
            var abc = (!($scope.title && $scope.publishable) || $scope.loading);
            return abc;
        }
        $scope.checkEditor = function() {
            console.log('checkEditor called');
            if ($scope.mediumEditor > $scope.trix) {
                $scope.creativity.items[0].text = $scope.mediumEditor;
                console.log($scope.creativity.items[0]);
            } else if ($scope.mediumEditor < $scope.trix) {
                $scope.creativity.items[0].text = $scope.trix;
                console.log($scope.creativity.items[0]);
            } else {
                console.log('else');
                $scope.creativity.items[0].text = '';
            }
        };

        $scope.publish = function() {
            $scope.checkEditor();
            $scope.loading = true;
            $scope.image = {};
            $scope.creativity.tags = $scope.tags;
            $scope.creativity.title = $scope.title;
            console.log($scope.creativity);
            tokenService.post("addNew", $scope.creativity)
                .then(function(status) {
                    alert(status.message);
                    if (status.status) {

                        $state.go('home.dashboard');
                    }
                    $state.go('home.dashboard');
                }).catch(function(status) {
                    alert(status.message);
                    $state.go('home.dashboard');
                    if (status.status) {

                        $state.go('home.dashboard');
                    }
                });

        };

        // Add tags shit staeted
        $scope.readonly = false;
        $scope.removable = true;
        $scope.selectedItem = null;
        $scope.searchText = null;
        $scope.querySearch = querySearch;
        $scope.vegetables = loadVegetables();
        $scope.tags = [];

        /**
         * Return the proper object when the append is called.
         */
        function transformChip(chip) {
            // If it is an object, it's already a known chip
            if (angular.isObject(chip)) {
                return chip;
            }
            // Otherwise, create a new one
            return { name: chip };
        }

        /**
         * Search for vegetables.
         */
        function querySearch(query) {
            console.log('query funciton called');
            var results = query ? $scope.vegetables.filter(createFilterFor(query)) : [];
            return results;
        }
        var numberChips = [];
        var numberChips2 = [];
        var numberBuffer = '';
        $scope.autocompleteDemoRequireMatch = false;
        $scope.transformChip = transformChip;

        /**
         * Create filter function for a query string
         */
        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);

            return function filterFn(vegetable) {
                return (vegetable._lowername.indexOf(lowercaseQuery) === 0);
                // (vegetable._lowertype.indexOf(lowercaseQuery) === 0);
            };

        }

        function loadVegetables() {
            var veggies = [];

            return veggies.map(function(veg) {
                veg._lowername = veg.name.toLowerCase();
                return veg;
            });
        }
        $scope.skillsEdit = function() {
            $scope.readonly = !$scope.readonly;
            $scope.removable = !$scope.removable;
        }

        // Add tags shit ended
    }

})();
<|endoftext|>


<commit_before>let React = require("react")
let Colr = require('colr')
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, input, img} = React.DOM
let cx = require("classnames")

let colorMap = React.createFactory(require("./color/map"))
let sample =  React.createFactory(require("./color/sample"))
let hue_slider =  React.createFactory(require("./color/hue_slider"))

export default class extends React.Component {

  static displayName = "Frig.friggingBootstrap.Color"

  static defaultProps = Object.assign(require("../default_props.js"), {
    color: "#000000",
  })

  propTypes: {
    color: React.PropTypes.string,
  }

  state = this._getStateFrom(this.props.color)

  componentDidMount() {
   this.setState({ showPopup: false })
  }

  // compare props against state using hex strings
  // only use the new props if the color is different
  // this prevents data loss when converting between RGB and HSV
  componentWillReceiveProps(nextProps) {
    let nextColor = nextProps.color.toLowerCase()
    let currentColor = this._getCurrentHex()

    if(nextColor !== currentColor) {
      this.setState(this._getStateFrom(nextProps.color))
    }
  }

  // generate state object from a hex string
  _getStateFrom(color) {
    color = Colr.fromHex(color)
    return {
      color: color,
      hsv: color.toRawHsvObject(),
    }
  }

  _onInputClick() {
    this.setState({
      showPopup: !this.state.showPopup,
    })
  }

  // replace current color with another one
  _loadColor(color) {
    this.setState(this._getStateFrom(color))
    this.props.onChange(Colr.fromHex(color))
  }

  // update the current color using the raw hsv values
  _update() {
    let color = Colr.fromHsvObject(this.state.hsv)
    this.setState({ color: color })
  }

  // set the hue
  _setHue(hue) {
    this.state.hsv.h = hue
    this._update()
  }

  // set the saturation
  _setSaturation(saturation) {
    this.state.hsv.s = saturation
    this._update()
  }

  // set the value
  _setValue(value) {
    this.state.hsv.v = value
    this._update()
  }

  // set the saturation and the value
  _setSaturationAndValue(saturation, value) {
    this.state.hsv.s = saturation
    this.state.hsv.v = value
    this._update()
  }

  _getBackgroundHue() {
    return Colr.fromHsv(this.state.hsv.h, 100, 100).toHex()
  }

  _inputMap() {
    let hue = this._getBackgroundHue()
    let luminosity = this.state.color.toGrayscale()

    return colorMap({
      x: this.state.hsv.s,
      y: this.state.hsv.v,
      max: 100,
      backgroundColor: hue,
      className: cx({
        dark: luminosity <= 128,
        light: luminosity > 128,
      }),
      onChange: this._setSaturationAndValue.bind(this),
    })
  }

  _displayColorMap(){
    if (this.state.showPopup === false) return false
    return div({className: "controls colorpicker"},
      div({ className: "hue-slider" },
        hue_slider({
          value: this.state.hsv.h,
          max: 360,
          onChange: this._setHue.bind(this),
        })
      ),
      this._inputMap(),
    )
  }

  _getCurrentHex() {
    return Colr.fromHsvObject(this.state.hsv).toHex()
  }

  _getContrastYIQ(hexcolor){
    var r = parseInt(hexcolor.substr(1,2),16)
    var g = parseInt(hexcolor.substr(3,2),16)
    var b = parseInt(hexcolor.substr(5,2),16)
    var yiq = ((r*299)+(g*587)+(b*114))/1000

    return (yiq >= 128) ? 'black' : 'white'
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: formGroupCx(this.props)},
        label(this.props),
        input(Object.assign({}, this.props.inputHtml, {
            valueLink: {
              value: this._getCurrentHex(),
              requestChange: this._update.bind(this),
            },
            disabled: true,
            className: cx(this.props.inputHtml.className, "form-control"),
            onClick: this._onInputClick.bind(this),
            style: {
               backgroundColor: this._getCurrentHex(),
               color: this._getContrastYIQ(this._getCurrentHex()),
            },
          }),
        ),
        this._displayColorMap(),
        errorList(this.props.errors),
      )
    )
  }

}
<commit_msg>Fix Color Reset After Lose Of Force From Color<commit_after>let React = require("react")
let Colr = require('colr')
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, input, img} = React.DOM
let cx = require("classnames")

let colorMap = React.createFactory(require("./color/map"))
let sample =  React.createFactory(require("./color/sample"))
let hue_slider =  React.createFactory(require("./color/hue_slider"))

export default class extends React.Component {

  static displayName = "Frig.friggingBootstrap.Color"

  static defaultProps = Object.assign(require("../default_props.js"), {
    color: "#000000",
  })

  propTypes: {
    color: React.PropTypes.string,
  }

  state = this._getStateFrom(this.props.color)

  componentDidMount() {
   this.setState({ showPopup: false })
  }

  // generate state object from a hex string
  _getStateFrom(color) {
    color = Colr.fromHex(color)
    return {
      color: color,
      hsv: color.toRawHsvObject(),
    }
  }

  _onInputClick() {
    this.setState({
      showPopup: !this.state.showPopup,
    })
  }

  // replace current color with another one
  _loadColor(color) {
    this.setState(this._getStateFrom(color))
  }

  // update the current color using the raw hsv values
  _update() {
    let color = Colr.fromHsvObject(this.state.hsv)
    this.setState({ color: color })
  }

  // set the hue
  _setHue(hue) {
    this.state.hsv.h = hue
    this._update()
  }

  // set the saturation
  _setSaturation(saturation) {
    this.state.hsv.s = saturation
    this._update()
  }

  // set the value
  _setValue(value) {
    this.state.hsv.v = value
    this._update()
  }

  // set the saturation and the value
  _setSaturationAndValue(saturation, value) {
    this.state.hsv.s = saturation
    this.state.hsv.v = value
    this._update()
  }

  _getBackgroundHue() {
    return Colr.fromHsv(this.state.hsv.h, 100, 100).toHex()
  }

  _inputMap() {
    let hue = this._getBackgroundHue()
    let luminosity = this.state.color.toGrayscale()

    return colorMap({
      x: this.state.hsv.s,
      y: this.state.hsv.v,
      max: 100,
      backgroundColor: hue,
      className: cx({
        dark: luminosity <= 128,
        light: luminosity > 128,
      }),
      onChange: this._setSaturationAndValue.bind(this),
    })
  }

  _displayColorMap(){
    if (this.state.showPopup === false) return false
    return div({className: "controls colorpicker"},
      div({ className: "hue-slider" },
        hue_slider({
          value: this.state.hsv.h,
          max: 360,
          onChange: this._setHue.bind(this),
        })
      ),
      this._inputMap(),
    )
  }

  _getCurrentHex() {
    return Colr.fromHsvObject(this.state.hsv).toHex()
  }

  _getContrastYIQ(hexcolor){
    var r = parseInt(hexcolor.substr(1,2),16)
    var g = parseInt(hexcolor.substr(3,2),16)
    var b = parseInt(hexcolor.substr(5,2),16)
    var yiq = ((r*299)+(g*587)+(b*114))/1000

    return (yiq >= 128) ? 'black' : 'white'
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: formGroupCx(this.props)},
        label(this.props),
        input(Object.assign({}, this.props.inputHtml, {
            valueLink: {
              value: this._getCurrentHex(),
              requestChange: this._update.bind(this),
            },
            disabled: true,
            className: cx(this.props.inputHtml.className, "form-control"),
            onClick: this._onInputClick.bind(this),
            style: {
               backgroundColor: this._getCurrentHex(),
               color: this._getContrastYIQ(this._getCurrentHex()),
            },
          }),
        ),
        this._displayColorMap(),
        errorList(this.props.errors),
      )
    )
  }

}
<|endoftext|>


<commit_before>(function($) {
    $(function() {
        var formsubmission_form = $('#formsubmission_form');
        var form_field = $('select[id="id_form"]', formsubmission_form);
        var headers_field = $('.field-headers', formsubmission_form);

        var loadHeaders = function() {
            if (!form_field.val()) {
                headers_field.slideUp('fast');
                return;
            }

            var data = {
                'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
                'form': $('select[name="form"]').val(),
                'file_type': $('select[name="file_type"]').val()
            };

            $.ajax({
                type: 'POST',
                url: '',
                data: data,
                success: function(response) {
                    if (response.reloadBrowser) {
                        location.reload();
                    }
                    $('select[id="id_headers_to"]').find('option').remove();

                    var headers_input_from = $('select[id="id_headers_from"]');
                    headers_input_from.find('option').remove();

                    $.each(response.availableHeaders, function(index, value) {
                        headers_input_from.append('<option value=' + value + '>' + value + '</option>');
                    });

                    SelectBox.init('id_headers_from');
                    SelectBox.init('id_headers_to');
                    headers_field.slideDown();
                },
                error: function() {
                    alert('We\'re sorry. Something unexpected happened. Please reload the page and try again.');
                }
            });

            return false;
        };

        if ($('body').hasClass('export-form')) {
            loadHeaders();
            form_field.change(loadHeaders);
        }
    });
})(django.jQuery);
<commit_msg>Fix #12<commit_after>(function($) {
    $(function() {
        var form = $('#formsubmission_form'),
            formSelectorInput = $('select[id="id_form"]', form),
            headersFieldWrapper = $('.field-headers', form);

        var fetchAvailableHeaders = function() {
            if (!formSelectorInput.val()) {
                headersFieldWrapper.slideUp('fast');
                return;
            }

            var data = {
                'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]', form).val(),
                'form': formSelectorInput.val(),
                'file_type': $('select[id="id_file_type"]', form).val()
            };

            $.ajax({
                type: 'POST',
                data: data,
                success: function(response) {
                    if (response.reloadBrowser) {
                        location.reload(true);
                    }
                    var headersInput__from = $('select[id="id_headers_from"]', form),
                        headersInput__to = $('select[id="id_headers_to"]', form);

                    headersInput__to.find('option').remove();
                    headersInput__from.find('option').remove();

                    $.each(response.availableHeaders, function(index, value) {
                        headersInput__from.append($('<option/>', {
                            value: value,
                            text: value
                        }));
                    });

                    SelectBox.init('id_headers_from');
                    SelectBox.init('id_headers_to');
                    headersFieldWrapper.slideDown();
                },
                error: function() {
                    alert('We\'re sorry. Something unexpected happened. Please reload the page and try again.');
                }
            });

            return false;
        };

        if ($('body').hasClass('export-form')) {
            fetchAvailableHeaders();
            formSelectorInput.change(fetchAvailableHeaders);
        }
    });
})(django.jQuery);
<|endoftext|>


<commit_before>Object.prototype.values = function(obj) {
    var keys = Object.keys()
    return keys.map(function(key) {
        return obj[key]
    })
}

var INGRIDIENTS = {
    'cheese': {
        weight: 50,
        calories: 50
    },
    'sauce': {
        weight: 10,
        calories: 20
    },
    'mozzarela': {
        weight: 25,
        calories: 25
    },
    'camamber': {
        weight: 25,
        calories: 25
    },
    'feta': {
        weight: 25,
        calories: 25
    },
    'peperoni': {
        weight: 20,
        calories: 20
    }
}
function Pizza(recipe) {
    // правила создания объекта - его инициализация
    // this который доступен в этой функции - это новый объект, который будет создан если функцию вызвать с new
    this.base = recipe.base
    this.ingridients = recipe.ingridients
}

Pizza.prototype = { // or Object.create
    getWeight: function() { // 'эта функция называется метод объекта
        // this такой же как в функции-конструкторе
        // мы можем из него брать любые свойства
        var ingridientWeights = this.ingridients
            .map(function(el) {
                return el.weight
            })

        var allIngridientsWeight = ingridientWeights.reduce(function(sum, cur) {
            return sum + cur
        }, this.base.weight)
        return allIngridientsWeight
    },
    getCalories: function() {
        return this.calories
    }
}

// creating objects
var recipeMargarita = {
    id: 'margarita',
    name: 'Margarita',
    base: {
        weight: 100,
        calories: 30
    },
    ingridients: [
        INGRIDIENTS.cheese,
        INGRIDIENTS.sauce,
        INGRIDIENTS.mozzarela
    ]
}

var recipes = {
    'margarita': recipeMargarita,
    'four_cheeses': {
        id: 'four_cheeses',
        name: 'Four cheeses',
        base: {
            weight: 200,
            calories: 120
        },
        ingridients: [
            INGRIDIENTS.cheese,
            INGRIDIENTS.mozzarela,
            INGRIDIENTS.camamber,
            INGRIDIENTS.feta,
            INGRIDIENTS.sauce
        ]
    }
}
//var pizza = new Pizza(recipeMargarita)
//console.log('pizza weight: ', pizza.getWeight())

function logEvent(e) {
    alert('hello!')
    console.log(e)
}

$(function() {
    var $select = $('.js-choose-recipe')

    Object.values(recipes).forEach(function(recipe) {
        var $option = $('<option value="'+ recipe.id +'">' + recipe.name + '</option>')
        $select.append($option)
    })

    $select.on('change', function() {
        var chosenValue = $select.val()
        var chosenRecipe = recipes[chosenValue]
        console.log(chosenRecipe)

        var pizza = new Pizza(chosenRecipe)
        $('.js-chosen-recipe').text(chosenRecipe.name)

    })

})
<commit_msg>fix pollyfil<commit_after>Object.prototype.values = function(obj) {
    var keys = Object.keys(obj)
    return keys.map(function(key) {
        return obj[key]
    })
}

var INGRIDIENTS = {
    'cheese': {
        weight: 50,
        calories: 50
    },
    'sauce': {
        weight: 10,
        calories: 20
    },
    'mozzarela': {
        weight: 25,
        calories: 25
    },
    'camamber': {
        weight: 25,
        calories: 25
    },
    'feta': {
        weight: 25,
        calories: 25
    },
    'peperoni': {
        weight: 20,
        calories: 20
    }
}
function Pizza(recipe) {
    // правила создания объекта - его инициализация
    // this который доступен в этой функции - это новый объект, который будет создан если функцию вызвать с new
    this.base = recipe.base
    this.ingridients = recipe.ingridients
}

Pizza.prototype = { // or Object.create
    getWeight: function() { // 'эта функция называется метод объекта
        // this такой же как в функции-конструкторе
        // мы можем из него брать любые свойства
        var ingridientWeights = this.ingridients
            .map(function(el) {
                return el.weight
            })

        var allIngridientsWeight = ingridientWeights.reduce(function(sum, cur) {
            return sum + cur
        }, this.base.weight)
        return allIngridientsWeight
    },
    getCalories: function() {
        return this.calories
    }
}

// creating objects
var recipeMargarita = {
    id: 'margarita',
    name: 'Margarita',
    base: {
        weight: 100,
        calories: 30
    },
    ingridients: [
        INGRIDIENTS.cheese,
        INGRIDIENTS.sauce,
        INGRIDIENTS.mozzarela
    ]
}

var recipes = {
    'margarita': recipeMargarita,
    'four_cheeses': {
        id: 'four_cheeses',
        name: 'Four cheeses',
        base: {
            weight: 200,
            calories: 120
        },
        ingridients: [
            INGRIDIENTS.cheese,
            INGRIDIENTS.mozzarela,
            INGRIDIENTS.camamber,
            INGRIDIENTS.feta,
            INGRIDIENTS.sauce
        ]
    }
}
//var pizza = new Pizza(recipeMargarita)
//console.log('pizza weight: ', pizza.getWeight())

function logEvent(e) {
    alert('hello!')
    console.log(e)
}

$(function() {
    var $select = $('.js-choose-recipe')

    Object.values(recipes).forEach(function(recipe) {
        var $option = $('<option value="'+ recipe.id +'">' + recipe.name + '</option>')
        $select.append($option)
    })

    $select.on('change', function() {
        var chosenValue = $select.val()
        var chosenRecipe = recipes[chosenValue]
        console.log(chosenRecipe)

        var pizza = new Pizza(chosenRecipe)
        $('.js-chosen-recipe').text(chosenRecipe.name)

    })

})
<|endoftext|>


<commit_before>/*
* Apllication Controller
*
*/

angularIO.controller('AppCtrl', ['$scope', '$mdDialog', '$timeout', function($scope, $mdDialog, $timeout) {
  $scope.showDocsNav = false;
  $scope.showMainNav = false;
  $scope.showMenu = false;

  // TOGGLE MAIN NAV (TOP) ON MOBILE
  $scope.toggleDocsMenu = function(event) {
    event.preventDefault();
    $scope.showDocsNav = !$scope.showDocsNav;
  };

  // TOGGLE DOCS NAV
  $scope.toggleMainMenu = function(event) {
    event.preventDefault();
    $scope.showMainNav = !$scope.showMainNav;
  };

  // TOGGLE DOCS VERSION & LANGUAGE
  $scope.toggleVersionMenu = function(event) {
    event.preventDefault();
    $scope.showMenu = !$scope.showMenu;
  };

  /*
  * Prettify Code
  *
  * Finish Rendereding code directives then prettify code
  */

  // GRAB ALL TAGS NOT USING DIRECTIVES
  var preTags = angular.element(document.body).find('pre');

  // LOOP THROUGH AND ADD PRETTIFY CLASS
  _.each(preTags, function(element) {
    var preTag = angular.element(element);

    // IF NOT FORMATTED, ADD PRETTY PRINT
    if(!preTag.hasClass('prettyprint')) {
      preTag.addClass('prettyprint linums');
    }
  });

  // TRIGGER PRETTYPRINT AFTER DIGEST LOOP COMPLETE
  $timeout(prettyPrint, 1);
}]);<commit_msg>linenums<commit_after>/*
* Apllication Controller
*
*/

angularIO.controller('AppCtrl', ['$scope', '$mdDialog', '$timeout', function($scope, $mdDialog, $timeout) {
  $scope.showDocsNav = false;
  $scope.showMainNav = false;
  $scope.showMenu = false;

  // TOGGLE MAIN NAV (TOP) ON MOBILE
  $scope.toggleDocsMenu = function(event) {
    event.preventDefault();
    $scope.showDocsNav = !$scope.showDocsNav;
  };

  // TOGGLE DOCS NAV
  $scope.toggleMainMenu = function(event) {
    event.preventDefault();
    $scope.showMainNav = !$scope.showMainNav;
  };

  // TOGGLE DOCS VERSION & LANGUAGE
  $scope.toggleVersionMenu = function(event) {
    event.preventDefault();
    $scope.showMenu = !$scope.showMenu;
  };

  /*
  * Prettify Code
  *
  * Finish Rendereding code directives then prettify code
  */

  // GRAB ALL TAGS NOT USING DIRECTIVES
  var preTags = angular.element(document.body).find('pre');

  // LOOP THROUGH AND ADD PRETTIFY CLASS
  _.each(preTags, function(element) {
    var preTag = angular.element(element);

    // IF NOT FORMATTED, ADD PRETTY PRINT
    if(!preTag.hasClass('prettyprint')) {
      preTag.addClass('prettyprint linenums');
    }
  });

  // TRIGGER PRETTYPRINT AFTER DIGEST LOOP COMPLETE
  $timeout(prettyPrint, 1);
}]);<|endoftext|>


<commit_before>'use strict';

var db   = require('mano').db,
	user = db.User.prototype;

module.exports = exports = require('../../view/business-process-revision-form');

exports._officialForm = function (context) {
	return context.businessProcess.certificates.map.docA.dataForm.toDOMForm(document);
};
<commit_msg>Fix build.<commit_after>'use strict';

module.exports = exports = require('../../view/business-process-revision-form');

exports._officialForm = function (context) {
	return context.businessProcess.certificates.map.docA.dataForm.toDOMForm(document);
};
<|endoftext|>