<commit_before>'use strict';

var fs = require('fs'),
    resolve = require('path').resolve,
    join = require('path').join,
    cp = require('child_process'),
    exec = cp.exec;

// logging helper function
var msg = function (msg) {
    var div = '=====';
    console.log(div, msg, div, '\n');
};

var lib = resolve(__dirname, '../lib/');
var node_modules = resolve(__dirname, '../node_modules');
var symlinkPath = join(node_modules, '_');

// setup symlink from node_modules to lib
fs.lstat(symlinkPath, function (err, stat) {
    var createSymlink = function () {
        fs.symlinkSync(lib, symlinkPath, 'dir');
    };

    if (err) {
        if ('ENOENT' === err.code) {
            msg('Creating Symlink to Lib...');
            createSymlink();
        } else {
            console.log(err);
        }
    } else if (!stat.isSymbolicLink()) {
        msg('File is not a Symlink. Replacing with Symlink...');
        fs.unlinkSync(symlinkPath);
        createSymlink();
    } else {
        msg('Symlink Found, Continuing...');
    }
});

// npm install sub-modules
fs.readdirSync(lib)
    .forEach(function (mod) {
        var modPath = join(lib, mod);

        // ensure path has package.json
        if (!fs.existsSync(join(modPath, 'package.json'))) return;

        // exec npm install in sub-module
        exec('npm install', {
            env: process.env,
            cwd: modPath,
        }, function (error, stdout, stderr) {

            msg('Installing ' + mod + ' dependencies...');

            if (stdout) {
                console.log('stdout: ' + stdout);
            }
            if (stderr) {
                console.log('stderr: ' + stderr);
            }
            if (error) {
                console.log('exec error: ' + error);
            }
        });
    });
<commit_msg>Update preinstall to check for node_modules<commit_after>'use strict';

const fs = require('fs'),
    resolve = require('path').resolve,
    join = require('path').join,
    exec = require('child_process').exec;

// logging helper function
const msg = function (msg) {
    var div = '=====';
    console.log(div, msg, div, '\n');
};

// resolve necessary paths
const lib = resolve(__dirname, '../lib/');
const node_modules = resolve(__dirname, '../node_modules');
const symlinkPath = join(node_modules, '_');

// make sure node_modules directory exists
try {
    fs.mkdirSync(node_modules);
} catch (e) {
    if (e.code !== 'EEXIST') throw e;
}

// setup symlink from node_modules to lib
fs.lstat(symlinkPath, function (err, stat) {
    const createSymlink = function () {
        fs.symlinkSync(lib, symlinkPath, 'dir');
    };

    if (err) {
        if ('ENOENT' === err.code) {
            msg('Creating Symlink to Lib...');
            createSymlink();
        } else {
            console.log(err);
        }
    } else if (!stat.isSymbolicLink()) {
        msg('File is not a Symlink. Replacing with Symlink...');
        fs.unlinkSync(symlinkPath);
        createSymlink();
    } else {
        msg('Symlink Found, Continuing...');
    }
});

// npm install sub-modules
fs.readdirSync(lib)
    .forEach(function (mod) {
        const modPath = join(lib, mod);

        // ensure path has package.json
        if (!fs.existsSync(join(modPath, 'package.json'))) return;

        // exec npm install in sub-module
        exec('npm install', {
            env: process.env,
            cwd: modPath,
        }, function (error, stdout, stderr) {

            msg('Installing ' + mod + ' dependencies...');

            if (stdout) {
                console.log('stdout: ' + stdout);
            }
            if (stderr) {
                console.log('stderr: ' + stderr);
            }
            if (error) {
                console.log('exec error: ' + error);
            }
        });
    });
<|endoftext|>


<commit_before>module.exports = (opt, moduleCallback) => {
  if (typeof(opt.table) == 'undefined') return moduleCallback('Table required for ' + opt.source)

  const creds = require(opt.cfg.dirs.creds + opt.source)
  const oracledb = require('oracledb')
  const async = require('async')
  const fs = require('fs')
  const table = opt.table
  const log = opt.log
  const bindQuery = require(opt.bin + 'bind-query')
  const opfile = opt.opfile
  const moment = require('moment')

  let oracle

  async.waterfall([
      //connect
      (cb) => {
        oracledb.getConnection(creds, (e, c) => {
          if (e) return cb(e)
          oracle = c
          cb(null)
        })
      },
      //read query
      (cb) => {
        fs.readFile(`${opt.cfg.dirs.input}//${opt.source}/${table}.sql`, 'utf8', (e, data) => {
          if (e) return cb('fs readFile error')
          cb(null, data)
        })
      },
      //bind variables
      (data, cb) => {
        bindQuery(data, opt, (e, sql) => {
          if (e) return cb(e)
          cb(null, sql)
        })
      },
      //execute
      (sql, cb) => {
        let counter = 0
        let stream = oracle.queryStream(sql, [], {
          resultSet: true,
          prefetchRows: 10000
        })
        let columns = []
          //hold data temporarily in array until columns are written
          // TODO move this temporary hold to opfile module and handle all sources this way
        let tempHold = []
        let flag = false
          // on rows either put in temporary data or append to file
          // if columns are already in
        stream.on('data', (d) => {
            counter++
            let row = d.map((c) => {
              if (c instanceof Date) return moment(c).format('YYYY-MM-DD HH:mm:ss Z')
              return c
            })
            if (flag === false) {
              //columns not written yet
              tempHold.push(row.join('\t') + '\n')
            } else {
              //columns written, dump tempHold and start appending data
              let t = tempHold.join('')
              tempHold = []
              opfile.append(t + row.join('\t') + '\n', (e) => {
                if (e) return cb(e)
              })
            }
          })
          .on('error', (e) => {
            cb(e)
          })
          .on('end', () => {
            //may need to dump tempHold data
            if (tempHold.length > 0) {
              opfile.append(tempHold.join(''), (e) => {
                if (e) return cb(e)
                cb(null, counter, columns)
              })
            } else {
              cb(null, counter, columns)
            }
          })
          .on('metadata', (m) => {
            //this is column names
            m.forEach((c) => {
              columns.push(c.name.replace(/_DEC|_IND/g, ''))
            })
            opfile.append(columns.join('\t') + '\n', (e) => {
              if (e) return cb(e)
              flag = true
            })
          })
      }
    ],
    (err, rows, columns) => {
      if (err) {
        log.error(err)
        try {
          oracle.release()
        } catch (e) {
          log.error(e)
        }
        return moduleCallback(err)
      }
      moduleCallback(null, rows, columns)
    })

}
<commit_msg>fix date<commit_after>module.exports = (opt, moduleCallback) => {
  if (typeof(opt.table) == 'undefined') return moduleCallback('Table required for ' + opt.source)

  const creds = require(opt.cfg.dirs.creds + opt.source)
  const oracledb = require('oracledb')
  const async = require('async')
  const fs = require('fs')
  const table = opt.table
  const log = opt.log
  const bindQuery = require(opt.bin + 'bind-query')
  const opfile = opt.opfile
  const moment = require('moment')

  let oracle

  async.waterfall([
      //connect
      (cb) => {
        oracledb.getConnection(creds, (e, c) => {
          if (e) return cb(e)
          oracle = c
          cb(null)
        })
      },
      //read query
      (cb) => {
        fs.readFile(`${opt.cfg.dirs.input}//${opt.source}/${table}.sql`, 'utf8', (e, data) => {
          if (e) return cb('fs readFile error')
          cb(null, data)
        })
      },
      //bind variables
      (data, cb) => {
        bindQuery(data, opt, (e, sql) => {
          if (e) return cb(e)
          cb(null, sql)
        })
      },
      //execute
      (sql, cb) => {
        let counter = 0
        let stream = oracle.queryStream(sql, [], {
          resultSet: true,
          prefetchRows: 10000
        })
        let columns = []
          //hold data temporarily in array until columns are written
          // TODO move this temporary hold to opfile module and handle all sources this way
        let tempHold = []
        let flag = false
          // on rows either put in temporary data or append to file
          // if columns are already in
        stream.on('data', (d) => {
            counter++
            let row = d.map((c) => {
              if (c instanceof Date) return moment(c).format('YYYY-MM-DD HH:mm:ss')
              return c
            })
            if (flag === false) {
              //columns not written yet
              tempHold.push(row.join('\t') + '\n')
            } else {
              //columns written, dump tempHold and start appending data
              let t = tempHold.join('')
              tempHold = []
              opfile.append(t + row.join('\t') + '\n', (e) => {
                if (e) return cb(e)
              })
            }
          })
          .on('error', (e) => {
            cb(e)
          })
          .on('end', () => {
            //may need to dump tempHold data
            if (tempHold.length > 0) {
              opfile.append(tempHold.join(''), (e) => {
                if (e) return cb(e)
                cb(null, counter, columns)
              })
            } else {
              cb(null, counter, columns)
            }
          })
          .on('metadata', (m) => {
            //this is column names
            m.forEach((c) => {
              columns.push(c.name.replace(/_DEC|_IND/g, ''))
            })
            opfile.append(columns.join('\t') + '\n', (e) => {
              if (e) return cb(e)
              flag = true
            })
          })
      }
    ],
    (err, rows, columns) => {
      if (err) {
        log.error(err)
        try {
          oracle.release()
        } catch (e) {
          log.error(e)
        }
        return moduleCallback(err)
      }
      moduleCallback(null, rows, columns)
    })

}
<|endoftext|>


<commit_before>//jtwt.js by Harbor (http://jtwt.hrbor.com)

