<commit_before>const serveStatic = require('serve-static')
const favicon = require('serve-favicon')
const compression = require('compression')
const path = require('path')
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))
const url = require('url')
const requestLog = require('./requestLog')

module.exports = (reporter, definition) => {
  reporter.addRequestContextMetaConfig('htmlTitle', { sandboxReadOnly: true })

  const distPath = reporter.execution ? reporter.execution.tempDirectory : path.join(__dirname, '../static/dist')
  if (definition.options.requestLogEnabled !== false) {
    requestLog(reporter)
  }
  let compiler

  function sendIndex (req, res, next) {
    const indexHtml = path.join(distPath, 'index.html')

    function send (err, content) {
      if (err) {
        return next(err)
      }

      content = content.replace('client.js', reporter.options.appPath + 'studio/assets/client.js')

      res.send(content.replace('$jsreportTitle', req.context.htmlTitle || `jsreport ${reporter.version} ${reporter.options.mode}`))
    }

    function tryRead () {
      compiler.outputFileSystem.readFile(indexHtml, 'utf8', (err, content) => {
        if (err) {
          return setTimeout(tryRead, 1000)
        }

        send(null, content)
      })
    }

    if (reporter.options.mode === 'jsreport-development') {
      tryRead()
    } else {
      fs.readFile(indexHtml, 'utf8', send)
    }
  }

  function redirectOrSendIndex (req, res, next) {
    const reqUrl = url.parse(req.originalUrl)
    if (reqUrl.pathname[reqUrl.pathname.length - 1] !== '/') {
      return res.redirect(reqUrl.pathname + '/' + (reqUrl.search || ''))
    }

    sendIndex(req, res, next)
  }

  reporter.on('after-authentication-express-routes', () => reporter.express.app.get('/', redirectOrSendIndex))

  reporter.on('after-express-static-configure', () => {
    if (!reporter.authentication) {
      return reporter.express.app.get('/', redirectOrSendIndex)
    }
  })

  reporter.on('before-express-configure', () => {
    reporter.express.app.use('/api/report', (req, res, next) => {
      res.cookie('render-complete', true)
      next()
    })
  })

  reporter.on('express-configure', () => {
    const extsInNormalMode = []

    if (reporter.options.mode !== 'jsreport-development') {
      if (!fs.existsSync(path.join(distPath, 'extensions.client.js'))) {
        fs.renameSync(path.join(distPath, '1.client.js'), path.join(distPath, 'extensions.client.js'))
      }
      const webpackWrap = fs.readFileSync(path.join(distPath, 'extensions.client.js'), 'utf8')
      const webpackExtensions = webpackWrap.replace('$extensionsHere', () => {
        return reporter.extensionsManager.extensions.map((e) => {
          try {
            if (reporter.execution && reporter.execution.resource(e.name)) {
              return reporter.execution.resource(e.name)
            }
            return fs.readFileSync(path.join(e.directory, 'studio/main.js'))
          } catch (e) {
            return ''
          }
        }).join('\n')
      })
      fs.writeFileSync(path.join(distPath, '1.client.js'), webpackExtensions)
    } else {
      const extsConfiguredInDevMode = process.env.JSREPORT_CURRENT_EXTENSION != null ? [process.env.JSREPORT_CURRENT_EXTENSION] : []

      if (definition.options.extensionsInDevMode != null) {
        let extensionsDefined = []

        if (Array.isArray(definition.options.extensionsInDevMode)) {
          extensionsDefined = [...definition.options.extensionsInDevMode]
        } else if (typeof definition.options.extensionsInDevMode === 'string') {
          extensionsDefined = [definition.options.extensionsInDevMode]
        }

        extensionsDefined.forEach((ext) => {
          if (ext !== '' && !extsConfiguredInDevMode.includes(ext)) {
            extsConfiguredInDevMode.push(ext)
          }
        })
      }

      if (extsConfiguredInDevMode.length > 0) {
        reporter.logger.debug(`studio extensions configured in dev mode: ${extsConfiguredInDevMode.join(', ')}`)
      } else {
        reporter.logger.debug('all studio extensions are configured in dev mode')
      }

      fs.writeFileSync(path.join(__dirname, '../src/extensions_dev.js'), reporter.extensionsManager.extensions.map((e) => {
        const shouldUseMainEntry = extsConfiguredInDevMode.length > 0 && !extsConfiguredInDevMode.includes(e.name)

        try {
          fs.statSync(path.join(e.directory, '/studio/main_dev.js'))

          const extensionPath = shouldUseMainEntry ? (
            path.join(e.directory, '/studio/main.js')
          ) : path.join(e.directory, '/studio/main_dev.js')

          if (shouldUseMainEntry) {
            extsInNormalMode.push(e)
          }

          return `import '${path.relative(path.join(__dirname, '../src'), extensionPath).replace(/\\/g, '/')}'`
        } catch (e) {
          return ''
        }
      }).join('\n'))
    }

    const app = reporter.express.app

    app.use(compression())
    app.use(favicon(path.join(reporter.execution ? distPath : path.join(__dirname, '../static'), 'favicon.ico')))

    if (reporter.options.mode === 'jsreport-development') {
      const webpack = require('jsreport-studio-dev').deps.webpack

      const webpackConfig = require('../webpack/dev.config')(
        reporter.extensionsManager.extensions,
        extsInNormalMode
      )

      compiler = webpack(webpackConfig)
      reporter.express.app.use(require('webpack-dev-middleware')(compiler, {
        publicPath: '/studio/assets/',
        hot: true,
        inline: true,
        lazy: false,
        stats: { colors: true, chunks: false }
      }))
      reporter.express.app.use(require('webpack-hot-middleware')(compiler))
    }

    app.use('/studio/assets', serveStatic(reporter.execution ? reporter.execution.tempDirectory : path.join(__dirname, '../static', 'dist')))

    app.use('/studio/hierarchyMove', async (req, res) => {
      const source = req.body.source
      const target = req.body.target
      const shouldCopy = req.body.copy === true
      const shouldReplace = req.body.replace === true

      try {
        if (!source || !target) {
          const missing = !source ? 'source' : 'target'
          throw new Error(`No "${missing}" for specified in payload`)
        }

        const updatedItems = await reporter.folders.move({
          source,
          target,
          shouldCopy,
          shouldReplace
        }, req)

        res.status(200).json({
          items: updatedItems
        })
      } catch (e) {
        const errorRes = { message: e.message }

        if (e.code === 'DUPLICATED_ENTITY') {
          errorRes.code = e.code
        }

        res.status(400).json(errorRes)
      }
    })

    app.post('/studio/validate-entity-name', (req, res) => {
      const entityName = req.body.name

      try {
        reporter.validateEntityName(entityName)
        res.status(200).end()
      } catch (e) {
        res.status(400).end(e.message)
      }
    })

    app.get('/studio/*', sendIndex)
  })

  if (reporter.compilation) {
    reporter.compilation.exclude('webpack-dev-middleware', 'webpack-hot-middleware', 'webpack', 'babel-polyfill', 'html-webpack-plugin', 'jsreport-studio-dev')
    reporter.compilation.resourceInTemp('favicon.ico', path.join(__dirname, '../static', 'favicon.ico'))

    reporter.initializeListeners.add('studio', async () => {
      const mains = await Promise.all(reporter.extensionsManager.extensions.map(async (e) => {
        try {
          await fs.statAsync(path.join(e.directory, 'studio', 'main.js'))
          return e
        } catch (e) {
          return null
        }
      }))

      mains.forEach((e) => {
        if (e) {
          reporter.compilation.resource(e.name, path.join(e.directory, 'studio', 'main.js'))
        }
      })

      const files = await fs.readdirAsync(distPath)
      files.forEach(function (f) {
        if (f.indexOf('.map') === -1 && f.indexOf('1.client.js') === -1) {
          reporter.compilation.resourceInTemp(f, path.join(distPath, f))
        }
      })
    })
  }
}
<commit_msg>convert entities buffers to base64 before responding back to client<commit_after>const serveStatic = require('serve-static')
const favicon = require('serve-favicon')
const compression = require('compression')
const path = require('path')
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))
const url = require('url')
const requestLog = require('./requestLog')

