<commit_before>'use strict';

var compact    = require('es5-ext/lib/Array/prototype/compact')
  , i          = require('es5-ext/lib/Function/i')
  , partial    = require('es5-ext/lib/Function/prototype/partial')
  , mapToArray = require('es5-ext/lib/Object/map-to-array')
  , callable   = require('es5-ext/lib/Object/valid-callable')
  , value      = require('es5-ext/lib/Object/valid-value')
  , numPad     = require('es5-ext/lib/Number/prototype/pad')
  , pad        = require('es5-ext/lib/String/prototype/pad')
  , repeat     = require('es5-ext/lib/String/prototype/repeat')
  , memoize    = require('memoizee')
  , deferred   = require('deferred')
  , clc        = require('cli-color')
  , readFile   = require('next/lib/fs/read-file')
  , normalize  = require('./_normalize-source')

  , isArray = Array.isArray
  , ceil = Math.ceil, max = Math.max, min = Math.min
  , log = process.stdout.write.bind(process.stdout)
  , nextTick = process.nextTick
  , reportFile, isStatus

  , eolRe = /(?:\r\n|[\n\r\u2028\u2029])/

  , Reporter;

Reporter = function () {};
Reporter.prototype = {
	parsed: 0,
	failed: 0,
	errors: 0,
	all: 0,
	init: function (data, options) {
		var waiting, status, isStatus;
		if (options.progress) {
			waiting = [];
			status = memoize(function () {  nextTick(function () {
				status.clear();
				this.status();
				isStatus = true;
			}.bind(this)); }.bind(this));

			data.on('change', function (event) {
				this.calc(event.report);
				waiting.push(this.normalize(event.report)(function (report) {
					if (report) {
						if (isStatus) {
							log(clc.bol(-3, true));
							isStatus = false;
						}
						this.file(event.name, report);
						status();
					}
				}.bind(this)));
			}.bind(this));
			return data(function () {
				return deferred.map(waiting);
			}.bind(this));
		} else {
			return data(function (data) {
				return deferred.map(mapToArray(data, function (report, name) {
					this.calc(report);
					return this.normalize(report)(function (report) {
						if (report) {
							this.file(name, report);
						}
					}.bind(this));
				}, this));
			}.bind(this))(this.status.bind(this));
		}
	},
	emap: {
		report: {
			name: clc.bold,
			options: clc.xterm(239),

			count: clc.xterm(232),
			messageErr: clc.yellow,
			lineNum: clc.xterm(240),
			code: clc.xterm(250),
			at: clc.xterm(250).bgXterm(235),
			messageOK: clc.green
		},
		status: {
			OK: i,
			failed: clc.bold.red,
			errors: clc.red
		}
	},
	options: function (options) {
		var escape = this.emap.report.options;
		options = compact.call(mapToArray(options, function (value, name) {
			if (value === true) {
				return name;
			} else if (value === false) {
				return null;
			} else {
				return name + '=' + value;
			}
		}));
		return escape(options.length ? options.join(' ') : 'no options');
	},
	calc: function (report) {
		++this.all;
		if (report.length) {
			++this.failed;
			this.errors += report.length;
		}
	},
	directOutput: function (report, name) {
		this.calc(report);
		return this.normalize(report)(function (report) {
			if (report) {
				this.file(name, report);
			}
		}.bind(this));
	},
	normalize: function (report) {
		if (report.length) {
			if (!report.src) {
				return readFile(report.path)(function (src) {
					report.src = normalize(String(src));
					return this.normalize(report);
				}.bind(this), function (err) {
					if (!err.code || (err.code === 'EMFILE')) {
						return err;
					}
					--this.all;
					if (report.length) {
						--this.failed;
						this.errors -= report.length;
					}
				}.bind(this));
			} else {
				report.srcLines = report.src.split(eolRe);
			}
		}
		return deferred(report);
	},
	file: function (name, report) {
		var emap = this.emap.report, str = '', countPad, srcPad, indent;
		str += (name ? (emap.name(name) + '\n') : '') + this.options(report.options);
		if (report.length) {
			str += '\n';
			countPad = partial.call(pad, ' ', String(report.length).length);
			srcPad = partial.call(numPad, max(String(report.srcLines.length).length,
				String(report.length).length + 1));
			indent = repeat.call(' ', isNaN(report.options.indent) ? 4 :
				max(min(Number(report.options.indent), 16), 1));

			report.forEach(function (data, index) {
				var line = report.srcLines[data.line - 1].replace(/\t/g, indent)
				  , at = data.character - 1;

				str += emap.count('#' + countPad.call(index + 1)) + ' '
					+ emap.messageErr(data.message) + '\n'
					+ emap.lineNum(srcPad.call(data.line)) + ' '
					+ emap.code(line.slice(0, at)) + emap.at(line[at])
					+ emap.code(line.slice(at + 1)) + '\n';
			});
		} else {
			str += ' ' + emap.messageOK('OK') + '\n';
		}
		log(str + '\n');
	},
	status: function () {
		var str = '\n', ok, emap = this.emap.status;
		if (this.single) {
			if (this.failed) {
				str += emap.failed(this.errors + ' Errors');
			} else {
				str += emap.OK("All OK\n\n");
			}
		} else {
			ok = (this.all - this.failed);
			str += emap.OK(ok + ' OK [' + ((ok / this.all) * 100).toFixed(2) + '%]')
				+ '  ' + emap.failed(this.failed + ' Failed') + ' '
				+ emap.errors('[' + this.errors + ' Errors]');
		}
		log(str + '\n\n');
	}
};

module.exports = function (report, options) {
	var reporter;
	callable(report) && value(options);

	reporter = new Reporter();
	return reporter.init(report, options);
};
<commit_msg>Do not display OK statuses<commit_after>'use strict';

var compact    = require('es5-ext/lib/Array/prototype/compact')
  , i          = require('es5-ext/lib/Function/i')
  , partial    = require('es5-ext/lib/Function/prototype/partial')
  , mapToArray = require('es5-ext/lib/Object/map-to-array')
  , callable   = require('es5-ext/lib/Object/valid-callable')
  , value      = require('es5-ext/lib/Object/valid-value')
  , numPad     = require('es5-ext/lib/Number/prototype/pad')
  , pad        = require('es5-ext/lib/String/prototype/pad')
  , repeat     = require('es5-ext/lib/String/prototype/repeat')
  , memoize    = require('memoizee')
  , deferred   = require('deferred')
  , clc        = require('cli-color')
  , readFile   = require('next/lib/fs/read-file')
  , normalize  = require('./_normalize-source')

  , isArray = Array.isArray
  , ceil = Math.ceil, max = Math.max, min = Math.min
  , log = process.stdout.write.bind(process.stdout)
  , nextTick = process.nextTick
  , reportFile, isStatus

  , eolRe = /(?:\r\n|[\n\r\u2028\u2029])/

  , Reporter;