(function($){

 	$.fn.jtwt = function(options) {

			//Declare defaults
			var defaults = {
				username : 'harbor',
				query: '',
                count : 4,
                image_size: 48,
                convert_links: true,
                loader_text: 'loading new tweets',
                no_result: 'No recent tweets found'

			}

			//Merge default with options
			var options =  $.extend(defaults, options);

			// customized parseTwitterDate. Base by http://stackoverflow.com/users/367154/brady - Special thanks to @mikloshenrich
			var parseTwitterDate = function(tdate) {

	    			var system_date = new Date(tdate.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/, "$1 $2 $4 $3 UTC"));
	    			var user_date = new Date();

	    			var diff = Math.floor((user_date - system_date) / 1000);
	    			if (diff <= 1) {return "ahora";}
	    			if (diff < 20) {return "hace " + diff + " segundos";}
	    			if (diff < 40) {return "hace medio minuto";}
	    			if (diff < 60) {return "hace menos de un minuto";}
	    			if (diff <= 90) {return "hace un minuto";}
	    			if (diff <= 3540) {return "hace " + Math.round(diff / 60) + " minutos";}
	    			if (diff <= 5400) {return "hace una hora";}
	    			if (diff <= 86400) {return "hace " + Math.round(diff / 3600) + " horas";}
	    			if (diff <= 129600) {return "hace un día";}
	    			if (diff < 604800) {return "hace " + Math.round(diff / 86400) + " días";}
	    			if (diff <= 777600) {return "Hace una semana";}
	    			return "el " + system_date;

    		}

    		return this.each(function() {

				var o = options;
                var obj = $(this);
                var q;

				$(obj).append('

');
				$(".jtwt", obj).append('
' + o.loader_text + '
');
				$(".jtwt_loader", obj).fadeIn('slow');

				//Check if there is a search query given, if not fetch user tweets
				if(o.query) {

					q = encodeURIComponent(o.query);

				} else {

					q = 'from:' + encodeURIComponent(o.username);

				}

				//get the tweets from the API
				$.getJSON('http://search.twitter.com/search.json?q=' + q + '&callback=?', function(data){

console.log(data);

					var results = data['results'];

					if(results.length) {

						//Loop through results and append them to the parent
						for(var i = 0; i < o.count && i < results.length; i++) {

							var item = results[i];

							jtweet = '
';

			                if (o.image_size) {

			                	today = new Date();

				                jtweet += '
';
				                jtweet += ''
				                jtweet += '';
				                jtweet += '';
				                jtweet += '
';

			                }

			                var tweettext = item.text;
			                var tweetdate = parseTwitterDate(item.created_at);

			                if (o.convert_links) {

				                tweettext = tweettext.replace(/(http\:\/\/[A-Za-z0-9\/\.\?\=\-]*)/g,'$1');
				                tweettext = tweettext.replace(/@([A-Za-z0-9\/_]*)/g,'@$1');
				                tweettext = tweettext.replace(/#([a-zA-Z0-9ßÄÖÜäöüÑñÉéÈèÁáÀàÂâŶĈĉĜĝŷÊêÔôÛûŴŵ-]*)/g,'#$1');

			                }

			                jtweet += '
' + tweettext + '
';
			                jtweet += '' + tweetdate + '';

			                jtweet += '
';

			                $(".jtwt", obj).append(jtweet);

		                }

					} else {

						//If there are not any tweets, display the "no results" container
						$(".jtwt_loader", obj).fadeOut('fast', function() {

							$(".jtwt", obj).append('
' + o.no_result + '
');
							$(".jtwt_noresult", obj).fadeIn('slow');

						});

					}

					$(".jtwt_loader", obj).fadeOut('fast');

				});

			});

    	}

})(jQuery);
<commit_msg>[tweets] - insecure content con jquery.jtwt para http://twitter.com/search...<commit_after>//jtwt.js by Harbor (http://jtwt.hrbor.com)

(function($){

 	$.fn.jtwt = function(options) {

			//Declare defaults
			var defaults = {
				username : 'harbor',
				query: '',
                count : 4,
                image_size: 48,
                convert_links: true,
                loader_text: 'loading new tweets',
                no_result: 'No recent tweets found'

			}

			//Merge default with options
			var options =  $.extend(defaults, options);

			// customized parseTwitterDate. Base by http://stackoverflow.com/users/367154/brady - Special thanks to @mikloshenrich
			var parseTwitterDate = function(tdate) {

	    			var system_date = new Date(tdate.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/, "$1 $2 $4 $3 UTC"));
	    			var user_date = new Date();

	    			var diff = Math.floor((user_date - system_date) / 1000);
	    			if (diff <= 1) {return "ahora";}
	    			if (diff < 20) {return "hace " + diff + " segundos";}
	    			if (diff < 40) {return "hace medio minuto";}
	    			if (diff < 60) {return "hace menos de un minuto";}
	    			if (diff <= 90) {return "hace un minuto";}
	    			if (diff <= 3540) {return "hace " + Math.round(diff / 60) + " minutos";}
	    			if (diff <= 5400) {return "hace una hora";}
	    			if (diff <= 86400) {return "hace " + Math.round(diff / 3600) + " horas";}
	    			if (diff <= 129600) {return "hace un día";}
	    			if (diff < 604800) {return "hace " + Math.round(diff / 86400) + " días";}
	    			if (diff <= 777600) {return "Hace una semana";}
	    			return "el " + system_date;

    		}

    		return this.each(function() {

				var o = options;
                var obj = $(this);
                var q;

				$(obj).append('

');
				$(".jtwt", obj).append('
' + o.loader_text + '
');
				$(".jtwt_loader", obj).fadeIn('slow');

				//Check if there is a search query given, if not fetch user tweets
				if(o.query) {

					q = encodeURIComponent(o.query);

				} else {

					q = 'from:' + encodeURIComponent(o.username);

				}

				//get the tweets from the API
				$.getJSON('https://search.twitter.com/search.json?q=' + q + '&callback=?', function(data){

console.log(data);

					var results = data['results'];

					if(results.length) {

						//Loop through results and append them to the parent
						for(var i = 0; i < o.count && i < results.length; i++) {

							var item = results[i];

							jtweet = '
';

			                if (o.image_size) {

			                	today = new Date();

				                jtweet += '
';
				                jtweet += ''
				                jtweet += '';
				                jtweet += '';
				                jtweet += '
';

			                }

			                var tweettext = item.text;
			                var tweetdate = parseTwitterDate(item.created_at);

			                if (o.convert_links) {

				                tweettext = tweettext.replace(/(http\:\/\/[A-Za-z0-9\/\.\?\=\-]*)/g,'$1');
				                tweettext = tweettext.replace(/@([A-Za-z0-9\/_]*)/g,'@$1');
				                tweettext = tweettext.replace(/#([a-zA-Z0-9ßÄÖÜäöüÑñÉéÈèÁáÀàÂâŶĈĉĜĝŷÊêÔôÛûŴŵ-]*)/g,'#$1');

			                }

			                jtweet += '
' + tweettext + '
';
			                jtweet += '' + tweetdate + '';

			                jtweet += '
';

			                $(".jtwt", obj).append(jtweet);

		                }

					} else {

						//If there are not any tweets, display the "no results" container
						$(".jtwt_loader", obj).fadeOut('fast', function() {

							$(".jtwt", obj).append('
' + o.no_result + '
');
							$(".jtwt_noresult", obj).fadeIn('slow');

						});

					}

					$(".jtwt_loader", obj).fadeOut('fast');

				});

			});

    	}

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

exports['incorporation-tabs'] = function () {
	a({ class: 'tab', href: '/official/non-revision/user-id/' }, "Certificate of incorporation");
	a({ class: 'tab active' }, "Documents and data of petitioner");

	div(
		{ class: 'user-official-application-revision' },
		h3(
			{ class: 'heading-tools' },
			"Documents received from petitioner",
			div(
				a(span({ class: 'fa fa-download' }), "View and print form"),
				a(span({ class: 'fa fa-download' }), "Payment receipt")
			)
		),

		ol({ 'class': 'submitted-documents-list' },
			li(
				a({ 'href': '' }, "Memorandum and articles of association")
			),
			li(
				a({ 'href': '' }, "Proof of identity for director 1")
			),
			li(
				a({ 'href': '' }, "Proof of identity for director 2")
			),
			li(
				a({ 'href': '' }, "Registered title deed")
			)
			),
		h3("Certificates uploaded by institutions"),

		h3("Complete content of the company file"),
		ol({ 'class': 'submitted-documents-thumbs-list revision-required-documents-thumbs-list ' },
			li(
				a({ 'href': '' },
					span({ class: 'document-confirmation success fa fa-check ' }),
					img({ 'src': '/uploads/docASubFile2.thumb.idoc.png.jpg' })
					)
			),
			li(
				a({ 'href': '' },
					span({ class: 'document-confirmation success fa fa-check ' }),
					img({ 'src': '/uploads/docASubFile1.thumb.idoc.jpg' })
					)
			),
			li(
				a({ 'href': '' },
					span({ class: 'document-confirmation error fa fa-exclamation ' }),
					img({ 'src': '/uploads/docBSubFile1.thumb.idoc.jpg' })
					)
			),
			li(
				a({ 'href': '' },
					span({ class: 'document-confirmation success fa fa-check ' }),
					img({ 'src': '/uploads/docASubFile2.thumb.idoc.png.jpg' })
					)
			)
			)
	);
	section(
		{ 'class': 'section-primary revision' },
		div({ 'class': 'revision-document' },
			h3(
				i({ 'class': 'list-item-number' },
						"1"),
				"Memorandum and articles of association"
			),
			div({ 'class': 'revision-document-preview' },
				a({ 'href': '' },
					img({ 'src': '/uploads/docASubFile2.idoc.png.jpg' })
					)
				)
			),
		div({ 'class': 'revision-user-data-section' },
			h3("Application form"),
			a({ 'class': 'fa fa-print nav-alternatives' }, "Print"),
			h4("Proposed company name"),
			table(
				tbody(
					tr(
						td("Blink IT Solutions")
					)
				)
			),
			h4("Business activity"),
			table(
				tbody(
					tr(
						th("Activity"),
						td("Air chater agent")
					),
					tr(
						th("Activity starting date"),
						td("7/30/2014")
					),
					tr(
						th("Date of account year end"),
						td("12/31/2014")
					),
					tr(
						th("Does the company have branches?"),
						td("Yes")
					)
				)
			),
			h4("Company secretary"),
			table(
				tbody(
					tr(
						th("Title"),
						td("Mr")
					),
					tr(
						th("First Name"),
						td("Andrei")
					),
					tr(
						th("Middle Name"),
						td("Mihai")
					),
					tr(
						th("Surname"),
						td("Balan")
					)
				)
			),
			h5("Residential address"),
			table(
				tbody(
					tr(
						th("Plot"),
						td("1")
					),
					tr(
						th("Block"),
						td("1")
					),
					tr(
						th("Street or location"),
						td("Nicolae Filipescu")
					),
					tr(
						th("City, district or town"),
						td("Bucharest")
					),
					tr(
						th("P.O. box"),
						td("1")
					),
					tr(
						th("Country"),
						td("Romania")
					)
				)
			),
			h4("Applicants"),
			h5("Marko Zagola"),
			h6("Personal data"),
			table(
				tbody(
					tr(
						th("Name"),
						td("Marko")
					),
					tr(
						th("Surname"),
						td("Zagalo")
					),
					tr(
						th("Document type"),
						td("X")
					),
					tr(
						th("Document number"),
						td("123")
					),
					tr(
						th("Marital status"),
						td("")
					),
					tr(
						th("Date of birth"),
						td("25-06-1991")
					),
					tr(
						th("Nationality"),
						td("Romanian")
					),
					tr(
						th("E-mail"),
						td("andrei.balan@blink-it.ro")
					)
				)
			),
			h6("Address"),
				table(
				tbody(
					tr(
						th("Address"),
						td("XXX")
					),
					tr(
						th("Number"),
						td("1")
					),
					tr(
						th("Postal code"),
						td("X")
					),
					tr(
						th("City"),
						td("Bucharest")
					),
					tr(
						th("Country"),
						td("Romania")
					)
				)
			)
			)
	);
};
<commit_msg>Unused class removed<commit_after>'use strict';

exports['incorporation-tabs'] = function () {
	a({ class: 'tab', href: '/official/non-revision/user-id/' }, "Certificate of incorporation");
	a({ class: 'tab active' }, "Documents and data of petitioner");

	div(
		h3(
			{ class: 'heading-tools' },
			"Documents received from petitioner",
			div(
				a(span({ class: 'fa fa-download' }), "View and print form"),
				a(span({ class: 'fa fa-download' }), "Payment receipt")
			)
		),

		ol({ 'class': 'submitted-documents-list' },
			li(
				a({ 'href': '' }, "Memorandum and articles of association")
			),
			li(
				a({ 'href': '' }, "Proof of identity for director 1")
			),
			li(
				a({ 'href': '' }, "Proof of identity for director 2")
			),
			li(
				a({ 'href': '' }, "Registered title deed")
			)
			),
		h3("Certificates uploaded by institutions"),

		h3("Complete content of the company file"),
		ol({ 'class': 'submitted-documents-thumbs-list revision-required-documents-thumbs-list ' },
			li(
				a({ 'href': '' },
					span({ class: 'document-confirmation success fa fa-check ' }),
					img({ 'src': '/uploads/docASubFile2.thumb.idoc.png.jpg' })
					)
			),
			li(
				a({ 'href': '' },
					span({ class: 'document-confirmation success fa fa-check ' }),
					img({ 'src': '/uploads/docASubFile1.thumb.idoc.jpg' })
					)
			),
			li(
				a({ 'href': '' },
					span({ class: 'document-confirmation error fa fa-exclamation ' }),
					img({ 'src': '/uploads/docBSubFile1.thumb.idoc.jpg' })
					)
			),
			li(
				a({ 'href': '' },
					span({ class: 'document-confirmation success fa fa-check ' }),
					img({ 'src': '/uploads/docASubFile2.thumb.idoc.png.jpg' })
					)
			)
			)
	);
	section(
		{ 'class': 'section-primary revision' },
		div({ 'class': 'revision-document' },
			h3(
				i({ 'class': 'list-item-number' },
						"1"),
				"Memorandum and articles of association"
			),
			div({ 'class': 'revision-document-preview' },
				a({ 'href': '' },
					img({ 'src': '/uploads/docASubFile2.idoc.png.jpg' })
					)
				)
			),
		div({ 'class': 'revision-user-data-section' },
			h3("Application form"),
			a({ 'class': 'fa fa-print nav-alternatives' }, "Print"),
			h4("Proposed company name"),
			table(
				tbody(
					tr(
						td("Blink IT Solutions")
					)
				)
			),
			h4("Business activity"),
			table(
				tbody(
					tr(
						th("Activity"),
						td("Air chater agent")
					),
					tr(
						th("Activity starting date"),
						td("7/30/2014")
					),
					tr(
						th("Date of account year end"),
						td("12/31/2014")
					),
					tr(
						th("Does the company have branches?"),
						td("Yes")
					)
				)
			),
			h4("Company secretary"),
			table(
				tbody(
					tr(
						th("Title"),
						td("Mr")
					),
					tr(
						th("First Name"),
						td("Andrei")
					),
					tr(
						th("Middle Name"),
						td("Mihai")
					),
					tr(
						th("Surname"),
						td("Balan")
					)
				)
			),
			h5("Residential address"),
			table(
				tbody(
					tr(
						th("Plot"),
						td("1")
					),
					tr(
						th("Block"),
						td("1")
					),
					tr(
						th("Street or location"),
						td("Nicolae Filipescu")
					),
					tr(
						th("City, district or town"),
						td("Bucharest")
					),
					tr(
						th("P.O. box"),
						td("1")
					),
					tr(
						th("Country"),
						td("Romania")
					)
				)
			),
			h4("Applicants"),
			h5("Marko Zagola"),
			h6("Personal data"),
			table(
				tbody(
					tr(
						th("Name"),
						td("Marko")
					),
					tr(
						th("Surname"),
						td("Zagalo")
					),
					tr(
						th("Document type"),
						td("X")
					),
					tr(
						th("Document number"),
						td("123")
					),
					tr(
						th("Marital status"),
						td("")
					),
					tr(
						th("Date of birth"),
						td("25-06-1991")
					),
					tr(
						th("Nationality"),
						td("Romanian")
					),
					tr(
						th("E-mail"),
						td("andrei.balan@blink-it.ro")
					)
				)
			),
			h6("Address"),
				table(
				tbody(
					tr(
						th("Address"),
						td("XXX")
					),
					tr(
						th("Number"),
						td("1")
					),
					tr(
						th("Postal code"),
						td("X")
					),
					tr(
						th("City"),
						td("Bucharest")
					),
					tr(
						th("Country"),
						td("Romania")
					)
				)
			)
			)
	);
};
<|endoftext|>


<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2017 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';
/*
  This component can be used to add in-page links to ids e.g. it could be used
  within a readme heading to link to .../#readme.
 */
YUI.add('hash-link', function() {

  juju.components.HashLink = React.createClass({
    displayName: 'HashLink',

    propTypes: {
      changeState: React.PropTypes.func.isRequired,
      hash: React.PropTypes.string.isRequired
    },

    /**
      Update the hash state.
    */
    _handleClick: function() {
      this.props.changeState({hash: this.props.hash});
    },

    render: function() {
      return (

          <juju.components.SvgIcon
            name="anchor_16"
            size="16" />

      );
    }
  });

}, '0.1.0', {
  requires: [
    'svg-icon'
  ]
});
<commit_msg>Update HashLink component.<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2017 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';
/*
  This component can be used to add in-page links to ids e.g. it could be used
  within a readme heading to link to .../#readme.
 */
const HashLink = React.createClass({
  displayName: 'HashLink',

  propTypes: {
    changeState: React.PropTypes.func.isRequired,
    hash: React.PropTypes.string.isRequired
  },

  /**
    Update the hash state.
  */
  _handleClick: function() {
    this.props.changeState({hash: this.props.hash});
  },

  render: function() {
    return (

        <juju.components.SvgIcon
          name="anchor_16"
          size="16" />

    );
  }
});

YUI.add('hash-link', function() {
  juju.components.HashLink = HashLink;
}, '0.1.0', {
  requires: [
    'svg-icon'
  ]
});
<|endoftext|>


<commit_before>import _ from 'lodash'
import Card from '../model/Card'
import PlayStack from '../model/PlayStack'
import DiscardStack from '../model/DiscardStack'
import DrawStack from '../model/DrawStack'
import DropStack from '../model/DropStack'
import * as helpers from './helpers'

export const resetUndos = state => {
  state.undoCount = 0
}

export const incrementScore = state => {
  state.score++
}

export const deal = (state) => {
  var deck, i, j, stack

  deck = generateDeck()

  state.logOn = false

  state.playStacks = []
  for (i = 0; i < 10; i++) {
    stack = new PlayStack(i)

    state.playStacks.push(stack)

    for (j = 0; j < 4; j++) {
      helpers.pushCard(stack, deck.pop())
    }
  }

  state.discardStack = new DiscardStack()
  state.drawStack = new DrawStack(state.discardStack)

  while (deck.length > 0) {
    helpers.pushCard(state.drawStack, deck.pop())
  }

  state.dropStacks = []
  for (i = 0; i < 8; i++) {
    stack = new DropStack(i)
    state.dropStacks.push(stack)
  }

  state.logOn = true
  state.score = 0
  state.startTime = new Date()
}

const consts = {
  cardNumbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
  cardSuits: ['C', 'D', 'S', 'H'],
  decks: 2
}

function generateDeck () {
  var deck = []

  _.forEach(_.range(consts.decks), () => {
    _.forEach(consts.cardNumbers, (cardNumber) => {
      _.forEach(consts.cardSuits, (cardSuit) => {
        deck.push(new Card(cardNumber, cardSuit))
      })
    })
  })

  // one shuffle didnt seem all that random. Similar cards seemed to be right next to each other
  deck = _(deck).shuffle().shuffle().shuffle().value()

  return deck
}

export const deselect = function (state) {
  if (state.selectedCard) {
    state.selectedCard.selected = false
  }

  state.selectedCard = null
  state.selectedStack = null
}

export const drawCard = function (state) {
  deselect(state)
  var card = helpers.popCard(state.drawStack)

  if (card) {
    helpers.pushCard(state.discardStack, card)
    state.score++
  }
}

export const selectDiscardStack = function (state) {
  var card = helpers.topCard(state.discardStack)

  if (card) {
    if (card === state.selectedCard) {
      deselect(state)
    } else {
      if (state.selectedCard) {
        deselect(state)
      }

      card.selected = true
      state.selectedCard = card
      state.selectedStack = state.discardStack
    }
  }
}

export const selectPlayStack = function (state, playStackIndex) {
  var playStack = state.playStacks[playStackIndex]
  var card = helpers.topCard(playStack)

  var previousCard = state.selectedCard

  if (card) {
    if (card === previousCard) {
      deselect(state)
    } else {
      if (previousCard && helpers.canDropOnOpenCard(card, previousCard)) {
        move(state, previousCard, playStack)
      } else {
        selectCard(state, card, playStack)
      }
    }
  }
}

export const selectDropStack = function (state, dropStackIndex) {
  var dropStack = state.dropStacks[dropStackIndex]
  var card = helpers.topCard(dropStack)

  var previousCard = state.selectedCard

  if (previousCard) {
    if (card === previousCard) {
      deselect(state)
    } else {
      if (previousCard && helpers.canDropOnDropStackCard(previousCard, card)) {
        move(state, previousCard, dropStack)
      } else {
        selectCard(state, card, dropStack)
      }
    }
  }
}

function move (state, card, newStack) {
  // todo need to remove the true case
  if (state.selectedStack.popCard) {
    state.selectedStack.popCard()
  } else {
    helpers.popCard(state.selectedStack)
  }

  if (newStack.pushCard) {
    newStack.pushCard(card)
  } else {
    helpers.pushCard(newStack, card)
  }

  deselect(state)
}

function selectCard (state, card, stack) {
  deselect(state)

  card.selected = true
  state.selectedCard = card
  state.selectedStack = stack
}
<commit_msg>fix bug in selecting empty drop stack<commit_after>import _ from 'lodash'
import Card from '../model/Card'
import PlayStack from '../model/PlayStack'
import DiscardStack from '../model/DiscardStack'
import DrawStack from '../model/DrawStack'
import DropStack from '../model/DropStack'
import * as helpers from './helpers'

export const resetUndos = state => {
  state.undoCount = 0
}

export const incrementScore = state => {
  state.score++
}

export const deal = (state) => {
  var deck, i, j, stack

  deck = generateDeck()

  state.logOn = false

  state.playStacks = []
  for (i = 0; i < 10; i++) {
    stack = new PlayStack(i)

    state.playStacks.push(stack)

    for (j = 0; j < 4; j++) {
      helpers.pushCard(stack, deck.pop())
    }
  }

  state.discardStack = new DiscardStack()
  state.drawStack = new DrawStack(state.discardStack)

  while (deck.length > 0) {
    helpers.pushCard(state.drawStack, deck.pop())
  }

  state.dropStacks = []
  for (i = 0; i < 8; i++) {
    stack = new DropStack(i)
    state.dropStacks.push(stack)
  }

  state.logOn = true
  state.score = 0
  state.startTime = new Date()
}

const consts = {
  cardNumbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
  cardSuits: ['C', 'D', 'S', 'H'],
  decks: 2
}

function generateDeck () {
  var deck = []

  _.forEach(_.range(consts.decks), () => {
    _.forEach(consts.cardNumbers, (cardNumber) => {
      _.forEach(consts.cardSuits, (cardSuit) => {
        deck.push(new Card(cardNumber, cardSuit))
      })
    })
  })

  // one shuffle didnt seem all that random. Similar cards seemed to be right next to each other
  deck = _(deck).shuffle().shuffle().shuffle().value()

  return deck
}

export const deselect = function (state) {
  if (state.selectedCard) {
    state.selectedCard.selected = false
  }

  state.selectedCard = null
  state.selectedStack = null
}

export const drawCard = function (state) {
  deselect(state)
  var card = helpers.popCard(state.drawStack)

  if (card) {
    helpers.pushCard(state.discardStack, card)
    state.score++
  }
}

export const selectDiscardStack = function (state) {
  var card = helpers.topCard(state.discardStack)

  if (card) {
    if (card === state.selectedCard) {
      deselect(state)
    } else {
      if (state.selectedCard) {
        deselect(state)
      }

      card.selected = true
      state.selectedCard = card
      state.selectedStack = state.discardStack
    }
  }
}

export const selectPlayStack = function (state, playStackIndex) {
  var playStack = state.playStacks[playStackIndex]
  var card = helpers.topCard(playStack)

  var previousCard = state.selectedCard

  if (card) {
    if (card === previousCard) {
      deselect(state)
    } else {
      if (previousCard && helpers.canDropOnOpenCard(card, previousCard)) {
        move(state, previousCard, playStack)
      } else {
        selectCard(state, card, playStack)
      }
    }
  }
}

export const selectDropStack = function (state, dropStackIndex) {
  var dropStack = state.dropStacks[dropStackIndex]
  var card = helpers.topCard(dropStack)

  var previousCard = state.selectedCard

  if (previousCard) {
    if (card === previousCard) {
      deselect(state)
    } else {
      if (previousCard && helpers.canDropOnDropStackCard(previousCard, card)) {
        move(state, previousCard, dropStack)
      } else {
        selectCard(state, card, dropStack)
      }
    }
  }
}

function move (state, card, newStack) {
  // todo need to remove the true case
  if (state.selectedStack.popCard) {
    state.selectedStack.popCard()
  } else {
    helpers.popCard(state.selectedStack)
  }

  if (newStack.pushCard) {
    newStack.pushCard(card)
  } else {
    helpers.pushCard(newStack, card)
  }

  deselect(state)
}

function selectCard (state, card, stack) {
  deselect(state)

  if (card) {
    card.selected = true
    state.selectedCard = card
    state.selectedStack = stack
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import './index.css';
import App from './App';

function loadPage(contents, estimatedTime, reward) {
  ReactDOM.render(<App contents={contents} estimatedTime={estimatedTime} reward={reward} />, document.getElementById('root'));
}

const url = new URL(window.location);
const estimatedTime = document.getElementById('input-time').value;
const reward = document.getElementById('input-reward').value;
const rawContents = document.getElementById('input-document').value;

// Better mechanism to select which to render.
if (url.pathname.match(/\/([0-9])+/)) {
  let fname = url.pathname.match(/\/([0-9])+/)[1];
  axios.get("/data/pilot/" + fname + ".json")
    .then((result) => {
      let contents = result.data;
      loadPage(contents, estimatedTime, reward);
    })
} else
  if (rawContents.length > 0 && rawContents[0] !== '$') {
  let contents = JSON.parse(rawContents);
  loadPage(contents, estimatedTime, reward);
} else {
  let contents = {
    "title": "Title",
    "paragraphs": ["A line of text."],
    "viewSelections": [],
    "recommendedMinWordCount": 10,
    "recommendedMaxWordCount": 50,
    "prompt": "",
  };
  loadPage(contents, estimatedTime, reward);
}

// Some hijinks for AMT
if (document.getElementById('submitButton') !== null) {
  document.getElementById('submitButton').remove();
}
<commit_msg>Fix handling of paths<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import './index.css';
import App from './App';

function loadPage(contents, estimatedTime, reward) {
  ReactDOM.render(<App contents={contents} estimatedTime={estimatedTime} reward={reward} />, document.getElementById('root'));
}

const url = new URL(window.location);
const estimatedTime = document.getElementById('input-time').value;
const reward = document.getElementById('input-reward').value;
const rawContents = document.getElementById('input-document').value;

// Better mechanism to select which to render.
if (url.pathname.match(/\/([0-9]+)/)) {
  let fname = url.pathname.match(/\/([0-9]+)/)[1];
  console.log("Getting file " + fname);
  axios.get("/data/pilot-20170810/" + fname + ".json")
    .then((result) => {
      let contents = result.data;
      loadPage(contents, estimatedTime, reward);
    })
} else
  if (rawContents.length > 0 && rawContents[0] !== '$') {
  let contents = JSON.parse(rawContents);
  loadPage(contents, estimatedTime, reward);
} else {
  let contents = {
    "title": "Title",
    "paragraphs": ["A line of text."],
    "viewSelections": [],
    "recommendedMinWordCount": 10,
    "recommendedMaxWordCount": 50,
    "prompt": "",
  };
  loadPage(contents, estimatedTime, reward);
}

// Some hijinks for AMT
if (document.getElementById('submitButton') !== null) {
  document.getElementById('submitButton').remove();
}
<|endoftext|>


<commit_before>var jQD = require('jquery-detached');
var page = require('../../util/page.js');
var jenkinsLocalStorage = require('../../util/jenkinsLocalStorage.js');
var tableMetadata = require('./model/ConfigTableMetaData.js');
var behaviorShim = require('../../util/behavior-shim');

exports.tabBarShowPreferenceKey = 'config:usetabs';

exports.addPageTabs = function(configSelector, onEachConfigTable, options) {
    var $ = jQD.getJQuery();

    $(function() {
        behaviorShim.specify(".dd-handle", 'config-drag-start', 1000, function() {
            page.fixDragEvent();
        });

        // We need to wait until after radioBlock.js Behaviour.js rules
        // have been applied, otherwise row-set rows become visible across sections.
        page.onload('.block-control', function() {
            // Only do job configs for now.
            var configTables = $(configSelector);
            if (configTables.size() > 0) {
                var tabBarShowPreference = jenkinsLocalStorage.getGlobalItem(exports.tabBarShowPreferenceKey, "yes");

                page.fixDragEvent(configTables);

                if (tabBarShowPreference === "yes") {
                    configTables.each(function() {
                        var configTable = $(this);
                        var tabBar = exports.addTabs(configTable, options);

                        onEachConfigTable.call(configTable, tabBar);

                        tabBar.deactivator.click(function() {
                            jenkinsLocalStorage.setGlobalItem(exports.tabBarShowPreferenceKey, "no");
                            require('window-handle').getWindow().location.reload();
                        });
                    });
                } else {
                    configTables.each(function() {
                        var configTable = $(this);
                        var activator = exports.addTabsActivator(configTable);
                        tableMetadata.markConfigTableParentForm(configTable);
                        activator.click(function() {
                            jenkinsLocalStorage.setGlobalItem(exports.tabBarShowPreferenceKey, "yes");
                            require('window-handle').getWindow().location.reload();
                        });
                    });
                }
            }
        }, configSelector);
    });
};

exports.addTabsOnFirst = function() {
    return exports.addTabs(tableMetadata.findConfigTables().first());
};

exports.addTabs = function(configTable, options) {
    var $ = jQD.getJQuery();
    var configTableMetadata;
    var tabOptions = (options || {});
    var trackSectionVisibility = (tabOptions.trackSectionVisibility || false);

    if ($.isArray(configTable)) {
        // It's a config
 metadata block
        configTableMetadata = configTable;
    } else if (typeof configTable === 'string') {
        // It's a config
 selector
        var configTableEl = $(configTable);
        if (configTableEl.size() === 0) {
            throw "No config table found using selector '" + configTable + "'";
        } else {
            configTableMetadata = tableMetadata.fromConfigTable(configTableEl);
        }
    } else {
        // It's a config
 element
        configTableMetadata = tableMetadata.fromConfigTable(configTable);
    }

    var tabBar = $('

');
    configTableMetadata.activatorContainer = tabBar;

    function newTab(section) {
        var tab = $('

');

        tab.text(section.title);
        tab.addClass(section.id);

        return tab;
    }

    var section;
    for (var i = 0; i < configTableMetadata.sections.length; i++) {
        section = configTableMetadata.sections[i];
        var tab = newTab(section);
        tabBar.append(tab);
        section.setActivator(tab);
    }

    var tabs = $('

');
    var noTabs = $('
Remove tabs
');

    configTableMetadata.configWidgets.append(tabs);
    configTableMetadata.configWidgets.prepend(noTabs);
    tabs.append(tabBar);

    tabs.mouseenter(function() {
        tabs.addClass('mouse-over');
    });
    tabs.mouseleave(function() {
        tabs.removeClass('mouse-over');
    });
    configTableMetadata.deactivator = noTabs;

    // Always activate the first section by default.
    configTableMetadata.activateFirstSection();

    if (trackSectionVisibility === true) {
        configTableMetadata.trackSectionVisibility();
    }

    return configTableMetadata;
};

exports.addTabsActivator = function(configTable) {
    var $ = jQD.getJQuery();
    var configWidgets = $('

Add tabs

');
    configWidgets.insertBefore(configTable.parent());
    return configWidgets;
};

exports.addFinderToggle = function(configTableMetadata) {
    var $ = jQD.getJQuery();
    var findToggle = $('

');
    var finderShowPreferenceKey = 'config:showfinder';

    findToggle.click(function() {
        var findContainer = $('.find-container', configTableMetadata.configWidgets);
        if (findContainer.hasClass('visible')) {
            findContainer.removeClass('visible');
            jenkinsLocalStorage.setGlobalItem(finderShowPreferenceKey, "no");
        } else {
            findContainer.addClass('visible');
            $('input', findContainer).focus();
            jenkinsLocalStorage.setGlobalItem(finderShowPreferenceKey, "yes");
        }
    });

    if (jenkinsLocalStorage.getGlobalItem(finderShowPreferenceKey, "yes") === 'yes') {
        findToggle.click();
    }
};<commit_msg>Applying @kzantow fix for the draggable sections regression<commit_after>var jQD = require('jquery-detached');
var page = require('../../util/page.js');
var jenkinsLocalStorage = require('../../util/jenkinsLocalStorage.js');
var tableMetadata = require('./model/ConfigTableMetaData.js');
var behaviorShim = require('../../util/behavior-shim');

exports.tabBarShowPreferenceKey = 'config:usetabs';

exports.addPageTabs = function(configSelector, onEachConfigTable, options) {
    var $ = jQD.getJQuery();

    $(function() {
        behaviorShim.specify(".dd-handle", 'config-drag-start', 1000, function(el) {
            page.fixDragEvent(el);
        });

        // We need to wait until after radioBlock.js Behaviour.js rules
        // have been applied, otherwise row-set rows become visible across sections.
        page.onload('.block-control', function() {
            // Only do job configs for now.
            var configTables = $(configSelector);
            if (configTables.size() > 0) {
                var tabBarShowPreference = jenkinsLocalStorage.getGlobalItem(exports.tabBarShowPreferenceKey, "yes");

                page.fixDragEvent(configTables);

                if (tabBarShowPreference === "yes") {
                    configTables.each(function() {
                        var configTable = $(this);
                        var tabBar = exports.addTabs(configTable, options);

                        onEachConfigTable.call(configTable, tabBar);

                        tabBar.deactivator.click(function() {
                            jenkinsLocalStorage.setGlobalItem(exports.tabBarShowPreferenceKey, "no");
                            require('window-handle').getWindow().location.reload();
                        });
                    });
                } else {
                    configTables.each(function() {
                        var configTable = $(this);
                        var activator = exports.addTabsActivator(configTable);
                        tableMetadata.markConfigTableParentForm(configTable);
                        activator.click(function() {
                            jenkinsLocalStorage.setGlobalItem(exports.tabBarShowPreferenceKey, "yes");
                            require('window-handle').getWindow().location.reload();
                        });
                    });
                }
            }
        }, configSelector);
    });
};

exports.addTabsOnFirst = function() {
    return exports.addTabs(tableMetadata.findConfigTables().first());
};

exports.addTabs = function(configTable, options) {
    var $ = jQD.getJQuery();
    var configTableMetadata;
    var tabOptions = (options || {});
    var trackSectionVisibility = (tabOptions.trackSectionVisibility || false);

    if ($.isArray(configTable)) {
        // It's a config
 metadata block
        configTableMetadata = configTable;
    } else if (typeof configTable === 'string') {
        // It's a config
 selector
        var configTableEl = $(configTable);
        if (configTableEl.size() === 0) {
            throw "No config table found using selector '" + configTable + "'";
        } else {
            configTableMetadata = tableMetadata.fromConfigTable(configTableEl);
        }
    } else {
        // It's a config
 element
        configTableMetadata = tableMetadata.fromConfigTable(configTable);
    }

    var tabBar = $('

');
    configTableMetadata.activatorContainer = tabBar;

    function newTab(section) {
        var tab = $('

');

        tab.text(section.title);
        tab.addClass(section.id);

        return tab;
    }

    var section;
    for (var i = 0; i < configTableMetadata.sections.length; i++) {
        section = configTableMetadata.sections[i];
        var tab = newTab(section);
        tabBar.append(tab);
        section.setActivator(tab);
    }

    var tabs = $('

');
    var noTabs = $('
Remove tabs
');

    configTableMetadata.configWidgets.append(tabs);
    configTableMetadata.configWidgets.prepend(noTabs);
    tabs.append(tabBar);

    tabs.mouseenter(function() {
        tabs.addClass('mouse-over');
    });
    tabs.mouseleave(function() {
        tabs.removeClass('mouse-over');
    });
    configTableMetadata.deactivator = noTabs;

    // Always activate the first section by default.
    configTableMetadata.activateFirstSection();

    if (trackSectionVisibility === true) {
        configTableMetadata.trackSectionVisibility();
    }

    return configTableMetadata;
};

exports.addTabsActivator = function(configTable) {
    var $ = jQD.getJQuery();
    var configWidgets = $('

Add tabs

');
    configWidgets.insertBefore(configTable.parent());
    return configWidgets;
};

exports.addFinderToggle = function(configTableMetadata) {
    var $ = jQD.getJQuery();
    var findToggle = $('

');
    var finderShowPreferenceKey = 'config:showfinder';

    findToggle.click(function() {
        var findContainer = $('.find-container', configTableMetadata.configWidgets);
        if (findContainer.hasClass('visible')) {
            findContainer.removeClass('visible');
            jenkinsLocalStorage.setGlobalItem(finderShowPreferenceKey, "no");
        } else {
            findContainer.addClass('visible');
            $('input', findContainer).focus();
            jenkinsLocalStorage.setGlobalItem(finderShowPreferenceKey, "yes");
        }
    });

    if (jenkinsLocalStorage.getGlobalItem(finderShowPreferenceKey, "yes") === 'yes') {
        findToggle.click();
    }
};<|endoftext|>


<commit_before>
  /**
   *  Advanced combo with extra parameters
   *
   */

  cdb.forms.ColumnTypeCombo = cdb.forms.Combo.extend({

    options: {
      minimumResultsForSearch: 20,
      placeholder: '',
      formatResult: true,
      dropdownCssClass: 'column-type'
    },

    _formatResult: function(data) {
      return  '' + data.id + 'asdf asdf asdf asdf asf asf' + '' + (data.text && data.text.charAt(0)) + ''
    }

  });<commit_msg>Removes 'asdf asdf asdf asdf' string<commit_after>
  /**
   *  Advanced combo with extra parameters
   *
   */

  cdb.forms.ColumnTypeCombo = cdb.forms.Combo.extend({

    options: {
      minimumResultsForSearch: 20,
      placeholder: '',
      formatResult: true,
      dropdownCssClass: 'column-type'
    },

    _formatResult: function(data) {
      return  '' + data.id + '' + '' + (data.text && data.text.charAt(0)) + ''
    }

  });
<|endoftext|>


<commit_before>var cdb = require('cartodb.js');
var $ = require('jquery');
var _ = require('underscore');
var navigateThroughRouter = require('../new_common/view_helpers/navigate_through_router');
var pluralizeString = require('../new_common/view_helpers/pluralize_string');
var CreateDialog = require('../new_common/dialogs/create/create_view');
var DeleteItemsDialog = require('../new_dashboard/dialogs/delete_items_view');
var ChangeLockDialog = require('../new_dashboard/dialogs/change_lock_view');
var ChangeLockViewModel = require('./dialogs/change_lock_view_model');
var DeleteItemsViewModel = require('./dialogs/delete_items_view_model');

/**
 *  Dashboard filters.
 *
 *  - 'Order by' (time,likes,etc) collection.
 *  - 'Filter by' collection.
 *  - 'Search' any pattern within collection.
 *
 */
module.exports = cdb.core.View.extend({

  _TOOLTIPS: ['js-likes', 'js-mapviews', 'js-updated_at', 'js-size'],

  events: {
    'submit .js-search-form':   '_submitSearch',
    'click .js-search-form':    'killEvent',
    'click .js-search-link':    '_onSearchClick',
    'click .js-clean-search':   '_onCleanSearchClick',
    'click .js-deselect_all':   '_unselectAll',
    'click .js-select_all':     '_selectAll',
    'click .js-order-link':     '_changeOrder',
    'click .js-delete':         '_openDeleteItemsDialog',
    'click .js-new_dataset':    '_connectDataset',
    'click .js-new_map':        '_newMap',
    'click .js-lock':           '_openChangeLockDialog',
    'click .js-privacy':        '_openPrivacyDialog',
    'click .js-link':           navigateThroughRouter
  },

  initialize: function() {
    this.router = this.options.router;
    this.user = this.options.user;
    this.localStorage = this.options.localStorage;
    this.template = cdb.templates.getTemplate('new_dashboard/views/filters');

    this._preRender();
    this._initBinds();
  },

  // It is necessary to add two static elements because
  // they can't be removed/replaced using render method
  // each time a change (in a model or a collection) happens.
  // This is due to the behaviour of the CSS animations.
  _preRender: function() {
    var $uInner = $('<div>').addClass('u-inner');
    var $filtersInner = $('<div>').addClass('Filters-inner');
    this.$el.append($uInner.append($filtersInner));
  },

  render: function(m, c) {
    this.clearSubViews();

    var selectedItemsCount = this._selectedItems().length;
    // If a change is made from content type we have to know
    // preventing show wrong data about total items
    var changedContentType = c && c.changes && c.changes.content_type;

    this.$('.Filters-inner').html(
      this.template(
        _.extend({
            canCreateDatasets:     this.user.canCreateDatasets(),
            order:                 this.localStorage.get('dashboard.order'),
            isInsideOrg:           this.user.isInsideOrg(),
            selectedItemsCount:    selectedItemsCount,
            maxLayersByMap:        this.user.get('max_layers'),
            totalShared:           changedContentType ? 0 : this.collection.total_shared,
            totalLiked:            changedContentType ? 0 : this.collection.total_likes,
            totalItems:            changedContentType ? 0 : this.collection.total_user_entries,
            pageItems:             this.collection.size(),
            router:                this.router,
            currentDashboardUrl:   this.router.currentDashboardUrl(),
            pluralizedContentType: pluralizeString(this.router.model.get('content_type') === "datasets" ? 'dataset' : 'map', changedContentType ? 0 : this.collection.total_user_entries),
            pluralizedContentTypeSelected: pluralizeString(this.router.model.get('content_type') === "datasets" ? 'dataset' : 'map', selectedItemsCount)
          },
          this.router.model.attributes
        )
      )
    );

    this._initViews();
    this._checkScroll();
    this._animate();

    return this;
  },

  _initBinds: function() {
    this.router.model.bind('change', this.render, this);
    this.collection.bind('loading', function() {
      this.$el.removeClass('is-relative');
    }, this);
    this.collection.bind('add remove change reset', this.render, this);
    this.user.bind('change:remaining_byte_quota', this.render, this);
    cdb.god.bind('closeDialogs', this._animate, this);
    cdb.god.bind('closeDialogs', this._unselectAll, this);
    _.bindAll(this, '_onWindowScroll');

    this.add_related_model(this.collection);
    this.add_related_model(this.router.model);
    this.add_related_model(this.user);
    this.add_related_model(cdb.god);
  },

  _checkScroll: function() {
    var content_type = this.router.model.get('content_type');
    var shared = this.router.model.get('shared');
    var locked = this.router.model.get('locked');
    var liked = this.router.model.get('liked');
    var search = this.router.model.isSearching();
    var total_entries = this.collection.total_entries;

    // Bind scroll
    if (total_entries === 0 && content_type === "maps" && !shared && !locked && !liked && !search) {
      // If there is no maps, onboarding should appear
      // and filters block should be after that section
      this.$el.addClass('is-relative');
      this._unbindScroll();
    } else {
      this.$el.removeClass('is-relative');
      this._bindScroll();
    }
  },

  _bindScroll: function() {
    this._unbindScroll();
    $(window).bind('scroll', this._onWindowScroll);
  },

  _unbindScroll: function() {
    $(window).unbind('scroll', this._onWindowScroll);
  },

  _initViews: function() {
    // Tipsys?
    var self = this;
    _.each(this._TOOLTIPS, function(el) {
      self.addView(
        new cdb.common.TipsyTooltip({
          el: self.$('.' + el),
          title: function() {
            var isFixed = self.$el.hasClass('is-fixed');
            return isFixed ? '' : $(this).attr('data-title');
          }
        })
      )
    });
  },

  _selectedItems: function() {
    return this.collection.where({ selected: true });
  },

  _animate: function() {
    // Show filters or selected items actions
    var selectedItemsCount = this._selectedItems().length;
    this.$('.Filters-inner')[ selectedItemsCount > 0 ? 'addClass' : 'removeClass' ]('items--selected');

    // Check if any search is applied
    this.$('.Filters-inner')[ this.router.model.isSearching() ? 'addClass' : 'removeClass' ]('search--enabled');
  },

  _selectAll: function(e) {
    this._select(e, true);
  },

  _unselectAll: function(e) {
    this._select(e, false);
  },

  _select: function(e, val) {
    this.killEvent(e);
    this.collection.each(function(vis) {
      vis.set('selected', val);
    });
  },

  _openDeleteItemsDialog: function(e) {
    this.killEvent(e);

    var viewModel = new DeleteItemsViewModel(this._selectedItems(), {
      contentType: this.router.model.get('content_type')
    });

    viewModel.bind('DeleteItemsDone', function() {
      this.user.fetch(); // needed in order to keep the "quota" synchronized
    }, this);

    var view = new DeleteItemsDialog({
      viewModel: viewModel,
      user: this.user,
      clean_on_hide: true,
      enter_to_confirm: true
    });
    this.addView(view);

    view.appendToBody();
  },

  _openChangeLockDialog: function(e) {
    this.killEvent(e);

    var viewModel = new ChangeLockViewModel(this._selectedItems());
    viewModel.bind('ProcessItemsDone', function() {
      this.collection.fetch();
    }, this);

    var view = new ChangeLockDialog({
      contentType: this.router.model.get('content_type'),
      viewModel: viewModel,
      clean_on_hide: true,
      enter_to_confirm: true
    });
    this.addView(view);

    view.appendToBody();
  },

  _openPrivacyDialog: function(e) {
    this.killEvent(e);
    cdb.god.trigger('openPrivacyDialog', this._selectedItems()[0]);
  },

  _onSearchClick: function(e) {
    this.killEvent(e);
    var wasSearchInputVisible = this.$('.Filters-inner').hasClass('search--enabled');
    this.$('.Filters-inner').toggleClass('search--enabled', !wasSearchInputVisible);

    if (this.router.model.isSearching()) {
      this._cleanSearch();
    } else if (!wasSearchInputVisible) {
      this.$('.js-search-input').focus();
    }
  },

  // Creation actions

  _newMap: function(e) {
    if (e) e.preventDefault();
    this._openCreateDialog('map');
  },

  _connectDataset: function(e) {
    if (e) e.preventDefault();

    if (this.user.canCreateDatasets()) {
      this._openCreateDialog('dataset');
    }
  },

  _openCreateDialog: function(type) {
    var createDialog = new CreateDialog({
      type: type || 'map',
      user: this.user,
      clean_on_hide: true
    });
    createDialog.bind('mapCreated', function(vis) {
      window.location = vis.viewUrl().edit();
    }, this);
    createDialog.bind('datasetCreated', function(tableMetadata) {
      window.location = tableMetadata.viewUrl();
    }, this);
    createDialog.bind('datasetSelected', function(d) {
      this.trigger('datasetSelected', d, this);
    }, this);
    createDialog.bind('remoteSelected', function(d) {
      this.trigger('remoteSelected', d, this);
    }, this);
    createDialog.appendToBody();
  },

  // Filter actions

  _onCleanSearchClick: function(e) {
    this.killEvent(e);
    this._cleanSearch();
  },

  _submitSearch: function(e) {
    this.killEvent(e);
    this._navigateToUrl({
      search: this.$('.js-search-input').val().trim(),
      library: this.router.model.get('library'),
      shared: this.router.model.get('shared')
    });
  },

  _cleanSearch: function() {
    this._navigateToUrl({
      search: '',
      library: this.router.model.get('library'),
      shared: this.router.model.get('shared')
    });
  },

  _navigateToUrl: function(opts) {
    this.router.navigate(this.router.currentUrl(opts), { trigger: true });
  },

  _changeOrder: function(e) {
    if (e) e.preventDefault();

    var $el = $(e.target).closest('.js-order-link');
    var order = 'updated_at';

    if ($el.hasClass('js-mapviews')) order = 'mapviews';
    if ($el.hasClass('js-likes')) order = 'likes';
    if ($el.hasClass('js-size')) order = 'size';

    // Order change?
    if (this.router.model.get('order') !== order) {
      this.localStorage.set({ 'dashboard.order': order });
      this.router.model.set('order', order);
    }
  },

  _onWindowScroll: function() {
    var offset = $(window).scrollTop();
    this.$el[ offset > 81 ? 'addClass' : 'removeClass' ]('is-fixed')
  },

  clean: function() {
    this._unbindScroll();
    cdb.core.View.prototype.clean.call(this);
  }

});
<commit_msg>Hide filters search on ESC<commit_after>var cdb = require('cartodb.js');
var $ = require('jquery');
var _ = require('underscore');
var navigateThroughRouter = require('../new_common/view_helpers/navigate_through_router');
var pluralizeString = require('../new_common/view_helpers/pluralize_string');
var CreateDialog = require('../new_common/dialogs/create/create_view');
var DeleteItemsDialog = require('../new_dashboard/dialogs/delete_items_view');
var ChangeLockDialog = require('../new_dashboard/dialogs/change_lock_view');
var ChangeLockViewModel = require('./dialogs/change_lock_view_model');
var DeleteItemsViewModel = require('./dialogs/delete_items_view_model');

/**
 *  Dashboard filters.
 *
 *  - 'Order by' (time,likes,etc) collection.
 *  - 'Filter by' collection.
 *  - 'Search' any pattern within collection.
 *
 */
module.exports = cdb.core.View.extend({

  _TOOLTIPS: ['js-likes', 'js-mapviews', 'js-updated_at', 'js-size'],

  events: {
    'submit .js-search-form':   '_submitSearch',
    'keydown .js-search-form':  '_onSearchKeyDown',
    'click .js-search-form':    'killEvent',
    'click .js-search-link':    '_onSearchClick',
    'click .js-clean-search':   '_onCleanSearchClick',
    'click .js-deselect_all':   '_unselectAll',
    'click .js-select_all':     '_selectAll',
    'click .js-order-link':     '_changeOrder',
    'click .js-delete':         '_openDeleteItemsDialog',
    'click .js-new_dataset':    '_connectDataset',
    'click .js-new_map':        '_newMap',
    'click .js-lock':           '_openChangeLockDialog',
    'click .js-privacy':        '_openPrivacyDialog',
    'click .js-link':           navigateThroughRouter
  },

  initialize: function() {
    this.router = this.options.router;
    this.user = this.options.user;
    this.localStorage = this.options.localStorage;
    this.template = cdb.templates.getTemplate('new_dashboard/views/filters');

    this._preRender();
    this._initBinds();
  },

  // It is necessary to add two static elements because
  // they can't be removed/replaced using render method
  // each time a change (in a model or a collection) happens.
  // This is due to the behaviour of the CSS animations.
  _preRender: function() {
    var $uInner = $('<div>').addClass('u-inner');
    var $filtersInner = $('<div>').addClass('Filters-inner');
    this.$el.append($uInner.append($filtersInner));
  },

  render: function(m, c) {
    this.clearSubViews();

    var selectedItemsCount = this._selectedItems().length;
    // If a change is made from content type we have to know
    // preventing show wrong data about total items
    var changedContentType = c && c.changes && c.changes.content_type;

    this.$('.Filters-inner').html(
      this.template(
        _.extend({
            canCreateDatasets:     this.user.canCreateDatasets(),
            order:                 this.localStorage.get('dashboard.order'),
            isInsideOrg:           this.user.isInsideOrg(),
            selectedItemsCount:    selectedItemsCount,
            maxLayersByMap:        this.user.get('max_layers'),
            totalShared:           changedContentType ? 0 : this.collection.total_shared,
            totalLiked:            changedContentType ? 0 : this.collection.total_likes,
            totalItems:            changedContentType ? 0 : this.collection.total_user_entries,
            pageItems:             this.collection.size(),
            router:                this.router,
            currentDashboardUrl:   this.router.currentDashboardUrl(),
            pluralizedContentType: pluralizeString(this.router.model.get('content_type') === "datasets" ? 'dataset' : 'map', changedContentType ? 0 : this.collection.total_user_entries),
            pluralizedContentTypeSelected: pluralizeString(this.router.model.get('content_type') === "datasets" ? 'dataset' : 'map', selectedItemsCount)
          },
          this.router.model.attributes
        )
      )
    );

    this._initViews();
    this._checkScroll();
    this._animate();

    return this;
  },

  _initBinds: function() {
    this.router.model.bind('change', this.render, this);
    this.collection.bind('loading', function() {
      this.$el.removeClass('is-relative');
    }, this);
    this.collection.bind('add remove change reset', this.render, this);
    this.user.bind('change:remaining_byte_quota', this.render, this);
    cdb.god.bind('closeDialogs', this._animate, this);
    cdb.god.bind('closeDialogs', this._unselectAll, this);
    _.bindAll(this, '_onWindowScroll');

    this.add_related_model(this.collection);
    this.add_related_model(this.router.model);
    this.add_related_model(this.user);
    this.add_related_model(cdb.god);
  },

  _checkScroll: function() {
    var content_type = this.router.model.get('content_type');
    var shared = this.router.model.get('shared');
    var locked = this.router.model.get('locked');
    var liked = this.router.model.get('liked');
    var search = this.router.model.isSearching();
    var total_entries = this.collection.total_entries;

    // Bind scroll
    if (total_entries === 0 && content_type === "maps" && !shared && !locked && !liked && !search) {
      // If there is no maps, onboarding should appear
      // and filters block should be after that section
      this.$el.addClass('is-relative');
      this._unbindScroll();
    } else {
      this.$el.removeClass('is-relative');
      this._bindScroll();
    }
  },

  _bindScroll: function() {
    this._unbindScroll();
    $(window).bind('scroll', this._onWindowScroll);
  },

  _unbindScroll: function() {
    $(window).unbind('scroll', this._onWindowScroll);
  },

  _initViews: function() {
    // Tipsys?
    var self = this;
    _.each(this._TOOLTIPS, function(el) {
      self.addView(
        new cdb.common.TipsyTooltip({
          el: self.$('.' + el),
          title: function() {
            var isFixed = self.$el.hasClass('is-fixed');
            return isFixed ? '' : $(this).attr('data-title');
          }
        })
      )
    });
  },

  _selectedItems: function() {
    return this.collection.where({ selected: true });
  },

  _animate: function() {
    // Show filters or selected items actions
    var selectedItemsCount = this._selectedItems().length;
    this.$('.Filters-inner')[ selectedItemsCount > 0 ? 'addClass' : 'removeClass' ]('items--selected');

    // Check if any search is applied
    this.$('.Filters-inner')[ this.router.model.isSearching() ? 'addClass' : 'removeClass' ]('search--enabled');
  },

  _selectAll: function(e) {
    this._select(e, true);
  },

  _unselectAll: function(e) {
    this._select(e, false);
  },

  _select: function(e, val) {
    this.killEvent(e);
    this.collection.each(function(vis) {
      vis.set('selected', val);
    });
  },

  _openDeleteItemsDialog: function(e) {
    this.killEvent(e);

    var viewModel = new DeleteItemsViewModel(this._selectedItems(), {
      contentType: this.router.model.get('content_type')
    });

    viewModel.bind('DeleteItemsDone', function() {
      this.user.fetch(); // needed in order to keep the "quota" synchronized
    }, this);

    var view = new DeleteItemsDialog({
      viewModel: viewModel,
      user: this.user,
      clean_on_hide: true,
      enter_to_confirm: true
    });
    this.addView(view);

    view.appendToBody();
  },

  _openChangeLockDialog: function(e) {
    this.killEvent(e);

    var viewModel = new ChangeLockViewModel(this._selectedItems());
    viewModel.bind('ProcessItemsDone', function() {
      this.collection.fetch();
    }, this);

    var view = new ChangeLockDialog({
      contentType: this.router.model.get('content_type'),
      viewModel: viewModel,
      clean_on_hide: true,
      enter_to_confirm: true
    });
    this.addView(view);

    view.appendToBody();
  },

  _openPrivacyDialog: function(e) {
    this.killEvent(e);
    cdb.god.trigger('openPrivacyDialog', this._selectedItems()[0]);
  },

  _onSearchClick: function(e) {
    this.killEvent(e);
    var wasSearchInputVisible = this.$('.Filters-inner').hasClass('search--enabled');
    this.$('.Filters-inner').toggleClass('search--enabled', !wasSearchInputVisible);

    if (this.router.model.isSearching()) {
      this._cleanSearch();
    } else if (!wasSearchInputVisible) {
      this.$('.js-search-input').val('');
      this.$('.js-search-input').focus();
    }
  },

  _onSearchKeyDown: function(e) {
    if (e.keyCode === 27) {
      this._onSearchClick(e);
    }
  },

  // Creation actions

  _newMap: function(e) {
    if (e) e.preventDefault();
    this._openCreateDialog('map');
  },

  _connectDataset: function(e) {
    if (e) e.preventDefault();

    if (this.user.canCreateDatasets()) {
      this._openCreateDialog('dataset');
    }
  },

  _openCreateDialog: function(type) {
    var createDialog = new CreateDialog({
      type: type || 'map',
      user: this.user,
      clean_on_hide: true
    });
    createDialog.bind('mapCreated', function(vis) {
      window.location = vis.viewUrl().edit();
    }, this);
    createDialog.bind('datasetCreated', function(tableMetadata) {
      window.location = tableMetadata.viewUrl();
    }, this);
    createDialog.bind('datasetSelected', function(d) {
      this.trigger('datasetSelected', d, this);
    }, this);
    createDialog.bind('remoteSelected', function(d) {
      this.trigger('remoteSelected', d, this);
    }, this);
    createDialog.appendToBody();
  },

  // Filter actions

  _onCleanSearchClick: function(e) {
    this.killEvent(e);
    this._cleanSearch();
  },

  _submitSearch: function(e) {
    this.killEvent(e);
    this._navigateToUrl({
      search: this.$('.js-search-input').val().trim(),
      library: this.router.model.get('library'),
      shared: this.router.model.get('shared')
    });
  },

  _cleanSearch: function() {
    this._navigateToUrl({
      search: '',
      library: this.router.model.get('library'),
      shared: this.router.model.get('shared')
    });
  },

  _navigateToUrl: function(opts) {
    this.router.navigate(this.router.currentUrl(opts), { trigger: true });
  },

  _changeOrder: function(e) {
    if (e) e.preventDefault();

    var $el = $(e.target).closest('.js-order-link');
    var order = 'updated_at';

    if ($el.hasClass('js-mapviews')) order = 'mapviews';
    if ($el.hasClass('js-likes')) order = 'likes';
    if ($el.hasClass('js-size')) order = 'size';

    // Order change?
    if (this.router.model.get('order') !== order) {
      this.localStorage.set({ 'dashboard.order': order });
      this.router.model.set('order', order);
    }
  },

  _onWindowScroll: function() {
    var offset = $(window).scrollTop();
    this.$el[ offset > 81 ? 'addClass' : 'removeClass' ]('is-fixed')
  },

  clean: function() {
    this._unbindScroll();
    cdb.core.View.prototype.clean.call(this);
  }

});
<|endoftext|>


<commit_before>angular.module('Components').directive('asAutocomplete', ['$injector', function($injector){
  return {
    restrict: 'EAC',
    scope: {
      minLength: '@'
    },
    transclude: true,
    template: '
',
    replace: true,
    controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
      var
        fetcher = $injector.get($attrs.fetcher),
        is_searching = false,

        can_search = function(term){
          return !is_searching && term && term.length >= $scope.minLength && term !== $scope.last_search;
        },
        process_data = function(data){
          is_searching = false;
          $scope.show_list = true;
          $scope.results = data;
        },
        term_changed = function(term){
          $scope.show_list = false;
          if(!can_search(term)){ return; }
          is_searching = true;
          fetcher.get(term, process_data);
        }

      this.scope = $scope;

      this.set_items = function(items_scope){
        items_scope.$watch('selected_item', function(selected_item){
          $scope.last_search = selected_item;
          $scope.results = [];
        });
      };

      this.set_input = function(input){
        $scope.input = input;
        input.bind("input", function(){
          $scope.results = [];
          term_changed(input.val());
        });
      };
    }]
  }
}]);

angular.module('Components').directive('asAutocompleteItem', ['$timeout', 'Offset', 'KeyCodes', function($timeout, Offset, KeyCodes){
  return {
    restrict: 'EAC',
    require: '^asAutocomplete',
    transclude: true,
    replace: true,
    template:
      '
' +
        '
' +
          '

' +
        '
' +
      '
',
    link: function(scope, iElement, iAttrs, asAutocompleteCtrl){
      asAutocompleteCtrl.set_items(scope);
      asAutocompleteCtrl.scope.$watch('input', function(input){
        scope.bind_input(input);
      });
      asAutocompleteCtrl.scope.$watch('results', function(items){ scope.items = items; });
      asAutocompleteCtrl.scope.$watch('show_list', function(show_list){ scope.show_list = show_list });
    },
    controller: ['$scope', '$element', function($scope, $element){
      var
        directions = {
          next: function(){
            $scope.hovered_index++;
            if($scope.items.length <= $scope.hovered_index){ $scope.hovered_index = 0}
          },
          prev: function(){
            $scope.hovered_index--;
            if(0 > $scope.hovered_index){ $scope.hovered_index = $scope.items.length - 1}
          }
        };

      $scope.hovered_index = -1;
      $scope.show_list = true;

      $scope.bind_input = function(input){
        var body = angular.element(document.body);
        body.append($element);
        Offset.dock_to(input[0], $element);

        input
          .bind('input', function(){
            $scope.$apply('hovered_index = -1');
          })
          .bind('focus', function(){
            $scope.$apply('show_list = true');
          })
          .bind('blur', function(){
            $timeout(function(){
              $scope.$apply('show_list = false');
              $scope.$apply('hovered_index = -1');
            }, 200);
          })
          .bind("keydown", function(event){
            switch(KeyCodes.get(event.keyCode)){
            case 'UP':
              $scope.$apply(function(scope){ scope.change_hovered('prev') });
              break;
            case 'DOWN':
              $scope.$apply(function(scope){ scope.change_hovered('next') });
              break;
            case 'ENTER':
              event.preventDefault();
              $scope.$apply(function(scope){ scope.item_selected() });
              break;
            case 'NUMPAD_ENTER':
              $scope.$apply(function(scope){ scope.item_selected() });
              break;
            case 'ESCAPE':
              $scope.$apply('show_list = false');
              break;
            }
          });
      };

      $scope.change_hovered = function(direction){
        if(!$scope.items){return;}
        directions[direction]();
      };

      $scope.is_hovered = function(item){
        return $scope.items.indexOf(item) === $scope.hovered_index;
      };

      $scope.item_hovered = function(item){
        $scope.hovered_index = $scope.items.indexOf(item);
      };

      $scope.item_selected = function(){
        $scope.selected_item = $scope.items[$scope.hovered_index];
        $scope.show_list = false;
      };
    }]
  }
}]);

angular.module('Components').directive('asAutocompleteInput', [function(){
  return {
    restrict: "EAC",
    require: '^asAutocomplete',

    link: function(scope, iElement, iAttrs, asAutocompleteCtrl){
      var input = iElement.children('input');
      asAutocompleteCtrl.set_input(input);
      asAutocompleteCtrl.scope.$watch('last_search', function(last_search){ scope.search = last_search });
    }
  }
}]);

<commit_msg>Autocomplete fixes for map app<commit_after>angular.module('Components').directive('asAutocomplete', ['$injector', function($injector){
  return {
    restrict: 'EAC',
    scope: {
      minLength: '@',
      acModel: '=acModel'
    },
    transclude: true,
    template: '
',
    replace: true,
    controller: ['$scope', '$element', '$timeout', '$attrs', function($scope, $element, $timeout, $attrs){
      var
        fetcher = $injector.get($attrs.fetcher),
        is_searching = false,

        can_search = function(term){
          return !is_searching && term && term.length >= $scope.minLength && term !== $scope.last_search;
        },
        process_data = function(data){
          is_searching = false;
          $scope.show_list = true;
          $scope.results = data;
        },
        term_changed = function(term){
          $scope.show_list = false;
          if(!can_search(term)){ return; }
          is_searching = true;
          fetcher.get(term, process_data);
        }

      this.scope = $scope;

      $scope.initial_value = angular.copy($scope.acModel);
      $timeout(function(){
        $scope.$apply('last_search=initial_value');
      }, 100);

      this.set_items = function(items_scope){
        items_scope.$watch('selected_item', function(selected_item){
          if(!selected_item){return;}
          $scope.last_search = selected_item;
          $scope.acModel = selected_item;
          $scope.results = [];
        });
      };

      this.set_input = function(input){
        $scope.input = input;
        input.bind("input", function(){
          $scope.results = [];
          term_changed(input.val());
        });
      };
    }]
  }
}]);

angular.module('Components').directive('asAutocompleteItem', ['$timeout', 'Offset', 'KeyCodes', function($timeout, Offset, KeyCodes){
  return {
    restrict: 'EAC',
    require: '^asAutocomplete',
    transclude: true,
    replace: true,
    template:
      '
' +
        '
' +
          '

' +
        '
' +
      '
',
    link: function(scope, iElement, iAttrs, asAutocompleteCtrl){
      asAutocompleteCtrl.set_items(scope);
      asAutocompleteCtrl.scope.$watch('input', function(input){
        scope.bind_input(input);
      });
      asAutocompleteCtrl.scope.$watch('results', function(items){ scope.items = items; });
      asAutocompleteCtrl.scope.$watch('show_list', function(show_list){ scope.show_list = show_list });
    },
    controller: ['$scope', '$element', function($scope, $element){
      var
        directions = {
          next: function(){
            $scope.hovered_index++;
            if($scope.items.length <= $scope.hovered_index){ $scope.hovered_index = 0}
          },
          prev: function(){
            $scope.hovered_index--;
            if(0 > $scope.hovered_index){ $scope.hovered_index = $scope.items.length - 1}
          }
        };

      $scope.hovered_index = -1;
      $scope.show_list = true;

      $scope.bind_input = function(input){
        var body = angular.element(document.body);
        body.append($element);

        input
          .bind('input', function(){
            $scope.$apply('hovered_index = -1');
          })
          .bind('focus', function(){
            Offset.dock_to(input[0], $element);
            $scope.$apply('show_list = true');
          })
          .bind('blur', function(){
            $timeout(function(){
              $scope.$apply('show_list = false');
              $scope.$apply('hovered_index = -1');
            }, 200);
          })
          .bind("keydown", function(event){
            switch(KeyCodes.get(event.keyCode)){
            case 'UP':
              $scope.$apply(function(scope){ scope.change_hovered('prev') });
              break;
            case 'DOWN':
              $scope.$apply(function(scope){ scope.change_hovered('next') });
              break;
            case 'ENTER':
              event.preventDefault();
              $scope.$apply(function(scope){ scope.item_selected() });
              break;
            case 'NUMPAD_ENTER':
              $scope.$apply(function(scope){ scope.item_selected() });
              break;
            case 'ESCAPE':
              $scope.$apply('show_list = false');
              break;
            }
          });
      };

      $scope.change_hovered = function(direction){
        if(!$scope.items){return;}
        directions[direction]();
      };

      $scope.is_hovered = function(item){
        return $scope.items.indexOf(item) === $scope.hovered_index;
      };

      $scope.item_hovered = function(item){
        $scope.hovered_index = $scope.items.indexOf(item);
      };

      $scope.item_selected = function(){
        $scope.selected_item = $scope.items[$scope.hovered_index];
        $scope.show_list = false;
      };
    }]
  }
}]);

angular.module('Components').directive('asAutocompleteInput', [function(){
  return {
    restrict: "EAC",
    require: '^asAutocomplete',
    link: function(scope, iElement, iAttrs, asAutocompleteCtrl){
      var input = iElement.children('input');
      asAutocompleteCtrl.set_input(input);
      asAutocompleteCtrl.scope.$watch('last_search', function(last_search){
        scope.search = last_search;
      });
    }
  }
}]);

<|endoftext|>


<commit_before>// script = document.createElement('script');
// script.src = 'https://rawgit.com/rplaurindo/javascript_collections-rails/master/lib/assets/javascripts/javascript_collections/collections.js';
// head = document.querySelector('head');
// head.appendChild(script);

doQuery = function(query){
    var collection = [],
        query = document.querySelectorAll(query);
    if(query.length > 0) {
        query.each(function(e) {
            collection.push(e);
        });
    }
    return collection;
}

HTMLElement.prototype.is = function(selector) {
    var obj = this;

    switch(selector) {
        case ':hidden':
            if(obj.style.display === 'none') {
                return true;
            }
            break;
    }
    return false;
}

Array.prototype.prev = function(selector) {
    var collection = [];

    this.each(function(e) {
        if(e.previousElementSibling){
            collection.push(e.previousElementSibling);
        }
    });
    return collection;
}

Array.prototype.item = function(index) {
    var _a = this;
    if(_a.hasOwnProperty(index)) {
        return this[index];
    }
    return null;
}

Array.prototype.parents = function(nodeName){
    var _parents = [],
        collection = this,
        parent = null;

    collection.each(function(e) {
        parent = e.parentNode;
        if(parent.nodeName.toLowerCase() === nodeName) {
            _parents.push(parent);
        } else {
            while(true) {
                parent = parent.parentNode;
                if(parent){
                    if(parent.nodeName.toLowerCase() === nodeName) {
                        _parents.push(parent);
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    });
    return _parents;
}

Array.prototype.css = function(attr, value) {
    var collection = this;
    if(attr.constructor === Object) {
        var attrs = attr;
        collection.each(function(e) {
            for(i in attrs){
                if( attrs.hasOwnProperty(i) ){
                    e.style[i] = attr[i];
                }
            }
        });
    } else {
        collection.each(function(e) {
            e.style[attr] = value;
        });
    }
    return this;
}

Array.prototype.each = function(callback){
    var _a = this,
    i = 0;
    while (true) {
        if( _a.hasOwnProperty(i) ){
            callback(_a[i], i);
            i++;
            if (i === _a.length) {
                break;
            }
        }
    }
}

NodeList.prototype.each = function(callback){
    var _a = this,
        i = 0;
    while (true) {
        if( _a.hasOwnProperty(i) ) {
            callback(_a.item(i), i);
            i++;
            if(i === _a.length) {
                break;
            }
        }
    }
}
<commit_msg>Update collections.js<commit_after>// script = document.createElement('script');
// script.src = 'https://rawgit.com/rplaurindo/javascript_collections-rails/master/lib/assets/javascripts/javascript_collections/collections.js';
// head = document.querySelector('head');
// head.appendChild(script);

doQuery = function(query){
    var collection = [],
        query = document.querySelectorAll(query);
    if(query.length > 0) {
        query.each(function(e) {
            collection.push(e);
        });
    }
    return collection;
}

HTMLElement.prototype.prev = function() {
    return this.previousElementSibling;
}

HTMLElement.prototype.next = function() {
    return this.nextElementSibling;
}

Array.prototype.prev = function(selector) {
    var collection = [];

    this.each(function(e) {
        if(e.previousElementSibling){
            collection.push(e.previousElementSibling);
        }
    });
    return collection;
}

HTMLElement.prototype.is = function(selector) {
    var obj = this;

    if(selector[0] === ':'){
        switch(selector) {
            case ':hidden':
                if(obj.style.display === 'none') {
                    return true;
                }
                break;
        }
    } else {
        if(document.querySelector(selector)) {
            return true;
        }
    }

    return false;
}

Array.prototype.item = function(index) {
    var _a = this;
    if(_a.hasOwnProperty(index)) {
        return this[index];
    }
    return null;
}

Array.prototype.parents = function(nodeName){
    var _parents = [],
        collection = this,
        parent = null;

    collection.each(function(e) {
        parent = e.parentNode;
        if(parent.nodeName.toLowerCase() === nodeName) {
            _parents.push(parent);
        } else {
            while(true) {
                parent = parent.parentNode;
                if(parent){
                    if(parent.nodeName.toLowerCase() === nodeName) {
                        _parents.push(parent);
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    });
    return _parents;
}

Array.prototype.css = function(attr, value) {
    var collection = this;
    if(attr.constructor === Object) {
        var attrs = attr;
        collection.each(function(e) {
            for(i in attrs){
                if( attrs.hasOwnProperty(i) ){
                    e.style[i] = attr[i];
                }
            }
        });
    } else {
        collection.each(function(e) {
            e.style[attr] = value;
        });
    }
    return this;
}

Array.prototype.each = function(callback){
    var _a = this,
    i = 0;
    while (true) {
        if( _a.hasOwnProperty(i) ){
            callback(_a[i], i);
            i++;
            if (i === _a.length) {
                break;
            }
        }
    }
}

NodeList.prototype.each = function(callback){
    var _a = this,
        i = 0;
    while (true) {
        if( _a.hasOwnProperty(i) ) {
            callback(_a.item(i), i);
            i++;
            if(i === _a.length) {
                break;
            }
        }
    }
}
<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace arcsine
*/
var arcsine = {};

/**
* @name Arcsine
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/ctor}
*/
setReadOnly( arcsine, 'Arcsine', require( '@stdlib/math/base/dist/arcsine/ctor' ) );

/**
* @name cdf
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/cdf}
*/
setReadOnly( arcsine, 'cdf', require( '@stdlib/math/base/dist/arcsine/cdf' ) );

/**
* @name entropy
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/entropy}
*/
setReadOnly( arcsine, 'entropy', require( '@stdlib/math/base/dist/arcsine/entropy' ) );

/**
* @name kurtosis
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/kurtosis}
*/
setReadOnly( arcsine, 'kurtosis', require( '@stdlib/math/base/dist/arcsine/kurtosis' ) );

/**
* @name logpdf
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/logpdf}
*/
setReadOnly( arcsine, 'logpdf', require( '@stdlib/math/base/dist/arcsine/logpdf' ) );

/**
* @name mean
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/mean}
*/
setReadOnly( arcsine, 'mean', require( '@stdlib/math/base/dist/arcsine/mean' ) );

/**
* @name median
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/median}
*/
setReadOnly( arcsine, 'median', require( '@stdlib/math/base/dist/arcsine/median' ) );

/**
* @name mode
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/mode}
*/
setReadOnly( arcsine, 'mode', require( '@stdlib/math/base/dist/arcsine/mode' ) );

/**
* @name pdf
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/pdf}
*/
setReadOnly( arcsine, 'pdf', require( '@stdlib/math/base/dist/arcsine/pdf' ) );

/**
* @name quantile
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/quantile}
*/
setReadOnly( arcsine, 'quantile', require( '@stdlib/math/base/dist/arcsine/quantile' ) );

/**
* @name skewness
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/skewness}
*/
setReadOnly( arcsine, 'skewness', require( '@stdlib/math/base/dist/arcsine/skewness' ) );

/**
* @name stdev
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/stdev}
*/
setReadOnly( arcsine, 'stdev', require( '@stdlib/math/base/dist/arcsine/stdev' ) );

/**
* @name variance
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/variance}
*/
setReadOnly( arcsine, 'variance', require( '@stdlib/math/base/dist/arcsine/variance' ) );

// EXPORTS //

module.exports = arcsine;
<commit_msg>Add logcdf to distribution namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace arcsine
*/
var arcsine = {};

/**
* @name Arcsine
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/ctor}
*/
setReadOnly( arcsine, 'Arcsine', require( '@stdlib/math/base/dist/arcsine/ctor' ) );

/**
* @name cdf
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/cdf}
*/
setReadOnly( arcsine, 'cdf', require( '@stdlib/math/base/dist/arcsine/cdf' ) );

/**
* @name entropy
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/entropy}
*/
setReadOnly( arcsine, 'entropy', require( '@stdlib/math/base/dist/arcsine/entropy' ) );

/**
* @name kurtosis
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/kurtosis}
*/
setReadOnly( arcsine, 'kurtosis', require( '@stdlib/math/base/dist/arcsine/kurtosis' ) );

/**
* @name logcdf
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/logcdf}
*/
setReadOnly( arcsine, 'logcdf', require( '@stdlib/math/base/dist/arcsine/logcdf' ) );

/**
* @name logpdf
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/logpdf}
*/
setReadOnly( arcsine, 'logpdf', require( '@stdlib/math/base/dist/arcsine/logpdf' ) );

/**
* @name mean
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/mean}
*/
setReadOnly( arcsine, 'mean', require( '@stdlib/math/base/dist/arcsine/mean' ) );

/**
* @name median
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/median}
*/
setReadOnly( arcsine, 'median', require( '@stdlib/math/base/dist/arcsine/median' ) );

/**
* @name mode
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/mode}
*/
setReadOnly( arcsine, 'mode', require( '@stdlib/math/base/dist/arcsine/mode' ) );

/**
* @name pdf
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/pdf}
*/
setReadOnly( arcsine, 'pdf', require( '@stdlib/math/base/dist/arcsine/pdf' ) );

/**
* @name quantile
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/quantile}
*/
setReadOnly( arcsine, 'quantile', require( '@stdlib/math/base/dist/arcsine/quantile' ) );

/**
* @name skewness
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/skewness}
*/
setReadOnly( arcsine, 'skewness', require( '@stdlib/math/base/dist/arcsine/skewness' ) );

/**
* @name stdev
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/stdev}
*/
setReadOnly( arcsine, 'stdev', require( '@stdlib/math/base/dist/arcsine/stdev' ) );

/**
* @name variance
* @memberof arcsine
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/arcsine/variance}
*/
setReadOnly( arcsine, 'variance', require( '@stdlib/math/base/dist/arcsine/variance' ) );

// EXPORTS //

module.exports = arcsine;
<|endoftext|>