module.exports = (reporter, definition) => {
  reporter.addRequestContextMetaConfig('htmlTitle', { sandboxReadOnly: true })

  const distPath = reporter.execution ? reporter.execution.tempDirectory : path.join(__dirname, '../static/dist')
  if (definition.options.requestLogEnabled !== false) {
    requestLog(reporter)
  }
  let compiler

  function sendIndex (req, res, next) {
    const indexHtml = path.join(distPath, 'index.html')

    function send (err, content) {
      if (err) {
        return next(err)
      }

      content = content.replace('client.js', reporter.options.appPath + 'studio/assets/client.js')

      res.send(content.replace('$jsreportTitle', req.context.htmlTitle || `jsreport ${reporter.version} ${reporter.options.mode}`))
    }

    function tryRead () {
      compiler.outputFileSystem.readFile(indexHtml, 'utf8', (err, content) => {
        if (err) {
          return setTimeout(tryRead, 1000)
        }

        send(null, content)
      })
    }

    if (reporter.options.mode === 'jsreport-development') {
      tryRead()
    } else {
      fs.readFile(indexHtml, 'utf8', send)
    }
  }

  function redirectOrSendIndex (req, res, next) {
    const reqUrl = url.parse(req.originalUrl)
    if (reqUrl.pathname[reqUrl.pathname.length - 1] !== '/') {
      return res.redirect(reqUrl.pathname + '/' + (reqUrl.search || ''))
    }

    sendIndex(req, res, next)
  }

  reporter.on('after-authentication-express-routes', () => reporter.express.app.get('/', redirectOrSendIndex))

  reporter.on('after-express-static-configure', () => {
    if (!reporter.authentication) {
      return reporter.express.app.get('/', redirectOrSendIndex)
    }
  })

  reporter.on('before-express-configure', () => {
    reporter.express.app.use('/api/report', (req, res, next) => {
      res.cookie('render-complete', true)
      next()
    })
  })

  reporter.on('express-configure', () => {
    const extsInNormalMode = []

    if (reporter.options.mode !== 'jsreport-development') {
      if (!fs.existsSync(path.join(distPath, 'extensions.client.js'))) {
        fs.renameSync(path.join(distPath, '1.client.js'), path.join(distPath, 'extensions.client.js'))
      }
      const webpackWrap = fs.readFileSync(path.join(distPath, 'extensions.client.js'), 'utf8')
      const webpackExtensions = webpackWrap.replace('$extensionsHere', () => {
        return reporter.extensionsManager.extensions.map((e) => {
          try {
            if (reporter.execution && reporter.execution.resource(e.name)) {
              return reporter.execution.resource(e.name)
            }
            return fs.readFileSync(path.join(e.directory, 'studio/main.js'))
          } catch (e) {
            return ''
          }
        }).join('\n')
      })
      fs.writeFileSync(path.join(distPath, '1.client.js'), webpackExtensions)
    } else {
      const extsConfiguredInDevMode = process.env.JSREPORT_CURRENT_EXTENSION != null ? [process.env.JSREPORT_CURRENT_EXTENSION] : []

      if (definition.options.extensionsInDevMode != null) {
        let extensionsDefined = []

        if (Array.isArray(definition.options.extensionsInDevMode)) {
          extensionsDefined = [...definition.options.extensionsInDevMode]
        } else if (typeof definition.options.extensionsInDevMode === 'string') {
          extensionsDefined = [definition.options.extensionsInDevMode]
        }

        extensionsDefined.forEach((ext) => {
          if (ext !== '' && !extsConfiguredInDevMode.includes(ext)) {
            extsConfiguredInDevMode.push(ext)
          }
        })
      }

      if (extsConfiguredInDevMode.length > 0) {
        reporter.logger.debug(`studio extensions configured in dev mode: ${extsConfiguredInDevMode.join(', ')}`)
      } else {
        reporter.logger.debug('all studio extensions are configured in dev mode')
      }

      fs.writeFileSync(path.join(__dirname, '../src/extensions_dev.js'), reporter.extensionsManager.extensions.map((e) => {
        const shouldUseMainEntry = extsConfiguredInDevMode.length > 0 && !extsConfiguredInDevMode.includes(e.name)

        try {
          fs.statSync(path.join(e.directory, '/studio/main_dev.js'))

          const extensionPath = shouldUseMainEntry ? (
            path.join(e.directory, '/studio/main.js')
          ) : path.join(e.directory, '/studio/main_dev.js')

          if (shouldUseMainEntry) {
            extsInNormalMode.push(e)
          }

          return `import '${path.relative(path.join(__dirname, '../src'), extensionPath).replace(/\\/g, '/')}'`
        } catch (e) {
          return ''
        }
      }).join('\n'))
    }

    const app = reporter.express.app

    app.use(compression())
    app.use(favicon(path.join(reporter.execution ? distPath : path.join(__dirname, '../static'), 'favicon.ico')))

    if (reporter.options.mode === 'jsreport-development') {
      const webpack = require('jsreport-studio-dev').deps.webpack

      const webpackConfig = require('../webpack/dev.config')(
        reporter.extensionsManager.extensions,
        extsInNormalMode
      )

      compiler = webpack(webpackConfig)
      reporter.express.app.use(require('webpack-dev-middleware')(compiler, {
        publicPath: '/studio/assets/',
        hot: true,
        inline: true,
        lazy: false,
        stats: { colors: true, chunks: false }
      }))
      reporter.express.app.use(require('webpack-hot-middleware')(compiler))
    }

    app.use('/studio/assets', serveStatic(reporter.execution ? reporter.execution.tempDirectory : path.join(__dirname, '../static', 'dist')))

    app.use('/studio/hierarchyMove', async (req, res) => {
      const source = req.body.source
      const target = req.body.target
      const shouldCopy = req.body.copy === true
      const shouldReplace = req.body.replace === true

      try {
        if (!source || !target) {
          const missing = !source ? 'source' : 'target'
          throw new Error(`No "${missing}" for specified in payload`)
        }

        const updatedItems = await reporter.folders.move({
          source,
          target,
          shouldCopy,
          shouldReplace
        }, req)

        for (const e of updatedItems) {
          Object.assign(e, reporter.documentStore.collection(e.__entitySet).convertBufferToBase64InEntity([e])[0])
        }

        res.status(200).json({
          items: updatedItems
        })
      } catch (e) {
        const errorRes = { message: e.message }

        if (e.code === 'DUPLICATED_ENTITY') {
          errorRes.code = e.code
        }

        res.status(400).json(errorRes)
      }
    })

    app.post('/studio/validate-entity-name', (req, res) => {
      const entityName = req.body.name

      try {
        reporter.validateEntityName(entityName)
        res.status(200).end()
      } catch (e) {
        res.status(400).end(e.message)
      }
    })

    app.get('/studio/*', sendIndex)
  })

  if (reporter.compilation) {
    reporter.compilation.exclude('webpack-dev-middleware', 'webpack-hot-middleware', 'webpack', 'babel-polyfill', 'html-webpack-plugin', 'jsreport-studio-dev')
    reporter.compilation.resourceInTemp('favicon.ico', path.join(__dirname, '../static', 'favicon.ico'))

    reporter.initializeListeners.add('studio', async () => {
      const mains = await Promise.all(reporter.extensionsManager.extensions.map(async (e) => {
        try {
          await fs.statAsync(path.join(e.directory, 'studio', 'main.js'))
          return e
        } catch (e) {
          return null
        }
      }))

      mains.forEach((e) => {
        if (e) {
          reporter.compilation.resource(e.name, path.join(e.directory, 'studio', 'main.js'))
        }
      })

      const files = await fs.readdirAsync(distPath)
      files.forEach(function (f) {
        if (f.indexOf('.map') === -1 && f.indexOf('1.client.js') === -1) {
          reporter.compilation.resourceInTemp(f, path.join(distPath, f))
        }
      })
    })
  }
}
<|endoftext|>


<commit_before>/******************************************
* Row Officers List View
*/
app.Views.OfficersListView = Backbone.View.extend({

	tagName      : 'tr',

	className    : 'row-nested-objects-collapse',

	templateHTML : 'officersList',

	isDisplay    : false,

	// The DOM events  //
	events: {
		'click button.modalCreateOfficer' : 'modalCreateOfficer'
	},

	/** View Initialization
	*/
	initialize: function () {
		// Instantiate the collection //
		this.collection = new app.Collections.Officers();

		this.collection.off();
		this.listenTo(this.collection, 'add', this.add);

	},

	/** When the model ara created //
	*/
	add: function(model){

		var itemOfficerView  = new app.Views.ItemOfficerView({ model: model });
		$('#rows-officers').prepend(itemOfficerView.render().el);
		app.Helpers.Main.highlight($(itemOfficerView.el))

		app.notify('', 'success', app.lang.infoMessages.information, model.getName()+' : '+app.lang.infoMessages.officerCreateOk);
	},

	/** Display the view
	*/
    render: function () {
    	var self = this;

		// Retrieve the template //
		$.get("templates/" + this.templateHTML + ".html", function(templateData){
			var template = _.template(templateData, {
				lang      : app.lang,
				service   : self.model
			});

			$(self.el).html(template);

		});

		return this;
	},

	collapse: function(e){
		var self = this;

		// Is know hide //
		if(this.isDisplay){
			this.isDisplay = false;
		}
		// Is Know Display //
		else{

			if(!_.isEmpty(self.model.getUsersId())){

				// Fetch the Officers //
				self.fetchOfficers().done(function(){

					$('#rows-officers').html('');

					// Create item Officer view //
					_.each(self.collection.models, function(officer, i){
						var itemOfficerView  = new app.Views.ItemOfficerView({model: officer});
						$(self.el).find('#rows-officers').append(itemOfficerView.render().el);
					});
				})
			}

			this.isDisplay = true;
		}

		$(this.el).stop().fadeToggle();

	},

	/** Modal form to create a new Officer
	*/
	modalCreateOfficer: function(e){
		e.preventDefault();

		app.views.modalOfficerView = new app.Views.ModalOfficerView({
			el  : '#modalSaveOfficer',
			officersListView : this
		});
	},

	/** Collection Initialisation
	*/
	fetchOfficers: function(){
		var self = this;

		this.options.sort = this.collection.default_sort;

		// Create Fetch params //
		this.fetchParams = {
			silent : true,
			data   : {
				sort    : this.options.sort.by+' '+this.options.sort.order,
				filters : {0: {field: 'service_id.id', operator: '=', value: this.model.getId()}}
			}
		};

		return $.when(self.collection.fetch(this.fetchParams))
			.fail(function(e){
				console.log(e);
			})
	}

});<commit_msg>other bugfixed on officerLists: updated jquery selector to reset correct officersList (same selector update as 1st commit on this bug)<commit_after>/******************************************
* Row Officers List View
*/
app.Views.OfficersListView = Backbone.View.extend({

	tagName      : 'tr',

	className    : 'row-nested-objects-collapse',

	templateHTML : 'officersList',

	isDisplay    : false,

	// The DOM events  //
	events: {
		'click button.modalCreateOfficer' : 'modalCreateOfficer'
	},

	/** View Initialization
	*/
	initialize: function () {
		// Instantiate the collection //
		this.collection = new app.Collections.Officers();

		this.collection.off();
		this.listenTo(this.collection, 'add', this.add);

	},

	/** When the model ara created //
	*/
	add: function(model){

		var itemOfficerView  = new app.Views.ItemOfficerView({ model: model });
		$('#rows-officers').prepend(itemOfficerView.render().el);
		app.Helpers.Main.highlight($(itemOfficerView.el))

		app.notify('', 'success', app.lang.infoMessages.information, model.getName()+' : '+app.lang.infoMessages.officerCreateOk);
	},

	/** Display the view
	*/
    render: function () {
    	var self = this;

		// Retrieve the template //
		$.get("templates/" + this.templateHTML + ".html", function(templateData){
			var template = _.template(templateData, {
				lang      : app.lang,
				service   : self.model
			});

			$(self.el).html(template);

		});

		return this;
	},

	collapse: function(e){
		var self = this;

		// Is know hide //
		if(this.isDisplay){
			this.isDisplay = false;
		}
		// Is Know Display //
		else{

			if(!_.isEmpty(self.model.getUsersId())){

				// Fetch the Officers //
				self.fetchOfficers().done(function(){

					$(self.el).find('#rows-officers').html('');

					// Create item Officer view //
					_.each(self.collection.models, function(officer, i){
						var itemOfficerView  = new app.Views.ItemOfficerView({model: officer});
						$(self.el).find('#rows-officers').append(itemOfficerView.render().el);
					});
				})
			}

			this.isDisplay = true;
		}

		$(this.el).stop().fadeToggle();

	},

	/** Modal form to create a new Officer
	*/
	modalCreateOfficer: function(e){
		e.preventDefault();

		app.views.modalOfficerView = new app.Views.ModalOfficerView({
			el  : '#modalSaveOfficer',
			officersListView : this
		});
	},

	/** Collection Initialisation
	*/
	fetchOfficers: function(){
		var self = this;

		this.options.sort = this.collection.default_sort;

		// Create Fetch params //
		this.fetchParams = {
			silent : true,
			data   : {
				sort    : this.options.sort.by+' '+this.options.sort.order,
				filters : {0: {field: 'service_id.id', operator: '=', value: this.model.getId()}}
			}
		};

		return $.when(self.collection.fetch(this.fetchParams))
			.fail(function(e){
				console.log(e);
			})
	}

});<|endoftext|>