Reporter = function () {};
Reporter.prototype = {
	parsed: 0,
	failed: 0,
	errors: 0,
	all: 0,
	init: function (data, options) {
		var waiting, status, isStatus;
		if (options.progress) {
			waiting = [];
			status = memoize(function () {  nextTick(function () {
				status.clear();
				this.status();
				isStatus = true;
			}.bind(this)); }.bind(this));

			data.on('change', function (event) {
				this.calc(event.report);
				if (event.report.length) {
					waiting.push(this.normalize(event.report)(function (report) {
						if (report) {
							if (isStatus) {
								log(clc.bol(-3, true));
								isStatus = false;
							}
							this.file(event.name, report);
							status();
						}
					}.bind(this)));
				}
			}.bind(this));
			return data(function () {
				return deferred.map(waiting);
			}.bind(this));
		} else {
			return data(function (data) {
				return deferred.map(mapToArray(data, function (report, name) {
					this.calc(report);
					if (report.length) {
						return this.normalize(report)(function (report) {
							if (report) {
								this.file(name, report);
							}
						}.bind(this));
					}
				}, this));
			}.bind(this))(this.status.bind(this));
		}
	},
	emap: {
		report: {
			name: clc.bold,
			options: clc.xterm(239),

			count: clc.xterm(232),
			messageErr: clc.yellow,
			lineNum: clc.xterm(240),
			code: clc.xterm(250),
			at: clc.xterm(250).bgXterm(235),
			messageOK: clc.green
		},
		status: {
			OK: i,
			failed: clc.bold.red,
			errors: clc.red
		}
	},
	options: function (options) {
		var escape = this.emap.report.options;
		options = compact.call(mapToArray(options, function (value, name) {
			if (value === true) {
				return name;
			} else if (value === false) {
				return null;
			} else {
				return name + '=' + value;
			}
		}));
		return escape(options.length ? options.join(' ') : 'no options');
	},
	calc: function (report) {
		++this.all;
		if (report.length) {
			++this.failed;
			this.errors += report.length;
		}
	},
	directOutput: function (report, name) {
		this.calc(report);
		return this.normalize(report)(function (report) {
			if (report) {
				this.file(name, report);
			}
		}.bind(this));
	},
	normalize: function (report) {
		if (report.length) {
			if (!report.src) {
				return readFile(report.path)(function (src) {
					report.src = normalize(String(src));
					return this.normalize(report);
				}.bind(this), function (err) {
					if (!err.code || (err.code === 'EMFILE')) {
						return err;
					}
					--this.all;
					if (report.length) {
						--this.failed;
						this.errors -= report.length;
					}
				}.bind(this));
			} else {
				report.srcLines = report.src.split(eolRe);
			}
		}
		return deferred(report);
	},
	file: function (name, report) {
		var emap = this.emap.report, str = '', countPad, srcPad, indent;
		str += (name ? (emap.name(name) + '\n') : '') + this.options(report.options);
		if (report.length) {
			str += '\n';
			countPad = partial.call(pad, ' ', String(report.length).length);
			srcPad = partial.call(numPad, max(String(report.srcLines.length).length,
				String(report.length).length + 1));
			indent = repeat.call(' ', isNaN(report.options.indent) ? 4 :
				max(min(Number(report.options.indent), 16), 1));

			report.forEach(function (data, index) {
				var line = report.srcLines[data.line - 1].replace(/\t/g, indent)
				  , at = data.character - 1;

				str += emap.count('#' + countPad.call(index + 1)) + ' '
					+ emap.messageErr(data.message) + '\n'
					+ emap.lineNum(srcPad.call(data.line)) + ' '
					+ emap.code(line.slice(0, at)) + emap.at(line[at])
					+ emap.code(line.slice(at + 1)) + '\n';
			});
		} else {
			str += ' ' + emap.messageOK('OK') + '\n';
		}
		log(str + '\n');
	},
	status: function () {
		var str = '\n', ok, emap = this.emap.status;
		if (this.single) {
			if (this.failed) {
				str += emap.failed(this.errors + ' Errors');
			} else {
				str += emap.OK("All OK\n\n");
			}
		} else {
			ok = (this.all - this.failed);
			str += emap.OK(ok + ' OK [' + ((ok / this.all) * 100).toFixed(2) + '%]')
				+ '  ' + emap.failed(this.failed + ' Failed') + ' '
				+ emap.errors('[' + this.errors + ' Errors]');
		}
		log(str + '\n\n');
	}
};

module.exports = function (report, options) {
	var reporter;
	callable(report) && value(options);

	reporter = new Reporter();
	return reporter.init(report, options);
};
<|endoftext|>


<commit_before>define([
    '/api/config?cb=' + Math.random().toString(16).substring(2),
    '/common/messages.js',
    '/common/crypto.js',
    '/common/realtime-input.js',
    '/common/convert.js',
    '/common/toolbar.js',
    '/common/cursor.js',
    '/common/json-ot.js',
    '/bower_components/diff-dom/diffDOM.js',
    '/bower_components/jquery/dist/jquery.min.js',
    '/customize/pad.js'
], function (Config, Messages, Crypto, realtimeInput, Convert, Toolbar, Cursor, JsonOT) {
    var $ = window.jQuery;
    var ifrw = $('#pad-iframe')[0].contentWindow;
    var Ckeditor; // to be initialized later...
    var DiffDom = window.diffDOM;
    var userName = Crypto.rand64(8),
        toolbar;

    var andThen = function (Ckeditor) {
        $(window).on('hashchange', function() {
            window.location.reload();
        });
        if (window.location.href.indexOf('#') === -1) {
            window.location.href = window.location.href + '#' + Crypto.genKey();
            return;
        }

        var fixThings = false;
        var key = Crypto.parseKey(window.location.hash.substring(1));
        var editor = window.editor = Ckeditor.replace('editor1', {
            // https://dev.ckeditor.com/ticket/10907
            needsBrFiller: fixThings,
            needsNbspFiller: fixThings,
            removeButtons: 'Source,Maximize',
            // magicline plugin inserts html crap into the document which is not part of the
            // document itself and causes problems when it's sent across the wire and reflected back
            removePlugins: 'magicline,resize'
        });

        editor.on('instanceReady', function (Ckeditor) {
            editor.execCommand('maximize');
            var documentBody = ifrw.$('iframe')[0].contentDocument.body;

            documentBody.innerHTML = Messages.initialState;

            var inner = documentBody;
            window.inner = inner;
            var cursor = window.cursor = Cursor(inner);

            var $textarea = $('#feedback');

            var applyHjson = function (shjson) {
                var userDocStateDom = Convert.hjson.to.dom(JSON.parse(shjson));
                userDocStateDom.setAttribute("contentEditable", "true"); // lol wtf
                var patch = (new DiffDom()).diff(inner, userDocStateDom);
                (new DiffDom()).apply(inner, patch);
            };

            var onRemote = function (shjson) {
                // remember where the cursor is
                cursor.update()

                // build a dom from HJSON, diff, and patch the editor
                applyHjson(shjson);

                // 1 if start is lost, 2 if end is lost, 3 if both, else 0
                var cursorState = cursor.isLost();
                if (cursorState) {
                    console.log("cursor is lost!");
                    cursor.find();

                    // pass in the cursorState so we don't try to recover nodes
                    // which weren't lost to begin with
                    cursor.recover(cursorState);

                    cursorState = cursor.isLost();
                    if (cursorState) {
                        console.log("cursor is STILL lost after trying to recover");
                    } else {
                        console.log("recovered the cursor!");
                    }
                } else {
                    // cursor is not lost
                    console.log("cursor retained");
                }
            };

            var onInit = function (info) { /* TODO initialize the toolbar */ };

            var rti = realtimeInput.start($textarea[0], // synced element
                                    Config.websocketURL, // websocketURL, ofc
                                    userName, // userName
                                    key.channel, // channelName
                                    key.cryptKey, // key
                                    { // configuration :D
                                        doc: inner,
                                        // first thing called
                                        onInit: onInit,

                                        onReady: function (info) {
                                            applyHjson($textarea.val());
                                            $textarea.trigger('keyup');
                                        },
                                        // when remote changes occur
                                        onRemote: onRemote,
                                        // really basic operational transform
                                        transformFunction : JsonOT.validate
                                        // pass in websocket/netflux object TODO
                                    });

            $textarea.val(JSON.stringify(Convert.dom.to.hjson(inner)));

            editor.on('change', function () {
                var hjson = Convert.core.hyperjson.fromDOM(inner);

                $textarea.val(JSON.stringify(hjson));
                rti.bumpSharejs();
            });

            // a mouseup or keyup might change the cursor but not the contents
/*          ['mouseup', 'keyup'].forEach(function (type) {
                editor.document.on(type, function (e) {
                    // when this is the case, update the cursor
                    //cursor.update();
                });
            }); */
        });
    };

    var interval = 100;
    var first = function () {
        Ckeditor = ifrw.CKEDITOR;
        if (Ckeditor) {
            andThen(Ckeditor);
        } else {
            console.log("Ckeditor was not defined. Trying again in %sms",interval);
            setTimeout(first, interval);
        }
    };

    $(first);
});
<commit_msg>main.js : tiny patch until things are working correctly.<commit_after>define([
    '/api/config?cb=' + Math.random().toString(16).substring(2),
    '/common/messages.js',
    '/common/crypto.js',
    '/common/realtime-input.js',
    '/common/convert.js',
    '/common/toolbar.js',
    '/common/cursor.js',
    '/common/json-ot.js',
    '/bower_components/diff-dom/diffDOM.js',
    '/bower_components/jquery/dist/jquery.min.js',
    '/customize/pad.js'
], function (Config, Messages, Crypto, realtimeInput, Convert, Toolbar, Cursor, JsonOT) {
    var $ = window.jQuery;
    var ifrw = $('#pad-iframe')[0].contentWindow;
    var Ckeditor; // to be initialized later...
    var DiffDom = window.diffDOM;
    var userName = Crypto.rand64(8),
        toolbar;

    var andThen = function (Ckeditor) {
        $(window).on('hashchange', function() {
            window.location.reload();
        });
        if (window.location.href.indexOf('#') === -1) {
            window.location.href = window.location.href + '#' + Crypto.genKey();
            return;
        }

        var fixThings = false;
        var key = Crypto.parseKey(window.location.hash.substring(1));
        var editor = window.editor = Ckeditor.replace('editor1', {
            // https://dev.ckeditor.com/ticket/10907
            needsBrFiller: fixThings,
            needsNbspFiller: fixThings,
            removeButtons: 'Source,Maximize',
            // magicline plugin inserts html crap into the document which is not part of the
            // document itself and causes problems when it's sent across the wire and reflected back
            removePlugins: 'magicline,resize'
        });

        editor.on('instanceReady', function (Ckeditor) {
            editor.execCommand('maximize');
            var documentBody = ifrw.$('iframe')[0].contentDocument.body;

            documentBody.innerHTML = Messages.initialState;

            var inner = documentBody;
            window.inner = inner;
            var cursor = window.cursor = Cursor(inner);

            var $textarea = $('#feedback');

            var applyHjson = function (shjson) {
                var userDocStateDom = Convert.hjson.to.dom(JSON.parse(shjson));
                userDocStateDom.setAttribute("contentEditable", "true"); // lol wtf
                var patch = (new DiffDom()).diff(inner, userDocStateDom);
                (new DiffDom()).apply(inner, patch);
            };

            var onRemote = function (shjson) {
                // remember where the cursor is
                cursor.update()

                // build a dom from HJSON, diff, and patch the editor
                applyHjson(shjson);

                // 1 if start is lost, 2 if end is lost, 3 if both, else 0
                var cursorState = cursor.isLost();
                if (cursorState) {
                    console.log("cursor is lost!");
                    cursor.find();

                    // pass in the cursorState so we don't try to recover nodes
                    // which weren't lost to begin with
                    // TODO recover doesn't handle its arguments correctly
                    // so for now just pass in 3 :(
                    cursor.recover(3||cursorState);

                    cursorState = cursor.isLost();
                    if (cursorState) {
                        console.log("cursor is STILL lost after trying to recover");
                    } else {
                        console.log("recovered the cursor!");
                    }
                } else {
                    // cursor is not lost
                    console.log("cursor retained");
                }
            };

            var onInit = function (info) { /* TODO initialize the toolbar */ };

            var rti = realtimeInput.start($textarea[0], // synced element
                                    Config.websocketURL, // websocketURL, ofc
                                    userName, // userName
                                    key.channel, // channelName
                                    key.cryptKey, // key
                                    { // configuration :D
                                        doc: inner,
                                        // first thing called
                                        onInit: onInit,

                                        onReady: function (info) {
                                            applyHjson($textarea.val());
                                            $textarea.trigger('keyup');
                                        },
                                        // when remote changes occur
                                        onRemote: onRemote,
                                        // really basic operational transform
                                        transformFunction : JsonOT.validate
                                        // pass in websocket/netflux object TODO
                                    });

            $textarea.val(JSON.stringify(Convert.dom.to.hjson(inner)));

            editor.on('change', function () {
                var hjson = Convert.core.hyperjson.fromDOM(inner);

                $textarea.val(JSON.stringify(hjson));
                rti.bumpSharejs();
            });

            // a mouseup or keyup might change the cursor but not the contents
/*          ['mouseup', 'keyup'].forEach(function (type) {
                editor.document.on(type, function (e) {
                    // when this is the case, update the cursor
                    //cursor.update();
                });
            }); */
        });
    };

    var interval = 100;
    var first = function () {
        Ckeditor = ifrw.CKEDITOR;
        if (Ckeditor) {
            andThen(Ckeditor);
        } else {
            console.log("Ckeditor was not defined. Trying again in %sms",interval);
            setTimeout(first, interval);
        }
    };

    $(first);
});
<|endoftext|>


