<commit_before>'use strict';

module.exports = {
  // Disable updates during automation
  'app.update.disabledForTesting': true,
  // Use hidden time_to_non_blank_paint
  'dom.performance.time_to_non_blank_paint.enabled': true,
  // Use hidden time to DOM Content flush
  'dom.performance.time_to_dom_content_flushed.enabled': true,
  // Use hidden TTFI
  'dom.performance.time_to_first_interactive.enabled': true,
  // Use hidden TTCP
  'dom.performance.time_to_contentful_paint.enabled': true,
  'browser.startup.homepage': 'about:blank',
  /* Extra tracking protection https://wiki.mozilla.org/Security/Tracking_protection */
  'privacy.trackingprotection.enabled': false,
  'privacy.trackingprotection.pbmode.enabled': false,
  'privacy.trackingprotection.annotate_channels': false,
  'services.sync.prefs.sync.privacy.trackingprotection.enabled': false,
  'services.sync.prefs.sync.privacy.trackingprotection.pbmode.enabled': false,
  'browser.safebrowsing.provider.mozilla.updateURL': '',
  'browser.safebrowsing.provider.mozilla.gethashURL': '',

  /* Disable heartbeat https://wiki.mozilla.org/Firefox/Shield/Heartbeat */
  'browser.selfsupport.url': '',
  'browser.selfsupport.enabled': false,

  'devtools.devedition.promo.enabled': false,

  /* Disable detectportal.firefox.com */
  'network.captive-portal-service.enabled': false,
  'browser.search.geoip.url': '',
  /* Disable telemetry  https://wiki.mozilla.org/Telemetry/Testing */
  'toolkit.telemetry.prompted': 2,
  'toolkit.telemetry.rejected': true,
  'toolkit.telemetry.enabled': false,
  'toolkit.telemetry.reportingpolicy.firstRun': false,

  /* https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections */
  'browser.safebrowsing.downloads.remote.enabled': false,
  'browser.startup.homepage_override.mstone': 'ignore',
  'extensions.getAddons.cache.enabled': false,

  // Preferences from
  // https://searchfox.org/mozilla-central/source/testing/talos/talos/config.py
  // slightly modified - all URLs are set to blank
  'app.update.enabled': false,
  'app.update.url': '',
  'browser.aboutHomeSnippets.updateUrl': '',
  'browser.bookmarks.restore_default_bookmarks': false,
  'browser.bookmarks.added_static_root': true,
  'browser.places.importBookmarksHTML': false,
  'browser.newtabpage.directory.ping': '',
  'browser.newtabpage.directory.source': 'data:application/json,{}',
  'browser.newtabpage.enabled': false,
  'browser.newtabpage.enhanced': false,
  'browser.newtabpage.introShown': true,
  'browser.newtab.preload': false,
  'browser.pagethumbnails.capturing_disabled': true,
  'browser.rights.3.shown': true,
  'browser.safebrowsing.downloads.enabled': false,
  'browser.safebrowsing.enabled': false,
  'browser.safebrowsing.phishing.enabled': false,
  'browser.safebrowsing.malware.enabled': false,
  'browser.safebrowsing.remotelookups': false,
  'browser.safebrowsing.provider.mozilla.updateURL ': '',
  'browser.search.update': false,
  'browser.sessionstore.resume_from_crash': false,
  'browser.shell.checkDefaultBrowser': false,
  'browser.startup.page': 0,
  'browser.uitour.enabled': false,
  'browser.tabs.warnOnClose': false,
  'datareporting.healthreport.service.enabled': false,
  'datareporting.healthreport.uploadEnabled': false,
  'datareporting.healthreport.service.firstRun': false,
  'datareporting.healthreport.logging.consoleEnabled': false,
  'datareporting.policy.dataSubmissionEnabled': false,
  'datareporting.policy.dataSubmissionPolicyResponseType':
    'accepted-info-bar-dismissed',
  'datareporting.policy.dataSubmissionPolicyAccepted': false,
  'dom.ipc.plugins.flash.disable-protected-mode': true,
  'dom.max_chrome_script_run_time': 0,
  'dom.max_script_run_time': 0,
  'dom.webnotifications.enabled': false,
  'extensions.checkCompatibility': false,
  'extensions.update.enabled': false,
  'extensions.update.notifyUser': false,
  'extensions.shownSelectionUI': true,
  'extensions.autoDisableScopes': 14,
  'extensions.shield-recipe-client.enabled': false,
  'extensions.systemAddon.update.url': '',
  'intl.charsetmenu.browser.cache': 'UTF-8',
  'media.gmp-gmpopenh264.autoupdate': false,
  'network.cookie.prefsMigrated': true,
  'network.proxy.type': 0,
  'pageThumbs.enabled': false,
  'pref.browser.homepage.disable_button.current_page': false,
  'privacy.cpd.siteSettings': true,
  'privacy.sanitize.migrateFx3Prefs': true,
  'privacy.sanitize.timeSpan': 0,
  'reader.parse-on-load.enabled': false,
  'security.enable_java': false,
  'security.warn_entering_weak': false,
  'security.warn_viewing_mixed': false,
  'security.warn_entering_secure': false,
  'security.warn_leaving_secure': false,
  'security.warn_submit_insecure': false,
  'services.sync.migrated': true,
  'services.sync.engine.bookmarks': false,
  'toolkit.content-background-hang-monitor.disabled': true,
  'gfx.webrender.force-disabled': true,
  'xpinstall.whitelist.add': '',
  'xpinstall.whitelist.add.36': '',
  'xpinstall.signatures.required': false,
  'signon.rememberSignons': false,
  'javascript.options.asyncstack': false,
  'javascript.options.showInConsole': true,
  'devtools.chrome.enabled': true,
  'devtools.debugger.remote-enabled': true,
  'devtools.sourcemap.locations.enabled': false,
  'dom.push.serverURL': ''
};
<commit_msg>Firefox: rollback some changes to try to find what caused ff regression (#972)<commit_after>'use strict';

module.exports = {
  // Disable updates during automation
  'app.update.disabledForTesting': true,
  // Use hidden time_to_non_blank_paint
  'dom.performance.time_to_non_blank_paint.enabled': true,
  // Use hidden time to DOM Content flush
  'dom.performance.time_to_dom_content_flushed.enabled': true,
  // Use hidden TTFI
  'dom.performance.time_to_first_interactive.enabled': true,
  // Use hidden TTCP
  'dom.performance.time_to_contentful_paint.enabled': true,
  'browser.startup.homepage': 'about:blank',
  /* Extra tracking protection https://wiki.mozilla.org/Security/Tracking_protection */
  'privacy.trackingprotection.enabled': false,
  'privacy.trackingprotection.pbmode.enabled': false,
  'privacy.trackingprotection.annotate_channels': false,
  'services.sync.prefs.sync.privacy.trackingprotection.enabled': false,
  'services.sync.prefs.sync.privacy.trackingprotection.pbmode.enabled': false,
  'browser.safebrowsing.provider.mozilla.updateURL': '',
  'browser.safebrowsing.provider.mozilla.gethashURL': '',

  /* Disable heartbeat https://wiki.mozilla.org/Firefox/Shield/Heartbeat */
  'browser.selfsupport.url': '',
  'browser.selfsupport.enabled': false,

  'devtools.devedition.promo.enabled': false,

  /* Disable detectportal.firefox.com */
  'network.captive-portal-service.enabled': false,
  'browser.search.geoip.url': '',
  /* Disable telemetry  https://wiki.mozilla.org/Telemetry/Testing */
  'toolkit.telemetry.prompted': 2,
  'toolkit.telemetry.rejected': true,
  'toolkit.telemetry.enabled': false,
  'toolkit.telemetry.reportingpolicy.firstRun': false,

  /* https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections */
  'browser.safebrowsing.downloads.remote.enabled': false,
  'browser.startup.homepage_override.mstone': 'ignore',
  'extensions.getAddons.cache.enabled': false,

  // Preferences from
  // https://searchfox.org/mozilla-central/source/testing/talos/talos/config.py
  // slightly modified - all URLs are set to blank
  'app.update.enabled': false,
  'app.update.url': '',
  'browser.aboutHomeSnippets.updateUrl': '',
  'browser.bookmarks.restore_default_bookmarks': false,
  'browser.bookmarks.added_static_root': true,
  'browser.places.importBookmarksHTML': false,
  'browser.newtabpage.directory.ping': '',
  'browser.newtabpage.directory.source': 'data:application/json,{}',
  'browser.newtabpage.enabled': false,
  'browser.newtabpage.enhanced': false,
  'browser.newtabpage.introShown': true,
  'browser.newtab.preload': false,
  'browser.pagethumbnails.capturing_disabled': true,
  'browser.rights.3.shown': true,
  'browser.safebrowsing.downloads.enabled': false,
  'browser.safebrowsing.enabled': false,
  'browser.safebrowsing.phishing.enabled': false,
  'browser.safebrowsing.malware.enabled': false,
  'browser.safebrowsing.remotelookups': false,
  'browser.safebrowsing.provider.mozilla.updateURL ': '',
  'browser.search.update': false,
  'browser.sessionstore.resume_from_crash': false,
  'browser.shell.checkDefaultBrowser': false,
  'browser.startup.page': 0,
  'browser.uitour.enabled': false,
  'browser.tabs.warnOnClose': false,
  'datareporting.healthreport.service.enabled': false,
  'datareporting.healthreport.uploadEnabled': false,
  'datareporting.healthreport.service.firstRun': false,
  'datareporting.healthreport.logging.consoleEnabled': false,
  'datareporting.policy.dataSubmissionEnabled': false,
  'datareporting.policy.dataSubmissionPolicyResponseType':
    'accepted-info-bar-dismissed',
  'datareporting.policy.dataSubmissionPolicyAccepted': false,
  'dom.ipc.plugins.flash.disable-protected-mode': true,
  'dom.max_chrome_script_run_time': 0,
  'dom.max_script_run_time': 0,
  'dom.webnotifications.enabled': false,
  'extensions.checkCompatibility': false,
  'extensions.update.enabled': false,
  'extensions.update.notifyUser': false,
  'extensions.shownSelectionUI': true,
  'extensions.autoDisableScopes': 14,
  'extensions.shield-recipe-client.enabled': false,
  'extensions.systemAddon.update.url': '',
  'intl.charsetmenu.browser.cache': 'UTF-8',
  'media.gmp-gmpopenh264.autoupdate': false,
  'network.cookie.prefsMigrated': true,
  'network.proxy.type': 0,
  'pageThumbs.enabled': false,
  'pref.browser.homepage.disable_button.current_page': false,
  'privacy.cpd.siteSettings': true,
  'privacy.sanitize.migrateFx3Prefs': true,
  'privacy.sanitize.timeSpan': 0,
  'reader.parse-on-load.enabled': false,
  'security.enable_java': false,
  'security.warn_entering_weak': false,
  'security.warn_viewing_mixed': false,
  'security.warn_entering_secure': false,
  'security.warn_leaving_secure': false,
  'security.warn_submit_insecure': false,
  'services.sync.migrated': true,
  'services.sync.engine.bookmarks': false,
  'toolkit.content-background-hang-monitor.disabled': true,
  'gfx.webrender.force-disabled': true,
  'layers.acceleration.disabled': true,
  'gfx.direct2d.disabled': true,
  'xpinstall.whitelist.add': '',
  'xpinstall.whitelist.add.36': '',
  'xpinstall.signatures.required': false,
  'signon.rememberSignons': false,
  'javascript.options.asyncstack': false,
  'javascript.options.showInConsole': true,
  'devtools.chrome.enabled': true,
  'devtools.debugger.remote-enabled': true,
  'devtools.sourcemap.locations.enabled': false,
  'dom.push.serverURL': ''
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');

var gulp = require('gulp');
var wiredep = require('wiredep');
var karma = require('gulp-karma');
var protractor = require('gulp-protractor');

var env = require('../utils/env');
var log = require('../utils/log');
var plugins = require('../utils/plugins');

var getTestFiles = function () {
  // 添加所有bower文件
  var bowerDeps = [];
  if (fs.existsSync(env.folders.library)) {
    bowerDeps = wiredep({
      directory: env.folders.library,
      dependencies: true,
      devDependencies: true
    }).js;
  }
  var bowerFiles = gulp.src(bowerDeps, {read: false});

  var filter = '/**/*.js';
  // 添加app目录中除了bower之外的所有文件
  var appFiles = gulp.src([env.folders.app + filter, '!' + env.folders.library + filter], {base: env.folders.app});
  // 添加临时目录下的文件
  var tmpFiles = gulp.src(env.folders.temp + '/app' + filter, {base: env.folders.temp + '/app'});
  // 按照angular依赖关系排序
  var sortedFiles = plugins.merge(appFiles, tmpFiles)
    .pipe(plugins.angularFileSort())
    // merge不能确保两个流中文件的顺序，所以稍微延迟一下，以确保bower的文件排在app文件的前面。
    .pipe(plugins.wait(200));

  var testFiles = gulp.src(env.folders.test + '/unit/**/*.js', {read: false})
    .pipe(plugins.wait(400));
  return plugins.merge(bowerFiles, sortedFiles, testFiles);
};
gulp.task('ut', function () {
  return getTestFiles()
    .pipe(karma({
      configFile: env.folders.test + '/karma.conf.js',
      action: 'run'
    }))
    .on('error', function () {
      // Make sure failed tests cause gulp to exit non-zero
      log.error("Unit test Failed!")
    });
});

gulp.task('tdd', function () {
  // TODO: 看看添加/删除文件时是否有问题
  return getTestFiles()
    .pipe(karma({
      configFile: env.folders.test + '/karma.conf.js',
      action: 'watch'
    }))
    .on('error', function () {
      // Make sure failed tests cause gulp to exit non-zero
      log.error("Unit test Failed!")
    });
});

gulp.task('e2e', function (done) {
  var testFiles = [
    env.folders.test + '/e2e/**/*.js'
  ];

  gulp.src(testFiles)
    .pipe(protractor.protractor({
      configFile: 'test/protractor.conf.js'
    }))
    .on('error', function (err) {
      log.error("端到端测试运行失败");
      process.exit(1);
    })
    .on('end', function () {
      done();
      process.exit();
    });
});

gulp.task('test', function (done) {
  plugins.runSequence('ut', 'e2e', done)
});
<commit_msg>从临时文件夹中排除bower_components 增补注释<commit_after>'use strict';

var fs = require('fs');

var gulp = require('gulp');
var wiredep = require('wiredep');
var karma = require('gulp-karma');
var protractor = require('gulp-protractor');

var env = require('../utils/env');
var log = require('../utils/log');
var plugins = require('../utils/plugins');

var getTestFiles = function () {
  // 添加所有bower文件
  var bowerDeps = [];
  if (fs.existsSync(env.folders.library)) {
    bowerDeps = wiredep({
      directory: env.folders.library,
      dependencies: true,
      devDependencies: true
    }).js;
  }
  var bowerFiles = gulp.src(bowerDeps, {read: false});

  var filter = '/**/*.js';
  // 添加app目录中除了bower之外的所有文件
  var appFiles = gulp.src([env.folders.app + filter, '!' + env.folders.library + filter], {base: env.folders.app});
  // 添加临时目录下的文件，这些通常是coffee等文件的编译结果
  var tmpFiles = gulp.src([env.folders.temp + '/app' + filter, '!' + env.folders.temp + '/app/bower_components' + filter], {base: env.folders.temp + '/app'});
  // 按照angular依赖关系排序
  var sortedFiles = plugins.merge(appFiles, tmpFiles)
    .pipe(plugins.angularFileSort())
    // merge不能确保两个流中文件的顺序，所以稍微延迟一下，以确保bower的文件排在app文件的前面。
    .pipe(plugins.wait(200));

  var testFiles = gulp.src(env.folders.test + '/unit/**/*.js', {read: false})
    .pipe(plugins.wait(400));
  return plugins.merge(bowerFiles, sortedFiles, testFiles);
};
gulp.task('ut', function () {
  return getTestFiles()
    .pipe(karma({
      configFile: env.folders.test + '/karma.conf.js',
      action: 'run'
    }))
    .on('error', function () {
      // Make sure failed tests cause gulp to exit non-zero
      log.error("Unit test Failed!")
    });
});

gulp.task('tdd', function () {
  // TODO: 看看添加/删除文件时是否有问题
  return getTestFiles()
    .pipe(karma({
      configFile: env.folders.test + '/karma.conf.js',
      action: 'watch'
    }))
    .on('error', function () {
      // Make sure failed tests cause gulp to exit non-zero
      log.error("Unit test Failed!")
    });
});

gulp.task('e2e', function (done) {
  var testFiles = [
    env.folders.test + '/e2e/**/*.js'
  ];

  gulp.src(testFiles)
    .pipe(protractor.protractor({
      configFile: 'test/protractor.conf.js'
    }))
    .on('error', function (err) {
      log.error("端到端测试运行失败");
      process.exit(1);
    })
    .on('end', function () {
      done();
      process.exit();
    });
});

gulp.task('test', function (done) {
  plugins.runSequence('ut', 'e2e', done)
});
<|endoftext|>


<commit_before>/**
	Copyright (C) 2014  Matheus Borges Teixeira

	This is a part of Arkanos Organizer Suite (AOS) app.
	AOS is a web application for organizing personal goals.

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

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY 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/>.
**/

Ext.define('AOS.view.Goals', {
    extend: 'Ext.Container',
    requires: [	'AOS.store.Goals',
				'AOS.model.Goal',
				'Ext.dataview.List',
				'AOS.view.bar.TopToolbar',
				'AOS.view.overlay.GoalOverlay',
				'AOS.form.Task'],
    config: {
        layout: 'fit',
        items: [
			{
				docked: 'top',
				title: 'Goals',
				xtype:'aos-toolbar-toptoolbar'
			},
			{
		        xtype: 'list',
		        store: 'Goals',
				itemId: 'list-display',
		        itemTpl: '

{title}	Completed
{completion}%	Spent
{total_time_spent} hours	Dedication
{dedication}%

',
				listeners: {
					select: function() {
						this.parent.enableActions();
					}
				}
		    },
			{
				xtype: 'toolbar',
				ui: 'neutral',
				docked: 'bottom',
				scrollable: 'horizontal',
				layout: {pack:'center'},
				items:[
					{
						disabled: true,
						itemId: 'goal-details',
						ui: 'small',
						text: 'Details',
						iconCls: 'aos-icon-details',
						handler: function(){
							var grandfather = this.parent.parent;
							var selected = grandfather.down('#list-display').getSelection();
							if(selected && selected.length > 0){
								if(!grandfather.overlay){
									grandfather.overlay = Ext.Viewport.add(Ext.create('AOS.view.overlay.GoalOverlay'));
								}
								grandfather.overlay.popUp(selected[0]);
							}
						}
					},
					{
						disabled: true,
						itemId: 'goal-remove',
						ui: 'small',
						text: 'Remove',
						iconCls: 'aos-icon-remove',
						handler: function(){
							var grandfather = this.parent.parent;
							var list = grandfather.down('#list-display');
							var selected = list.getSelection();
							if(selected && selected.length > 0){
								var before = list.getScrollable().getScroller().position.y;
								AOS.Helper.remove(selected[0],'Goals');
								AOS.Helper.purgeStore('Tasks');
								AOS.Helper.purgeStore('Worklog');
								list.getScrollable().getScroller().scrollTo(0, before);
								grandfather.disableActions();
							}
						}
					},
					{
						disabled: true,
						itemId: 'goal-tasks',
						ui: 'small',
						text: 'New Task',
						iconCls: 'aos-icon-tasks',
						align: 'left',
						handler: function(){
							var grandfather = this.parent.parent;
							var selected = grandfather.down('#list-display').getSelection();
							if(selected && selected.length > 0){
								AOS.Helper.switchTo('AOS.form.Task',{ type: 'slide', direction: 'left' });
								Ext.Viewport.getActiveItem().setGoal(selected[0].get('id'),selected[0].get('title'));
							}
						}
					},
					{
						itemId: 'new-goal',
						ui: 'small',
						text: 'New Goal',
						iconCls: 'aos-icon-new',
						handler: function(){
							AOS.Helper.switchTo('AOS.form.Goal',{ type: 'slide', direction: 'left' });
						}
					}
				]
			}
		],
		listeners: {
			show: function() {
				//Ext.getStore('Goals').load();
				var list = this.down('#list-display');
				if(list){
					AOS.Helper.moveToSelection(list);
				}
			}
		}
    },
	enableActions: function(){
		this.down('#goal-details').enable();
		this.down('#goal-remove').enable();
		this.down('#goal-tasks').enable();
	},
	disableActions: function(){
		this.down('#goal-details').disable();
		this.down('#goal-remove').disable();
		this.down('#goal-tasks').disable();
	}
});
<commit_msg>Documenting Goals.js<commit_after>/**
	Copyright (C) 2014  Matheus Borges Teixeira

	This is a part of Arkanos Organizer Suite (AOS) app.
	AOS is a web application for organizing personal goals.

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

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY 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/>.
**/

/**
 * View for administrating Goals.
 */
Ext.define('AOS.view.Goals', {
	extend: 'Ext.Container',
	requires: [
		'Ext.dataview.List',
		'AOS.store.Goals',
		'AOS.model.Goal',
		'AOS.view.bar.TopToolbar',
		'AOS.view.overlay.GoalOverlay',
		'AOS.form.Task'
	],
	config: {
		layout: 'fit',
		items: [
			{
				docked: 'top',
				title: 'Goals',
				xtype:'aos-toolbar-toptoolbar'
			},
			{
				xtype: 'list',
				store: 'Goals',
				itemId: 'list-display',
				itemTpl:	'

'+
							'{title}	'+
							'Completed
{completion}%	'+
							'Spent
{total_time_spent} hours	'+
							'Dedication
{dedication}%	'+
							'

',
				listeners: {
					select: function() {
						this.parent.enableActions();
					}
				}
			},
			{
				xtype: 'toolbar',
				ui: 'neutral',
				docked: 'bottom',
				scrollable: 'horizontal',
				layout: {pack:'center'},
				items:[
					{
						disabled: true,
						itemId: 'goal-details',
						ui: 'small',
						text: 'Details',
						iconCls: 'aos-icon-details',
						handler: function(){
							var grandfather = this.parent.parent;
							var selected = grandfather.down('#list-display').getSelection();
							if(selected && selected.length > 0){
								if(!grandfather.overlay){
									grandfather.overlay = Ext.Viewport.add(Ext.create('AOS.view.overlay.GoalOverlay'));
								}
								grandfather.overlay.popUp(selected[0]);
							}
						}
					},
					{
						disabled: true,
						itemId: 'goal-remove',
						ui: 'small',
						text: 'Remove',
						iconCls: 'aos-icon-remove',
						handler: function(){
							var grandfather = this.parent.parent;
							var list = grandfather.down('#list-display');
							var selected = list.getSelection();
							if(selected && selected.length > 0){
								var before = list.getScrollable().getScroller().position.y;
								AOS.Helper.remove(selected[0],'Goals');
								AOS.Helper.purgeStore('Tasks');
								AOS.Helper.purgeStore('Worklog');
								list.getScrollable().getScroller().scrollTo(0, before);
								grandfather.disableActions();
							}
						}
					},
					{
						disabled: true,
						itemId: 'goal-tasks',
						ui: 'small',
						text: 'New Task',
						iconCls: 'aos-icon-tasks',
						align: 'left',
						handler: function(){
							var grandfather = this.parent.parent;
							var selected = grandfather.down('#list-display').getSelection();
							if(selected && selected.length > 0){
								AOS.Helper.switchTo('AOS.form.Task',{ type: 'slide', direction: 'left' });
								Ext.Viewport.getActiveItem().setGoal(selected[0].get('id'),selected[0].get('title'));
							}
						}
					},
					{
						itemId: 'new-goal',
						ui: 'small',
						text: 'New Goal',
						iconCls: 'aos-icon-new',
						handler: function(){
							AOS.Helper.switchTo('AOS.form.Goal',{ type: 'slide', direction: 'left' });
						}
					}
				]
			}
		],
		listeners: {
			show: function() {
				var list = this.down('#list-display');
				if(list){
					AOS.Helper.moveToSelection(list);
				}
			}
		}
	},

	/**
	 * Enables all buttons related to selection.
	 */
	enableActions: function(){
		this.down('#goal-details').enable();
		this.down('#goal-remove').enable();
		this.down('#goal-tasks').enable();
	},

	/**
	 * Disables all buttons related to selection.
	 */
	disableActions: function(){
		this.down('#goal-details').disable();
		this.down('#goal-remove').disable();
		this.down('#goal-tasks').disable();
	}
});
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var passport = require('passport')
  , uri = require('url')
  , util = require('util')
  , utils = require('./utils');

/**
 * `TokenStrategy` constructor.
 *
 * The OAuth token authentication strategy authenticates requests based on the
 * `oauth_token` parameter contained in an HTTP request.  This parameter can be
 * located in an `Authorization` header field, the request entity body, or the
 * URL query parameters.
 *
 * This strategy requires three functions as callbacks, referred to as
 * `consumer`, `verify` and `validate`.
 *
 * The `consumer` callback accepts `consumerKey` and must call `done` supplying
 * a `consumer` and `consumerSecret`.  The strategy will use the secret to
 * compute the signature, failing authentication if it does not match the
 * request's signature.  If an exception occured, `err` should be set.
 *
 * The `verify` callback accepts `accessToken` and must call `done` supplying
 * a `user`, `tokenSecret` and optional `info`.  Note that `user` is the
 * authenticating entity of this strategy, and will be set by Passport at
 * `req.user` upon success.  The strategy will use the secret to compute the
 * signature, failing authentication if it does not match the request's
 * signature.  The optional `info` is typically used to carry additional
 * authorization details associated with the token (scope of access, for
 * example).  `info` will be set by Passport at `req.authInfo`, where it can be
 * used by later middleware, avoiding the need to re-query a database for the
 * same information.  If an exception occured, `err` should be set.
 *
 * The `validate` callback is optional, accepting `timestamp` and `nonce` as a
 * means to protect against replay attacks.
 *
 *
 * Note that despite defining a single authentication scheme, OAuth
 * authentication serves two distinct purposes:
 *   1. Authenticating consumers (aka clients) that are requesting access to
 *      protected resources.
 *   2. Authenticating users associated with an access token obtained by a
 *      consumer, with possibly limited scope.
 *
 * This strategy covers the latter purpose (see `ConsumerStrategy` for the
 * former).  Due to the nature of OAuth, both the user and the consumer will be
 * identified by employing this strategy, with the user being the entity of
 * primary interest.
 *
 * When authenticating using the `TokenStrategy`, `authInfo` will contain the
 * following properties (in addition to any optional info supplied by the
 * application to the `verify` callback):
 *
 *     scheme        always set to `OAuth`
 *     consumer      the consumer instance supplied by the application to the `consumer` callback
 *     client        alias for `consumer`
 *
 * This strategy is intended to be employed in routes for protected resources.
 *
 * Examples:
 *
 *     passport.use('token', new TokenStrategy(
 *       function(consumerKey, done) {
 *         Consumer.findByKey({ key: consumerKey }, function (err, consumer) {
 *           if (err) { return done(err); }
 *           if (!consumer) { return done(null, false); }
 *           return done(null, consumer, consumer.secret);
 *         });
 *       },
 *       function(accessToken, done) {
 *         AccessToken.findOne(accessToken, function (err, token) {
 *           if (err) { return done(err); }
 *           if (!token) { return done(null, false); }
 *           Users.findOne(token.userId, function(err, user) {
 *             if (err) { return done(err); }
 *             if (!user) { return done(null, false); }
 *             // fourth argument is optional info.  typically used to pass
 *             // details needed to authorize the request (ex: `scope`)
 *             return done(null, user, token.secret, { scope: token.scope });
 *           });
 *         });
 *       },
 *       function(timestamp, nonce, done) {
 *         // validate the timestamp and nonce as necessary
 *         done(null, true)
 *       }
 *     ));
 *
 * References:
 *  - [Authenticated Requests](http://tools.ietf.org/html/rfc5849#section-3)
 *  - [Accessing Protected Resources](http://oauth.net/core/1.0a/#anchor12)
 *  - [Accessing Protected Resources](http://oauth.net/core/1.0/#anchor13)
 *
 * @param {Object} options
 * @param {Function} consumer
 * @param {Function} verify
 * @api public
 */
function TokenStrategy(options, consumer, verify, validate) {
  if (typeof options == 'function') {
    validate = verify;
    verify = consumer;
    consumer = options;
    options = {};
  }
  if (!consumer) throw new Error('HTTP OAuth token authentication strategy requires a consumer function');
  if (!verify) throw new Error('HTTP OAuth token authentication strategy requires a verify function');

  passport.Strategy.call(this);
  this.name = 'oauth';
  this._consumer = consumer;
  this._verify = verify;
  this._validate = validate;
  this._host = options.host || null;
  this._realm = options.realm || 'Users';
  this._ignoreVersion = options.ignoreVersion || false;
}

/**
 * Inherit from `passport.Strategy`.
 */
util.inherits(TokenStrategy, passport.Strategy);

/**
 * Authenticate request based on the contents of a HTTP OAuth authorization
 * header, body parameters, or query parameters.
 *
 * @param {Object} req
 * @api protected
 */
TokenStrategy.prototype.authenticate = function(req) {
  var params = undefined
    , header = null;

  if (req.headers && req.headers['authorization']) {
    var parts = req.headers['authorization'].split(' ');
    if (parts.length >= 2) {
      var scheme = parts[0];
      var credentials = null;

      parts.shift();
      credentials = parts.join(' ');

      if (/OAuth/i.test(scheme)) {
        params = utils.parseHeader(credentials);
        header = params;
      }
    } else {
      return this.fail(400);
    }
  }

  if (req.body && req.body['oauth_signature']) {
    if (params) { return this.fail(400); }
    params = req.body;
  }

  if (req.query && req.query['oauth_signature']) {
    if (params) { return this.fail(400); }
    token = req.query['access_token'];
    params = req.query;
  }

  if (!params) { return this.fail(this._challenge()); }

  if (!params['oauth_consumer_key'] ||
      !params['oauth_token'] ||
      !params['oauth_signature_method'] ||
      !params['oauth_signature'] ||
      !params['oauth_timestamp'] ||
      !params['oauth_nonce']) {
    return this.fail(this._challenge('parameter_absent'), 400);
  }

  var consumerKey = params['oauth_consumer_key']
    , accessToken = params['oauth_token']
    , signatureMethod = params['oauth_signature_method']
    , signature = params['oauth_signature']
    , timestamp = params['oauth_timestamp']
    , nonce = params['oauth_nonce']
    , version = params['oauth_version']

  if (version && version !== '1.0' && !this._ignoreVersion) {
    return this.fail(this._challenge('version_rejected'), 400);
  }

  var self = this;
  this._consumer(consumerKey, function(err, consumer, consumerSecret) {
    if (err) { return self.error(err); }
    if (!consumer) { return self.fail(self._challenge('consumer_key_rejected')); }

    self._verify(accessToken, verified);

    function verified(err, user, tokenSecret, info) {
      if (err) { return self.error(err); }
      if (!user) { return self.fail(self._challenge('token_rejected')); }

      info = info || {};
      info.scheme = 'OAuth';
      info.client =
      info.consumer = consumer;

      var url = utils.originalURL(req, self._host)
        , query = req.query
        , body = req.body;

      var sources = [ header, query ];
      if (req.headers['content-type'] &&
          req.headers['content-type'].slice(0, 'application/x-www-form-urlencoded'.length) ===
              'application/x-www-form-urlencoded') {
        sources.push(body);
      }

      var normalizedURL = utils.normalizeURI(url)
        , normalizedParams = utils.normalizeParams.apply(undefined, sources)
        , base = utils.constructBaseString(req.method, normalizedURL, normalizedParams);

      if (signatureMethod == 'HMAC-SHA1') {
        var key = utils.encode(consumerSecret) + '&';
        if (tokenSecret) { key += utils.encode(tokenSecret); }
        var computedSignature = utils.hmacsha1(key, base);

        if (signature !== computedSignature) {
          return self.fail(self._challenge('signature_invalid'));
        }

      } else if (signatureMethod == 'HMAC-SHA256') {
        var key = utils.encode(consumerSecret) + '&';
        if (tokenSecret) { key += utils.encode(tokenSecret); }
        var computedSignature = utils.hmacsha256(key, base);

        if (signature !== computedSignature) {
          return self.fail(self._challenge('signature_invalid'));
        }

      } else if (signatureMethod == 'PLAINTEXT') {
        var computedSignature = utils.plaintext(consumerSecret, tokenSecret);

        if (signature !== computedSignature) {
          return self.fail(self._challenge('signature_invalid'));
        }

      } else {
        return self.fail(self._challenge('signature_method_rejected'), 400);
      }

      // If execution reaches this point, the request signature has been
      // verified and authentication is successful.
      if (self._validate) {
        // Give the application a chance it validate the timestamp and nonce, if
        // it so desires.
        self._validate(timestamp, nonce, function(err, valid) {
          if (err) { return self.error(err); }
          if (!valid) { return self.fail(self._challenge('nonce_used')); }
          return self.success(user, info);
        });
      } else {
        return self.success(user, info);
      }
    }
  });
}

/**
 * Authentication challenge.
 *
 * References:
 *  - [Problem Reporting](http://wiki.oauth.net/w/page/12238543/ProblemReporting)
 *
 * @api private
 */
TokenStrategy.prototype._challenge = function(problem, advice) {
  var challenge = 'OAuth realm="' + this._realm + '"';
  if (problem) {
    challenge += ', oauth_problem="' + utils.encode(problem) + '"';
  }
  if (advice && advice.length) {
    challenge += ', oauth_problem_advice="' + utils.encode(advice) + '"';
  }

  return challenge;
}

/**
 * Expose `TokenStrategy`.
 */
module.exports = TokenStrategy;
<commit_msg>provide user to nonce verification handler<commit_after>/**
 * Module dependencies.
 */
var passport = require('passport')
  , uri = require('url')
  , util = require('util')
  , utils = require('./utils');

/**
 * `TokenStrategy` constructor.
 *
 * The OAuth token authentication strategy authenticates requests based on the
 * `oauth_token` parameter contained in an HTTP request.  This parameter can be
 * located in an `Authorization` header field, the request entity body, or the
 * URL query parameters.
 *
 * This strategy requires three functions as callbacks, referred to as
 * `consumer`, `verify` and `validate`.
 *
 * The `consumer` callback accepts `consumerKey` and must call `done` supplying
 * a `consumer` and `consumerSecret`.  The strategy will use the secret to
 * compute the signature, failing authentication if it does not match the
 * request's signature.  If an exception occured, `err` should be set.
 *
 * The `verify` callback accepts `accessToken` and must call `done` supplying
 * a `user`, `tokenSecret` and optional `info`.  Note that `user` is the
 * authenticating entity of this strategy, and will be set by Passport at
 * `req.user` upon success.  The strategy will use the secret to compute the
 * signature, failing authentication if it does not match the request's
 * signature.  The optional `info` is typically used to carry additional
 * authorization details associated with the token (scope of access, for
 * example).  `info` will be set by Passport at `req.authInfo`, where it can be
 * used by later middleware, avoiding the need to re-query a database for the
 * same information.  If an exception occured, `err` should be set.
 *
 * The `validate` callback is optional, accepting `timestamp` and `nonce` as a
 * means to protect against replay attacks.
 *
 *
 * Note that despite defining a single authentication scheme, OAuth
 * authentication serves two distinct purposes:
 *   1. Authenticating consumers (aka clients) that are requesting access to
 *      protected resources.
 *   2. Authenticating users associated with an access token obtained by a
 *      consumer, with possibly limited scope.
 *
 * This strategy covers the latter purpose (see `ConsumerStrategy` for the
 * former).  Due to the nature of OAuth, both the user and the consumer will be
 * identified by employing this strategy, with the user being the entity of
 * primary interest.
 *
 * When authenticating using the `TokenStrategy`, `authInfo` will contain the
 * following properties (in addition to any optional info supplied by the
 * application to the `verify` callback):
 *
 *     scheme        always set to `OAuth`
 *     consumer      the consumer instance supplied by the application to the `consumer` callback
 *     client        alias for `consumer`
 *
 * This strategy is intended to be employed in routes for protected resources.
 *
 * Examples:
 *
 *     passport.use('token', new TokenStrategy(
 *       function(consumerKey, done) {
 *         Consumer.findByKey({ key: consumerKey }, function (err, consumer) {
 *           if (err) { return done(err); }
 *           if (!consumer) { return done(null, false); }
 *           return done(null, consumer, consumer.secret);
 *         });
 *       },
 *       function(accessToken, done) {
 *         AccessToken.findOne(accessToken, function (err, token) {
 *           if (err) { return done(err); }
 *           if (!token) { return done(null, false); }
 *           Users.findOne(token.userId, function(err, user) {
 *             if (err) { return done(err); }
 *             if (!user) { return done(null, false); }
 *             // fourth argument is optional info.  typically used to pass
 *             // details needed to authorize the request (ex: `scope`)
 *             return done(null, user, token.secret, { scope: token.scope });
 *           });
 *         });
 *       },
 *       function(timestamp, nonce, done) {
 *         // validate the timestamp and nonce as necessary
 *         done(null, true)
 *       }
 *     ));
 *
 * References:
 *  - [Authenticated Requests](http://tools.ietf.org/html/rfc5849#section-3)
 *  - [Accessing Protected Resources](http://oauth.net/core/1.0a/#anchor12)
 *  - [Accessing Protected Resources](http://oauth.net/core/1.0/#anchor13)
 *
 * @param {Object} options
 * @param {Function} consumer
 * @param {Function} verify
 * @api public
 */
function TokenStrategy(options, consumer, verify, validate) {
  if (typeof options == 'function') {
    validate = verify;
    verify = consumer;
    consumer = options;
    options = {};
  }
  if (!consumer) throw new Error('HTTP OAuth token authentication strategy requires a consumer function');
  if (!verify) throw new Error('HTTP OAuth token authentication strategy requires a verify function');

  passport.Strategy.call(this);
  this.name = 'oauth';
  this._consumer = consumer;
  this._verify = verify;
  this._validate = validate;
  this._host = options.host || null;
  this._realm = options.realm || 'Users';
  this._ignoreVersion = options.ignoreVersion || false;
}

/**
 * Inherit from `passport.Strategy`.
 */
util.inherits(TokenStrategy, passport.Strategy);

/**
 * Authenticate request based on the contents of a HTTP OAuth authorization
 * header, body parameters, or query parameters.
 *
 * @param {Object} req
 * @api protected
 */
TokenStrategy.prototype.authenticate = function(req) {
  var params = undefined
    , header = null;

  if (req.headers && req.headers['authorization']) {
    var parts = req.headers['authorization'].split(' ');
    if (parts.length >= 2) {
      var scheme = parts[0];
      var credentials = null;

      parts.shift();
      credentials = parts.join(' ');

      if (/OAuth/i.test(scheme)) {
        params = utils.parseHeader(credentials);
        header = params;
      }
    } else {
      return this.fail(400);
    }
  }

  if (req.body && req.body['oauth_signature']) {
    if (params) { return this.fail(400); }
    params = req.body;
  }

  if (req.query && req.query['oauth_signature']) {
    if (params) { return this.fail(400); }
    token = req.query['access_token'];
    params = req.query;
  }

  if (!params) { return this.fail(this._challenge()); }

  if (!params['oauth_consumer_key'] ||
      !params['oauth_token'] ||
      !params['oauth_signature_method'] ||
      !params['oauth_signature'] ||
      !params['oauth_timestamp'] ||
      !params['oauth_nonce']) {
    return this.fail(this._challenge('parameter_absent'), 400);
  }

  var consumerKey = params['oauth_consumer_key']
    , accessToken = params['oauth_token']
    , signatureMethod = params['oauth_signature_method']
    , signature = params['oauth_signature']
    , timestamp = params['oauth_timestamp']
    , nonce = params['oauth_nonce']
    , version = params['oauth_version']

  if (version && version !== '1.0' && !this._ignoreVersion) {
    return this.fail(this._challenge('version_rejected'), 400);
  }

  var self = this;
  this._consumer(consumerKey, function(err, consumer, consumerSecret) {
    if (err) { return self.error(err); }
    if (!consumer) { return self.fail(self._challenge('consumer_key_rejected')); }

    self._verify(accessToken, verified);

    function verified(err, user, tokenSecret, info) {
      if (err) { return self.error(err); }
      if (!user) { return self.fail(self._challenge('token_rejected')); }

      info = info || {};
      info.scheme = 'OAuth';
      info.client =
      info.consumer = consumer;

      var url = utils.originalURL(req, self._host)
        , query = req.query
        , body = req.body;

      var sources = [ header, query ];
      if (req.headers['content-type'] &&
          req.headers['content-type'].slice(0, 'application/x-www-form-urlencoded'.length) ===
              'application/x-www-form-urlencoded') {
        sources.push(body);
      }

      var normalizedURL = utils.normalizeURI(url)
        , normalizedParams = utils.normalizeParams.apply(undefined, sources)
        , base = utils.constructBaseString(req.method, normalizedURL, normalizedParams);

      if (signatureMethod == 'HMAC-SHA1') {
        var key = utils.encode(consumerSecret) + '&';
        if (tokenSecret) { key += utils.encode(tokenSecret); }
        var computedSignature = utils.hmacsha1(key, base);

        if (signature !== computedSignature) {
          return self.fail(self._challenge('signature_invalid'));
        }

      } else if (signatureMethod == 'HMAC-SHA256') {
        var key = utils.encode(consumerSecret) + '&';
        if (tokenSecret) { key += utils.encode(tokenSecret); }
        var computedSignature = utils.hmacsha256(key, base);

        if (signature !== computedSignature) {
          return self.fail(self._challenge('signature_invalid'));
        }

      } else if (signatureMethod == 'PLAINTEXT') {
        var computedSignature = utils.plaintext(consumerSecret, tokenSecret);

        if (signature !== computedSignature) {
          return self.fail(self._challenge('signature_invalid'));
        }

      } else {
        return self.fail(self._challenge('signature_method_rejected'), 400);
      }

      // If execution reaches this point, the request signature has been
      // verified and authentication is successful.
      if (self._validate) {
        // Give the application a chance it validate the timestamp and nonce, if
        // it so desires.
        self._validate(user, timestamp, nonce, function(err, valid) {
          if (err) { return self.error(err); }
          if (!valid) { return self.fail(self._challenge('nonce_used')); }
          return self.success(user, info);
        });
      } else {
        return self.success(user, info);
      }
    }
  });
}

/**
 * Authentication challenge.
 *
 * References:
 *  - [Problem Reporting](http://wiki.oauth.net/w/page/12238543/ProblemReporting)
 *
 * @api private
 */
TokenStrategy.prototype._challenge = function(problem, advice) {
  var challenge = 'OAuth realm="' + this._realm + '"';
  if (problem) {
    challenge += ', oauth_problem="' + utils.encode(problem) + '"';
  }
  if (advice && advice.length) {
    challenge += ', oauth_problem_advice="' + utils.encode(advice) + '"';
  }

  return challenge;
}

/**
 * Expose `TokenStrategy`.
 */
module.exports = TokenStrategy;
<|endoftext|>


<commit_before>var util = require('util'),
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    Relation = require('./Relation');

function JavaScriptSourceMappingUrl(config) {
    Relation.call(this, config);
}

util.inherits(JavaScriptSourceMappingUrl, Relation);

extendWithGettersAndSetters(JavaScriptSourceMappingUrl.prototype, {
    get href() {
        return this.node.value.match(/[@#]\s*sourceMappingURL=([^\s]*)/)[1];
    },

    set href(href) {
        this.node.value = this.node.value.replace(/([@#]\s*sourceMappingURL=)[^\s]*/, '$1' + href);
    },

    inline: function () {
        throw new Error('JavaScriptSourceMappingUrl.inline(): Not supported');
    },

    attach: function (asset, position, adjacentRelation) {
        if (position !== 'last') {
            throw new Error('JavaScriptSourceMappingUrl.attach(): Only position === \'last\' is supported');
        }
        var parseTree = asset.parseTree;
        var lastStatement;
        if (parseTree.body.length === 0) {
            lastStatement = { type: 'EmptyStatement' };
            parseTree.body.push(lastStatement);
        } else {
            lastStatement = parseTree.body[parseTree.body.length - 1];
        }
        lastStatement.trailingComments = lastStatement.trailingComments || [];
        this.node = { value: '@ sourceMappingURL=', type: 'Line' };
        lastStatement.trailingComments.push(this.node);
        // As far as I can tell //# sourceMappingURL isn't widely supported yet, so be conservative:
        return Relation.prototype.attach.call(this, asset, position, adjacentRelation);
    },

    detach: function () {
        this.node.value = this.node.value.replace(/[@#]\s*sourceMappingURL=([^\s]*)/, '');
        this.node = null;
        return Relation.prototype.detach.call(this);
    }
});

module.exports = JavaScriptSourceMappingUrl;
<commit_msg>Implement JavaScriptSourceMappingUrl.inline.<commit_after>var util = require('util'),
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    Relation = require('./Relation');

function JavaScriptSourceMappingUrl(config) {
    Relation.call(this, config);
}

util.inherits(JavaScriptSourceMappingUrl, Relation);

extendWithGettersAndSetters(JavaScriptSourceMappingUrl.prototype, {
    get href() {
        return this.node.value.match(/[@#]\s*sourceMappingURL=([^\s]*)/)[1];
    },

    set href(href) {
        this.node.value = this.node.value.replace(/([@#]\s*sourceMappingURL=)[^\s]*/, '$1' + href);
    },

    inline: function () {
        Relation.prototype.inline.call(this);
        this.href = this.to.dataUrl;
        this.from.markDirty();
        return this;
    },

    attach: function (asset, position, adjacentRelation) {
        if (position !== 'last') {
            throw new Error('JavaScriptSourceMappingUrl.attach(): Only position === \'last\' is supported');
        }
        var parseTree = asset.parseTree;
        var lastStatement;
        if (parseTree.body.length === 0) {
            lastStatement = { type: 'EmptyStatement' };
            parseTree.body.push(lastStatement);
        } else {
            lastStatement = parseTree.body[parseTree.body.length - 1];
        }
        lastStatement.trailingComments = lastStatement.trailingComments || [];
        this.node = { value: '@ sourceMappingURL=', type: 'Line' };
        lastStatement.trailingComments.push(this.node);
        // As far as I can tell //# sourceMappingURL isn't widely supported yet, so be conservative:
        return Relation.prototype.attach.call(this, asset, position, adjacentRelation);
    },

    detach: function () {
        this.node.value = this.node.value.replace(/[@#]\s*sourceMappingURL=([^\s]*)/, '');
        this.node = null;
        return Relation.prototype.detach.call(this);
    }
});

module.exports = JavaScriptSourceMappingUrl;
<|endoftext|>


<commit_before>'use babel'
var NativeStorage;
import DEStorage from './../storage/DEStorage'
import MotifConnector from './MotifConnector'
import DEUtilities from './../DEUtilities'
import _ from 'lodash';
var mockImplementation=undefined;
var chokidar = require('chokidar');
var reload = require('require-reload')(require);

export default class MotifConnectorMock extends MotifConnector {
  constructor(remoteURL,config,logger){
    super(remoteURL,config,logger);
    // init NativeStorage
    if(NativeStorage == undefined){
      this.logger.info("NativeStorage reload")
      NativeStorage = reload('./../storage/NativeStorage')(config);
    }
  }
  sendRequest(request, callback){
    try {
          var app = request.req.app;
          var dom = request.req.dom;
          var op = request.req.op;
          var srv = request.req.srv;
          var objectToCall = null;
          var that = this;

          this.logger.debug("Sending request to MOTIF: " + JSON.stringify(request));

          objectToCall = mockImplementation[dom][app][srv];
          this.executeRequest(objectToCall, op, request, callback);

      } catch(ex){
          var errMsg = "MOTIF Mock Connector error: " + ex;
          if (ex.lineNumber){
              errMsg = errMsg + " (line:" + ex.lineNumber +")";
          }
          if (ex.fileName){
              errMsg = errMsg + " (line:" + ex.fileName +")";
          }
          this.logger.error(errMsg);
          //TODO!! reply with error
      }
  }
  executeRequest(objectToCall, operation, request, callback){
    var ret = (objectToCall[operation](request));
    if (callback){
        callback(ret);
    }
  }

  requireMockInformation(path,config){
    var mockImplInfo={
      "implPath":path,
      "libraryLoader":config.libraryLoader
    };
    return mockImplInfo;
  }

  setupForDebug(params) {
      try {
          //mockImplementation = require(params.mockImplementationFilePath);
          if (mockImplementation==null){
              var path=this.config.MockImplementationPath;
              var mockInfo=this.requireMockInformation(path,this.config);
              this.fileWatcher = chokidar.watch(path, 'file', {
                ignored: /[\/\\]\./,
                persistent: true
              });
              this.fileWatcher.on('change', path => this.reloadMockImpl(path.mockInfo));

              //mockImplementation = reload(path)(this.logger,  NativeStorage, DEStorage, DEUtilities, _);
              mockImplementation = reload('./MotifConnectorMockWrapper.js')(this.logger,  NativeStorage, DEStorage, DEUtilities, _, mockInfo);
              if (mockImplementation.appStarted) {
                  mockImplementation.appStarted();
              }
          }

      } catch(exx){
          this.logger.error(exx.toString());
      }
  }
  reloadMockImpl(path,mockInfo){
    this.logger.info('Mock implementation file '+ path + ' has been changed.');
    mockImplementation = reload('./MotifConnectorMockWrapper.js')(this.logger,  NativeStorage, DEStorage, DEUtilities, _, mockInfo);
    this.logger.info('Mock implementation file '+ path + ' has been reloaded!');
  }

  clean(){
    this.logger.debug("Clean motif connector mock");
    if(this.fileWatcher){
      this.fileWatcher.close();
    }
    NativeStorage=undefined
    DEStorage.clear();
    mockImplementation=undefined;
  }
}
<commit_msg>fix reload bug<commit_after>'use babel'
var NativeStorage;
import DEStorage from './../storage/DEStorage'
import MotifConnector from './MotifConnector'
import DEUtilities from './../DEUtilities'
import _ from 'lodash';
var mockImplementation=undefined;
var chokidar = require('chokidar');
var reload = require('require-reload')(require);

export default class MotifConnectorMock extends MotifConnector {
  constructor(remoteURL,config,logger){
    super(remoteURL,config,logger);
    // init NativeStorage
    if(NativeStorage == undefined){
      this.logger.info("NativeStorage reload")
      NativeStorage = reload('./../storage/NativeStorage')(config);
    }
  }
  sendRequest(request, callback){
    try {
          var app = request.req.app;
          var dom = request.req.dom;
          var op = request.req.op;
          var srv = request.req.srv;
          var objectToCall = null;
          var that = this;

          this.logger.debug("Sending request to MOTIF: " + JSON.stringify(request));

          objectToCall = mockImplementation[dom][app][srv];
          this.executeRequest(objectToCall, op, request, callback);

      } catch(ex){
          var errMsg = "MOTIF Mock Connector error: " + ex;
          if (ex.lineNumber){
              errMsg = errMsg + " (line:" + ex.lineNumber +")";
          }
          if (ex.fileName){
              errMsg = errMsg + " (line:" + ex.fileName +")";
          }
          this.logger.error(errMsg);
          //TODO!! reply with error
      }
  }
  executeRequest(objectToCall, operation, request, callback){
    var ret = (objectToCall[operation](request));
    if (callback){
        callback(ret);
    }
  }

  requireMockInformation(path,config){
    var mockImplInfo={
      "implPath":path,
      "libraryLoader":config.libraryLoader
    };
    return mockImplInfo;
  }

  setupForDebug(params) {
      try {
          //mockImplementation = require(params.mockImplementationFilePath);
          if (mockImplementation==null){
              var path=this.config.MockImplementationPath;
              var mockInfo=this.requireMockInformation(path,this.config);
              this.fileWatcher = chokidar.watch(path, 'file', {
                ignored: /[\/\\]\./,
                persistent: true
              });
              this.fileWatcher.on('change', path => this.reloadMockImpl(path,mockInfo));

              //mockImplementation = reload(path)(this.logger,  NativeStorage, DEStorage, DEUtilities, _);
              mockImplementation = reload('./MotifConnectorMockWrapper.js')(this.logger,  NativeStorage, DEStorage, DEUtilities, _, mockInfo);
              if (mockImplementation.appStarted) {
                  mockImplementation.appStarted();
              }
          }

      } catch(exx){
          this.logger.error(exx.toString());
      }
  }
  reloadMockImpl(path,mockInfo){
    console.log("reloadMockImpl")
    this.logger.info('Mock implementation file '+ path + ' has been changed.');
    mockImplementation = reload('./MotifConnectorMockWrapper.js')(this.logger,  NativeStorage, DEStorage, DEUtilities, _, mockInfo);
    this.logger.info('Mock implementation file '+ path + ' has been reloaded!');
  }

  clean(){
    this.logger.debug("Clean motif connector mock");
    if(this.fileWatcher){
      this.fileWatcher.close();
    }
    NativeStorage=undefined
    DEStorage.clear();
    mockImplementation=undefined;
  }
}
<|endoftext|>


<commit_before>"use strict";

const path = require("path");
const {CompositeDisposable, Disposable} = require("atom");
const {escapeRegExp} = require("../../utils/general.js");
const IconTables = require("../../icons/icon-tables.js");
const Strategy = require("../strategy.js");

class UsertypeStrategy extends Strategy {

	constructor(){
		super({
			name:          "usertypes",
			priority:      3,
			matchesFiles:  true,
			matchesDirs:   false,
			ignoreVirtual: false
		});

		this.configDisposable = null;
		this.customTypes      = null;
		this.customTypeIcons  = null;
		this.hasCustomTypes   = false;
	}

	enable(){
		if(!this.enabled && !this.configDisposable){
			this.customTypes      = new Map();
			this.customTypeIcons  = new Map();
			this.hasCustomTypes   = false;

			this.configDisposable = new CompositeDisposable(
				atom.config.onDidChange("core.customFileTypes", types => {
					this.updateCustomTypes(types.newValue);
					this.checkAll(false);
				})
			);

			const types = atom.config.get("core.customFileTypes");
			this.updateCustomTypes(types);
		}
		return super.enable();
	}

	disable(){
		if(this.enabled && this.configDisposable){
			this.configDisposable.dispose();
			this.configDisposable = null;
			this.customTypes      = null;
			this.customTypeIcons  = null;
			this.hasCustomTypes   = false;
		}
		return super.disable();
	}

	matchIcon(resource){
		if(!this.hasCustomTypes)
			return null;

		for(const [scopeName, patterns] of this.customTypes){
			const {names, paths} = patterns;
			if((null !== names && names.test(resource.name))
			||  null !== paths && paths.test(resource.path))
				return this.customTypeIcons.get(scopeName);
		}

		return null;
	}

	updateCustomTypes(types){
		this.customTypes.clear();
		this.customTypeIcons.clear();

		for(const scopeName in types){
			const icon = IconTables.matchScope(scopeName);
			if(!icon)
				continue; // Skip types without icons
			this.customTypeIcons.set(scopeName, icon);

			const names = [];
			const paths = [];

			const patterns = types[scopeName];
			for(const pattern of patterns)
				(-1 === pattern.indexOf(path.sep))
					? names.push(pattern)
					: paths.push(pattern);

			this.customTypes.set(scopeName, {
				names: this.makeNamePattern(names),
				paths: this.makePathPattern(paths)
			});
		}

		this.hasCustomTypes = !!this.customTypes.size;
	}

	/**
	 * Compile an expression to match one or more file extensions.
	 *
	 * @param {String[]} names
	 * @return {RegExp|null}
	 * @private
	 */
	makeNamePattern(names){
		const {length} = names;

		if(!length)
			return null;

		names = names.map(s => escapeRegExp(s)).join("|");

		if(length > 1)
			names = `(?:${names})`;

		return new RegExp("(?:^|\\.)" + names + "$", "i");
	}

	/**
	 * Compile an expression to match one or more pathnames.
	 *
	 * @param {String[]} paths
	 * @return {RegExp|null}
	 * @private
	 */
	makePathPattern(paths){
		const {length} = paths;

		if(!length)
			return null;

		paths = paths.map(s => escapeRegExp(s)).join("|");

		if(length > 1)
			paths = `(?:${paths})`;

		return new RegExp("(?:^|[\\/\\\\])" + paths + "$", "i");
	}
}

module.exports = new UsertypeStrategy();
<commit_msg>Support leading dots in user-defined filetypes<commit_after>"use strict";

const path = require("path");
const {CompositeDisposable, Disposable} = require("atom");
const {escapeRegExp} = require("../../utils/general.js");
const IconTables = require("../../icons/icon-tables.js");
const Strategy = require("../strategy.js");

class UsertypeStrategy extends Strategy {

	constructor(){
		super({
			name:          "usertypes",
			priority:      3,
			matchesFiles:  true,
			matchesDirs:   false,
			ignoreVirtual: false
		});

		this.configDisposable = null;
		this.customTypes      = null;
		this.customTypeIcons  = null;
		this.hasCustomTypes   = false;
	}

	enable(){
		if(!this.enabled && !this.configDisposable){
			this.customTypes      = new Map();
			this.customTypeIcons  = new Map();
			this.hasCustomTypes   = false;

			this.configDisposable = new CompositeDisposable(
				atom.config.onDidChange("core.customFileTypes", types => {
					this.updateCustomTypes(types.newValue);
					this.checkAll(false);
				})
			);

			const types = atom.config.get("core.customFileTypes");
			this.updateCustomTypes(types);
		}
		return super.enable();
	}

	disable(){
		if(this.enabled && this.configDisposable){
			this.configDisposable.dispose();
			this.configDisposable = null;
			this.customTypes      = null;
			this.customTypeIcons  = null;
			this.hasCustomTypes   = false;
		}
		return super.disable();
	}

	matchIcon(resource){
		if(!this.hasCustomTypes)
			return null;

		for(const [scopeName, patterns] of this.customTypes){
			const {names, paths} = patterns;
			if((null !== names && names.test(resource.name))
			||  null !== paths && paths.test(resource.path))
				return this.customTypeIcons.get(scopeName);
		}

		return null;
	}

	updateCustomTypes(types){
		this.customTypes.clear();
		this.customTypeIcons.clear();

		for(const scopeName in types){
			const icon = IconTables.matchScope(scopeName);
			if(!icon)
				continue; // Skip types without icons
			this.customTypeIcons.set(scopeName, icon);

			const names = [];
			const paths = [];

			const patterns = types[scopeName];
			for(const pattern of patterns)
				(-1 === pattern.indexOf(path.sep))
					? names.push(pattern)
					: paths.push(pattern);

			this.customTypes.set(scopeName, {
				names: this.makeNamePattern(names),
				paths: this.makePathPattern(paths)
			});
		}

		this.hasCustomTypes = !!this.customTypes.size;
	}

	/**
	 * Compile an expression to match one or more file extensions.
	 *
	 * @param {String[]} names
	 * @return {RegExp|null}
	 * @private
	 */
	makeNamePattern(names){
		const {length} = names;

		if(!length)
			return null;

		names = names.map(s => escapeRegExp(s.replace(/^\./, ""))).join("|");

		if(length > 1)
			names = `(?:${names})`;

		return new RegExp("(?:^|\\.)" + names + "$", "i");
	}

	/**
	 * Compile an expression to match one or more pathnames.
	 *
	 * @param {String[]} paths
	 * @return {RegExp|null}
	 * @private
	 */
	makePathPattern(paths){
		const {length} = paths;

		if(!length)
			return null;

		paths = paths.map(s => escapeRegExp(s)).join("|");

		if(length > 1)
			paths = `(?:${paths})`;

		return new RegExp("(?:^|[\\/\\\\])" + paths + "$", "i");
	}
}

module.exports = new UsertypeStrategy();
<|endoftext|>


<commit_before>var _ = require('lodash');

var periodTools = require('./periodTools');
var PRESTATIONS = require('../prestations');

module.exports = function reverseMap(openfiscaResponse, situation) {
    var period = periodTools.toOpenFiscaFormat(situation.dateDeValeur);

    var injectedRessources = _.uniq(_.flatten(_.map(situation.individus, function(individu) {
        return _.collect(individu.ressources, 'type');
    })));
    var injectedPrestations = _.intersection(_.keys(PRESTATIONS), injectedRessources);

    // Computed prestations can be in the 'familles' or 'individus' openfisca entity
    var openfiscaResults = _.merge(openfiscaResponse.value[0].familles[0], openfiscaResponse.value[0].individus[0]);

    var calculatedPrestations = _.pick(PRESTATIONS, function(format, prestationName) {
        return injectedPrestations.indexOf(prestationName) < 0;
    });

    return {
        injectedPrestations: injectedPrestations,
        calculatedPrestations: _.mapValues(calculatedPrestations, function(format, prestationName) {
            var type = format.type,
                computedPrestation = openfiscaResults[prestationName],
                result = computedPrestation[period];

            var uncomputabilityReason = openfiscaResults[prestationName + '_non_calculable'] && openfiscaResults[prestationName + '_non_calculable'][period];

            if (uncomputabilityReason) {
                return uncomputabilityReason;
            }

            if (format.montantAnnuel) {
                result *= 12;
            }

            if (type == Number) {
                result = Number(result.toFixed(2));
            }
            return result;
        }),
    };
};
<commit_msg>Make reverse mapping more robust<commit_after>var _ = require('lodash');

var periodTools = require('./periodTools');
var PRESTATIONS = require('../prestations');

module.exports = function reverseMap(openfiscaResponse, situation) {
    var period = periodTools.toOpenFiscaFormat(situation.dateDeValeur);

    var injectedRessources = _.uniq(_.flatten(_.map(situation.individus, function(individu) {
        return _.collect(individu.ressources, 'type');
    })));
    var injectedPrestations = _.intersection(_.keys(PRESTATIONS), injectedRessources);

    // Computed prestations can be in the 'familles' or 'individus' openfisca entity
    var openfiscaResults = _.merge(openfiscaResponse.value[0].familles[0], openfiscaResponse.value[0].individus[0]);

    var calculatedPrestations = _.pick(PRESTATIONS, function(format, prestationName) {
        return injectedPrestations.indexOf(prestationName) < 0;
    });

    return {
        injectedPrestations: injectedPrestations,
        calculatedPrestations: _.mapValues(calculatedPrestations, function(format, prestationName) {
            var result = openfiscaResults[prestationName] && openfiscaResults[prestationName][period],
                uncomputabilityReason = openfiscaResults[prestationName + '_non_calculable'] && openfiscaResults[prestationName + '_non_calculable'][period];

            if (uncomputabilityReason) {
                return uncomputabilityReason;
            }

            if (format.montantAnnuel) {
                result *= 12;
            }

            if (format.type == Number) {
                result = Number(result.toFixed(2));
            }
            return result;
        }),
    };
};
<|endoftext|>


<commit_before>window.AutoCompletedAddToChannelView = Backbone.View.extend({
  tagName: "div",
  className: "add_to_channel",

  events: {
    "keydown input.typeahead": "parseKeyDown",
    "keyup input.typeahead": "autoComplete",
    "focus input.typeahead": "focusInput",
    "click div.auto_complete": "parseReturn",
    "click div.fake_input a": "parseReturn",
    "blur input.typeahead": "blurInput",
    "click .show-input-button": "showInput",
    "mouseenter .auto_complete>div": "selectAddNew",
    "mouseleave .auto_complete>div": "deActivateAddNew"
  },

  tmpl: HoganTemplates["channels/_auto_completed_add_to_channel"],

  initialize: function () {
    this.collection = new OwnChannelCollection();
    this.collection.bind('add', this.addChannel, this);

    this._channelViews = {};
  },

  render: function () {
    this.$el.html( this.tmpl.render() );

    this.reset();

    return this;
  },

  parseKeyDown: function (e) {
    this._proceed = false;

    switch(e.keyCode) {
      case 13:
        this.parseReturn(e);
        break;
      case 40:
        this.moveSelectionDown(e);
        break;
      case 38:
        this.moveSelectionUp(e);
        break;
      case 27:
        this.hideAutoComplete();
        break;
      default:
        this._proceed = true;
        break;
    }
  },

  showInput: function () {
    this.$el
      .removeClass('hide-input')
      .find('.fake_input input').focus();
  },

  addChannel: function (channel) {
    var view = new AutoCompletedAddedChannelView({
      model: channel,
      rootView: this
    }).render();

    this.$el.addClass('hide-input');

    this.$el.find('.added_channels').append( view.el );

    this._channelViews[channel.id] = view;

    if ( window.updateHeight ) {
      window.updateHeight();
    }
  },

  reset: function () {
    _.each(this._channelViews, function (view) {
      view.remove();
    });

    this._channelViews = {};

    this.collection.each(function(channel) {
      this.addChannel(channel);
    }, this);
  },

  focusInput: function () { this.$el.addClass('focus'); },
  blurInput: function () { this.$el.removeClass('focus'); },

  moveSelectionUp: function (e) {
    var prevKey;

    if ( this._activeChannelKey !== undefined ) {
      // There is an active channel key
      if ( this._autoCompleteViews[this._activeChannelKey - 1] ) {
        // Select the previous key
        prevKey = this._activeChannelKey - 1;
      }
    }

    if ( typeof prevKey === "undefined" ) {
      // No previous item to be selected
      if ( ! this.isAddNewActive() ) {
        // Select addNew
        this.selectAddNew();

        if ( ! this.isAddNewActive() ) {
          prevKey = this._autoCompleteViews.length - 1;
        }
      } else {
        prevKey = this._autoCompleteViews.length - 1;
      }
    }

    if ( typeof prevKey === "number" ) {
      this.setActiveAutoComplete(prevKey, true);
    }

    e.preventDefault();
  },

  moveSelectionDown: function (e) {
    var nextKey;

    if ( this._activeChannelKey !== undefined ) {
      if ( this._autoCompleteViews[this._activeChannelKey + 1] ) {
        nextKey = this._activeChannelKey + 1;
      }
    } else {
      nextKey = 0;
    }

    if ( typeof nextKey === "undefined" ) {
      this.selectAddNew();

      if ( ! this.isAddNewActive() ) {
        nextKey = 0;
      }
    }

    if ( typeof nextKey === "number" ) {
      this.setActiveAutoComplete(nextKey, false);
    }

    e.preventDefault();
  },

  setActiveAutoComplete: function (key, scroll) {
    if ( this._autoCompleteViews[this._activeChannelKey] ) {
      this._autoCompleteViews[this._activeChannelKey].deActivate();
    }

    this.deActivateAddNew();

    this._autoCompleteViews[key].activate();

    if ( typeof scroll === "boolean" ) {
      this._autoCompleteViews[key].el.scrollIntoView(scroll);
    }

    this._activeChannelKey = key;
  },

  selectAddNew: function () {
    if ( ! this.isAddNewVisible() ) {
      return false;
    }

    if ( typeof this._activeChannelKey === "number" ) {
      this._autoCompleteViews[this._activeChannelKey].deActivate();

      this._activeChannelKey = undefined;
    }

    this.activateAddNew();
  },

  activateAddNew: function () {
    this.$el.find('.auto_complete>div').addClass('active');
  },

  deActivateAddNew: function () {
    this.$el.find('.auto_complete>div').removeClass('active');
  },

  isAddNewActive: function () {
    return this.$el.find('.auto_complete>div').hasClass('active');
  },

  activateAutoCompleteView: function (view) {
    _.each(this._autoCompleteViews, function (autocomplete, key) {
      if ( view === autocomplete ) {
        this.setActiveAutoComplete(key);
      }
    }, this);
  },

  deActivateAutoCompleteView: function (view) {
    this._autoCompleteViews[ this._activeChannelKey ].deActivate();

    this._activeChannelKey = undefined;
  },

  parseReturn: function (e) {
    e.preventDefault();
    e.stopPropagation();

    this.disable();

    if ( this._activeChannelKey !== undefined ) {
      var selected = this._autoCompleteViews[ this._activeChannelKey].model;

      this.$el.find('input.typeahead').val( selected.get('title') );

      if ( selected.get('user_channel') ) {
        this.addNewChannel( selected.get('user_channel') );

        return;
      }
    }

    this.createNewChannel(e);
  },

  createNewChannel: function (e) {
    var title = this.$el.find('input.typeahead').val();

    this.showLoading();

    var dupe = false;

    this.collection.each(function (channel) {
      if ( channel.get('title') === title ) {
        dupe = true;
      }
    });

    if ( dupe ) {
      this.hideAutoComplete();

      this.enable();
      this.hideLoading();
      this.clearInput();

      return;
    }

    if ( $.trim(title).length < 1 ) {
      this.hideAutoComplete();

      this.enable();
      this.hideLoading();

      return;
    }

    $.ajax({
      url: '/' + currentUser.get('username') + '/channels',
      data: {
        title: title
      },
      type: "POST"
    }).done( _.bind( this.addNewChannel, this ) );

    e.preventDefault();
  },

  addNewChannel: function (channel) {
    channel = new Channel(channel);

    currentUser.channels.add(channel);
    this.collection.add(channel);

    this.hideAutoComplete();

    this.enable();
    this.hideLoading();
    this.clearInput();
  },

  clearInput: function () {
    this.$el.find('input.typeahead').val('');

    if ( this.collection.length ) {
      this.$el.addClass('hide-input');
    }
  },

  disable: function () {
    this.$el
      .addClass('disabled')
      .find('input.typeahead').prop('disabled', true);

    this.$el.find('.btn').addClass('disabled');
  },

  enable: function () {
    this.$el
      .removeClass('disabled')
      .find('input.typeahead').prop('disabled', false);

    this.$el.find('.btn').removeClass('disabled');
  },

  showLoading: function () {
    this.$el.find('.loading').show();
  },

  hideLoading: function () {
    this.$el.find('.loading').hide();
  },

  updateText: function () {
    var value = this.$el.find('input.typeahead').val();
    if ( value.length ) {
      this.$el.addClass('has-text');

      this.$el.find(".search").text( value );
    } else {
      this.$el.removeClass('has-text');
    }
  },

  autoComplete: _.throttle(function () {
    var searchValue = this.$el.find('input.typeahead').val();

    this.updateText();

    if ( this._lastKnownSearchValue === searchValue
        || ! this._proceed ) {
      return;
    }

    this._lastKnownSearchValue = searchValue;
    this._activeChannelKey = undefined;

    if (searchValue.length < 1) {
      this.hideAutoComplete();
      return;
    }

    this.showLoading();

    $.ajax({
      type: "GET",
      url: "/" + currentUser.get('username') + "/channels/find",
      data: {
        s: searchValue
      }
    }).done( _.bind( function (data) {
      var channels = _.map(data, function (channel) {
        return new AutoCompletedChannel(channel);
      });

      this.updateAutoComplete(channels);

      this.hideLoading();
    }, this ) );
  }, 300),

  updateAutoComplete: function (channels) {
    this.clearAutoComplete();

    _.each(channels, this.addAutoComplete, this);

    this.showAutoComplete();

    if ( window.updateHeight ) {
      window.updateHeight();
    }
  },

  hideAddNew: function () {
    this.$el.addClass('hide-add-new');
  },

  showAddNew: function () {
    this.$el.removeClass('hide-add-new');
  },

  isAddNewVisible: function () {
    return ! this.$el.hasClass('hide-add-new');
  },

  hideAutoComplete: function () {
    this.$el.find('.auto_complete').hide();
  },

  showAutoComplete: function () {
    this.$el.find('.auto_complete').show();
  },

  clearAutoComplete: function () {
    _.each( this._autoCompleteViews, function (view) {
      view.remove();
    });

    this._autoCompleteViews = [];
    this._autoCompletes = [];

    this.$el.find('.auto_complete').addClass('empty');

    this.hideAutoComplete();

    this.deActivateAddNew();

    this.showAddNew();
  },

  addAutoComplete: function (channel) {
    if ( ! ( channel.get('user_channel')
                && this.collection.get( channel.get('user_channel').id ) ) ) {
      this._autoCompletes.push(channel);

      var view = new AutoCompletedChannelView({
        model: channel,
        query: this._lastKnownSearchValue,
        parent: this
      }).render();

      this.$el.find('.auto_complete>ul').append(view.el);

      this.$el.find('.auto_complete').removeClass('empty');

      this._autoCompleteViews.push(view);

      this.showAutoComplete();

      if ( channel.get('user_channel') ) {
        var lowerCaseTitle = channel.get('user_channel').title.toLowerCase();
        var lowerCaseSearch = this._lastKnownSearchValue.toLowerCase();

        if ( lowerCaseSearch === lowerCaseTitle ) {
          this.hideAddNew();
        }
      }
    }
  },

  removeAddedChannel: function (id) {
    this._channelViews[id].remove();

    delete this._channelViews[id];

    this.collection.remove(id);

    if ( this.collection.length ) {
      this.$el.addClass("hide-input");
    } else {
      this.$el.removeClass("hide-input");
    }
  }
});
<commit_msg>Fixed saving when a user channel is present<commit_after>window.AutoCompletedAddToChannelView = Backbone.View.extend({
  tagName: "div",
  className: "add_to_channel",

  events: {
    "keydown input.typeahead": "parseKeyDown",
    "keyup input.typeahead": "autoComplete",
    "focus input.typeahead": "focusInput",
    "click div.auto_complete": "parseReturn",
    "click div.fake_input a": "parseReturn",
    "blur input.typeahead": "blurInput",
    "click .show-input-button": "showInput",
    "mouseenter .auto_complete>div": "selectAddNew",
    "mouseleave .auto_complete>div": "deActivateAddNew"
  },

  tmpl: HoganTemplates["channels/_auto_completed_add_to_channel"],

  initialize: function () {
    this.collection = new OwnChannelCollection();
    this.collection.bind('add', this.addChannel, this);

    this._channelViews = {};
  },

  render: function () {
    this.$el.html( this.tmpl.render() );

    this.reset();

    return this;
  },

  parseKeyDown: function (e) {
    this._proceed = false;

    switch(e.keyCode) {
      case 13:
        this.parseReturn(e);
        break;
      case 40:
        this.moveSelectionDown(e);
        break;
      case 38:
        this.moveSelectionUp(e);
        break;
      case 27:
        this.hideAutoComplete();
        break;
      default:
        this._proceed = true;
        break;
    }
  },

  showInput: function () {
    this.$el
      .removeClass('hide-input')
      .find('.fake_input input').focus();
  },

  addChannel: function (channel) {
    var view = new AutoCompletedAddedChannelView({
      model: channel,
      rootView: this
    }).render();

    this.$el.addClass('hide-input');

    this.$el.find('.added_channels').append( view.el );

    this._channelViews[channel.id] = view;

    if ( window.updateHeight ) {
      window.updateHeight();
    }
  },

  reset: function () {
    _.each(this._channelViews, function (view) {
      view.remove();
    });

    this._channelViews = {};

    this.collection.each(function(channel) {
      this.addChannel(channel);
    }, this);
  },

  focusInput: function () { this.$el.addClass('focus'); },
  blurInput: function () { this.$el.removeClass('focus'); },

  moveSelectionUp: function (e) {
    var prevKey;

    if ( this._activeChannelKey !== undefined ) {
      // There is an active channel key
      if ( this._autoCompleteViews[this._activeChannelKey - 1] ) {
        // Select the previous key
        prevKey = this._activeChannelKey - 1;
      }
    }

    if ( typeof prevKey === "undefined" ) {
      // No previous item to be selected
      if ( ! this.isAddNewActive() ) {
        // Select addNew
        this.selectAddNew();

        if ( ! this.isAddNewActive() ) {
          prevKey = this._autoCompleteViews.length - 1;
        }
      } else {
        prevKey = this._autoCompleteViews.length - 1;
      }
    }

    if ( typeof prevKey === "number" ) {
      this.setActiveAutoComplete(prevKey, true);
    }

    e.preventDefault();
  },

  moveSelectionDown: function (e) {
    var nextKey;

    if ( this._activeChannelKey !== undefined ) {
      if ( this._autoCompleteViews[this._activeChannelKey + 1] ) {
        nextKey = this._activeChannelKey + 1;
      }
    } else {
      nextKey = 0;
    }

    if ( typeof nextKey === "undefined" ) {
      this.selectAddNew();

      if ( ! this.isAddNewActive() ) {
        nextKey = 0;
      }
    }

    if ( typeof nextKey === "number" ) {
      this.setActiveAutoComplete(nextKey, false);
    }

    e.preventDefault();
  },

  setActiveAutoComplete: function (key, scroll) {
    if ( this._autoCompleteViews[this._activeChannelKey] ) {
      this._autoCompleteViews[this._activeChannelKey].deActivate();
    }

    this.deActivateAddNew();

    this._autoCompleteViews[key].activate();

    if ( typeof scroll === "boolean" ) {
      this._autoCompleteViews[key].el.scrollIntoView(scroll);
    }

    this._activeChannelKey = key;
  },

  selectAddNew: function () {
    if ( ! this.isAddNewVisible() ) {
      return false;
    }

    if ( typeof this._activeChannelKey === "number" ) {
      this._autoCompleteViews[this._activeChannelKey].deActivate();

      this._activeChannelKey = undefined;
    }

    this.activateAddNew();
  },

  activateAddNew: function () {
    this.$el.find('.auto_complete>div').addClass('active');
  },

  deActivateAddNew: function () {
    this.$el.find('.auto_complete>div').removeClass('active');
  },

  isAddNewActive: function () {
    return this.$el.find('.auto_complete>div').hasClass('active');
  },

  activateAutoCompleteView: function (view) {
    _.each(this._autoCompleteViews, function (autocomplete, key) {
      if ( view === autocomplete ) {
        this.setActiveAutoComplete(key);
      }
    }, this);
  },

  deActivateAutoCompleteView: function (view) {
    this._autoCompleteViews[ this._activeChannelKey ].deActivate();

    this._activeChannelKey = undefined;
  },

  parseReturn: function (e) {
    e.preventDefault();
    e.stopPropagation();

    this.disable();

    if ( this._activeChannelKey !== undefined ) {
      var selected = this._autoCompleteViews[ this._activeChannelKey].model;

      this.$el.find('input.typeahead').val( selected.get('title') );

      if ( selected.get('user_channel') ) {
        this.addNewChannel( selected.get('user_channel') );

        return;
      }
    }

    this.createNewChannel(e);
  },

  createNewChannel: function (e) {
    var title = this.$el.find('input.typeahead').val();
    var dupe = false;
    var isUserChannel = false;

    this.showLoading();

    if ( $.trim(title).length < 1 ) {
      this.hideAutoComplete();

      this.enable();
      this.hideLoading();

      return;
    }

    this.collection.each(function (channel) {
      if ( channel.get('title') === title ) {
        dupe = true;
      }
    });

    if ( dupe ) {
      this.hideAutoComplete();

      this.enable();
      this.hideLoading();
      this.clearInput();

      return;
    }

    _.each(this._autoCompletes, function (autoComplete) {
      if ( autoComplete.get('title') === title && autoComplete.get('user_channel') ) {
        isUserChannel = true;

        this.addNewChannel(autoComplete);

        return false;
      }
    }, this);

    if ( isUserChannel ) {
      return;
    }

    $.ajax({
      url: '/' + currentUser.get('username') + '/channels',
      data: {
        title: title
      },
      type: "POST"
    }).done( _.bind( this.addNewChannel, this ) );

    e.preventDefault();
  },

  addNewChannel: function (channel) {
    channel = new Channel(channel);

    currentUser.channels.add(channel);
    this.collection.add(channel);

    this.hideAutoComplete();

    this.enable();
    this.hideLoading();
    this.clearInput();
  },

  clearInput: function () {
    this.$el.find('input.typeahead').val('');

    if ( this.collection.length ) {
      this.$el.addClass('hide-input');
    }
  },

  disable: function () {
    this.$el
      .addClass('disabled')
      .find('input.typeahead').prop('disabled', true);

    this.$el.find('.btn').addClass('disabled');
  },

  enable: function () {
    this.$el
      .removeClass('disabled')
      .find('input.typeahead').prop('disabled', false);

    this.$el.find('.btn').removeClass('disabled');
  },

  showLoading: function () {
    this.$el.find('.loading').show();
  },

  hideLoading: function () {
    this.$el.find('.loading').hide();
  },

  updateText: function () {
    var value = this.$el.find('input.typeahead').val();
    if ( value.length ) {
      this.$el.addClass('has-text');

      this.$el.find(".search").text( value );
    } else {
      this.$el.removeClass('has-text');
    }
  },

  autoComplete: _.throttle(function () {
    var searchValue = this.$el.find('input.typeahead').val();

    this.updateText();

    if ( this._lastKnownSearchValue === searchValue
        || ! this._proceed ) {
      return;
    }

    this._lastKnownSearchValue = searchValue;
    this._activeChannelKey = undefined;

    if (searchValue.length < 1) {
      this.hideAutoComplete();
      return;
    }

    this.showLoading();

    $.ajax({
      type: "GET",
      url: "/" + currentUser.get('username') + "/channels/find",
      data: {
        s: searchValue
      }
    }).done( _.bind( function (data) {
      var channels = _.map(data, function (channel) {
        return new AutoCompletedChannel(channel);
      });

      this.updateAutoComplete(channels);

      this.hideLoading();
    }, this ) );
  }, 300),

  updateAutoComplete: function (channels) {
    this.clearAutoComplete();

    _.each(channels, this.addAutoComplete, this);

    this.showAutoComplete();

    if ( window.updateHeight ) {
      window.updateHeight();
    }
  },

  hideAddNew: function () {
    this.$el.addClass('hide-add-new');
  },

  showAddNew: function () {
    this.$el.removeClass('hide-add-new');
  },

  isAddNewVisible: function () {
    return ! this.$el.hasClass('hide-add-new');
  },

  hideAutoComplete: function () {
    this.$el.find('.auto_complete').hide();
  },

  showAutoComplete: function () {
    this.$el.find('.auto_complete').show();
  },

  clearAutoComplete: function () {
    _.each( this._autoCompleteViews, function (view) {
      view.remove();
    });

    this._autoCompleteViews = [];
    this._autoCompletes = [];

    this.$el.find('.auto_complete').addClass('empty');

    this.hideAutoComplete();

    this.deActivateAddNew();

    this.showAddNew();
  },

  addAutoComplete: function (channel) {
    if ( ! ( channel.get('user_channel')
                && this.collection.get( channel.get('user_channel').id ) ) ) {
      this._autoCompletes.push(channel);

      var view = new AutoCompletedChannelView({
        model: channel,
        query: this._lastKnownSearchValue,
        parent: this
      }).render();

      this.$el.find('.auto_complete>ul').append(view.el);

      this.$el.find('.auto_complete').removeClass('empty');

      this._autoCompleteViews.push(view);

      this.showAutoComplete();

      if ( channel.get('user_channel') ) {
        var lowerCaseTitle = channel.get('user_channel').title.toLowerCase();
        var lowerCaseSearch = this._lastKnownSearchValue.toLowerCase();

        if ( lowerCaseSearch === lowerCaseTitle ) {
          this.hideAddNew();
        }
      }
    }
  },

  removeAddedChannel: function (id) {
    this._channelViews[id].remove();

    delete this._channelViews[id];

    this.collection.remove(id);

    if ( this.collection.length ) {
      this.$el.addClass("hide-input");
    } else {
      this.$el.removeClass("hide-input");
    }
  }
});
<|endoftext|>


<commit_before>/// <vs />
// Include plug-ins
var isProduction = require('yargs').argv.env === 'production',
	gulp = require('gulp'),
	gulpIf = require('gulp-if'),
	jshint = require('gulp-jshint'),
	concat = require('gulp-concat'),
	minifyCSS = require('gulp-minify-css'),
	autoprefixer = require('gulp-autoprefixer'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	inject = require('gulp-inject'),
	minifyHTML = require('gulp-minify-html'),
	del = require('del'),
	angularFilesort = require('gulp-angular-filesort');

// File paths
var config = {
    vendorJsSrc: [
        'scripts/epona/plugins/jquery-2.1.3.min.js',
        'scripts/epona/plugins/bootstrap/js/bootstrap.min.js',
        'scripts/epona/plugins/magnific-popup/jquery.magnific-popup.min.js',
        'scripts/epona/plugins/owl-carousel/owl.carousel.min.js',
        'scripts/epona/plugins/layerslider/js/layerslider_pack.js',
        'scripts/epona/js/scripts.js',
        'scripts/toastr.js',
        'scripts/angular.js',
        'scripts/angular-route.js',
        'scripts/angular-cookies.js',
        'scripts/angular-animate.js',
        'scripts/loading-bar.js',
        'scripts/jquery.tokeninput.js',
        'scripts/Chart.js',
        'scripts/ng-infinite-scroll.min.js',
        'Scripts/angular-ui/ui-bootstrap-tpls.js'
    ],
    vendorCssSrc: [
        'content/epona/css/font-awesome.css',
        'content/epona/css/sky-forms.css',
        'scripts/epona/plugins/owl-carousel/owl.pack.css',
        'scripts/epona/plugins/magnific-popup/magnific-popup.css',
        'content/epona/css/animate.css',
        'content/epona/css/layerslider.css',
        'content/epona/css/essentials.css',
        'content/epona/css/layout.css',
        'content/epona/css/header-4.css',
        'content/epona/css/footer-default.css',
        'content/epona/css/color_scheme/green.css',
        'content/loading-bar.css',
        'content/token-input-showcase.css',
        'content/toastr.css'
    ],
    appJsSrc: ['app/**/*.js', '!app/build/*'],
    appCssSrc: ['content/main.css'],
    appIndexHtml: 'index-template.html'
}

// For browser caching
var getStamp = function () {
    var myDate = new Date();

    var myYear = myDate.getFullYear().toString();
    var myMonth = ('0' + (myDate.getMonth() + 1)).slice(-2);
    var myDay = ('0' + myDate.getDate()).slice(-2);
    var mySeconds = myDate.getSeconds().toString();

    var myFullDate = myYear + myMonth + myDay + mySeconds;

    return myFullDate;
};

// Minify, prefix and contat CSS
gulp.task('css', function () {
    del.sync(['app/build/allcss*']);

    var allCss = config.vendorCssSrc.concat(config.appCssSrc);

    return gulp.src(allCss)
		.pipe(gulpIf(isProduction, minifyCSS()))
		.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9'))
		.pipe(concat('allcss' + (isProduction ? getStamp() : '') + '.min.css', { newLine: '' }))
		.pipe(gulp.dest('app/build'))
});

// Lint Task
gulp.task('lint', function () {
    return gulp.src(config.appJsSrc)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

// Combine and minify all library JS files
gulp.task('vendors', function () {
    del.sync(['app/build/vendorjs*']);

    return gulp.src(config.vendorJsSrc)
		.pipe(gulpIf(isProduction, uglify()))
		.pipe(concat('vendorjs' + (isProduction ? getStamp() : '') + '.min.js', { newLine: '' }))
		.pipe(gulp.dest('app/build'));
});

// Combine and minify all JS files from the app folder
gulp.task('scripts', function () {
    del.sync(['app/build/alljs*']);

    return gulp.src(config.appJsSrc)
		.pipe(angularFilesort())
		.pipe(gulpIf(isProduction, uglify()))
		.pipe(concat('alljs' + (isProduction ? getStamp() : '') + '.min.js', { newLine: '' }))
		.pipe(gulp.dest('app/build'));
});

// Inject minified files into new HTML
gulp.task('html', ['css', 'scripts'], function () {
    del.sync(['index.html']);
    var target = gulp.src(config.appIndexHtml);
    var vendorSources = gulp.src(['app/build/vendorjs*'], { read: false });
    var appSources = gulp.src(['app/build/alljs*', 'app/build/allcss*'], { read: false });

    return target
        .pipe(inject(vendorSources, { starttag: '<!-- inject:vendors:{{ext}} -->' }))
        .pipe(inject(appSources))
		.pipe(minifyHTML({ conditionals: true }))
		.pipe(rename('index.html'))
		.pipe(gulp.dest('./'));
});

// Watch for changes
gulp.task('watch', ['lint', 'css', 'vendors', 'scripts', 'html'], function () {
    gulp.watch(config.appCssSrc, ['css', 'html']);
    gulp.watch(config.appJsSrc, ['lint', 'scripts', 'html']);
    gulp.watch(config.appIndexHtml, ['html']);
});

// Set  default tasks
gulp.task('default', ['lint', 'css', 'vendors', 'scripts', 'html'], function () { });<commit_msg>Added gulpfile.js to run with every build<commit_after>/// <vs BeforeBuild='watch' />
// Include plug-ins
var isProduction = require('yargs').argv.env === 'production',
	gulp = require('gulp'),
	gulpIf = require('gulp-if'),
	jshint = require('gulp-jshint'),
	concat = require('gulp-concat'),
	minifyCSS = require('gulp-minify-css'),
	autoprefixer = require('gulp-autoprefixer'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	inject = require('gulp-inject'),
	minifyHTML = require('gulp-minify-html'),
	del = require('del'),
	angularFilesort = require('gulp-angular-filesort');

// File paths
var config = {
    vendorJsSrc: [
        'scripts/epona/plugins/jquery-2.1.3.min.js',
        'scripts/epona/plugins/bootstrap/js/bootstrap.min.js',
        'scripts/epona/plugins/magnific-popup/jquery.magnific-popup.min.js',
        'scripts/epona/plugins/owl-carousel/owl.carousel.min.js',
        'scripts/epona/plugins/layerslider/js/layerslider_pack.js',
        'scripts/epona/js/scripts.js',
        'scripts/toastr.js',
        'scripts/angular.js',
        'scripts/angular-route.js',
        'scripts/angular-cookies.js',
        'scripts/angular-animate.js',
        'scripts/loading-bar.js',
        'scripts/jquery.tokeninput.js',
        'scripts/Chart.js',
        'scripts/ng-infinite-scroll.min.js',
        'Scripts/angular-ui/ui-bootstrap-tpls.js'
    ],
    vendorCssSrc: [
        'content/epona/css/font-awesome.css',
        'content/epona/css/sky-forms.css',
        'scripts/epona/plugins/owl-carousel/owl.pack.css',
        'scripts/epona/plugins/magnific-popup/magnific-popup.css',
        'content/epona/css/animate.css',
        'content/epona/css/layerslider.css',
        'content/epona/css/essentials.css',
        'content/epona/css/layout.css',
        'content/epona/css/header-4.css',
        'content/epona/css/footer-default.css',
        'content/epona/css/color_scheme/green.css',
        'content/loading-bar.css',
        'content/token-input-showcase.css',
        'content/toastr.css'
    ],
    appJsSrc: ['app/**/*.js', '!app/build/*'],
    appCssSrc: ['content/main.css'],
    appIndexHtml: 'index-template.html'
}

// For browser caching
var getStamp = function () {
    var myDate = new Date();

    var myYear = myDate.getFullYear().toString();
    var myMonth = ('0' + (myDate.getMonth() + 1)).slice(-2);
    var myDay = ('0' + myDate.getDate()).slice(-2);
    var mySeconds = myDate.getSeconds().toString();

    var myFullDate = myYear + myMonth + myDay + mySeconds;

    return myFullDate;
};

// Minify, prefix and contat CSS
gulp.task('css', function () {
    del.sync(['app/build/allcss*']);

    var allCss = config.vendorCssSrc.concat(config.appCssSrc);

    return gulp.src(allCss)
		.pipe(gulpIf(isProduction, minifyCSS()))
		.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9'))
		.pipe(concat('allcss' + (isProduction ? getStamp() : '') + '.min.css', { newLine: '' }))
		.pipe(gulp.dest('app/build'))
});

// Lint Task
gulp.task('lint', function () {
    return gulp.src(config.appJsSrc)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

// Combine and minify all library JS files
gulp.task('vendors', function () {
    del.sync(['app/build/vendorjs*']);

    return gulp.src(config.vendorJsSrc)
		.pipe(gulpIf(isProduction, uglify()))
		.pipe(concat('vendorjs' + (isProduction ? getStamp() : '') + '.min.js', { newLine: '' }))
		.pipe(gulp.dest('app/build'));
});

// Combine and minify all JS files from the app folder
gulp.task('scripts', function () {
    del.sync(['app/build/alljs*']);

    return gulp.src(config.appJsSrc)
		.pipe(angularFilesort())
		.pipe(gulpIf(isProduction, uglify()))
		.pipe(concat('alljs' + (isProduction ? getStamp() : '') + '.min.js', { newLine: '' }))
		.pipe(gulp.dest('app/build'));
});

// Inject minified files into new HTML
gulp.task('html', ['css', 'scripts'], function () {
    del.sync(['index.html']);
    var target = gulp.src(config.appIndexHtml);
    var vendorSources = gulp.src(['app/build/vendorjs*'], { read: false });
    var appSources = gulp.src(['app/build/alljs*', 'app/build/allcss*'], { read: false });

    return target
        .pipe(inject(vendorSources, { starttag: '<!-- inject:vendors:{{ext}} -->' }))
        .pipe(inject(appSources))
		.pipe(minifyHTML({ conditionals: true }))
		.pipe(rename('index.html'))
		.pipe(gulp.dest('./'));
});

// Watch for changes
gulp.task('watch', ['lint', 'css', 'vendors', 'scripts', 'html'], function () {
    gulp.watch(config.appCssSrc, ['css', 'html']);
    gulp.watch(config.appJsSrc, ['lint', 'scripts', 'html']);
    gulp.watch(config.appIndexHtml, ['html']);
});

// Set  default tasks
gulp.task('default', ['lint', 'css', 'vendors', 'scripts', 'html'], function () { });<|endoftext|>