<commit_before>$(function(){
    $.confirm({
        title: '',
        content: '
'
        + '
Imglab is an open source free to use application.
'
        + '
 Please consider small donation for support.
'
        + '
 Give us a star on GitHub or showcase your project as a motivation.
',
        escapeKey: true,
        backgroundDismiss: true,
        buttons: {
            confirm: {
                text: "Donate",
                action : function () {
                    displayDonationPrompt();
                }
            },
            leave : {
                text: "Umm! may be next time."
            }
        }
    });
});

function displayDonationPrompt(){
    $.dialog({
        title: 'Donate',
        content: `

                         Tez

`,
        escapeKey: true,
        backgroundDismiss: true,
    });
}

function tezpayment(){
    $.dialog({
        title: "Tez Payment",
        content: "
Please scan the below QR code or use UPI : amitgupta.gwl@okhdfcbank
" + ''
    })
    gtag('event', 'click', {
        'event_category': 'outbound',
        'event_label': "tez",
        'transport_type': 'beacon',
    });
}

function logPaypal(){
    gtag('event', 'click', {
        'event_category': 'outbound',
        'event_label': "paypal",
        'transport_type': 'beacon',
    });
}

function logPateron(){
    gtag('event', 'click', {
        'event_category': 'outbound',
        'event_label': "patreon",
        'transport_type': 'beacon',
    });
}

<commit_msg>Update prompt.js<commit_after>$(function(){
    $.confirm({
        title: '',
        content: '
'
        + '
Imglab is an open source free to use application.
'
        + '
 Please consider small donation for support.
'
        + '
 Give us a star on GitHub or showcase your project as a motivation.
',
        escapeKey: true,
        backgroundDismiss: true,
        buttons: {
            confirm: {
                text: "Donate",
                action : function () {
                    displayDonationPrompt();
                }
            },
            leave : {
                text: "Umm! may be next time."
            }
        }
    });
});

function displayDonationPrompt(){
    $.dialog({
        title: 'Donate',
        content: `

                         Tez

`,
        escapeKey: true,
        backgroundDismiss: true,
    });
}

function tezpayment(){
    $.dialog({
        title: "Tez Payment",
        content: "
Please scan the below QR code or use UPI : amitgupta.gwl@okhdfcbank
" + ''
    })
    gtag('event', 'click', {
        'event_category': 'outbound',
        'event_label': "tez",
        'transport_type': 'beacon',
    });
}

function logPaypal(){
    gtag('event', 'click', {
        'event_category': 'outbound',
        'event_label': "paypal",
        'transport_type': 'beacon',
    });
}

function logPateron(){
    gtag('event', 'click', {
        'event_category': 'outbound',
        'event_label': "patreon",
        'transport_type': 'beacon',
    });
}

<|endoftext|>


<commit_before>/*
 * https://github.com/starzou
 *
 * Copyright (c) 2014 StarZou
 * Licensed under the MIT license.
 */

/**
 * @class app
 * @description
 * @time 2014-12-14 20:24
 * @author StarZou
 **/
(function (window, document) {
    'use strict';

    var App = angular.module('app', ['ui.router']);

    App.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {

        $urlRouterProvider.otherwise('/home/');

        $stateProvider
            .state('home', {
                url        : '/home/:name',
                templateUrl: 'home.html',
                controller : 'HomeController'
            })
            .state('home.list', {
                url     : '/list',
                template: '
this home list
'
            })
            .state('page1', {
                url     : '/page1',
                template: '
page1
'
            })
            .state('page1.list', {
                url     : '/list',
                template: '
page1-list
'
            })
            .state('page2', {
                url     : '/page2',
                template: '
page2
'
            })
            .state('page3', {
                url        : '/page3',
                templateUrl: 'page3.html',
                resolve    : {
                    user : function () {
                        return {name: 'StarZou'};
                    },
                    users: ['$http', function ($http) {
                        return $http.get('/rest/users');
                    }]
                },
                controller : ['$scope', 'user', 'users', function ($scope, user, users) {
                    $scope.title = 'page3';
                    console.log($scope, user);
                    console.log(users);
                }]
            });
    }]);

    App.run(['$rootScope', function ($rootScope) {
        $rootScope.title = 'ui-router 示例';
    }]);

    App.controller('AppController', ['$scope', function ($scope) {
        console.log('AppController', $scope);
    }]);

    App.controller('HomeController', ['$scope', '$stateParams', function ($scope, $stateParams) {
        console.log('HomeController', $stateParams);
    }]);

})(window, document);<commit_msg>添加 ui-router 示例<commit_after>/*
 * https://github.com/starzou
 *
 * Copyright (c) 2014 StarZou
 * Licensed under the MIT license.
 */

/**
 * @class app
 * @description
 * @time 2014-12-14 20:24
 * @author StarZou
 **/
(function (window, document) {
    'use strict';

    var App = angular.module('app', ['ui.router']);

    App.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {

        $urlRouterProvider.otherwise('/home/');

        $stateProvider
            .state('home', {
                abstract   : true,
                url        : '/home/:name',
                templateUrl: 'home.html',
                controller : 'HomeController'
            })
            .state('home.list', {
                url     : '/list',
                template: '
this home list
'
            })
            .state('page1', {
                url     : '/page1',
                template: '
page1
'
            })
            .state('page1.list', {
                url     : '/list',
                template: '
page1-list
'
            })
            .state('page2', {
                url     : '/page2',
                template: '
page2
'
            })
            .state('page3', {
                url        : '/page3',
                templateUrl: 'page3.html',
                resolve    : {
                    user : function () {
                        return {name: 'StarZou'};
                    },
                    users: ['$http', function ($http) {
                        return $http.get('/rest/users');
                    }]
                },
                controller : ['$scope', 'user', 'users', function ($scope, user, users) {
                    $scope.title = 'page3';
                    console.log($scope, user);
                    console.log(users);
                }]
            });
    }]);

    App.run(['$rootScope', function ($rootScope) {
        $rootScope.title = 'ui-router 示例';
    }]);

    App.controller('AppController', ['$scope', function ($scope) {
        console.log('AppController', $scope);
    }]);

    App.controller('HomeController', ['$scope', '$stateParams', function ($scope, $stateParams) {
        console.log('HomeController', $stateParams);
    }]);

})(window, document);<|endoftext|>


<commit_before>String.prototype.replaceAll = function(search, replace)
{
    //if replace is null, return original string otherwise it will
    //replace search string with 'undefined'.
    if(!replace)
        return this;

    return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};

function github(username){
    var mess = "Repositories:\n";
    var list = [];

    jQuery.githubUser = function(username, callback) {
        jQuery.getJSON('https://api.github.com/users/'+username+'/repos?callback=?',callback);
    }

    $.githubUser(username, function(data) {
        var repos = data.data; // JSON Parsing

        $(repos).each(function() {
            var message = this.name + " - " + this.description + "\n";
            if (this.name != (username.toLowerCase()+'.github.com')) {

                list.push(message);
                mess += message;
            }

        });
        console.log(mess);
        return mess;
    });

 return mess;
}

// Variables
var title = "Welcome to " + name + "'s résumé. Enter command `help` for command list";

// Command map
var commandMap = {};
var commandFunctionMap = {};

function init(){
    commandMap["clear"] = " - clear command history from screen.";

    commandMap["github"] = " - list Github repositories.";

    commandMap["name"] = " - owner of the résumé.";
    commandFunctionMap["name"] = name;

    commandMap["pdf"] = " - pdf version of the resume.";
    commandFunctionMap["pdf"] = pdf;

    commandMap["lookingfor"] = " - looking for.";
    commandFunctionMap["lookingfor"] = lookingfor;

    commandMap["location"] = " - current location.";
    commandFunctionMap["location"] = loc;

    commandMap["education"] = " - education history. [-top]";
    commandFunctionMap["education -top"] = getTop(education);
    commandFunctionMap["education"] = getAll("Education:\n", education);

    commandMap["employment"] = " - employment history. [-top]";
    commandFunctionMap["employment -top"] = getTop(employment);
    commandFunctionMap["employment"] = getAll("Employment:\n", employment);

    commandMap["volunteering"] = " - volunteering history. [-top]";
    commandFunctionMap["volunteering -top"] = getTop(volunteering);
    commandFunctionMap["volunteering"] = getAll("Volunteering:\n", volunteering);

    commandMap["awards"] = " - awards obtained.";
    commandFunctionMap["awards"] = getAll("Awards:\n", awards);

    commandMap["membership"] = " - membership obtained.";
    commandFunctionMap["membership"] = getAll("Professional membership:\n", membership);

    commandMap["skills"] = " - membership obtained. [-languages|l][-tools|t][-concepts|c]";
    commandFunctionMap["skills"] = getSkillTable();
    commandFunctionMap["skills -l"] = commandFunctionMap["skills -language"]
        = getAll("Languages:\n", skillsLanguages);
    commandFunctionMap["skills -t"] = commandFunctionMap["skills -tools"]
        = getAll("Tools:\n", skillsTools);
    commandFunctionMap["skills -c"] = commandFunctionMap["skills -concepts"]
        = getAll("Concepts:\n", skillsConcepts);

    commandMap["socialmedia"] = " - Social Media profiles.";
    commandFunctionMap["socialmedia"] = getSocialMedia();

    commandMap.getKeys = function (){
    var commands = "Commands:\n";
    for(var key in this) {

        if( typeof this[key] !== 'function') {
            commands += key + commandMap[key] + "\n";
        }
    }
    return commands;
    };
}

function pdf(){
    window.open(pdfLink);
    return "Hint: May need to allow pop-ups.";
}