<commit_before>/* Copyright (c) 2015-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

/* global define, Handlebars, isNode */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading search.ui.js ...');
  var TSCORE = require('tscore');
  var TSPOSTIO = require("tspostioapi");

  var initUI = function() {
    // Search UI
    $('#searchBox')
      .keyup(function(e) {
        if (e.keyCode === 13) { // Start the search on ENTER
          startSearch();
        } else if (e.keyCode == 27) { // Hide search on ESC
          cancelSearch();
        } else {
          TSCORE.Search.nextQuery = this.value;
        }
        if (this.value.length === 0) {
          TSCORE.Search.nextQuery = this.value;
          TSCORE.PerspectiveManager.redrawCurrentPerspective();
        }
      })
      .focus(function(e) {
        $("#searchOptions").hide();
      });

    $('#showSearchButton').on('click', function() {
      // Showing the expanded search area
      TSCORE.showSearchArea();
    });

    $('#searchButton').on("click", function(e) {
      startSearch();
    });

    $('#startSearchButton').on("click", function(e) {
      e.preventDefault();
      updateQuery();
      startSearch();
    });

    $('#showSearchOptionsButton').on("click", function() {
      showSearchOptions();
    });

    $('#searchOptions').on('click', '.close', function() {
      $('#searchOptions').hide();
    });

    $('#resetSearchButton').on('click', function(e) {
      e.preventDefault();
      resetSearchOptions();
      $('#searchBox').val("");
    });

    $('#clearSearchButton').on('click', function(e) {
      e.preventDefault();
      $('#searchOptions').hide();
      cancelSearch();
    });

    $('#searchRecursive').attr('checked', TSCORE.Config.getUseSearchInSubfolders());

    $('#searchRecursive').on('click', function(e) {
      updateQuery();
    });

    $('#searchTerms').on('blur', function(e) {
      updateQuery();
    }).keypress(startSearchOnEnter);

    $('#searchTags').on('blur', function(e) {
      updateQuery();
    }).keypress(startSearchOnEnter);

    $('#searchFileType').on('change', function(e) {
      updateQuery();
    });

    if (TSCORE.PRO) {
      $('#searchFileType').prop('disabled', false);
      $('#searchHistory').prop('disabled', false);
      $('#searchFileType').attr('title', '');
      $('#searchHistory').attr('title', '');
      $('#searchFileType').removeClass('disabled');
      $('#searchHistory').removeClass('disabled');
    }
  };

  function startSearchOnEnter(e) {
    if (e.which == 13) {
      e.preventDefault();
      updateQuery();
      startSearch();
    }
  }

  //function parseQuery() {}

  function updateQuery() {
    var query = "";
    if (!$('#searchRecursive').is(':checked')) {
      query = TSCORE.Search.recursiveSymbol + " ";
    }

    var searchTerms = $('#searchTerms').val();
    if (searchTerms.length > 0) {
      searchTerms = searchTerms.split(" ");
      searchTerms.forEach(function(term) {
        if (term.length > 1) {
          query = query + " " + term;
        }
      });
    }

    var tags = $('#searchTags').val();
    if (tags.length > 0) {
      tags = tags.split(" ");
      tags.forEach(function(tag) {
        if (tag.length > 1) {
          query = query + " +" + tag;
        }
      });
    }

    var fileType = $('#searchFileType').val();
    if (fileType.length > 0) {
      query = query + " " + fileType;
    }

    console.log();
    $('#searchBox').val(query);
    TSCORE.Search.nextQuery = query;
  }

  function resetSearchOptions() {
    $('#searchRecursive').prop('checked', TSCORE.Config.getUseSearchInSubfolders());
    $('#searchTerms').val("");
    $('#searchTags').val("");
    $('#searchFileType').val("");
    $('#searchHistory').val("");
  }

  function showSearchOptions() {
    resetSearchOptions();
    if (TSCORE.PRO && TSCORE.PRO.Search) {
      TSCORE.PRO.Search.loadSearchHistory();
    }
    var leftPosition = $(".col2").position().left + $(".col2").width();
    leftPosition = leftPosition - ($("#searchOptions").width() + 2);
    $("#searchOptions").css({left: leftPosition});
    $("#searchOptions").show();
  }

  function startSearch() {
    if (TSCORE.IO.stopWatchingDirectories) {
      TSCORE.IO.stopWatchingDirectories();
    }
    if ($('#searchBox').val().length > 0) {
      var origSearchVal = $('#searchBox').val();
      origSearchVal = origSearchVal.trim();

      if ($('#searchRecursive').prop('checked')) {
        $('#searchBox').val(origSearchVal);
      } else {
        if (origSearchVal.indexOf(TSCORE.Search.recursiveSymbol) === 0) {
          $('#searchBox').val(origSearchVal);
        } else {
          //origSearchVal = origSearchVal.substring(1, origSearchVal.length);
          $('#searchBox').val(TSCORE.Search.recursiveSymbol + " " + origSearchVal);
        }
      }

      if (TSCORE.PRO && TSCORE.PRO.Search) {
        TSCORE.PRO.Search.addQueryToHistory(origSearchVal);
      }
      TSCORE.Search.nextQuery = $('#searchBox').val();
    }
    $('#searchOptions').hide();
    TSCORE.PerspectiveManager.redrawCurrentPerspective();
  }

  function cancelSearch() {
    clearSearchFilter();
    // Restoring initial dir listing without subdirectories
    TSCORE.IO.listDirectoryPromise(TSCORE.currentPath).then(
      function(entries) {
        TSPOSTIO.listDirectory(entries);
      }
    ).catch(function(err) {
      TSPOSTIO.errorOpeningPath(TSCORE.currentPath);
      console.warn("Error listing directory" + err);
    });
  }

  function showSearchArea() {
    $('#showSearchButton').hide();
    $('#searchToolbar').show();
    $('#searchBox').focus();
  }

  function clearSearchFilter() {
    $('#searchToolbar').hide();
    $('#showSearchButton').show();
    $('#searchOptions').hide();
    $('#searchBox').val('');
    $('#clearFilterButton').removeClass('filterOn');
    TSCORE.Search.nextQuery = '';
  }

  function searchForTag(tagQuery) {
    if (TSCORE.isOneColumn()) {
      TSCORE.closeLeftPanel();
    }
    TSCORE.Search.nextQuery = TSCORE.Search.recursiveSymbol + ' +' + tagQuery;
    $('#searchBox').val(TSCORE.Search.recursiveSymbol + ' +' + tagQuery);
    TSCORE.PerspectiveManager.redrawCurrentPerspective();
    $('#showSearchButton').hide();
    $('#searchToolbar').show();
    //TSCORE.showSearchArea();
  }

  // Public API definition
  exports.initUI = initUI;
  exports.clearSearchFilter = clearSearchFilter;
  exports.showSearchArea = showSearchArea;
  exports.searchForTag = searchForTag;
});
<commit_msg>fixing showing files containing a tag #441<commit_after>/* Copyright (c) 2015-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

/* global define, Handlebars, isNode */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading search.ui.js ...');
  var TSCORE = require('tscore');
  var TSPOSTIO = require("tspostioapi");

  var initUI = function() {
    // Search UI
    $('#searchBox')
      .keyup(function(e) {
        if (e.keyCode === 13) { // Start the search on ENTER
          startSearch();
        } else if (e.keyCode == 27) { // Hide search on ESC
          cancelSearch();
        } else {
          TSCORE.Search.nextQuery = this.value;
        }
        if (this.value.length === 0) {
          TSCORE.Search.nextQuery = this.value;
          TSCORE.PerspectiveManager.redrawCurrentPerspective();
        }
      })
      .focus(function(e) {
        $("#searchOptions").hide();
      });

    $('#showSearchButton').on('click', function() {
      // Showing the expanded search area
      TSCORE.showSearchArea();
    });

    $('#searchButton').on("click", function(e) {
      startSearch();
    });

    $('#startSearchButton').on("click", function(e) {
      e.preventDefault();
      updateQuery();
      startSearch();
    });

    $('#showSearchOptionsButton').on("click", function() {
      showSearchOptions();
    });

    $('#searchOptions').on('click', '.close', function() {
      $('#searchOptions').hide();
    });

    $('#resetSearchButton').on('click', function(e) {
      e.preventDefault();
      resetSearchOptions();
      $('#searchBox').val("");
    });

    $('#clearSearchButton').on('click', function(e) {
      e.preventDefault();
      $('#searchOptions').hide();
      cancelSearch();
    });

    $('#searchRecursive').attr('checked', TSCORE.Config.getUseSearchInSubfolders());

    $('#searchRecursive').on('click', function(e) {
      updateQuery();
    });

    $('#searchTerms').on('blur', function(e) {
      updateQuery();
    }).keypress(startSearchOnEnter);

    $('#searchTags').on('blur', function(e) {
      updateQuery();
    }).keypress(startSearchOnEnter);

    $('#searchFileType').on('change', function(e) {
      updateQuery();
    });

    if (TSCORE.PRO) {
      $('#searchFileType').prop('disabled', false);
      $('#searchHistory').prop('disabled', false);
      $('#searchFileType').attr('title', '');
      $('#searchHistory').attr('title', '');
      $('#searchFileType').removeClass('disabled');
      $('#searchHistory').removeClass('disabled');
    }
  };

  function startSearchOnEnter(e) {
    if (e.which == 13) {
      e.preventDefault();
      updateQuery();
      startSearch();
    }
  }

  //function parseQuery() {}

  function updateQuery() {
    var query = "";
    if (!$('#searchRecursive').is(':checked')) {
      query = TSCORE.Search.recursiveSymbol + " ";
    }

    var searchTerms = $('#searchTerms').val();
    if (searchTerms.length > 0) {
      searchTerms = searchTerms.split(" ");
      searchTerms.forEach(function(term) {
        if (term.length > 1) {
          query = query + " " + term;
        }
      });
    }

    var tags = $('#searchTags').val();
    if (tags.length > 0) {
      tags = tags.split(" ");
      tags.forEach(function(tag) {
        if (tag.length > 1) {
          query = query + " +" + tag;
        }
      });
    }

    var fileType = $('#searchFileType').val();
    if (fileType.length > 0) {
      query = query + " " + fileType;
    }

    console.log();
    $('#searchBox').val(query);
    TSCORE.Search.nextQuery = query;
  }

  function resetSearchOptions() {
    $('#searchRecursive').prop('checked', TSCORE.Config.getUseSearchInSubfolders());
    $('#searchTerms').val("");
    $('#searchTags').val("");
    $('#searchFileType').val("");
    $('#searchHistory').val("");
  }

  function showSearchOptions() {
    resetSearchOptions();
    if (TSCORE.PRO && TSCORE.PRO.Search) {
      TSCORE.PRO.Search.loadSearchHistory();
    }
    var leftPosition = $(".col2").position().left + $(".col2").width();
    leftPosition = leftPosition - ($("#searchOptions").width() + 2);
    $("#searchOptions").css({left: leftPosition});
    $("#searchOptions").show();
  }

  function startSearch() {
    if (TSCORE.IO.stopWatchingDirectories) {
      TSCORE.IO.stopWatchingDirectories();
    }
    if ($('#searchBox').val().length > 0) {
      var origSearchVal = $('#searchBox').val();
      origSearchVal = origSearchVal.trim();

      if ($('#searchRecursive').prop('checked')) {
        $('#searchBox').val(origSearchVal);
      } else {
        if (origSearchVal.indexOf(TSCORE.Search.recursiveSymbol) === 0) {
          $('#searchBox').val(origSearchVal);
        } else {
          //origSearchVal = origSearchVal.substring(1, origSearchVal.length);
          $('#searchBox').val(TSCORE.Search.recursiveSymbol + " " + origSearchVal);
        }
      }

      if (TSCORE.PRO && TSCORE.PRO.Search) {
        TSCORE.PRO.Search.addQueryToHistory(origSearchVal);
      }
      TSCORE.Search.nextQuery = $('#searchBox').val();
    }
    $('#searchOptions').hide();
    TSCORE.PerspectiveManager.redrawCurrentPerspective();
  }

  function cancelSearch() {
    clearSearchFilter();
    // Restoring initial dir listing without subdirectories
    TSCORE.IO.listDirectoryPromise(TSCORE.currentPath).then(
      function(entries) {
        TSPOSTIO.listDirectory(entries);
      }
    ).catch(function(err) {
      TSPOSTIO.errorOpeningPath(TSCORE.currentPath);
      console.warn("Error listing directory" + err);
    });
  }

  function showSearchArea() {
    $('#showSearchButton').hide();
    $('#searchToolbar').show();
    $('#searchBox').focus();
  }

  function clearSearchFilter() {
    $('#searchToolbar').hide();
    $('#showSearchButton').show();
    $('#searchOptions').hide();
    $('#searchBox').val('');
    $('#clearFilterButton').removeClass('filterOn');
    TSCORE.Search.nextQuery = '';
  }

  function searchForTag(tagQuery) {
    if (TSCORE.isOneColumn()) {
      TSCORE.closeLeftPanel();
    }
    var nxtQuery = ' +' + tagQuery; //TSCORE.Search.recursiveSymbol + ' +' + tagQuery;
    TSCORE.Search.nextQuery = nxtQuery
    $('#searchBox').val(nxtQuery);
    TSCORE.PerspectiveManager.redrawCurrentPerspective();
    $('#showSearchButton').hide();
    $('#searchToolbar').show();
    //TSCORE.showSearchArea();
  }

  // Public API definition
  exports.initUI = initUI;
  exports.clearSearchFilter = clearSearchFilter;
  exports.showSearchArea = showSearchArea;
  exports.searchForTag = searchForTag;
});
<|endoftext|>