function getAll(result, array){
    array.map( function(item) {
        result += (item.join()).replaceAll(",","\t") + "\n";
    });
    return result;
}

function getSocialMedia(){
    var result = "Social Media:\n";
    socialMedia.map(function(item){
        if (item[1].length > 0){
            result += item[0] + " - " + item[1] + "\n";
        }
    });
    return result;
}

function getRequired(skillList){
    var result = [];
    var i = 0;
    skillList.map(function(item){
        result[i] = item[1];
        i++;
    });
    return result;
}

function getSkillTable(){
    var result = "\t\t\t|\tProficient\t|\tExperienced\t|\tFamiliar\n";
    result += "Languages\t|" + getRequired(skillsLanguages).join().replaceAll(",","\t|\t") + "\n";
    result += "Tools\t|" + getRequired(skillsTools).join().replaceAll(",","\t|\t") + "\n";
    result += "Concepts\t|" + getRequired(skillsConcepts).join().replaceAll(",","\t|\t") + "\n";

    return result;
}

function getTop(array){
    return (array[0].join()).replaceAll(",","\t");
}

function social() {

}<commit_msg>Fixed missing title bug.<commit_after>String.prototype.replaceAll = function(search, replace)
{
    //if replace is null, return original string otherwise it will
    //replace search string with 'undefined'.
    if(!replace)
        return this;

    return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};

function github(username){
    var mess = "Repositories:\n";
    var list = [];

    jQuery.githubUser = function(username, callback) {
        jQuery.getJSON('https://api.github.com/users/'+username+'/repos?callback=?',callback);
    }

    $.githubUser(username, function(data) {
        var repos = data.data; // JSON Parsing

        $(repos).each(function() {
            var message = this.name + " - " + this.description + "\n";
            if (this.name != (username.toLowerCase()+'.github.com')) {

                list.push(message);
                mess += message;
            }

        });
        console.log(mess);
        return mess;
    });

 return mess;
}

// Variables
var title;

// Command map
var commandMap = {};
var commandFunctionMap = {};

function init(){
    title = "Welcome to " + name + "'s résumé. Enter command `help` for command list";

    commandMap["clear"] = " - clear command history from screen.";

    commandMap["github"] = " - list Github repositories.";

    commandMap["name"] = " - owner of the résumé.";
    commandFunctionMap["name"] = name;

    commandMap["pdf"] = " - pdf version of the resume.";
    commandFunctionMap["pdf"] = pdf;

    commandMap["lookingfor"] = " - looking for.";
    commandFunctionMap["lookingfor"] = lookingfor;

    commandMap["location"] = " - current location.";
    commandFunctionMap["location"] = loc;

    commandMap["education"] = " - education history. [-top]";
    commandFunctionMap["education -top"] = getTop(education);
    commandFunctionMap["education"] = getAll("Education:\n", education);

    commandMap["employment"] = " - employment history. [-top]";
    commandFunctionMap["employment -top"] = getTop(employment);
    commandFunctionMap["employment"] = getAll("Employment:\n", employment);

    commandMap["volunteering"] = " - volunteering history. [-top]";
    commandFunctionMap["volunteering -top"] = getTop(volunteering);
    commandFunctionMap["volunteering"] = getAll("Volunteering:\n", volunteering);

    commandMap["awards"] = " - awards obtained.";
    commandFunctionMap["awards"] = getAll("Awards:\n", awards);

    commandMap["membership"] = " - membership obtained.";
    commandFunctionMap["membership"] = getAll("Professional membership:\n", membership);

    commandMap["skills"] = " - membership obtained. [-languages|l][-tools|t][-concepts|c]";
    commandFunctionMap["skills"] = getSkillTable();
    commandFunctionMap["skills -l"] = commandFunctionMap["skills -language"]
        = getAll("Languages:\n", skillsLanguages);
    commandFunctionMap["skills -t"] = commandFunctionMap["skills -tools"]
        = getAll("Tools:\n", skillsTools);
    commandFunctionMap["skills -c"] = commandFunctionMap["skills -concepts"]
        = getAll("Concepts:\n", skillsConcepts);

    commandMap["socialmedia"] = " - Social Media profiles.";
    commandFunctionMap["socialmedia"] = getSocialMedia();

    commandMap.getKeys = function (){
    var commands = "Commands:\n";
    for(var key in this) {

        if( typeof this[key] !== 'function') {
            commands += key + commandMap[key] + "\n";
        }
    }
    return commands;
    };
}

function pdf(){
    window.open(pdfLink);
    return "Hint: May need to allow pop-ups.";
}

function getAll(result, array){
    array.map( function(item) {
        result += (item.join()).replaceAll(",","\t") + "\n";
    });
    return result;
}

function getSocialMedia(){
    var result = "Social Media:\n";
    socialMedia.map(function(item){
        if (item[1].length > 0){
            result += item[0] + " - " + item[1] + "\n";
        }
    });
    return result;
}

function getRequired(skillList){
    var result = [];
    var i = 0;
    skillList.map(function(item){
        result[i] = item[1];
        i++;
    });
    return result;
}

function getSkillTable(){
    var result = "\t\t\t|\tProficient\t|\tExperienced\t|\tFamiliar\n";
    result += "Languages\t|" + getRequired(skillsLanguages).join().replaceAll(",","\t|\t") + "\n";
    result += "Tools\t|" + getRequired(skillsTools).join().replaceAll(",","\t|\t") + "\n";
    result += "Concepts\t|" + getRequired(skillsConcepts).join().replaceAll(",","\t|\t") + "\n";

    return result;
}

function getTop(array){
    return (array[0].join()).replaceAll(",","\t");
}

function social() {

}<|endoftext|>


<commit_before>/*!
 * Teo.JS DB driver implementation
 * @author Andrew Teologov <teologov.and@gmail.com>
 * @date 2/8/16
 */

"use strict";

const
    Base = require("teo-base"),
    path = require("path");

module.exports = class TeoDB extends Base {
    constructor(config) {
        super(config);
        // if usage of db is enabled
        if (this.config.enabled === true) {
            try {
                this.loadAdapter();
                this.createAdapter();
            } catch(e) {
                console.error(e);
                throw e;
            }
        }
    }

    applyConfig(config) {
        this.config = {enabled: config.enabled, adapterConfig: {}};

        let adapterDefaultConfig = {
            adapterPath: config.adapterConfig.adapterPath || path.join(this.homeDir, "adapters"),
            adapterPrefix: config.adapterConfig.adapterPrefix || "teo.db.adapter.",
            adapterName: config.adapterConfig.adapterName || "default",
            adapterModule: config.adapterConfig.adapterModule,
            // adapters
            adapters: Object.assign({}, config.adapterConfig.adapters),
            // Connections Config
            // Setup connections using the named adapter configs
            connections: Object.assign({}, config.adapterConfig.connections)
        };

        Object.assign(this.config.adapterConfig, config.adapterConfig, adapterDefaultConfig);
    }

    /**
     * Loads ORM
     */
    loadAdapter() {
        if (this.adapterConfig.adapterModule) {
            this.loadAdapterFile(this.adapterConfig.adapterModule);
        }
        else {
            this.loadAdapterFile(path.join(this.adapterConfig.adapterPath, `${this.adapterConfig.adapterPrefix.toLowerCase()}${this.adapterConfig.adapterName.toLowerCase()}`));
        }
    }

    /**
     * Loads ORM module
     * @param {String} adapterPath
     */
    loadAdapterFile(adapterPath) {
        this.Adapter = this._load(adapterPath);
    }

    /**
     * Loads file or module
     * @param {String} path
     * @private
     */
    _load(path) {
        let module;
        try {
            module = require(path);
        } catch(e) {
            console.error(e);
            throw e;
        }
        return module;
    }

    /**
     * Creates ORM instance
     */
    createAdapter() {
        this.adapterInstance = new this.Adapter({
            // some inner adapters, if needed
            adapters: this.adapterConfig.adapters,
            // Connections Config
            // Setup connections using the named adapter configs
            connections: this.adapterConfig.connections
        });

        return this.adapterInstance;
    }

    /**
     * Getter of ORM instance
     * @returns {*}
     */
    getAdapterInstance() {
        return this.adapterInstance;
    }

    /**
     * Connects db
     */
    * connect() {
        yield* this.getAdapterInstance().connect();
    }

    /**
     * Disconnect db
     */
    * disconnect() {
        yield* this.getAdapterInstance().disconnect();
    }

    /**
     * Check if DB is connected
     * @returns {Boolean}
     */
    isConnected() {
        return this.getAdapterInstance().isConnected();
    }

    get homeDir() {
        return process.cwd().replace(/\\/g, "/");
    }

    get instance() {
        return this.adapterInstance;
    }

    get adapterConfig() {
        return this.config.adapterConfig;
    }
};<commit_msg>pass full config to adapter constructor<commit_after>/*!
 * Teo.JS DB driver implementation
 * @author Andrew Teologov <teologov.and@gmail.com>
 * @date 2/8/16
 */

"use strict";

const
    Base = require("teo-base"),
    path = require("path");