<commit_before>Appify(function (app) {
	var $div = Appify.templates.$div;
	var $a = Appify.templates.$a;

	app.route(function (next, details) {
		console.log('route middleware');

		next(details);
	});

	app.route('index', function (render, details) {
		console.log('route index');

		render('index', details);
	});

	app.route('other', function (render, details) {
		console.log('route other');

		render('other', details);
	});

	app.renderer(function ($outlet, details) {
		console.log('renderer middleware');

		return $div(
			$outlet(details)
		).class('application');
	});

	app.renderer('index', function (details) {
		console.log('renderer index');

		return $div(
			$div('Home Page'),
			$a('Go to Other Page').on('click', function () {
				app.transitionTo('other');
			})
		).class('home');
	});

	app.renderer('other', function (details) {
		console.log('renderer other');

		return $div(
			$div('Other Page'),
			$a('Go to Home Page').on('click', function () {
				app.transitionTo('index');
			})
		).class('other');
	});
});<commit_msg>clears routing log statements from simple sample<commit_after>Appify(function (app) {
	var $div = Appify.templates.$div;
	var $a = Appify.templates.$a;

	app.route(function (next, details) {
		next(details);
	});

	app.route('index', function (render, details) {
		render('index', details);
	});

	app.route('other', function (render, details) {
		render('other', details);
	});

	app.renderer(function ($outlet, details) {
		return $div(
			$outlet(details)
		).class('application');
	});

	app.renderer('index', function (details) {
		return $div(
			$div('Home Page'),
			$a('Go to Other Page').on('click', function () {
				app.transitionTo('other');
			})
		).class('home');
	});

	app.renderer('other', function (details) {
		return $div(
			$div('Other Page'),
			$a('Go to Home Page').on('click', function () {
				app.transitionTo('index');
			})
		).class('other');
	});
});<|endoftext|>


<commit_before>var Podcast = function(url) {
	var defaultImage = 'images/rss-alt-8x.png';

	this.url = url;
	this.image = defaultImage;
	this.status = 'new';
	this.episodes = [];

	function podcastChanged(podcast) {
		chrome.runtime.sendMessage({
			type: 'podcastChanged',
			podcast: podcast
		});
	}

	this.getKey = function() {
		return 'podcast' + this.url;
	}

	this.store = function() {
		var storageObject = {};

		var storedPodcast = {};

		storedPodcast.title = this.title;
		storedPodcast.description = this.description;
		storedPodcast.link = this.link;
		storedPodcast.pubDate = this.pubDate;
		storedPodcast.image = this.image;
		storedPodcast.episodes = this.episodes;

		storageObject[this.getKey()] = storedPodcast;

		chrome.storage.local.set(storageObject);
	}

	this.deleteFromStorage = function() {
		chrome.storage.local.remove(this.getKey());
	}

	this.update = function() {
		var that = this;

		if(this.status == 'updating') {
			console.log('Already updating: ' + this.url);
			return;
		}

		this.status = 'updating';
		console.log('Updating: ' + this.url);

		$.ajaxSetup({cache: false});

		$.get(this.url, function(data) {
			var xml = $(data);

			if(!xml.find('rss > channel')[0]) {
				that.status = 'failed';
				podcastChanged(that);
				return;
			}

			that.title = xml.find('rss > channel > title').text();
			that.description = xml.find('rss > channel > description').text();
			that.link = xml.find('rss > channel > link').text();

			that.pubDate = xml.find('rss > channel > pubDate').text();
			if(that.pubDate === '') {
				that.pubDate = xml.find('rss > channel > lastBuildDate').text();
			}

			that.image = xml.find('rss > channel > image > url').text();
			if(that.image === undefined || that.image === "") {
				that.image = xml.find('rss > channel > image').attr('href');
			}
			if(that.image === undefined || that.image === "") {
				that.image = defaultImage;
			}

			that.episodes = [];

			xml.find('rss > channel > item').each(function() {
				var feedItem = $(this);
				var episode = {};
				var enclosure;

				// the selector will find 'title' for all namespaces, we may find more
				// than one. They are in theory all the same, so we take the first.
				episode.title = $(feedItem.find('title')[0]).text();
				episode.link = feedItem.find('link').text();
				episode.pubDate = feedItem.find('pubDate').text();
				episode.description = feedItem.find('description').text();
				enclosure = feedItem.find('enclosure');
				episode.enclosure = {
					url: enclosure.attr('url'),
					length: enclosure.attr('length'),
					type: enclosure.attr('type')
				};

				that.episodes.push(episode);
			});

			that.episodes.sort(byPubDateDescending);

			if(that.episodes[0] && that.episodes[0].pubDate  &&
				(
					that.pubDate === undefined || that.pubDate === '' ||
					(new Date(that.episodes[0].pubDate)) > (new Date(that.pubDate))
				)
			) {
				that.pubDate = that.episodes[0].pubDate;
			}

			that.status = 'loaded';
			podcastChanged(that);
			that.store();

		}).fail(function() {
			that.status = 'failed';
			podcastChanged(that);

		});

		podcastChanged(this);
	}

	this.load = function() {
		var that = this;

		var podcastKey = this.getKey();

		chrome.storage.local.get(podcastKey, function(storageObject) {
			if(storageObject && storageObject[podcastKey]) {
				var storedPodcast = storageObject[podcastKey];

				that.title = storedPodcast.title;
				that.description = storedPodcast.description;
				that.link = storedPodcast.link;
				that.pubDate = storedPodcast.pubDate;
				that.image = storedPodcast.image;
				that.episodes = storedPodcast.episodes;
				that.status = 'loaded';
			}
			else {
				that.update();
			}
		});
	};
}
<commit_msg>added guid from podcast episodes, for future usage.<commit_after>var Podcast = function(url) {
	var defaultImage = 'images/rss-alt-8x.png';

	this.url = url;
	this.image = defaultImage;
	this.status = 'new';
	this.episodes = [];

	function podcastChanged(podcast) {
		chrome.runtime.sendMessage({
			type: 'podcastChanged',
			podcast: podcast
		});
	}

	this.getKey = function() {
		return 'podcast' + this.url;
	}

	this.store = function() {
		var storageObject = {};

		var storedPodcast = {};

		storedPodcast.title = this.title;
		storedPodcast.description = this.description;
		storedPodcast.link = this.link;
		storedPodcast.pubDate = this.pubDate;
		storedPodcast.image = this.image;
		storedPodcast.episodes = this.episodes;

		storageObject[this.getKey()] = storedPodcast;

		chrome.storage.local.set(storageObject);
	}

	this.deleteFromStorage = function() {
		chrome.storage.local.remove(this.getKey());
	}

	this.update = function() {
		var that = this;

		if(this.status == 'updating') {
			console.log('Already updating: ' + this.url);
			return;
		}

		this.status = 'updating';
		console.log('Updating: ' + this.url);

		$.ajaxSetup({cache: false});

		$.get(this.url, function(data) {
			var xml = $(data);

			if(!xml.find('rss > channel')[0]) {
				that.status = 'failed';
				podcastChanged(that);
				return;
			}

			that.title = xml.find('rss > channel > title').text();
			that.description = xml.find('rss > channel > description').text();
			that.link = xml.find('rss > channel > link').text();

			that.pubDate = xml.find('rss > channel > pubDate').text();
			if(that.pubDate === '') {
				that.pubDate = xml.find('rss > channel > lastBuildDate').text();
			}

			that.image = xml.find('rss > channel > image > url').text();
			if(that.image === undefined || that.image === "") {
				that.image = xml.find('rss > channel > image').attr('href');
			}
			if(that.image === undefined || that.image === "") {
				that.image = defaultImage;
			}

			that.episodes = [];

			xml.find('rss > channel > item').each(function() {
				var feedItem = $(this);
				var episode = {};
				var enclosure;

				// the selector will find 'title' for all namespaces, we may find more
				// than one. They are in theory all the same, so we take the first.
				episode.title = $(feedItem.find('title')[0]).text();
				episode.link = feedItem.find('link').text();
				episode.pubDate = feedItem.find('pubDate').text();
				episode.description = feedItem.find('description').text();
				episode.guid = feedItem.find('guid').text();
				enclosure = feedItem.find('enclosure');
				episode.enclosure = {
					url: enclosure.attr('url'),
					length: enclosure.attr('length'),
					type: enclosure.attr('type')
				};

				that.episodes.push(episode);
			});

			that.episodes.sort(byPubDateDescending);

			if(that.episodes[0] && that.episodes[0].pubDate  &&
				(
					that.pubDate === undefined || that.pubDate === '' ||
					(new Date(that.episodes[0].pubDate)) > (new Date(that.pubDate))
				)
			) {
				that.pubDate = that.episodes[0].pubDate;
			}

			that.status = 'loaded';
			podcastChanged(that);
			that.store();

		}).fail(function() {
			that.status = 'failed';
			podcastChanged(that);

		});

		podcastChanged(this);
	}

	this.load = function() {
		var that = this;

		var podcastKey = this.getKey();

		chrome.storage.local.get(podcastKey, function(storageObject) {
			if(storageObject && storageObject[podcastKey]) {
				var storedPodcast = storageObject[podcastKey];

				that.title = storedPodcast.title;
				that.description = storedPodcast.description;
				that.link = storedPodcast.link;
				that.pubDate = storedPodcast.pubDate;
				that.image = storedPodcast.image;
				that.episodes = storedPodcast.episodes;
				that.status = 'loaded';
			}
			else {
				that.update();
			}
		});
	};
}
<|endoftext|>