module.exports = class TeoDB extends Base {
    constructor(config) {
        super(config);
        // if usage of db is enabled
        if (this.config.enabled === true) {
            try {
                this.loadAdapter();
                this.createAdapter();
            } catch(e) {
                console.error(e);
                throw e;
            }
        }
    }

    applyConfig(config) {
        this.config = {enabled: config.enabled, adapterConfig: {}};

        let adapterDefaultConfig = {
            adapterPath: config.adapterConfig.adapterPath || path.join(this.homeDir, "adapters"),
            adapterPrefix: config.adapterConfig.adapterPrefix || "teo.db.adapter.",
            adapterName: config.adapterConfig.adapterName || "default",
            adapterModule: config.adapterConfig.adapterModule,
            // adapters
            //adapters: Object.assign({}, config.adapterConfig.adapters),
            // Connections Config
            // Setup connections using the named adapter configs
            connections: Object.assign({}, config.adapterConfig.connections)
        };

        Object.assign(this.config.adapterConfig, config.adapterConfig, adapterDefaultConfig);
    }

    /**
     * Loads ORM
     */
    loadAdapter() {
        if (this.adapterConfig.adapterModule) {
            this.loadAdapterFile(this.adapterConfig.adapterModule);
        }
        else {
            this.loadAdapterFile(path.join(this.adapterConfig.adapterPath, `${this.adapterConfig.adapterPrefix.toLowerCase()}${this.adapterConfig.adapterName.toLowerCase()}`));
        }
    }

    /**
     * Loads ORM module
     * @param {String} adapterPath
     */
    loadAdapterFile(adapterPath) {
        this.Adapter = this._load(adapterPath);
    }

    /**
     * Loads file or module
     * @param {String} path
     * @private
     */
    _load(path) {
        let module;
        try {
            module = require(path);
        } catch(e) {
            console.error(e);
            throw e;
        }
        return module;
    }

    /**
     * Creates ORM instance
     */
    createAdapter() {
        this.adapterInstance = new this.Adapter(this.adapterConfig);   // pass all adapter config
        return this.adapterInstance;
    }

    /**
     * Getter of ORM instance
     * @returns {*}
     */
    getAdapterInstance() {
        return this.adapterInstance;
    }

    /**
     * Connects db
     */
    * connect() {
        yield* this.getAdapterInstance().connect();
    }

    /**
     * Disconnect db
     */
    * disconnect() {
        yield* this.getAdapterInstance().disconnect();
    }

    /**
     * Check if DB is connected
     * @returns {Boolean}
     */
    isConnected() {
        return this.getAdapterInstance().isConnected();
    }

    get homeDir() {
        return process.cwd().replace(/\\/g, "/");
    }

    get instance() {
        return this.adapterInstance;
    }

    get adapterConfig() {
        return this.config.adapterConfig;
    }
};<|endoftext|>


<commit_before>"use strict";

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

// module definition
var hexTo = (function ($) {
 	// input
    var body, hexEl, rgbEl, hslEl, hwbEl, cssEl, fields, defaultColor;

    // init variables and listeners
    function init() {
    	hexEl = $("#hex"), rgbEl = $("#rgb"), hslEl = $("#hsl"),
    		hwbEl = $("#hwb"), cssEl = $("#css");
        defaultColor = new Color("#3d4d4d");
        body = $("body");
    	fields = $("input[type='text']");
    	fields.keyup(function(e) {
    		// ignore some keys
    		if (e.which == 9 || (e.which >= 16 && e.which <= 20) || (e.which >= 37 && e.which <= 40)) return;
    		var from = $(this);
    		delay(function(){
    			convert(from);
    		}, 200);
		});
		fields.blur(function(){
			var from = $(this);
			var type = from.attr("id");
			if(from.val() === "" && type != "css"){
				clearFields();
				return;
			}
    		var value = validateValue(type, from.val());
    		if(value !== false){
    			from.val(value);
    		}
		});
        // random color
        $("#btn-random").click(getRandomColor);
        // format tooltips
        var tooltips = $(".tooltip");
        tooltips.click(function(e){
            e.preventDefault();
        });
        tooltips.tooltipster({
            theme: "tooltipster-noir",
            trigger: "click",
            position: "left"
        });
        // about tooltip
        var about = $("#about");
        about.click(function(e){
            e.preventDefault();
        });
        about.tooltipster({
            theme: "tooltipster-noir",
            trigger: "click",
            position: "bottom",
            interactive: true,
            maxWidth: 490,
            content: $("
Hi there! My name is Viktor, I did this little utility to help convert from Hexadecimal to RGB. Hope it's useful for you as well.

You can see more on Github or if you want to chat, hit me @towanime.
")
        });
    }

    function convert(from){
    	var type = from.attr("id");
    	var value = validateValue(type, from.val());
    	if(value === false){
    		clearFields(type);
    		return;
    	}
    	try {
    		var color = new Color(value);
    		if(type != "hex"){
    			hexEl.val(color.hexString());
    		}
    		if(type != "rgb"){
    			rgbEl.val(color.rgbString());
    		}
    		if(type != "hsl"){
    			hslEl.val(color.hslString());
    		}
    		if(type != "hwb"){
    			hwbEl.val(color.hwbString());
    		}
    		if(type != "css"){
    			cssEl.val(color.keyword());
    		}
            // update theme
            update(color);
    	} catch(e){
    		clearFields(type);
    	}
    }

    // Depending on the origin check against regular expressions to avoid exceptions.
    function validateValue(type, value){
    	if(value.length < 3) return false;
    	switch(type){
    		case "hex":
    			var hexRE = /([#]?)([0-9a-f]{3})([0-9a-f]{3})?/i;
				var match = hexRE.exec(value);
                // ["#FFF153", "#", "FFF", "153", index: 0, input: "#FFF153"]
				if(match && match.input.length == match[0].length){
					var validated = match[0];
					// check if there's a #
					if(match[1] === "") validated = "#"+validated;
					return validated.toUpperCase();
				}
    		break;

    		case "rgb":
    			var rgbRE = /(rgb[a]?\(?)?(\d{1,3}),\s?(\d{1,3}),\s?(\d{1,3})(,?\s?([0-1]\.?[0-9]?))?\)?/i;
				var match = rgbRE.exec(value);
                //["rgba(255, 1, 55, 0.7)", "rgba(", "255", "1", "55", ", 0.7", "0.7", index: 0, input: "rgba(255, 1, 55, 0.7)"]
				if(match && match.input.length == match[0].length &&
                    match[2] && match[3] && match[4]){
					var start = match[1]?match[1]:"rgb(", end = ")", r = match[2], g = match[3], b = match[4], a = 1;
					// does it have alpha?
                     if(match[6] || start=="rgba("){
                        var aValue = !match[6]?a:parseFloat(match[6]);
                        if(aValue <= 1){
                            a = aValue;
							start = "rgba(";
                            end = ", " + a + ")";
						}else{
							return false;
						}
					}
					// less tan 255
					if(parseInt(r) <= 255 && parseInt(g) <= 255 && parseInt(b) <= 255){
						return start + r + ", " + g + ", " + b + end;
					}
				}
    		break;

            case "hsl":
            case "hwb":
                var re = /(hsl[a]?\(?|hwb\(?)?(\d{1,3}),\s?(\d{1,3}%),\s?(\d{1,3}%)(,?\s?([0-1]\.?[0-9]?))?\)?/i;
                var match = re.exec(value);
                // ["hsla(0, 0%, 100%, 1)", "hsla(", "0", "0%", "100%", ", 1", "1", index: 0, input: "hsla(0, 0%, 100%, 1)"]
                    // or
                //["hwb(0, 100%, 0%, 1)", "hwb(", "0", "100%", "0%", ",1", "1", index: 0, input: "hwb(0, 100%, 0%, 1)"]
                if(match && match.input.length == match[0].length
                    && match[2] && match[3] && match[4]){
                    var start = match[1]?match[1]:type+"(", end = ")", p1 = match[2], p2 = match[3], p3 = match[4], a = 1;
                    // does it have alpha?
                    if(match[6] || start=="hsla("){
                        var aValue = !match[6]?a:parseFloat(match[6]);
                        if(aValue <= 1){
                            a = aValue;
                            // hsla or hwb
                            start = (type=="hsl"?"hsla(":type+"(");
                            end = ", " + aValue + ")";
                        }else{
                            return false;
                        }
                    }
                    // less tan 255
                    if(parseInt(p1) <= 360 && parseInt(p2) <= 100 && parseInt(p3) <= 100){
                        return start + p1 + ", " + p2 + ", " + p3 + end;
                    }
                }
            break;

    		default:
                // for css strings
    			return value;
    		break;
    	}
    	return false;
    }

    function clearFields(ignore){
    	fields.each(function(index, element){
    		var el = $(element);
    		if(el.attr('id') != ignore) el.val('');
    	});
        update(defaultColor);
    }

    function update(color){
        body.attr("style", "background-color:"+color.hexString()+";");
        if(isLight(color.red(), color.green(), color.blue())){
            body.attr("class", "dark");
        }else{
            body.attr("class", "light");
        }
    }

    function isLight(r, g, b){
        // taken from http://stackoverflow.com/questions/12043187/how-to-check-if-hex-color-is-too-black
        /*var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709
        if (luma < 100) {
            return false;
        }else{
            return true;
        }*/
        // Better results with this one - http://stackoverflow.com/questions/1754211/evaluate-whether-a-hex-value-is-dark-or-light
        var luma = (r*0.299 + g*0.587 + b*0.114) / 256;
        if (luma < 0.55) {
            return false;
        }else{
            return true;
        }
    }

    function getRandomColor(e) {
        e.preventDefault();
        // taken from http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
        // might need something better
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        hexEl.val(color);
        convert(hexEl);
    }

    return {
        init: init
    };

})(jQuery);

$(document).ready(function()
{
	hexTo.init();
});<commit_msg>Typo fix<commit_after>"use strict";

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

// module definition
var hexTo = (function ($) {
 	// input
    var body, hexEl, rgbEl, hslEl, hwbEl, cssEl, fields, defaultColor;

    // init variables and listeners
    function init() {
    	hexEl = $("#hex"), rgbEl = $("#rgb"), hslEl = $("#hsl"),
    		hwbEl = $("#hwb"), cssEl = $("#css");
        defaultColor = new Color("#3d4d4d");
        body = $("body");
    	fields = $("input[type='text']");
    	fields.keyup(function(e) {
    		// ignore some keys
    		if (e.which == 9 || (e.which >= 16 && e.which <= 20) || (e.which >= 37 && e.which <= 40)) return;
    		var from = $(this);
    		delay(function(){
    			convert(from);
    		}, 200);
		});
		fields.blur(function(){
			var from = $(this);
			var type = from.attr("id");
			if(from.val() === "" && type != "css"){
				clearFields();
				return;
			}
    		var value = validateValue(type, from.val());
    		if(value !== false){
    			from.val(value);
    		}
		});
        // random color
        $("#btn-random").click(getRandomColor);
        // format tooltips
        var tooltips = $(".tooltip");
        tooltips.click(function(e){
            e.preventDefault();
        });
        tooltips.tooltipster({
            theme: "tooltipster-noir",
            trigger: "click",
            position: "left"
        });
        // about tooltip
        var about = $("#about");
        about.click(function(e){
            e.preventDefault();
        });
        about.tooltipster({
            theme: "tooltipster-noir",
            trigger: "click",
            position: "bottom",
            interactive: true,
            maxWidth: 490,
            content: $("
Hi there! My name is Viktor, I created this little utility to help me convert from Hexadecimal to RGB. Hope it's useful for you as well.

You can see more on Github or if you want to chat, hit me @towanime.
")
        });
    }

    function convert(from){
    	var type = from.attr("id");
    	var value = validateValue(type, from.val());
    	if(value === false){
    		clearFields(type);
    		return;
    	}
    	try {
    		var color = new Color(value);
    		if(type != "hex"){
    			hexEl.val(color.hexString());
    		}
    		if(type != "rgb"){
    			rgbEl.val(color.rgbString());
    		}
    		if(type != "hsl"){
    			hslEl.val(color.hslString());
    		}
    		if(type != "hwb"){
    			hwbEl.val(color.hwbString());
    		}
    		if(type != "css"){
    			cssEl.val(color.keyword());
    		}
            // update theme
            update(color);
    	} catch(e){
    		clearFields(type);
    	}
    }

    // Depending on the origin check against regular expressions to avoid exceptions.
    function validateValue(type, value){
    	if(value.length < 3) return false;
    	switch(type){
    		case "hex":
    			var hexRE = /([#]?)([0-9a-f]{3})([0-9a-f]{3})?/i;
				var match = hexRE.exec(value);
                // ["#FFF153", "#", "FFF", "153", index: 0, input: "#FFF153"]
				if(match && match.input.length == match[0].length){
					var validated = match[0];
					// check if there's a #
					if(match[1] === "") validated = "#"+validated;
					return validated.toUpperCase();
				}
    		break;

    		case "rgb":
    			var rgbRE = /(rgb[a]?\(?)?(\d{1,3}),\s?(\d{1,3}),\s?(\d{1,3})(,?\s?([0-1]\.?[0-9]?))?\)?/i;
				var match = rgbRE.exec(value);
                //["rgba(255, 1, 55, 0.7)", "rgba(", "255", "1", "55", ", 0.7", "0.7", index: 0, input: "rgba(255, 1, 55, 0.7)"]
				if(match && match.input.length == match[0].length &&
                    match[2] && match[3] && match[4]){
					var start = match[1]?match[1]:"rgb(", end = ")", r = match[2], g = match[3], b = match[4], a = 1;
					// does it have alpha?
                     if(match[6] || start=="rgba("){
                        var aValue = !match[6]?a:parseFloat(match[6]);
                        if(aValue <= 1){
                            a = aValue;
							start = "rgba(";
                            end = ", " + a + ")";
						}else{
							return false;
						}
					}
					// less tan 255
					if(parseInt(r) <= 255 && parseInt(g) <= 255 && parseInt(b) <= 255){
						return start + r + ", " + g + ", " + b + end;
					}
				}
    		break;

            case "hsl":
            case "hwb":
                var re = /(hsl[a]?\(?|hwb\(?)?(\d{1,3}),\s?(\d{1,3}%),\s?(\d{1,3}%)(,?\s?([0-1]\.?[0-9]?))?\)?/i;
                var match = re.exec(value);
                // ["hsla(0, 0%, 100%, 1)", "hsla(", "0", "0%", "100%", ", 1", "1", index: 0, input: "hsla(0, 0%, 100%, 1)"]
                    // or
                //["hwb(0, 100%, 0%, 1)", "hwb(", "0", "100%", "0%", ",1", "1", index: 0, input: "hwb(0, 100%, 0%, 1)"]
                if(match && match.input.length == match[0].length
                    && match[2] && match[3] && match[4]){
                    var start = match[1]?match[1]:type+"(", end = ")", p1 = match[2], p2 = match[3], p3 = match[4], a = 1;
                    // does it have alpha?
                    if(match[6] || start=="hsla("){
                        var aValue = !match[6]?a:parseFloat(match[6]);
                        if(aValue <= 1){
                            a = aValue;
                            // hsla or hwb
                            start = (type=="hsl"?"hsla(":type+"(");
                            end = ", " + aValue + ")";
                        }else{
                            return false;
                        }
                    }
                    // less tan 255
                    if(parseInt(p1) <= 360 && parseInt(p2) <= 100 && parseInt(p3) <= 100){
                        return start + p1 + ", " + p2 + ", " + p3 + end;
                    }
                }
            break;

    		default:
                // for css strings
    			return value;
    		break;
    	}
    	return false;
    }

    function clearFields(ignore){
    	fields.each(function(index, element){
    		var el = $(element);
    		if(el.attr('id') != ignore) el.val('');
    	});
        update(defaultColor);
    }

    function update(color){
        body.attr("style", "background-color:"+color.hexString()+";");
        if(isLight(color.red(), color.green(), color.blue())){
            body.attr("class", "dark");
        }else{
            body.attr("class", "light");
        }
    }

    function isLight(r, g, b){
        // taken from http://stackoverflow.com/questions/12043187/how-to-check-if-hex-color-is-too-black
        /*var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709
        if (luma < 100) {
            return false;
        }else{
            return true;
        }*/
        // Better results with this one - http://stackoverflow.com/questions/1754211/evaluate-whether-a-hex-value-is-dark-or-light
        var luma = (r*0.299 + g*0.587 + b*0.114) / 256;
        if (luma < 0.55) {
            return false;
        }else{
            return true;
        }
    }

    function getRandomColor(e) {
        e.preventDefault();
        // taken from http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
        // might need something better
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        hexEl.val(color);
        convert(hexEl);
    }

    return {
        init: init
    };

})(jQuery);

$(document).ready(function()
{
	hexTo.init();
});<|endoftext|>


<commit_before>/**
 * ownCloud - owncollab_timetracker
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author andy <info@eventgineering.de>
 * @copyright andy 2016
 */

(function ($, OC) {

	$(document).ready(function () {
		$('#hello').click(function () {
			alert('Hello from your script file');
		});

		$('#echo').click(function () {
			var url = OC.generateUrl('/apps/owncollab_timetracker/echo');
			var data = {
				echo: $('#echo-content').val()
			};

			$.post(url, data).success(function (response) {
				$('#echo-result').text(response.echo);
			});

		});
	});

})(jQuery, OC);

(function (OC, window, $, undefined) {
'use strict';

$(document).ready(function () {

var translations = {
    newEvent: $('#new-event-string').text()
};

// this events object holds all our events
var Events = function (baseUrl) {
    this._baseUrl = baseUrl;
    this._events = [];
    this._activeEvent = undefined;
};

Events.prototype = {
    load: function (id) {
        var self = this;
        this._events.forEach(function (event) {
            if (event.id === id) {
                event.active = true;
                self._activeEvent = event;
            } else {
                event.active = false;
            }
        });
    },
    getActive: function () {
        return this._activeEvent;
    },
    removeActive: function () {
        var index;
        var deferred = $.Deferred();
        var id = this._activeEvent.id;
        this._events.forEach(function (event, counter) {
            if (event.id === id) {
                index = counter;
            }
        });

        if (index !== undefined) {
            // delete cached active event if necessary
            if (this._activeEvent === this._events[index]) {
                delete this._activeEvent;
            }

            this._events.splice(index, 1);

            $.ajax({
                url: this._baseUrl + '/' + id,
                method: 'DELETE'
            }).done(function () {
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
        } else {
            deferred.reject();
        }
        return deferred.promise();
    },
    create: function (event) {
        var deferred = $.Deferred();
        var self = this;
        $.ajax({
            url: this._baseUrl,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(event)
        }).done(function (event) {
            self._events.push(event);
            self._activeEvent = event;
            self.load(event.id);
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    getAll: function () {
        return this._events;
    },
    loadAll: function () {
        var deferred = $.Deferred();
        var self = this;
        $.get(this._baseUrl).done(function (events) {
            self._activeEvent = undefined;
            self._events = events;
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    updateActive: function (title, content, start, end) {
        var event = this.getActive();
        event.title = title;
        event.content = content;
        event.start = start;
        event.end = end;

        return $.ajax({
            url: this._baseUrl + '/' + event.id,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(event)
        });
    }
};

// this will be the view that is used to update the html
var View = function (events) {
    this._events = events;
};

View.prototype = {
    renderContent: function () {
        var source = $('#content-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({event: this._events.getActive()});

        $('#editor').html(html);

        // handle saves
        var textarea = $('#app-content textarea');
        var self = this;
        $('#app-content button').click(function () {
            if ($('#start').val()==''){
                var start = $('#start').attr('placeholder');
            }
            else{
                var start = $('#start').val();
            }
            console.log('placeholder start value:', $('#start').attr('placeholder'));
            console.log(' start value:', start);
            var content = textarea.val();
            var title = content.split('\n')[0]; // first line is the title

            var end = $('#end').val();

            self._events.updateActive(title, content, start, end).done(function () {
                self.render();
            }).fail(function () {
                alert('Could not update event, not found');
            });
        });
    },
    renderNavigation: function () {
        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({events: this._events.getAll()});

        $('#app-navigation ul').html(html);

        // create a new event
        var self = this;
        $('#new-event').click(function () {
            var event = {
                title: translations.newEvent,
                content: 'content here . . .',
		start: '01.01.2016 00:00:00',
		end: '01.01.2016 00:00:01'
            };

            self._events.create(event).done(function() {
                self.render();
                $('#editor textarea').focus();
            }).fail(function () {
                alert('Could not create event');
            });

        });

        // show app menu
        $('#app-navigation .app-navigation-entry-utils-menu-button').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').toggleClass('open');
        });

        // delete a event
        $('#app-navigation .event .delete').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').removeClass('open');

            self._events.removeActive().done(function () {
                self.render();
            }).fail(function () {
                alert('Could not delete event, not found');
            });
        });

        // load a event
        $('#app-navigation .event > a').click(function () {
            var id = parseInt($(this).parent().data('id'), 10);
            self._events.load(id);
            self.render();
            $('#editor textarea').focus();
        });
    },
    render: function () {
        this.renderNavigation();
        this.renderContent();
    }
};

var events = new Events(OC.generateUrl('/apps/owncollab_timetracker/events'));
var view = new View(events);
events.loadAll().done(function () {
    view.render();
}).fail(function () {
    alert('Could not load events');
});

});

})(OC, window, jQuery);
<commit_msg>updated code<commit_after>/**
 * ownCloud - owncollab_timetracker
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author andy <info@eventgineering.de>
 * @copyright andy 2016
 */

(function ($, OC) {

	$(document).ready(function () {
		$('#hello').click(function () {
			alert('Hello from your script file');
		});

		$('#echo').click(function () {
			var url = OC.generateUrl('/apps/owncollab_timetracker/echo');
			var data = {
				echo: $('#echo-content').val()
			};

			$.post(url, data).success(function (response) {
				$('#echo-result').text(response.echo);
			});

		});
	});

})(jQuery, OC);

(function (OC, window, $, undefined) {
'use strict';

$(document).ready(function () {

var translations = {
    newEvent: $('#new-event-string').text()
};

// this events object holds all our events
var Events = function (baseUrl) {
    this._baseUrl = baseUrl;
    this._events = [];
    this._activeEvent = undefined;
};

Events.prototype = {
    load: function (id) {
        var self = this;
        this._events.forEach(function (event) {
            if (event.id === id) {
                event.active = true;
                self._activeEvent = event;
            } else {
                event.active = false;
            }
        });
    },
    getActive: function () {
        return this._activeEvent;
    },
    removeActive: function () {
        var index;
        var deferred = $.Deferred();
        var id = this._activeEvent.id;
        this._events.forEach(function (event, counter) {
            if (event.id === id) {
                index = counter;
            }
        });

        if (index !== undefined) {
            // delete cached active event if necessary
            if (this._activeEvent === this._events[index]) {
                delete this._activeEvent;
            }

            this._events.splice(index, 1);

            $.ajax({
                url: this._baseUrl + '/' + id,
                method: 'DELETE'
            }).done(function () {
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
        } else {
            deferred.reject();
        }
        return deferred.promise();
    },
    create: function (event) {
        var deferred = $.Deferred();
        var self = this;
        $.ajax({
            url: this._baseUrl,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(event)
        }).done(function (event) {
            self._events.push(event);
            self._activeEvent = event;
            self.load(event.id);
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    getAll: function () {
        return this._events;
    },
    loadAll: function () {
        var deferred = $.Deferred();
        var self = this;
        $.get(this._baseUrl).done(function (events) {
            self._activeEvent = undefined;
            self._events = events;
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    updateActive: function (title, content, start, end) {
        var event = this.getActive();
        event.title = title;
        event.content = content;
        event.start = start;
        event.end = end;

        return $.ajax({
            url: this._baseUrl + '/' + event.id,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(event)
        });
    }
};

// this will be the view that is used to update the html
var View = function (events) {
    this._events = events;
};

View.prototype = {
    renderContent: function () {
        var source = $('#content-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({event: this._events.getActive()});

        $('#editor').html(html);

        // handle saves
        var textarea = $('#app-content textarea');
        var self = this;
        $('#app-content button').click(function () {
            if ($('#start').val()==''){
                var start = $('#start').attr('placeholder');
            }
            else{
                var start = $('#start').val();
            }
            if ($('#end').val()==''){
                var start = $('#end').attr('placeholder');
            }
            else{
                var end = $('#end').val();
            }
            console.log('placeholder start value:', $('#start').attr('placeholder'));
            console.log(' start value:', start);
            var content = textarea.val();
            var title = content.split('\n')[0]; // first line is the title

            var end = $('#end').val();

            self._events.updateActive(title, content, start, end).done(function () {
                self.render();
            }).fail(function () {
                alert('Could not update event, not found');
            });
        });
    },
    renderNavigation: function () {
        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({events: this._events.getAll()});

        $('#app-navigation ul').html(html);

        // create a new event
        var self = this;
        $('#new-event').click(function () {
            var event = {
                title: translations.newEvent,
                content: 'content here . . .',
		start: '01.01.2016 00:00:00',
		end: '01.01.2016 00:00:01'
            };

            self._events.create(event).done(function() {
                self.render();
                $('#editor textarea').focus();
            }).fail(function () {
                alert('Could not create event');
            });

        });

        // show app menu
        $('#app-navigation .app-navigation-entry-utils-menu-button').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').toggleClass('open');
        });

        // delete a event
        $('#app-navigation .event .delete').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').removeClass('open');

            self._events.removeActive().done(function () {
                self.render();
            }).fail(function () {
                alert('Could not delete event, not found');
            });
        });

        // load a event
        $('#app-navigation .event > a').click(function () {
            var id = parseInt($(this).parent().data('id'), 10);
            self._events.load(id);
            self.render();
            $('#editor textarea').focus();
        });
    },
    render: function () {
        this.renderNavigation();
        this.renderContent();
    }
};

var events = new Events(OC.generateUrl('/apps/owncollab_timetracker/events'));
var view = new View(events);
events.loadAll().done(function () {
    view.render();
}).fail(function () {
    alert('Could not load events');
});

});

})(OC, window, jQuery);
<|endoftext|>


<commit_before>/**
 * Created by Nikolay Skovorodin on 29.04.14.
 */
$( document ).ready(function(){
    //Global variables
    var difficulty = 'easy'; //0-Easy 1-Normal 2-Hard
    var currentZIndex = 1;   //Z-index for blocks
    var Image = "assets/1.jpg"; //Default Image
    var check = [];             //Array for right checking
    var right = 0;              //Variable for right checking
    var selImage = 1;           //Selected image(number)
    var grid = 4;               //Grid size
    var col_md = 'col-md-3';    //Bootstrap default style
    var height = 150;           //Default height
    //First time open game or cookies disabled
    $.cookie.json = true;
    if(!checkCookies())
        $('#myModal').modal('show');

    //Click on image to select
    $('.thumbnail[id=imageselect]').click(function(e){
        var id = $(e.currentTarget).attr('name');
        if(id != selImage){
            var search = '.thumbnail[id=imageselect][name='+selImage+']';
            $(search).removeClass('selected');
            $(e.currentTarget).addClass('selected');
            selImage = $(e.currentTarget).attr('name');
        }
    });

    //Click on modal window button save
    $('.modal-footer > .btn-primary').click(function(){
        //Need to save preferences
        difficulty = $('#difficulty:checked').val();
        check = [];             //Array for right checking
        right = 0;
        //And generate game
        createPuzzle();

        //Create array for check
        for (var i = 0; i < grid; i++){
            check[i] = [];
            for (var j = 0; j < grid; j++){
                check[i][j] = 0;
            }
        }

        //Hide modal
        $('#myModal').modal('hide');
    });

    function solved(){
        $(".dblock").each(function(i,el){
            $(el).addClass('onspot');
            $(el).empty();
            $(el).draggable('destroy');
            $(el).css('opacity', '1');
            $('.body').css('cursor', 'auto');
        });
    }

    //Create Puzzle
    function createPuzzle(){
        Image = "assets/"+selImage+".jpg";
        currentZIndex = 1;
        $('.thumbnail[name='+selImage+']').addClass('selected');
        if(difficulty == 'easy'){
            grid = 4;
            col_md = 'col-md-3';
            height = 150;
        } else if(difficulty == 'medium' ){
            grid = 6;
            col_md = 'col-md-2';
            height = 100;
        }else{
            grid = 12;
            col_md = 'col-md-1';
            height = 50;
        }
        var content = "";

        for(var i = 0; i < grid; i++){
            content += "
";
            for(var j = 0; j < grid; j++){
                var index = (i*grid)+j;
                content += "

";
            }
            content += "
";
        }

        $('.canvas ').empty();
        $('.canvas ').append(content);
        $(".mblock").css("height", height);

        //Plus draggable blocks
        content = "";

        for(var i = 0; i < grid*grid; i++){
            content += "
"+i+"

";
        }

        $('.blocks ').empty();
        $('.blocks ').append(content);
        $('.dblock').each(function(i,el){
            var tLeft = Math.floor(Math.random()*400),
                tTop  = Math.floor(Math.random()*500);
            $(el).css({ left: tLeft, top: tTop, height: height, width: height, "z-index" : 1});
        });

        //Setup draggable objects
        $('.dblock').draggable({
            opacity: 0.95,
            snap: true,
            cursor: "move",
            start: function( event, ui ) {
                currentZIndex++;
                $(this).css('z-index',currentZIndex);
                if( check[$(ui.helper).attr('id')] == 1){
                    right--;
                    check[$(ui.helper).attr('id')] = 0;
                }
            }
        });
        //Load images to blocks
        $(".dblock").each(function(i,el){
            var y = ~~(i/grid);
            var x = i - (y*grid);
            var xOffset = -x*height;
            var yOffset = -y*height;
            $(el).css(
                {
                    display: "block",
                    backgroundImage: "url( '" + Image + "' )",
                    backgroundRepeat: "no-repeat",
                    backgroundPosition: (
                        xOffset + "px " +
                            yOffset + "px"
                        )
                }
            );
        });

        //Setup droppable grid
        $('.mblock').droppable({
            tolerance : 'intersect',
            drop : function(event, ui) {
                //Скидываем в любую клетку.
                var y = ~~($(this).attr('id')/grid);
                var x = $(this).attr('id') - (y*grid);
                var xOffset = x*height-602;
                var yOffset = y*height;
                $(ui.draggable).css({left: xOffset, top: yOffset});
                //Проверяем
                if($(this).attr('id') == $(ui.draggable).attr('id')){
                    check[$(this).attr('id')] = 1;
                    right++;
                    if(right == grid*grid) solved();
                }

            }
        });
    }

    //Solve
    $('a.solve').click(function(){
        $(".dblock").each(function(i,el){
            //Скидываем в нужные клетки
            var y = ~~($(el).attr('id')/grid);
            var x = $(el).attr('id') - (y*grid);
            var xOffset = x*height-602;
            var yOffset = y*height;
            $(el).css({left: xOffset, top: yOffset});
        });
        for(var i = 0; i < grid*grid; i++){
            check[i] = 1;
        }
        right = grid*grid;
        solved();
    });

    //Check cookies
    function checkCookies(){
        if($.cookie('has') != 'true'){
            return false;
        }
        difficulty = $.cookie('difficulty');
        selImage = $.cookie('image');
        right = $.cookie('right');
        check = $.cookie('check');
        var coords = JSON.parse(localStorage.getItem('coords'));
        //Прочли куки, теперь создадим игру
        createPuzzle();
        //Проставим координаты
        if( coords != null){
            $(".dblock").each(function(i,el){
                var a = coords[i].x;
                $(el).css('left', coords[i].x);
                $(el).css('top', coords[i].y);
            });
        }
        if(right == grid*grid)solved();
        //Конец
        return true;
    }

    $(window).unload(function(e){
        var coords = [];
        $(".dblock").each(function(i,el){
            coords[i] = {x: $(el).css('left'), y: $(el).css('top')};
        });
        coords = JSON.stringify(coords);
        localStorage.setItem("coords", coords);
        $.cookie('check', check, {
            expires: 30
        });
        $.cookie('has', 'true', {
            expires: 30
        });
        $.cookie('right', right, {
            expires: 30
        });
        $.cookie('image', selImage, {
            expires: 30
        });
        $.cookie('difficulty', difficulty, {
            expires: 30
        });
    });

});<commit_msg>Cookie check fixed 2<commit_after>/**
 * Created by Nikolay Skovorodin on 29.04.14.
 */
$( document ).ready(function(){
    //Global variables
    var difficulty = 'easy'; //0-Easy 1-Normal 2-Hard
    var currentZIndex = 1;   //Z-index for blocks
    var Image = "assets/1.jpg"; //Default Image
    var check = [];             //Array for right checking
    var right = 0;              //Variable for right checking
    var selImage = 1;           //Selected image(number)
    var grid = 4;               //Grid size
    var col_md = 'col-md-3';    //Bootstrap default style
    var height = 150;           //Default height
    //First time open game or cookies disabled
    $.cookie.json = true;
    if(!checkCookies()){
        $('.thumbnail[name='+selImage+']').addClass('selected');
        $('#myModal').modal('show');
    }

    //Click on image to select
    $('.thumbnail[id=imageselect]').click(function(e){
        var id = $(e.currentTarget).attr('name');
        if(id != selImage){
            var search = '.thumbnail[id=imageselect][name='+selImage+']';
            $(search).removeClass('selected');
            $(e.currentTarget).addClass('selected');
            selImage = $(e.currentTarget).attr('name');
        }
    });

    //Click on modal window button save
    $('.modal-footer > .btn-primary').click(function(){
        //Need to save preferences
        difficulty = $('#difficulty:checked').val();
        check = [];             //Array for right checking
        right = 0;
        //And generate game
        createPuzzle();

        //Create array for check
        for (var i = 0; i < grid; i++){
            check[i] = [];
            for (var j = 0; j < grid; j++){
                check[i][j] = 0;
            }
        }

        //Hide modal
        $('#myModal').modal('hide');
    });

    function solved(){
        $(".dblock").each(function(i,el){
            $(el).addClass('onspot');
            $(el).empty();
            $(el).draggable('destroy');
            $(el).css('opacity', '1');
            $('.body').css('cursor', 'auto');
        });
    }

    //Create Puzzle
    function createPuzzle(){
        Image = "assets/"+selImage+".jpg";
        currentZIndex = 1;
        if(!$('.thumbnail[name='+selImage+']').hasClass('selected')){
            $('.thumbnail[name='+selImage+']').addClass('selected');
        }
        if(difficulty == 'easy'){
            grid = 4;
            col_md = 'col-md-3';
            height = 150;
        } else if(difficulty == 'medium' ){
            grid = 6;
            col_md = 'col-md-2';
            height = 100;
        }else{
            grid = 12;
            col_md = 'col-md-1';
            height = 50;
        }
        var content = "";

        for(var i = 0; i < grid; i++){
            content += "
";
            for(var j = 0; j < grid; j++){
                var index = (i*grid)+j;
                content += "

";
            }
            content += "
";
        }

        $('.canvas ').empty();
        $('.canvas ').append(content);
        $(".mblock").css("height", height);

        //Plus draggable blocks
        content = "";

        for(var i = 0; i < grid*grid; i++){
            content += "
"+i+"

";
        }

        $('.blocks ').empty();
        $('.blocks ').append(content);
        $('.dblock').each(function(i,el){
            var tLeft = Math.floor(Math.random()*400),
                tTop  = Math.floor(Math.random()*500);
            $(el).css({ left: tLeft, top: tTop, height: height, width: height, "z-index" : 1});
        });

        //Setup draggable objects
        $('.dblock').draggable({
            opacity: 0.95,
            snap: true,
            cursor: "move",
            start: function( event, ui ) {
                currentZIndex++;
                $(this).css('z-index',currentZIndex);
                if( check[$(ui.helper).attr('id')] == 1){
                    right--;
                    check[$(ui.helper).attr('id')] = 0;
                }
            }
        });
        //Load images to blocks
        $(".dblock").each(function(i,el){
            var y = ~~(i/grid);
            var x = i - (y*grid);
            var xOffset = -x*height;
            var yOffset = -y*height;
            $(el).css(
                {
                    display: "block",
                    backgroundImage: "url( '" + Image + "' )",
                    backgroundRepeat: "no-repeat",
                    backgroundPosition: (
                        xOffset + "px " +
                            yOffset + "px"
                        )
                }
            );
        });

        //Setup droppable grid
        $('.mblock').droppable({
            tolerance : 'intersect',
            drop : function(event, ui) {
                //Скидываем в любую клетку.
                var y = ~~($(this).attr('id')/grid);
                var x = $(this).attr('id') - (y*grid);
                var xOffset = x*height-602;
                var yOffset = y*height;
                $(ui.draggable).css({left: xOffset, top: yOffset});
                //Проверяем
                if($(this).attr('id') == $(ui.draggable).attr('id')){
                    check[$(this).attr('id')] = 1;
                    right++;
                    if(right == grid*grid) solved();
                }

            }
        });
    }

    //Solve
    $('a.solve').click(function(){
        $(".dblock").each(function(i,el){
            //Скидываем в нужные клетки
            var y = ~~($(el).attr('id')/grid);
            var x = $(el).attr('id') - (y*grid);
            var xOffset = x*height-602;
            var yOffset = y*height;
            $(el).css({left: xOffset, top: yOffset});
        });
        for(var i = 0; i < grid*grid; i++){
            check[i] = 1;
        }
        right = grid*grid;
        solved();
    });

    //Check cookies
    function checkCookies(){
        if($.cookie('has') != 'true'){
            return false;
        }
        difficulty = $.cookie('difficulty');
        selImage = $.cookie('image');
        right = $.cookie('right');
        check = $.cookie('check');
        var coords = JSON.parse(localStorage.getItem('coords'));
        //Прочли куки, теперь создадим игру
        createPuzzle();
        //Проставим координаты
        if( coords != null){
            $(".dblock").each(function(i,el){
                var a = coords[i].x;
                $(el).css('left', coords[i].x);
                $(el).css('top', coords[i].y);
            });
        }
        if(right == grid*grid)solved();
        //Конец
        return true;
    }

    $(window).unload(function(e){
        var coords = [];
        $(".dblock").each(function(i,el){
            coords[i] = {x: $(el).css('left'), y: $(el).css('top')};
        });
        coords = JSON.stringify(coords);
        localStorage.setItem("coords", coords);
        $.cookie('check', check, {
            expires: 30
        });
        $.cookie('has', 'true', {
            expires: 30
        });
        $.cookie('right', right, {
            expires: 30
        });
        $.cookie('image', selImage, {
            expires: 30
        });
        $.cookie('difficulty', difficulty, {
            expires: 30
        });
    });

});<|endoftext|>


<commit_before>$(document).ready(function() {

	$(window).scroll(function () {

   $('#slow').css({
      'top' : -($(this).scrollTop()/3)+"px",
      "background-color" : "red"
   });

});
		//snapping
	$('body').panelSnap();

	$(".carousel-caption").animate({
        marginLeft: "+=9999px",
    }, 1000 );

	//scroling menu
	var sections = $('section')
  	, nav = $('nav')
  	, nav_height = 100;
 	//nav.outerHeight()

$(window).on('scroll', function () {
  var cur_pos = $(this).scrollTop();
  sections.each(function() {

    var top = $(this).offset().top - nav_height,
        bottom = top + $(this).outerHeight();
		scolor = rgb2hex($(this).css("background-color"));
		iscolor = getContrast50(scolor);
		iiscolor = getContrast50(iscolor);

    if (cur_pos >= top && cur_pos <= bottom) {

		sections.removeClass('active');
		$(this).addClass('active');

		nav.find('a').parent().removeClass('active');
		nav.find('a[href="#'+$(this).attr('id')+'"]').parent().addClass('active');

		nav.find('a').css("color",iscolor);
		nav.find('a[href="#'+$(this).attr('id')+'"]').css("color",iiscolor);
    }
  });
});
			//menu_click_scroling
	nav.find('a').on("click", function(){
		event.preventDefault();

			$(".navbar-collapse").collapse('hide');//hides mobile menu

		id = $(this).attr("href");
		scrollToID(id, 800);
	});

});

function scrollToID(id, speed){
	var targetOffset = $(id).offset().top;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ?
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

function getContrast50(hexcolor){
    return (parseInt(hexcolor, 16) > 0xffffff/2) ? 'black':'white';
}

$(document).ready(function() {

	for (i=0; i<144; i++){
		$('#game').wrapInner('

'+ i +'

');
	}
});
<commit_msg>144divs<commit_after>$(document).ready(function() {

	$(window).scroll(function () {

   $('#slow').css({
      'top' : -($(this).scrollTop()/3)+"px",
      "background-color" : "red"
   });

});
		//snapping
	$('body').panelSnap();

	$(".carousel-caption").animate({
        marginLeft: "+=9999px",
    }, 1000 );

	//scroling menu
	var sections = $('section')
  	, nav = $('nav')
  	, nav_height = 100;
 	//nav.outerHeight()

$(window).on('scroll', function () {
  var cur_pos = $(this).scrollTop();
  sections.each(function() {

    var top = $(this).offset().top - nav_height,
        bottom = top + $(this).outerHeight();
		scolor = rgb2hex($(this).css("background-color"));
		iscolor = getContrast50(scolor);
		iiscolor = getContrast50(iscolor);

    if (cur_pos >= top && cur_pos <= bottom) {

		sections.removeClass('active');
		$(this).addClass('active');

		nav.find('a').parent().removeClass('active');
		nav.find('a[href="#'+$(this).attr('id')+'"]').parent().addClass('active');

		nav.find('a').css("color",iscolor);
		nav.find('a[href="#'+$(this).attr('id')+'"]').css("color",iiscolor);
    }
  });
});
			//menu_click_scroling
	nav.find('a').on("click", function(){
		event.preventDefault();

			$(".navbar-collapse").collapse('hide');//hides mobile menu

		id = $(this).attr("href");
		scrollToID(id, 800);
	});

});

function scrollToID(id, speed){
	var targetOffset = $(id).offset().top;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ?
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

function getContrast50(hexcolor){
    return (parseInt(hexcolor, 16) > 0xffffff/2) ? 'black':'white';
}

$(document).ready(function() {

	for (i=0; i<144; i++){
		$('#game').append('
'+ i +'
');
	}
});
<|endoftext|>