<commit_before>goog.provide('olcs.VectorSynchronizer');

goog.require('ol.layer.Vector');
goog.require('olcs.AbstractSynchronizer');
goog.require('olcs.FeatureConverter');
goog.require('olcs.core');
goog.require('olcs.core.VectorLayerCounterpart');

/**
 * Unidirectionally synchronize OpenLayers vector layers to Cesium.
 * @param {!ol.Map} map
 * @param {!Cesium.Scene} scene
 * @param {olcs.FeatureConverter=} opt_converter
 * @constructor
 * @extends {olcs.AbstractSynchronizer.<olcs.core.VectorLayerCounterpart>}
 * @api
 */
olcs.VectorSynchronizer = function(map, scene, opt_converter) {

  /**
   * @protected
   */
  this.converter = opt_converter || new olcs.FeatureConverter(scene);

  /**
   * @private
   */
  this.csAllPrimitives_ = new Cesium.PrimitiveCollection();
  scene.primitives.add(this.csAllPrimitives_);
  this.csAllPrimitives_.destroyPrimitives = false;

  goog.base(this, map, scene);
};
goog.inherits(olcs.VectorSynchronizer, olcs.AbstractSynchronizer);

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.addCesiumObject = function(counterpart) {
  goog.asserts.assert(!goog.isNull(counterpart));
  counterpart.getRootPrimitive()['counterpart'] = counterpart;
  this.csAllPrimitives_.add(counterpart.getRootPrimitive());
};

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.destroyCesiumObject = function(object) {
  object.getRootPrimitive().destroy();
};

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.removeSingleCesiumObject =
    function(object, destroy) {
  object.destroy();
  this.csAllPrimitives_.destroyPrimitives = destroy;
  this.csAllPrimitives_.remove(object.getRootPrimitive());
  this.csAllPrimitives_.destroyPrimitives = false;
};

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.removeAllCesiumObjects = function(destroy) {
  this.csAllPrimitives_.destroyPrimitives = destroy;
  if (destroy) {
    for (var i = 0; i < this.csAllPrimitives_.length; ++i) {
      this.csAllPrimitives_.get(i)['counterpart'].destroy();
    }
  }
  this.csAllPrimitives_.removeAll();
  this.csAllPrimitives_.destroyPrimitives = false;
};

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.createSingleLayerCounterparts =
    function(olLayer) {
  if (!(olLayer instanceof ol.layer.Vector)) {
    return null;
  }
  goog.asserts.assertInstanceof(olLayer, ol.layer.Vector);
  goog.asserts.assert(!goog.isNull(this.view));

  var view = this.view;
  var source = olLayer.getSource();
  var featurePrimitiveMap = {};
  var counterpart = this.converter.olVectorLayerToCesium(olLayer, view,
      featurePrimitiveMap);
  var csPrimitives = counterpart.getRootPrimitive();
  var olListenKeys = counterpart.olListenKeys;

  olListenKeys.push(olLayer.on('change:visible', function(e) {
    csPrimitives.show = olLayer.getVisible();
  }));

  var onAddFeature = (function(feature) {
    goog.asserts.assertInstanceof(olLayer, ol.layer.Vector);
    var context = counterpart.context;
    var prim = this.converter.convert(olLayer, view, feature, context);
    if (prim) {
      featurePrimitiveMap[goog.getUid(feature)] = prim;
      csPrimitives.add(prim);
    }
  }).bind(this);

  var onRemoveFeature = (function(feature) {
    var geometry = feature.getGeometry();
    var id = goog.getUid(feature);
    if (!geometry || geometry.getType() == 'Point') {
      var context = counterpart.context;
      var bb = context.featureToCesiumMap[id];
      delete context.featureToCesiumMap[id];
      if (bb instanceof Cesium.Billboard) {
        context.billboards.remove(bb);
      }
    }
    var csPrimitive = featurePrimitiveMap[id];
    delete featurePrimitiveMap[id];
    if (goog.isDefAndNotNull(csPrimitive)) {
      csPrimitives.remove(csPrimitive);
    }
  }).bind(this);

  olListenKeys.push(source.on('addfeature', function(e) {
    goog.asserts.assert(goog.isDefAndNotNull(e.feature));
    onAddFeature(e.feature);
  }, this));

  olListenKeys.push(source.on('removefeature', function(e) {
    goog.asserts.assert(goog.isDefAndNotNull(e.feature));
    onRemoveFeature(e.feature);
  }, this));

  olListenKeys.push(source.on('changefeature', function(e) {
    var feature = e.feature;
    goog.asserts.assert(goog.isDefAndNotNull(feature));
    onRemoveFeature(feature);
    onAddFeature(feature);
  }, this));

  return counterpart ? [counterpart] : null;
};
<commit_msg>Initialize the root primitive visibility according to the layer<commit_after>goog.provide('olcs.VectorSynchronizer');

goog.require('ol.layer.Vector');
goog.require('olcs.AbstractSynchronizer');
goog.require('olcs.FeatureConverter');
goog.require('olcs.core');
goog.require('olcs.core.VectorLayerCounterpart');

/**
 * Unidirectionally synchronize OpenLayers vector layers to Cesium.
 * @param {!ol.Map} map
 * @param {!Cesium.Scene} scene
 * @param {olcs.FeatureConverter=} opt_converter
 * @constructor
 * @extends {olcs.AbstractSynchronizer.<olcs.core.VectorLayerCounterpart>}
 * @api
 */
olcs.VectorSynchronizer = function(map, scene, opt_converter) {

  /**
   * @protected
   */
  this.converter = opt_converter || new olcs.FeatureConverter(scene);

  /**
   * @private
   */
  this.csAllPrimitives_ = new Cesium.PrimitiveCollection();
  scene.primitives.add(this.csAllPrimitives_);
  this.csAllPrimitives_.destroyPrimitives = false;

  goog.base(this, map, scene);
};
goog.inherits(olcs.VectorSynchronizer, olcs.AbstractSynchronizer);

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.addCesiumObject = function(counterpart) {
  goog.asserts.assert(!goog.isNull(counterpart));
  counterpart.getRootPrimitive()['counterpart'] = counterpart;
  this.csAllPrimitives_.add(counterpart.getRootPrimitive());
};

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.destroyCesiumObject = function(object) {
  object.getRootPrimitive().destroy();
};

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.removeSingleCesiumObject =
    function(object, destroy) {
  object.destroy();
  this.csAllPrimitives_.destroyPrimitives = destroy;
  this.csAllPrimitives_.remove(object.getRootPrimitive());
  this.csAllPrimitives_.destroyPrimitives = false;
};

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.removeAllCesiumObjects = function(destroy) {
  this.csAllPrimitives_.destroyPrimitives = destroy;
  if (destroy) {
    for (var i = 0; i < this.csAllPrimitives_.length; ++i) {
      this.csAllPrimitives_.get(i)['counterpart'].destroy();
    }
  }
  this.csAllPrimitives_.removeAll();
  this.csAllPrimitives_.destroyPrimitives = false;
};

/**
 * @inheritDoc
 */
olcs.VectorSynchronizer.prototype.createSingleLayerCounterparts =
    function(olLayer) {
  if (!(olLayer instanceof ol.layer.Vector)) {
    return null;
  }
  goog.asserts.assertInstanceof(olLayer, ol.layer.Vector);
  goog.asserts.assert(!goog.isNull(this.view));

  var view = this.view;
  var source = olLayer.getSource();
  var featurePrimitiveMap = {};
  var counterpart = this.converter.olVectorLayerToCesium(olLayer, view,
      featurePrimitiveMap);
  var csPrimitives = counterpart.getRootPrimitive();
  var olListenKeys = counterpart.olListenKeys;

  csPrimitives.show = olLayer.getVisible();

  olListenKeys.push(olLayer.on('change:visible', function(e) {
    csPrimitives.show = olLayer.getVisible();
  }));

  var onAddFeature = (function(feature) {
    goog.asserts.assertInstanceof(olLayer, ol.layer.Vector);
    var context = counterpart.context;
    var prim = this.converter.convert(olLayer, view, feature, context);
    if (prim) {
      featurePrimitiveMap[goog.getUid(feature)] = prim;
      csPrimitives.add(prim);
    }
  }).bind(this);

  var onRemoveFeature = (function(feature) {
    var geometry = feature.getGeometry();
    var id = goog.getUid(feature);
    if (!geometry || geometry.getType() == 'Point') {
      var context = counterpart.context;
      var bb = context.featureToCesiumMap[id];
      delete context.featureToCesiumMap[id];
      if (bb instanceof Cesium.Billboard) {
        context.billboards.remove(bb);
      }
    }
    var csPrimitive = featurePrimitiveMap[id];
    delete featurePrimitiveMap[id];
    if (goog.isDefAndNotNull(csPrimitive)) {
      csPrimitives.remove(csPrimitive);
    }
  }).bind(this);

  olListenKeys.push(source.on('addfeature', function(e) {
    goog.asserts.assert(goog.isDefAndNotNull(e.feature));
    onAddFeature(e.feature);
  }, this));

  olListenKeys.push(source.on('removefeature', function(e) {
    goog.asserts.assert(goog.isDefAndNotNull(e.feature));
    onRemoveFeature(e.feature);
  }, this));

  olListenKeys.push(source.on('changefeature', function(e) {
    var feature = e.feature;
    goog.asserts.assert(goog.isDefAndNotNull(feature));
    onRemoveFeature(feature);
    onAddFeature(feature);
  }, this));

  return counterpart ? [counterpart] : null;
};
<|endoftext|>


<commit_before>(function($){
    $.fn.nomoretable = function(options){
        var defaults = {
        	"tablediv": "table"
        };
        var opts = $.extend(defaults, options);
        return this.each(function(){
        	jQuery(opts.tablediv).css({"display": "block"});
        	jQuery(opts.tablediv).find("table,thead, tbody, th, td, tr").css({"display": "block"});
        	jQuery(opts.tablediv).find("thead tr").css({"position": "absolute","top":"-9999px","left":"-9999px"});
        	jQuery(opts.tablediv).find("tr").css({"border": "1px solid black"});
        	jQuery(opts.tablediv).find("table, td").css({"border": "none","border-bottom":"1px solid grey","position":"relative","padding-left":"50%","white-space":"normal","text-align":"left"});
       		jQuery('head').append('<style>'+opts.tablediv+' td:before{position: absolute;top: 6px;left: 6px;width: 45%;padding-right: 10px;white-space: nowrap;text-align: left;font-weight: bold;content: attr(data-title);}</style>');
			var text = new Array();
			var ths = 0;
			jQuery(opts.tablediv).each(function(table){
				ths = 0;
				jQuery(this).find("th").each(function(index){
					text[index] = jQuery(this).text();
					ths = ths + 1;
			});

			var i=0;

			jQuery(this).find("td").each(function(index){
				if(i>=ths){
					i=0;
				}
				if(jQuery(this).text() == "" || jQuery(this).text() == null){
				}else{
				jQuery(this).attr('data-title',text[i]);
				i = i+1;
				}
			});
		});
        });
    };
})(jQuery);<commit_msg>commented code<commit_after>(function($){
    $.fn.nomoretable = function(options){
    	//Defaultsettings
        var defaults = {
        	"tableclass": "table" //Which tables should be nomoretables?
        	/*",maxwidth": 700 //Breakpoint, when window-width is smaller than this number, the selected tables become "nomoretable"*/
        };
        var opts = $.extend(defaults, options);
        return this.each(function(){

        	//CSS for the selected Tables
        	jQuery(opts.tableclass).css({"display": "block"});
        	jQuery(opts.tableclass).find("table,thead, tbody, th, td, tr").css({"display": "block"});
        	jQuery(opts.tableclass).find("thead tr").css({"position": "absolute","top":"-9999px","left":"-9999px"});
        	jQuery(opts.tableclass).find("tr").css({"border": "1px solid black"});
        	jQuery(opts.tableclass).find("table, td").css({"border": "none","border-bottom":"1px solid grey","position":"relative","padding-left":"50%","white-space":"normal","text-align":"left"});
       		jQuery('head').append('<style>'+opts.tableclass+' td:before{position: absolute;top: 6px;left: 6px;width: 45%;padding-right: 10px;white-space: nowrap;text-align: left;font-weight: bold;content: attr(data-title);}</style>');

			var text = new Array();
			var ths = 0;
			//goes truth all selected Tables
			jQuery(opts.tableclass).each(function(table){
				ths = 0; //Number of <th> Elements in the Table
				jQuery(this).find("th").each(function(index){
					text[index] = jQuery(this).text(); //Gets the Content of the <th> Element and saves it in an Array
					ths = ths + 1;
			});

			var i=0; //Row in the Table

			jQuery(this).find("td").each(function(index){
				if(i>=ths){ //When the value gets bigger then the number of Rows, reset Value
					i=0;
				}
				if(jQuery(this).text() == "" || jQuery(this).text() == null){ //Only set data-title when the field isn't empty
				}else{
				jQuery(this).attr('data-title',text[i]); //Set the content of the <th> Element as data-title
				i = i+1;
				}
			});
		});
        });
    };
})(jQuery);<|endoftext|>


<commit_before>$(function() {

    // Change train stops for each line
    $('#select-line').change(function() {
        var id = $(this).val();
        $(".convenient").addClass("hidden");
        $("#" + id).removeClass("hidden");
    });

    // Delete account and confirmation
    $("#delete-account-form").submit(function(event) {
        if ($("#delete-account").val() == "Are you sure?") {
            return true;
        } else {
            $("#delete-account").val("Are you sure?");
            return false;
        };
    });

    $(document).click(function(event) {
        if (!$(event.target).is('#delete-account')) {
            $("#delete-account").val("Delete account");
        };
    });

    // Delete a stop
    $(document).on("click", ".pure-button.delete.unique", function(event) {

        event.preventDefault();
        var id = $("#user").val();

        $.ajax({
            url: $(".delete-stop").attr("action"),
            method: 'POST',
            dataType: 'text',
            success: function(data) {
                $('#partials-div').load('/users/' + id + '/stops');
            },
            error: function(data) {
                $("#stop-table-header").text("An error occurred.");
                setTimeout(
                    function() {
                        $('#stop-table-header').text("Your stops");
                    }, 3500);
            }
        });
    });

    // Add a stop
    $("#new-stop").submit(function(event) {
        event.preventDefault();

        if (!$("#select-time").val() || $("input:checkbox:checked").length == 0) {
            $("#stop-header").text("Please enter a time and date.")
            setTimeout(
                function() {
                    $('#stop-header').text("Add a new stop");
                }, 3500);
        } else {
            var id = $("#user").val();

            $.ajax({
                url: '/users/' + id + '/trains/create',
                method: 'POST',
                type: 'json',
                data: {
                    time: $("#select-time").val(),
                    line: $("#select-line").val(),
                    stop: $("#select-stop-" + $("#select-line").val().toLowerCase()).val(),
                    days: {
                        monday: $("#monday:checked").val(),
                        tuesday: $("#tuesday:checked").val(),
                        wednesday: $("#wednesday:checked").val(),
                        thursday: $("#thursday:checked").val(),
                        friday: $("#friday:checked").val(),
                        saturday: $("#saturday:checked").val(),
                        sunday: $("#sunday:checked").val()
                    }
                },
                success: function(data) {
                    $("#stop-header").text(data);
                    $('#partials-div').load('/users/' + id + '/stops');
                    $("#new-stop").trigger('reset');
                    setTimeout(
                        function() {
                            $('#stop-header').text("Add a new stop");
                        }, 3500);
                },
                error: function(data) {
                    $("#stop-header").text("An error has occurred.");

                    setTimeout(
                        function() {
                            $('#stop-header').text("Add a new stop");
                        }, 3500);

                }
            });
        };
    });

});<commit_msg>minor edit for heroku error handling<commit_after>$(function() {

    // Change train stops for each line
    $('#select-line').change(function() {
        var id = $(this).val();
        $(".convenient").addClass("hidden");
        $("#" + id).removeClass("hidden");
    });

    // Delete account and confirmation
    $("#delete-account-form").submit(function(event) {
        if ($("#delete-account").val() == "Are you sure?") {
            return true;
        } else {
            $("#delete-account").val("Are you sure?");
            return false;
        };
    });

    $(document).click(function(event) {
        if (!$(event.target).is('#delete-account')) {
            $("#delete-account").val("Delete account");
        };
    });

    // Delete a stop
    $(document).on("click", ".pure-button.delete.unique", function(event) {

        event.preventDefault();
        var id = $("#user").val();

        $.ajax({
            url: $(".delete-stop").attr("action"),
            method: 'POST',
            dataType: 'text',
            success: function(data) {
                $('#partials-div').load('/users/' + id + '/stops');
            },
            error: function(data) {
                $("#stop-table-header").text("An error occurred.");
                setTimeout(
                    function() {
                        $('#stop-table-header').text("Your stops");
                    }, 3500);
            }
        });
    });

    // Add a stop
    $("#new-stop").submit(function(event) {
        event.preventDefault();

        if (!$("#select-time").val() || $("input:checkbox:checked").length == 0) {
            $("#stop-header").text("Please enter a time and date.")
            setTimeout(
                function() {
                    $('#stop-header').text("Add a new stop");
                }, 3500);
        } else {
            var id = $("#user").val();

            $.ajax({
                url: '/users/' + id + '/trains/create',
                method: 'POST',
                type: 'json',
                data: {
                    time: $("#select-time").val(),
                    line: $("#select-line").val(),
                    stop: $("#select-stop-" + $("#select-line").val().toLowerCase()).val(),
                    days: {
                        monday: $("#monday:checked").val(),
                        tuesday: $("#tuesday:checked").val(),
                        wednesday: $("#wednesday:checked").val(),
                        thursday: $("#thursday:checked").val(),
                        friday: $("#friday:checked").val(),
                        saturday: $("#saturday:checked").val(),
                        sunday: $("#sunday:checked").val()
                    }
                },
                success: function(data) {
                    $("#stop-header").text(data);
                    $('#partials-div').load('/users/' + id + '/stops');
                    $("#new-stop").trigger('reset');
                    setTimeout(
                        function() {
                            $('#stop-header').text("Add a new stop");
                        }, 3500);
                },
                error: function(data) {
                    $("#stop-header").text("An error has occurred.");
                    console.log(data);

                    setTimeout(
                        function() {
                            $('#stop-header').text("Add a new stop");
                        }, 3500);

                }
            });
        };
    });

});<|endoftext|>


<commit_before>'use strict';
const helpers = require('./helpers');

/**
 * Contructs a knex object ready to extract the required info to feed into the mapper
 * for auto-populating collections/associations.
 *
 * @param {JoinJsMap} models
 * @param {Object} model
 * @param {KnexInstance} knex
 */
module.exports = function (models, model, knex) {

  // Generate the select statements needed for the joins and result mapping
  const idSelect = helpers.createSelectStatement(
      model.viewId,
      model.idProperty,
      model.mapId
  );

  const propSelects = model.properties.map(prop =>
      helpers.createSelectStatement(model.viewId, prop)
  );

  const assocSelects = model.associations.map(assoc => {
    if (!assoc.populate) {
      // If an association is not populated, all we need is the regular column
      // in the table
      return [helpers.createSelectStatement(model.viewId, assoc.mapId)];
    }

    const assocModel = models.find(m => m.mapId === assoc.mapId);

    // Get the property fields
    let propSelects = assocModel.properties.map(prop =>
        helpers.createRenamedSelectStatement(assoc.viewId, prop, assoc.mapId)
    );
    // Get the ID field
    propSelects.push(
        helpers.createRenamedSelectStatement(assoc.viewId, assocModel.idProperty, assoc.mapId)
    );
    // Get the fields for associations of the populated association
    propSelects = propSelects.concat(assocModel.associations.map(assocAssoc =>
        helpers.createRenamedSelectStatement(assoc.viewId, assocAssoc.mapId, assoc.mapId)
    ));
    // Get the fields for collections of the populated association
    propSelects = propSelects.concat(assocModel.associations.map(assocAssoc =>
        helpers.createRenamedSelectStatement(assoc.viewId, assocAssoc.mapId, assoc.mapId)
    ));
    return propSelects;
  });

  const collectionSelects = model.collections.map(coll => {
    const collModel = models.find(m => m.mapId === coll.mapId);

    let propSelects = collModel.properties.map(prop =>
        helpers.createRenamedSelectStatement(coll.viewId, prop, coll.mapId)
    );

    propSelects.push(
        helpers.createRenamedSelectStatement(coll.viewId, collModel.idProperty, coll.mapId)
    );

    if (coll.populate) {
      propSelects = propSelects.concat(collModel.associations.map(collAssoc =>
          helpers.createRenamedSelectStatement(coll.viewId, collAssoc.mapId, coll.mapId)
      ));
      propSelects = propSelects.concat(collModel.associations.map(collAssoc =>
          helpers.createRenamedSelectStatement(coll.viewId, collAssoc.mapId, coll.mapId)
      ));
    }

    return propSelects;
  });

  // Generate a list of params to be passed to leftJoin
  const assocJoinParams = model.associations.map(assoc => {
    if (!assoc.populate) {
      return null;
    }
    return helpers.createAssociationJoinParameters(model.viewId, assoc.mapId, assoc.viewId);
  });
  const collJoinParams = model.collections.map(coll =>
    helpers.createCollectionJoinParameters(model.mapId, model.viewId, coll.mapId, coll.viewId)
  );

  const allSelects = [idSelect].concat(propSelects).concat(assocSelects).concat(collectionSelects);

  // Put it all together
  const queryObj = knex
      .select(
          // Flatten the array of select strings
          [].concat.apply([], allSelects)
      )
      .from(model.viewId);

  // Remove any null param sets
  const joinParams = assocJoinParams.concat(collJoinParams).filter(p => !!p);

  // Attach the join to the query Object and return it
  return helpers.attachJoins(queryObj, joinParams);
};
<commit_msg>remove dupe lines<commit_after>'use strict';
const helpers = require('./helpers');

/**
 * Contructs a knex object ready to extract the required info to feed into the mapper
 * for auto-populating collections/associations.
 *
 * @param {JoinJsMap} models
 * @param {Object} model
 * @param {KnexInstance} knex
 */
module.exports = function (models, model, knex) {

  // Generate the select statements needed for the joins and result mapping
  const idSelect = helpers.createSelectStatement(
      model.viewId,
      model.idProperty,
      model.mapId
  );

  const propSelects = model.properties.map(prop =>
      helpers.createSelectStatement(model.viewId, prop)
  );

  const assocSelects = model.associations.map(assoc => {
    if (!assoc.populate) {
      // If an association is not populated, all we need is the regular column
      // in the table
      return [helpers.createSelectStatement(model.viewId, assoc.mapId)];
    }

    const assocModel = models.find(m => m.mapId === assoc.mapId);

    // Get the property fields
    let propSelects = assocModel.properties.map(prop =>
        helpers.createRenamedSelectStatement(assoc.viewId, prop, assoc.mapId)
    );
    // Get the ID field
    propSelects.push(
        helpers.createRenamedSelectStatement(assoc.viewId, assocModel.idProperty, assoc.mapId)
    );
    // Get the fields for associations of the populated association
    propSelects = propSelects.concat(assocModel.associations.map(assocAssoc =>
        helpers.createRenamedSelectStatement(assoc.viewId, assocAssoc.mapId, assoc.mapId)
    ));
  });

  const collectionSelects = model.collections.map(coll => {
    const collModel = models.find(m => m.mapId === coll.mapId);

    let propSelects = collModel.properties.map(prop =>
        helpers.createRenamedSelectStatement(coll.viewId, prop, coll.mapId)
    );

    propSelects.push(
        helpers.createRenamedSelectStatement(coll.viewId, collModel.idProperty, coll.mapId)
    );

    if (coll.populate) {
      propSelects = propSelects.concat(collModel.associations.map(collAssoc =>
          helpers.createRenamedSelectStatement(coll.viewId, collAssoc.mapId, coll.mapId)
      ));
    }

    return propSelects;
  });

  // Generate a list of params to be passed to leftJoin
  const assocJoinParams = model.associations.map(assoc => {
    if (!assoc.populate) {
      return null;
    }
    return helpers.createAssociationJoinParameters(model.viewId, assoc.mapId, assoc.viewId);
  });
  const collJoinParams = model.collections.map(coll =>
    helpers.createCollectionJoinParameters(model.mapId, model.viewId, coll.mapId, coll.viewId)
  );

  const allSelects = [idSelect].concat(propSelects).concat(assocSelects).concat(collectionSelects);

  // Put it all together
  const queryObj = knex
      .select(
          // Flatten the array of select strings
          [].concat.apply([], allSelects)
      )
      .from(model.viewId);

  // Remove any null param sets
  const joinParams = assocJoinParams.concat(collJoinParams).filter(p => !!p);

  // Attach the join to the query Object and return it
  return helpers.attachJoins(queryObj, joinParams);
};
<|endoftext|>