<commit_before>/*jshint strict: false */

// /////////////////////////////////////////////////////////////////////////////
// @brief ArangoView
//
// @file
//
// DISCLAIMER
//
// Copyright 2013 triagens GmbH, Cologne, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright holder is triAGENS GmbH, Cologne, Germany
//
// @author Daniel H. Larkin
// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

const internal = require('internal');
const arangosh = require('@arangodb/arangosh');
const ArangoError = require('@arangodb').ArangoError;

// //////////////////////////////////////////////////////////////////////////////
// / @brief constructor
// //////////////////////////////////////////////////////////////////////////////

function ArangoView (database, data) {
  this._database = database;
  this._dbName = database._name();
  this._dbPrefix = '/_db/' + encodeURIComponent(database._name());

  if (typeof data === 'string') {
    this._id = null;
    this._name = data;
    this._type = null;
  }
  else if (data !== undefined) {
    this._id = data.id;
    this._name = data.name;
    this._type = data.type;
  } else {
    this._id = null;
    this._name = null;
    this._type = null;
  }
}

exports.ArangoView = ArangoView;

// /////////////////////////////////////////////////////////////////////////////
// @brief pretty print
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._PRINT = function (context) {
  const type = this.type();
  const name = this.name();

  const colors = internal.COLORS;
  const useColor = context.useColor;

  context.output += '[ArangoView ';
  if (useColor) { context.output += colors.COLOR_NUMBER; }
  context.output += this._id;
  if (useColor) { context.output += colors.COLOR_RESET; }
  context.output += ', "';
  if (useColor) { context.output += colors.COLOR_STRING; }
  context.output += name || 'unknown';
  if (useColor) { context.output += colors.COLOR_RESET; }
  context.output += '" (type ' + type + ')]';
};

// /////////////////////////////////////////////////////////////////////////////
// @brief append the waitForSync parameter to a URL
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._appendSyncParameter = function (url, waitForSync) {
  if (waitForSync) {
    if (url.indexOf('?') === -1) {
      url += '?';
    }else {
      url += '&';
    }
    url += 'waitForSync=true';
  }
  return url;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief append some boolean parameter to a URL
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._appendBoolParameter = function (url, name, val) {
  if (url.indexOf('?') === -1) {
    url += '?';
  }else {
    url += '&';
  }
  url += name + (val ? '=true' : '=false');
  return url;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief prefix a URL with the database name of the view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._prefixurl = function (url) {
  if (url.substr(0, 5) === '/_db/') {
    return url;
  }

  if (url[0] === '/') {
    return this._dbPrefix + url;
  }
  return this._dbPrefix + '/' + url;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief return the base url for view usage
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._baseurl = function (suffix) {
  var url = this._database._viewurl(this.name());

  if (suffix) {
    url += '/' + suffix;
  }

  return this._prefixurl(url);
};

// /////////////////////////////////////////////////////////////////////////////
// @brief converts into an array
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.toArray = function () {
  return this.all().toArray();
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief print the help for ArangoView
// //////////////////////////////////////////////////////////////////////////////

var helpArangoView = arangosh.createHelpHeadline('ArangoView help') +
  'ArangoView constructor:                                             ' + '\n' +
  ' > view = db._view("myview");                                       ' + '\n' +
  ' > col = db._createView("myview", "type", {[properties]});          ' + '\n' +
  '                                                                          ' + '\n' +
  'Administration Functions:                                                 ' + '\n' +
  '  name()                                view name                   ' + '\n' +
  '  type()                                type of the view            ' + '\n' +
  '  properties()                          show view properties        ' + '\n' +
  '  drop()                                delete a view               ' + '\n' +
  '  _help()                               this help                         ' + '\n' +
  '                                                                          ' + '\n' +
  'Attributes:                                                               ' + '\n' +
  '  _database                             database object                   ' + '\n' +
  '  _id                                   view identifier             ';

ArangoView.prototype._help = function () {
  internal.print(helpArangoView);
};

// /////////////////////////////////////////////////////////////////////////////
// @brief gets the name of a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.name = function () {
  if (this._name === null) {
    this.refresh();
  }

  return this._name;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief gets the type of a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.type = function () {
  if (this._type === null) {
    this.refresh();
  }

  return this._type;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief gets or sets the properties of a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.properties = function (properties, partialUpdate) {
  var requestResult;

  if (properties === undefined) {
    requestResult = this._database._connection.GET(this._baseurl('properties'));
  } else if (partialUpdate === undefined || partialUpdate === true) {
    requestResult = this._database._connection.PATCH(
      this._baseurl('properties'), properties
    );
  } else {
    requestResult = this._database._connection.PUT(
      this._baseurl('properties'), properties
    );
  }

  arangosh.checkRequestResult(requestResult);

  const attributes = {
    'commit': true,
    'links': true,
    'locale': true
  };

  var result = {};
  for (let a in attributes) {
    if (attributes.hasOwnProperty(a) &&
      requestResult.hasOwnProperty(a) &&
      requestResult[a] !== undefined) {
      result[a] = requestResult[a];
    }
  }

  return result;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief drops a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.drop = function () {
  var requestResult;
  if (typeof options === 'object' && options.isSystem) {
    requestResult = this._database._connection.DELETE(this._baseurl() + '?isSystem=true');
  } else {
    requestResult = this._database._connection.DELETE(this._baseurl());
  }

  if (requestResult !== null
    && requestResult !== undefined
    && requestResult.error === true
    && requestResult.errorNum !== internal.errors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.code) {
    // check error in case we got anything else but "view not found"
    arangosh.checkRequestResult(requestResult);
  }

  var database = this._database;
  var name;

  for (name in database) {
    if (database.hasOwnProperty(name)) {
      var view = database[name];

      if (view instanceof ArangoView) {
        if (view.name() === this.name()) {
          delete database[name];
        }
      }
    }
  }
};

// /////////////////////////////////////////////////////////////////////////////
// @brief renames a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.rename = function (name) {
  var body = { name: name };
  var requestResult = this._database._connection.PUT(this._baseurl('rename'), body);

  arangosh.checkRequestResult(requestResult);

  delete this._database[this._name];
  this._database[name] = this;
  this._name = name;
};
<commit_msg>fixed jslint error<commit_after>/*jshint strict: false */

// /////////////////////////////////////////////////////////////////////////////
// @brief ArangoView
//
// @file
//
// DISCLAIMER
//
// Copyright 2013 triagens GmbH, Cologne, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright holder is triAGENS GmbH, Cologne, Germany
//
// @author Daniel H. Larkin
// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

const internal = require('internal');
const arangosh = require('@arangodb/arangosh');
const ArangoError = require('@arangodb').ArangoError;

// //////////////////////////////////////////////////////////////////////////////
// / @brief constructor
// //////////////////////////////////////////////////////////////////////////////

function ArangoView (database, data) {
  this._database = database;
  this._dbName = database._name();
  this._dbPrefix = '/_db/' + encodeURIComponent(database._name());

  if (typeof data === 'string') {
    this._id = null;
    this._name = data;
    this._type = null;
  }
  else if (data !== undefined) {
    this._id = data.id;
    this._name = data.name;
    this._type = data.type;
  } else {
    this._id = null;
    this._name = null;
    this._type = null;
  }
}

exports.ArangoView = ArangoView;

// /////////////////////////////////////////////////////////////////////////////
// @brief pretty print
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._PRINT = function (context) {
  const type = this.type();
  const name = this.name();

  const colors = internal.COLORS;
  const useColor = context.useColor;

  context.output += '[ArangoView ';
  if (useColor) { context.output += colors.COLOR_NUMBER; }
  context.output += this._id;
  if (useColor) { context.output += colors.COLOR_RESET; }
  context.output += ', "';
  if (useColor) { context.output += colors.COLOR_STRING; }
  context.output += name || 'unknown';
  if (useColor) { context.output += colors.COLOR_RESET; }
  context.output += '" (type ' + type + ')]';
};

// /////////////////////////////////////////////////////////////////////////////
// @brief append the waitForSync parameter to a URL
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._appendSyncParameter = function (url, waitForSync) {
  if (waitForSync) {
    if (url.indexOf('?') === -1) {
      url += '?';
    }else {
      url += '&';
    }
    url += 'waitForSync=true';
  }
  return url;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief append some boolean parameter to a URL
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._appendBoolParameter = function (url, name, val) {
  if (url.indexOf('?') === -1) {
    url += '?';
  }else {
    url += '&';
  }
  url += name + (val ? '=true' : '=false');
  return url;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief prefix a URL with the database name of the view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._prefixurl = function (url) {
  if (url.substr(0, 5) === '/_db/') {
    return url;
  }

  if (url[0] === '/') {
    return this._dbPrefix + url;
  }
  return this._dbPrefix + '/' + url;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief return the base url for view usage
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype._baseurl = function (suffix) {
  var url = this._database._viewurl(this.name());

  if (suffix) {
    url += '/' + suffix;
  }

  return this._prefixurl(url);
};

// /////////////////////////////////////////////////////////////////////////////
// @brief converts into an array
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.toArray = function () {
  return this.all().toArray();
};

// //////////////////////////////////////////////////////////////////////////////
// / @brief print the help for ArangoView
// //////////////////////////////////////////////////////////////////////////////

var helpArangoView = arangosh.createHelpHeadline('ArangoView help') +
  'ArangoView constructor:                                             ' + '\n' +
  ' > view = db._view("myview");                                       ' + '\n' +
  ' > col = db._createView("myview", "type", {[properties]});          ' + '\n' +
  '                                                                          ' + '\n' +
  'Administration Functions:                                                 ' + '\n' +
  '  name()                                view name                   ' + '\n' +
  '  type()                                type of the view            ' + '\n' +
  '  properties()                          show view properties        ' + '\n' +
  '  drop()                                delete a view               ' + '\n' +
  '  _help()                               this help                         ' + '\n' +
  '                                                                          ' + '\n' +
  'Attributes:                                                               ' + '\n' +
  '  _database                             database object                   ' + '\n' +
  '  _id                                   view identifier             ';

ArangoView.prototype._help = function () {
  internal.print(helpArangoView);
};

// /////////////////////////////////////////////////////////////////////////////
// @brief gets the name of a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.name = function () {
  if (this._name === null) {
    this.refresh();
  }

  return this._name;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief gets the type of a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.type = function () {
  if (this._type === null) {
    this.refresh();
  }

  return this._type;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief gets or sets the properties of a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.properties = function (properties, partialUpdate) {
  var requestResult;

  if (properties === undefined) {
    requestResult = this._database._connection.GET(this._baseurl('properties'));
  } else if (partialUpdate === undefined || partialUpdate === true) {
    requestResult = this._database._connection.PATCH(
      this._baseurl('properties'), properties
    );
  } else {
    requestResult = this._database._connection.PUT(
      this._baseurl('properties'), properties
    );
  }

  arangosh.checkRequestResult(requestResult);

  const attributes = {
    'commit': true,
    'links': true,
    'locale': true
  };

  var result = {};
  for (let a in attributes) {
    if (attributes.hasOwnProperty(a) &&
      requestResult.hasOwnProperty(a) &&
      requestResult[a] !== undefined) {
      result[a] = requestResult[a];
    }
  }

  return result;
};

// /////////////////////////////////////////////////////////////////////////////
// @brief drops a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.drop = function (options) {
  var requestResult;
  if (typeof options === 'object' && options.isSystem) {
    requestResult = this._database._connection.DELETE(this._baseurl() + '?isSystem=true');
  } else {
    requestResult = this._database._connection.DELETE(this._baseurl());
  }

  if (requestResult !== null
    && requestResult !== undefined
    && requestResult.error === true
    && requestResult.errorNum !== internal.errors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.code) {
    // check error in case we got anything else but "view not found"
    arangosh.checkRequestResult(requestResult);
  }

  var database = this._database;
  var name;

  for (name in database) {
    if (database.hasOwnProperty(name)) {
      var view = database[name];

      if (view instanceof ArangoView) {
        if (view.name() === this.name()) {
          delete database[name];
        }
      }
    }
  }
};

// /////////////////////////////////////////////////////////////////////////////
// @brief renames a view
// /////////////////////////////////////////////////////////////////////////////

ArangoView.prototype.rename = function (name) {
  var body = { name: name };
  var requestResult = this._database._connection.PUT(this._baseurl('rename'), body);

  arangosh.checkRequestResult(requestResult);

  delete this._database[this._name];
  this._database[name] = this;
  this._name = name;
};
<|endoftext|>


<commit_before><commit_msg>Removed ionicPopup.js directive for #82<commit_after><|endoftext|>


<commit_before>// Copyright 2019-2020, University of Colorado Boulder

/**
 * Launch an instance of the simulation using puppeteer, gather the phet-io api of the simulation, see phetioEngine.getPhetioElementsBaseline
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Chris Klusendorf (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */

'use strict';

const puppeteer = require( 'puppeteer' );
const fs = require( 'fs' );

/**
 * @param {string} repo
 * @param {string} localTestingURL - the browser url to access the root of phet repos
 */
module.exports = async ( repo, localTestingURL ) => {

  return new Promise( async ( resolve, reject ) => {

    const phetioDirectory = 'js/phet-io';
    const baselineFileName = `${phetioDirectory}/${repo}-phet-io-elements-baseline.js`;
    const overridesFileName = `${phetioDirectory}/${repo}-phet-io-elements-overrides.js`;
    const typesFileName = `${phetioDirectory}/${repo}-phet-io-types.js`;

    if ( !fs.existsSync( phetioDirectory ) ) {
      fs.mkdirSync( phetioDirectory );
    }

    // empty the current baseline file so we know that a stale version is not left behind
    fs.writeFileSync( baselineFileName, '/* eslint-disable */' );

    // if there is already an overrides file, don't overwrite it with an empty one
    if ( !fs.existsSync( overridesFileName ) ) {
      fs.writeFileSync( overridesFileName,
        '/* eslint-disable */\nwindow.phet.preloads.phetio.phetioElementsOverrides = {};' );
    }

    let receivedBaseline = false;
    let receivedTypes = false;

    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    page.on( 'console', async msg => {
      if ( msg.text().indexOf( 'window.phet.preloads.phetio.phetioElementsBaseline' ) >= 0 ) {
        fs.writeFileSync( baselineFileName, msg.text() );
        receivedBaseline = true;
        await resolved();
      }

      else if ( msg.text().indexOf( 'window.phet.preloads.phetio.phetioTypes' ) >= 0 ) {
        fs.writeFileSync( typesFileName, msg.text() );
        receivedTypes = true;
        await resolved();
      }
      else if ( msg.type() === 'error' ) {
        const location = msg.location ? msg.location().url : '';
        console.error( 'Error from sim:', msg.text(), location );
      }
    } );

    const resolved = async () => {
      if ( receivedBaseline && receivedTypes ) {
        await browser.close();
        resolve();
      }
    };

    page.on( 'error', msg => reject( msg ) );
    page.on( 'pageerror', msg => reject( msg ) );

    try {
      await page.goto( `${localTestingURL}${repo}/${repo}_en.html?brand=phet-io&phetioStandalone&phetioPrintPhetioFiles` );
    }
    catch( e ) {
      reject( e );
    }
  } );
};
<commit_msg>Put error location on new line, see https://github.com/phetsims/chipper/issues/928<commit_after>// Copyright 2019-2020, University of Colorado Boulder

/**
 * Launch an instance of the simulation using puppeteer, gather the phet-io api of the simulation, see phetioEngine.getPhetioElementsBaseline
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Chris Klusendorf (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */

'use strict';

const puppeteer = require( 'puppeteer' );
const fs = require( 'fs' );

/**
 * @param {string} repo
 * @param {string} localTestingURL - the browser url to access the root of phet repos
 */
module.exports = async ( repo, localTestingURL ) => {

  return new Promise( async ( resolve, reject ) => {

    const phetioDirectory = 'js/phet-io';
    const baselineFileName = `${phetioDirectory}/${repo}-phet-io-elements-baseline.js`;
    const overridesFileName = `${phetioDirectory}/${repo}-phet-io-elements-overrides.js`;
    const typesFileName = `${phetioDirectory}/${repo}-phet-io-types.js`;

    if ( !fs.existsSync( phetioDirectory ) ) {
      fs.mkdirSync( phetioDirectory );
    }

    // empty the current baseline file so we know that a stale version is not left behind
    fs.writeFileSync( baselineFileName, '/* eslint-disable */' );

    // if there is already an overrides file, don't overwrite it with an empty one
    if ( !fs.existsSync( overridesFileName ) ) {
      fs.writeFileSync( overridesFileName,
        '/* eslint-disable */\nwindow.phet.preloads.phetio.phetioElementsOverrides = {};' );
    }

    let receivedBaseline = false;
    let receivedTypes = false;

    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    page.on( 'console', async msg => {
      if ( msg.text().indexOf( 'window.phet.preloads.phetio.phetioElementsBaseline' ) >= 0 ) {
        fs.writeFileSync( baselineFileName, msg.text() );
        receivedBaseline = true;
        await resolved();
      }

      else if ( msg.text().indexOf( 'window.phet.preloads.phetio.phetioTypes' ) >= 0 ) {
        fs.writeFileSync( typesFileName, msg.text() );
        receivedTypes = true;
        await resolved();
      }
      else if ( msg.type() === 'error' ) {
        const location = msg.location ? ':\n  ' + msg.location().url : '';
        const message = msg.text() + location;
        console.error( 'Error from sim:', message );
      }
    } );

    const resolved = async () => {
      if ( receivedBaseline && receivedTypes ) {
        await browser.close();
        resolve();
      }
    };

    page.on( 'error', msg => reject( msg ) );
    page.on( 'pageerror', msg => reject( msg ) );

    try {
      await page.goto( `${localTestingURL}${repo}/${repo}_en.html?brand=phet-io&phetioStandalone&phetioPrintPhetioFiles` );
    }
    catch( e ) {
      reject( e );
    }
  } );
};
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.addPost', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/addPost', {
        templateUrl: 'addPost/addPost.html',
        controller: 'AddPostCtrl'
    });
}])

.controller('AddPostCtrl', ['$scope','$firebase','CommonProp', function($scope,$firebase,CommonProp) {
	var firebaseObj = new Firebase("https://angbase-tutorial.firebaseio.com/Articles");
    var fb = $firebase(firebaseObj);

    $scope.AddPost = function() {
      	var title = $scope.article.title;
		var post = $scope.article.post;

 		fb.$push({
		    title: title,
		    post: post,
        	emailId: CommonProp.getUser()
		}).then(function(ref) {
		    console.log(ref);
		}, function(error) {
		    console.log("Error:", error);
		});
    }
}]);<commit_msg>Added redirect after new post<commit_after>'use strict';

angular.module('myApp.addPost', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/addPost', {
        templateUrl: 'addPost/addPost.html',
        controller: 'AddPostCtrl'
    });
}])

.controller('AddPostCtrl', ['$scope','$firebase','CommonProp','$location', function($scope,$firebase,CommonProp,$location) {
	var firebaseObj = new Firebase("https://angbase-tutorial.firebaseio.com/Articles");
    var fb = $firebase(firebaseObj);

    $scope.AddPost = function() {
      	var title = $scope.article.title;
		var post = $scope.article.post;

 		fb.$push({
		    title: title,
		    post: post,
        	emailId: CommonProp.getUser()
		}).then(function(ref) {
		    console.log(ref);
		    $location.path('/welcome');
		}, function(error) {
		    console.log("Error:", error);
		});
    }
}]);<|endoftext|>


<commit_before>/**
 * EditorManager.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 */

(function(tinymce) {
	// Shorten names
	var each = tinymce.each, extend = tinymce.extend,
		DOM = tinymce.DOM, Event = tinymce.dom.Event,
		ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,
		explode = tinymce.explode,
		Dispatcher = tinymce.util.Dispatcher;

	// Setup some URLs where the editor API is located and where the document is
	tinymce.documentBaseURL = window.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
	if (!/[\/\\]$/.test(tinymce.documentBaseURL))
		tinymce.documentBaseURL += '/';

	// Setup baseURL/baseURI
	tinymce.baseURL = new tinymce.util.URI(tinymce.documentBaseURL).toAbsolute(tinymce.baseURL);
	tinymce.baseURI = new tinymce.util.URI(tinymce.baseURL);

	// Add before unload listener
	// This was required since IE was leaking memory if you added and removed beforeunload listeners
	// with attachEvent/detatchEvent so this only adds one listener and instances can the attach to the onBeforeUnload event
	tinymce.onBeforeUnload = new Dispatcher(tinymce);

	// Must be on window or IE will leak if the editor is placed in frame or iframe
	Event.add(window, 'beforeunload', function(e) {
		tinymce.onBeforeUnload.dispatch(tinymce, e);
	});

	/**
	 * Fires when a new editor instance is added to the tinymce collection.
	 *
	 * @event onAddEditor
	 * @param {tinymce} sender Editor instance.
	 */
	tinymce.onAddEditor = new Dispatcher(tinymce);

	/**
	 * Fires when an editor instance is removed from the tinymce collection.
	 *
	 * @event onRemoveEditor
	 * @param {tinymce} sender Editor instance.
	 */
	tinymce.onRemoveEditor = new Dispatcher(tinymce);

	/**
	 * This class is used to create multiple editor instances and contain them in a collection. So it's both a factory and a manager for editor instances.
	 *
	 * @static
	 * @class tinymce.EditorManager
	 */
	tinymce.EditorManager = extend(tinymce, {
		/**
		 * Collection of editor instances.
		 *
		 * @property editors
		 * @type Object
		 */
		editors : [],

		i18n : {},

		/**
		 * Currently active editor instance.
		 *
		 * @property activeEditor
		 * @type tinymce.Editor
		 */
		activeEditor : null,

		/**
		 * Initializes a set of editors. This method will create a bunch of editors based in the input.
		 *
		 * @method init
		 * @param {Object} s Settings object to be passed to each editor instance.
		 */
		init : function(s) {
			var t = this, pl, sl = tinymce.ScriptLoader, c, e, el = [], ed;

			function execCallback(se, n, s) {
				var f = se[n];

				if (!f)
					return;

				if (tinymce.is(f, 'string')) {
					s = f.replace(/\.\w+$/, '');
					s = s ? tinymce.resolve(s) : 0;
					f = tinymce.resolve(f);
				}

				return f.apply(s || this, Array.prototype.slice.call(arguments, 2));
			};

			s = extend({
				theme : "simple",
				language : "en"
			}, s);

			t.settings = s;

			// Legacy call
			Event.add(document, 'init', function() {
				var l, co;

				execCallback(s, 'onpageload');

				switch (s.mode) {
					case "exact":
						l = s.elements || '';

						if(l.length > 0) {
							each(explode(l), function(v) {
								if (DOM.get(v)) {
									ed = new tinymce.Editor(v, s);
									el.push(ed);
									ed.render(1);
								} else {
									c = 0;

									each(document.forms, function(f) {
										each(f.elements, function(e) {
											if (e.name === v) {
												v = 'mce_editor_' + c;
												DOM.setAttrib(e, 'id', v);

												ed = new tinymce.Editor(v, s);
												el.push(ed);
												ed.render(1);
											}
										});
									});
								}
							});
						}
						break;

					case "textareas":
					case "specific_textareas":
						function hasClass(n, c) {
							return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c);
						};

						each(DOM.select('textarea'), function(v) {
							if (s.editor_deselector && hasClass(v, s.editor_deselector))
								return;

							if (!s.editor_selector || hasClass(v, s.editor_selector)) {
								// Can we use the name
								e = DOM.get(v.name);
								if (!v.id && !e)
									v.id = v.name;

								// Generate unique name if missing or already exists
								if (!v.id || t.get(v.id))
									v.id = DOM.uniqueId();

								ed = new tinymce.Editor(v.id, s);
								el.push(ed);
								ed.render(1);
							}
						});
						break;
				}

				// Call onInit when all editors are initialized
				if (s.oninit) {
					l = co = 0;

					each (el, function(ed) {
						co++;

						if (!ed.initialized) {
							// Wait for it
							ed.onInit.add(function() {
								l++;

								// All done
								if (l == co)
									execCallback(s, 'oninit');
							});
						} else
							l++;

						// All done
						if (l == co)
							execCallback(s, 'oninit');
					});
				}
			});
		},

		/**
		 * Returns a editor instance by id.
		 *
		 * @method get
		 * @param {String} id Editor instance id to return.
		 * @return {tinymce.Editor} Editor instance to return.
		 */
		get : function(id) {
			if (!id)
				return this.editors;

			return this.editors[id];
		},

		/**
		 * Returns a editor instance by id. This method was added for compatibility with the 2.x branch.
		 *
		 * @method getInstanceById
		 * @param {String} id Editor instance id to return.
		 * @return {tinymce.Editor} Editor instance to return.
		 * @deprecated Use get method instead.
		 * @see #get
		 */
		getInstanceById : function(id) {
			return this.get(id);
		},

		/**
		 * Adds an editor instance to the editor collection. This will also set it as the active editor.
		 *
		 * @method add
		 * @param {tinymce.Editor} editor Editor instance to add to the collection.
		 * @return {tinymce.Editor} The same instance that got passed in.
		 */
		add : function(editor) {
			var self = this, editors = self.editors;

			// Add named and index editor instance
			editors[editor.id] = editor;
			editors.push(editor);

			self._setActive(editor);
			self.onAddEditor.dispatch(self, editor);

			return editor;
		},

		/**
		 * Removes a editor instance from the collection.
		 *
		 * @method remove
		 * @param {tinymce.Editor} e Editor instance to remove.
		 * @return {tinymce.Editor} The editor that got passed in will be return if it was found otherwise null.
		 */
		remove : function(editor) {
			var t = this, i, editors = t.editors;

			// Not in the collection
			if (!editors[editor.id])
				return null;

			delete editors[editor.id];

			for (i = 0; i < editors.length; i++) {
				if (editors[i] == editor) {
					editors.splice(i, 1);
					break;
				}
			}

			// Select another editor since the active one was removed
			if (t.activeEditor == editor)
				t._setActive(editors[0]);

			editor.destroy();
			t.onRemoveEditor.dispatch(t, editor);

			return editor;
		},

		/**
		 * Executes a specific command on the currently active editor.
		 *
		 * @method execCommand
		 * @param {String} c Command to perform for example Bold.
		 * @param {Boolean} u Optional boolean state if a UI should be presented for the command or not.
		 * @param {String} v Optional value parameter like for example an URL to a link.
		 * @return {Boolean} true/false if the command was executed or not.
		 */
		execCommand : function(c, u, v) {
			var t = this, ed = t.get(v), w;

			// Manager commands
			switch (c) {
				case "mceFocus":
					ed.focus();
					return true;

				case "mceAddEditor":
				case "mceAddControl":
					if (!t.get(v))
						new tinymce.Editor(v, t.settings).render();

					return true;

				case "mceAddFrameControl":
					w = v.window;

					// Add tinyMCE global instance and tinymce namespace to specified window
					w.tinyMCE = tinyMCE;
					w.tinymce = tinymce;

					tinymce.DOM.doc = w.document;
					tinymce.DOM.win = w;

					ed = new tinymce.Editor(v.element_id, v);
					ed.render();

					// Fix IE memory leaks
					if (tinymce.isIE) {
						function clr() {
							ed.destroy();
							w.detachEvent('onunload', clr);
							w = w.tinyMCE = w.tinymce = null; // IE leak
						};

						w.attachEvent('onunload', clr);
					}

					v.page_window = null;

					return true;

				case "mceRemoveEditor":
				case "mceRemoveControl":
					if (ed)
						ed.remove();

					return true;

				case 'mceToggleEditor':
					if (!ed) {
						t.execCommand('mceAddControl', 0, v);
						return true;
					}

					if (ed.isHidden())
						ed.show();
					else
						ed.hide();

					return true;
			}

			// Run command on active editor
			if (t.activeEditor)
				return t.activeEditor.execCommand(c, u, v);

			return false;
		},

		/**
		 * Executes a command on a specific editor by id. This method was added for compatibility with the 2.x branch.
		 *
		 * @deprecated Use the execCommand method of a editor instance instead.
		 * @method execInstanceCommand
		 * @param {String} id Editor id to perform the command on.
		 * @param {String} c Command to perform for example Bold.
		 * @param {Boolean} u Optional boolean state if a UI should be presented for the command or not.
		 * @param {String} v Optional value parameter like for example an URL to a link.
		 * @return {Boolean} true/false if the command was executed or not.
		 */
		execInstanceCommand : function(id, c, u, v) {
			var ed = this.get(id);

			if (ed)
				return ed.execCommand(c, u, v);

			return false;
		},

		/**
		 * Calls the save method on all editor instances in the collection. This can be useful when a form is to be submitted.
		 *
		 * @method triggerSave
		 */
		triggerSave : function() {
			each(this.editors, function(e) {
				e.save();
			});
		},

		/**
		 * Adds a language pack, this gets called by the loaded language files like en.js.
		 *
		 * @method addI18n
		 * @param {String} p Prefix for the language items. For example en.myplugin
		 * @param {Object} o Name/Value collection with items to add to the language group.
		 */
		addI18n : function(p, o) {
			var lo, i18n = this.i18n;

			if (!tinymce.is(p, 'string')) {
				each(p, function(o, lc) {
					each(o, function(o, g) {
						each(o, function(o, k) {
							if (g === 'common')
								i18n[lc + '.' + k] = o;
							else
								i18n[lc + '.' + g + '.' + k] = o;
						});
					});
				});
			} else {
				each(o, function(o, k) {
					i18n[p + '.' + k] = o;
				});
			}
		},

		// Private methods

		_setActive : function(editor) {
			this.selectedInstance = this.activeEditor = editor;
		}
	});
})(tinymce);

/**
 * Shorter version of tinymce.EditorManager also added for 2.x compatibility.
 *
 * @member
 * @property tinyMCE
 * @type tinymce.EditorManager
 */
<commit_msg>Fixed issue where a zero based index to tinymce.get would result in an array of editors.<commit_after>/**
 * EditorManager.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 */

(function(tinymce) {
	// Shorten names
	var each = tinymce.each, extend = tinymce.extend,
		DOM = tinymce.DOM, Event = tinymce.dom.Event,
		ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,
		explode = tinymce.explode,
		Dispatcher = tinymce.util.Dispatcher, undefined;

	// Setup some URLs where the editor API is located and where the document is
	tinymce.documentBaseURL = window.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
	if (!/[\/\\]$/.test(tinymce.documentBaseURL))
		tinymce.documentBaseURL += '/';

	// Setup baseURL/baseURI
	tinymce.baseURL = new tinymce.util.URI(tinymce.documentBaseURL).toAbsolute(tinymce.baseURL);
	tinymce.baseURI = new tinymce.util.URI(tinymce.baseURL);

	// Add before unload listener
	// This was required since IE was leaking memory if you added and removed beforeunload listeners
	// with attachEvent/detatchEvent so this only adds one listener and instances can the attach to the onBeforeUnload event
	tinymce.onBeforeUnload = new Dispatcher(tinymce);

	// Must be on window or IE will leak if the editor is placed in frame or iframe
	Event.add(window, 'beforeunload', function(e) {
		tinymce.onBeforeUnload.dispatch(tinymce, e);
	});

	/**
	 * Fires when a new editor instance is added to the tinymce collection.
	 *
	 * @event onAddEditor
	 * @param {tinymce} sender Editor instance.
	 */
	tinymce.onAddEditor = new Dispatcher(tinymce);

	/**
	 * Fires when an editor instance is removed from the tinymce collection.
	 *
	 * @event onRemoveEditor
	 * @param {tinymce} sender Editor instance.
	 */
	tinymce.onRemoveEditor = new Dispatcher(tinymce);

	/**
	 * This class is used to create multiple editor instances and contain them in a collection. So it's both a factory and a manager for editor instances.
	 *
	 * @static
	 * @class tinymce.EditorManager
	 */
	tinymce.EditorManager = extend(tinymce, {
		/**
		 * Collection of editor instances.
		 *
		 * @property editors
		 * @type Object
		 */
		editors : [],

		i18n : {},

		/**
		 * Currently active editor instance.
		 *
		 * @property activeEditor
		 * @type tinymce.Editor
		 */
		activeEditor : null,

		/**
		 * Initializes a set of editors. This method will create a bunch of editors based in the input.
		 *
		 * @method init
		 * @param {Object} s Settings object to be passed to each editor instance.
		 */
		init : function(s) {
			var t = this, pl, sl = tinymce.ScriptLoader, c, e, el = [], ed;

			function execCallback(se, n, s) {
				var f = se[n];

				if (!f)
					return;

				if (tinymce.is(f, 'string')) {
					s = f.replace(/\.\w+$/, '');
					s = s ? tinymce.resolve(s) : 0;
					f = tinymce.resolve(f);
				}

				return f.apply(s || this, Array.prototype.slice.call(arguments, 2));
			};

			s = extend({
				theme : "simple",
				language : "en"
			}, s);

			t.settings = s;

			// Legacy call
			Event.add(document, 'init', function() {
				var l, co;

				execCallback(s, 'onpageload');

				switch (s.mode) {
					case "exact":
						l = s.elements || '';

						if(l.length > 0) {
							each(explode(l), function(v) {
								if (DOM.get(v)) {
									ed = new tinymce.Editor(v, s);
									el.push(ed);
									ed.render(1);
								} else {
									c = 0;

									each(document.forms, function(f) {
										each(f.elements, function(e) {
											if (e.name === v) {
												v = 'mce_editor_' + c;
												DOM.setAttrib(e, 'id', v);

												ed = new tinymce.Editor(v, s);
												el.push(ed);
												ed.render(1);
											}
										});
									});
								}
							});
						}
						break;

					case "textareas":
					case "specific_textareas":
						function hasClass(n, c) {
							return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c);
						};

						each(DOM.select('textarea'), function(v) {
							if (s.editor_deselector && hasClass(v, s.editor_deselector))
								return;

							if (!s.editor_selector || hasClass(v, s.editor_selector)) {
								// Can we use the name
								e = DOM.get(v.name);
								if (!v.id && !e)
									v.id = v.name;

								// Generate unique name if missing or already exists
								if (!v.id || t.get(v.id))
									v.id = DOM.uniqueId();

								ed = new tinymce.Editor(v.id, s);
								el.push(ed);
								ed.render(1);
							}
						});
						break;
				}

				// Call onInit when all editors are initialized
				if (s.oninit) {
					l = co = 0;

					each (el, function(ed) {
						co++;

						if (!ed.initialized) {
							// Wait for it
							ed.onInit.add(function() {
								l++;

								// All done
								if (l == co)
									execCallback(s, 'oninit');
							});
						} else
							l++;

						// All done
						if (l == co)
							execCallback(s, 'oninit');
					});
				}
			});
		},

		/**
		 * Returns a editor instance by id.
		 *
		 * @method get
		 * @param {String} id Editor instance id to return.
		 * @return {tinymce.Editor} Editor instance to return.
		 */
		get : function(id) {
			if (id === undefined)
				return this.editors;

			return this.editors[id];
		},

		/**
		 * Returns a editor instance by id. This method was added for compatibility with the 2.x branch.
		 *
		 * @method getInstanceById
		 * @param {String} id Editor instance id to return.
		 * @return {tinymce.Editor} Editor instance to return.
		 * @deprecated Use get method instead.
		 * @see #get
		 */
		getInstanceById : function(id) {
			return this.get(id);
		},

		/**
		 * Adds an editor instance to the editor collection. This will also set it as the active editor.
		 *
		 * @method add
		 * @param {tinymce.Editor} editor Editor instance to add to the collection.
		 * @return {tinymce.Editor} The same instance that got passed in.
		 */
		add : function(editor) {
			var self = this, editors = self.editors;

			// Add named and index editor instance
			editors[editor.id] = editor;
			editors.push(editor);

			self._setActive(editor);
			self.onAddEditor.dispatch(self, editor);

			return editor;
		},

		/**
		 * Removes a editor instance from the collection.
		 *
		 * @method remove
		 * @param {tinymce.Editor} e Editor instance to remove.
		 * @return {tinymce.Editor} The editor that got passed in will be return if it was found otherwise null.
		 */
		remove : function(editor) {
			var t = this, i, editors = t.editors;

			// Not in the collection
			if (!editors[editor.id])
				return null;

			delete editors[editor.id];

			for (i = 0; i < editors.length; i++) {
				if (editors[i] == editor) {
					editors.splice(i, 1);
					break;
				}
			}

			// Select another editor since the active one was removed
			if (t.activeEditor == editor)
				t._setActive(editors[0]);

			editor.destroy();
			t.onRemoveEditor.dispatch(t, editor);

			return editor;
		},

		/**
		 * Executes a specific command on the currently active editor.
		 *
		 * @method execCommand
		 * @param {String} c Command to perform for example Bold.
		 * @param {Boolean} u Optional boolean state if a UI should be presented for the command or not.
		 * @param {String} v Optional value parameter like for example an URL to a link.
		 * @return {Boolean} true/false if the command was executed or not.
		 */
		execCommand : function(c, u, v) {
			var t = this, ed = t.get(v), w;

			// Manager commands
			switch (c) {
				case "mceFocus":
					ed.focus();
					return true;

				case "mceAddEditor":
				case "mceAddControl":
					if (!t.get(v))
						new tinymce.Editor(v, t.settings).render();

					return true;

				case "mceAddFrameControl":
					w = v.window;

					// Add tinyMCE global instance and tinymce namespace to specified window
					w.tinyMCE = tinyMCE;
					w.tinymce = tinymce;

					tinymce.DOM.doc = w.document;
					tinymce.DOM.win = w;

					ed = new tinymce.Editor(v.element_id, v);
					ed.render();

					// Fix IE memory leaks
					if (tinymce.isIE) {
						function clr() {
							ed.destroy();
							w.detachEvent('onunload', clr);
							w = w.tinyMCE = w.tinymce = null; // IE leak
						};

						w.attachEvent('onunload', clr);
					}

					v.page_window = null;

					return true;

				case "mceRemoveEditor":
				case "mceRemoveControl":
					if (ed)
						ed.remove();

					return true;

				case 'mceToggleEditor':
					if (!ed) {
						t.execCommand('mceAddControl', 0, v);
						return true;
					}

					if (ed.isHidden())
						ed.show();
					else
						ed.hide();

					return true;
			}

			// Run command on active editor
			if (t.activeEditor)
				return t.activeEditor.execCommand(c, u, v);

			return false;
		},

		/**
		 * Executes a command on a specific editor by id. This method was added for compatibility with the 2.x branch.
		 *
		 * @deprecated Use the execCommand method of a editor instance instead.
		 * @method execInstanceCommand
		 * @param {String} id Editor id to perform the command on.
		 * @param {String} c Command to perform for example Bold.
		 * @param {Boolean} u Optional boolean state if a UI should be presented for the command or not.
		 * @param {String} v Optional value parameter like for example an URL to a link.
		 * @return {Boolean} true/false if the command was executed or not.
		 */
		execInstanceCommand : function(id, c, u, v) {
			var ed = this.get(id);

			if (ed)
				return ed.execCommand(c, u, v);

			return false;
		},

		/**
		 * Calls the save method on all editor instances in the collection. This can be useful when a form is to be submitted.
		 *
		 * @method triggerSave
		 */
		triggerSave : function() {
			each(this.editors, function(e) {
				e.save();
			});
		},

		/**
		 * Adds a language pack, this gets called by the loaded language files like en.js.
		 *
		 * @method addI18n
		 * @param {String} p Prefix for the language items. For example en.myplugin
		 * @param {Object} o Name/Value collection with items to add to the language group.
		 */
		addI18n : function(p, o) {
			var lo, i18n = this.i18n;

			if (!tinymce.is(p, 'string')) {
				each(p, function(o, lc) {
					each(o, function(o, g) {
						each(o, function(o, k) {
							if (g === 'common')
								i18n[lc + '.' + k] = o;
							else
								i18n[lc + '.' + g + '.' + k] = o;
						});
					});
				});
			} else {
				each(o, function(o, k) {
					i18n[p + '.' + k] = o;
				});
			}
		},

		// Private methods

		_setActive : function(editor) {
			this.selectedInstance = this.activeEditor = editor;
		}
	});
})(tinymce);

/**
 * Shorter version of tinymce.EditorManager also added for 2.x compatibility.
 *
 * @member
 * @property tinyMCE
 * @type tinymce.EditorManager
 */
<|endoftext|>


<commit_before>'use strict';
angular
  .module('PitchEvaluator')
  .controller('addTeamCtrl', function($rootScope, $scope, $firebaseObject, $firebaseArray, $location, db_url) {
    // var ref = new Firebase("https://pitchevaluator.firebaseio.com/team");
    $scope.name = "";
    $scope.product = "";
    $scope.desc = "";
    $scope.teamPass = ""

    class Team {
      constructor(name,product,desc, teamPass) {
        this.name=name;
        this.product=product;
        this.desc=desc;
        this.teamPass = teamPass;
        this.avg1 = 0;
        this.avg2 = 0;
        this.avg3 = 0;
        this.avg4 = 0;
        this.avgYes = 0;
        this.ovrAvg = 0;
        this.rank = 0;
      }
      parse() {
        var temp = {
          name: this.name,
          product: this.product,
          desc: this.desc,
          avg1: this.avg1,
          avg2: this.avg2,
          avg3: this.avg3,
          avg4: this.avg4,
          avgYes: this.avgYes,
          ovrAvg: this.ovrAvg
        }
        return temp;
      }
    }

    $scope.addTeam = function() {

      if (!$rootScope.session) {
        return ('Invalid or No Session');
      }
      var newTeam = new Team($scope.name,$scope.product,$scope.desc, $scope.teamPass);
      var ref = new Firebase($rootScope.sessionRef);
      ref.once("value", function(snapshot) {
        var count = snapshot.child("teams").numChildren();
        newTeam.rank = count+1;
        ref.child('teams').push(newTeam);
        $location.path('#/view1');
      });

      // var ref = new Firebase(db_url + "/sessions");
      // var sessArr = new $firebaseArray(ref);

      // sessArr.$loaded(function() {
      //   sessArr.forEach(function(session) {
      //     if (session.name == $rootScope.session) {
      //       var newTeam = new Team($scope.name,$scope.product,$scope.desc);
      //
      //       var key = sessArr.$keyAt(session);
      //       var specificSession = new Firebase(ref + "/" + key);
      //       specificSession.child('teams').push(newTeam);
      //       $location.path('#/view1');
      //     }
      //   });
      // });

      // console.log($scope.name);
      // console.log($scope.product);
      // console.log($scope.desc);
      // $location.path('#/view1');
    }

  });
<commit_msg>Added functionality for checking if team already exists<commit_after>'use strict';
angular
  .module('PitchEvaluator')
  .controller('addTeamCtrl', function($rootScope, $scope, $firebaseObject, $firebaseArray, $location, db_url) {
    // var ref = new Firebase("https://pitchevaluator.firebaseio.com/team");
    $scope.name = "";
    $scope.product = "";
    $scope.desc = "";
    $scope.teamPass = ""

    class Team {
      constructor(name,product,desc, teamPass) {
        this.name=name;
        this.product=product;
        this.desc=desc;
        this.teamPass = teamPass;
        this.avg1 = 0;
        this.avg2 = 0;
        this.avg3 = 0;
        this.avg4 = 0;
        this.avgYes = 0;
        this.ovrAvg = 0;
        this.rank = 0;
      }
      parse() {
        var temp = {
          name: this.name,
          product: this.product,
          desc: this.desc,
          avg1: this.avg1,
          avg2: this.avg2,
          avg3: this.avg3,
          avg4: this.avg4,
          avgYes: this.avgYes,
          ovrAvg: this.ovrAvg
        }
        return temp;
      }
    }

    $scope.addTeam = function() {

      if (!$rootScope.session) {
        throw new Error('Invalid or No Session');
        return;
      }
      var newTeam = new Team($scope.name,$scope.product,$scope.desc, $scope.teamPass);
      var ref = new Firebase($rootScope.sessionRef);
      ref.once("value", function(snapshot) {
        var count = snapshot.child("teams").numChildren();
        newTeam.rank = count+1;
        var refTeams = new Firebase($rootScope.sessionRef + "/teams")
        var teams = new $firebaseArray(refTeams);
        teams.$loaded(function() {
          var exists = false;
          teams.forEach(function(team) {
            if (exists) return;
            if (team.name==$scope.name) {
              exists = true;
              return;
            }
          });
          if (exists) {
            throw new Error('Team already exists');
          }
          else {
            ref.child('teams').push(newTeam);
            $location.path('#/view1');
          }
        });
      });

      // var ref = new Firebase(db_url + "/sessions");
      // var sessArr = new $firebaseArray(ref);

      // sessArr.$loaded(function() {
      //   sessArr.forEach(function(session) {
      //     if (session.name == $rootScope.session) {
      //       var newTeam = new Team($scope.name,$scope.product,$scope.desc);
      //
      //       var key = sessArr.$keyAt(session);
      //       var specificSession = new Firebase(ref + "/" + key);
      //       specificSession.child('teams').push(newTeam);
      //       $location.path('#/view1');
      //     }
      //   });
      // });

      // console.log($scope.name);
      // console.log($scope.product);
      // console.log($scope.desc);
      // $location.path('#/view1');
    }

  });
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Longtail Ad Solutions Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 **/

var VERSION = '1.0.6';
var OPTIONS, CONFIG;

/** Launch the app **/
App.onLaunch = function(opts) {
  OPTIONS = opts;
  console.log("Initing with options %o", OPTIONS);

  var scripts = [
    `${OPTIONS.baseURL}/js/utils/Utils.js`,
    `${OPTIONS.baseURL}/js/utils/Promise.js`,
    `${OPTIONS.baseURL}/js/utils/Http.js`,
    `${OPTIONS.baseURL}/js/events/EventBus.js`,
    `${OPTIONS.baseURL}/js/events/Events.js`,
    `${OPTIONS.baseURL}/js/ConfigLoader.js`,
    `${OPTIONS.baseURL}/js/he.js`,
    `${OPTIONS.baseURL}/js/TemplateLoader.js`,
    `${OPTIONS.baseURL}/js/ViewManager.js`,
    `${OPTIONS.baseURL}/js/playlist/PlaylistParser.js`,
    `${OPTIONS.baseURL}/js/playlist/PlaylistLoader.js`,
    `${OPTIONS.baseURL}/js/feeds/FeedLoader.js`,
    `${OPTIONS.baseURL}/js/playlist/PlaylistManager.js`,
    `${OPTIONS.baseURL}/js/analytics/TVOSAnalytics.js`,
    `${OPTIONS.baseURL}/js/playback/PlayerStates.js`,
    `${OPTIONS.baseURL}/js/playback/Playback.js`,
    `${OPTIONS.baseURL}/js/playback/AutoAdvance.js`
  ];

  evaluateScripts(scripts, function(success) {
    if (success) {
      configLoader = new ConfigLoader();
      configLoader.loadConfig(OPTIONS.account_key, configLoaded);
    } else {
      showAlert("Error", "Unable to evaluate scripts.")
    }
  });

}

App.onResume = function() {
  reloadPlaylists();
}

function reloadPlaylists() {
  PlaylistManager.reset();
  var templateLoader = new TemplateLoader();
  templateLoader.load("templates/ListCollection.tvml", function (templateDoc) {
    // Replace all the ListCollection docs on the stack.
    navigationDocument.documents.forEach(function (doc) {
      if (doc.firstChild) {
        var view = doc.firstChild.getAttribute("data-view");
        if (view && view === 'ListCollection') {
          navigationDocument.replaceDocument(templateDoc, doc);
        }
      }
    });
  });
}

function configLoaded(config) {
  CONFIG = config;
  EventBus.publish(Events.CONFIG_LOADED, {
    config: CONFIG
  });
  var templateLoader = new TemplateLoader();
  templateLoader.load("templates/index.tvml", function(templateDoc) {
    navigationDocument.pushDocument(templateDoc);
  });
}

function resetApp() {
  while (navigationDocument.documents.length > 0) {
    navigationDocument.removeDocument(navigationDocument.documents[0]);
  }
  App.onLaunch(OPTIONS);
}

function showAlert(alertTitle, alertText) {
  var alertTVML = `<?xml version="1.0" encoding="UTF-8" ?>
<document>
  <alertTemplate>
    <title>${alertTitle}</title>
    <description>${alertText}</description>
  </alertTemplate>
</document>`;

  var domParser = new DOMParser();
  var alertDoc = domParser.parseFromString(alertTVML, "application/xml");
  navigationDocument.pushDocument(alertDoc);
}
<commit_msg>Bumped the version number to 1.0.7<commit_after>/**
 * Copyright 2015 Longtail Ad Solutions Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 **/

var VERSION = '1.0.7';
var OPTIONS, CONFIG;

/** Launch the app **/
App.onLaunch = function(opts) {
  OPTIONS = opts;
  console.log("Initing with options %o", OPTIONS);

  var scripts = [
    `${OPTIONS.baseURL}/js/utils/Utils.js`,
    `${OPTIONS.baseURL}/js/utils/Promise.js`,
    `${OPTIONS.baseURL}/js/utils/Http.js`,
    `${OPTIONS.baseURL}/js/events/EventBus.js`,
    `${OPTIONS.baseURL}/js/events/Events.js`,
    `${OPTIONS.baseURL}/js/ConfigLoader.js`,
    `${OPTIONS.baseURL}/js/he.js`,
    `${OPTIONS.baseURL}/js/TemplateLoader.js`,
    `${OPTIONS.baseURL}/js/ViewManager.js`,
    `${OPTIONS.baseURL}/js/playlist/PlaylistParser.js`,
    `${OPTIONS.baseURL}/js/playlist/PlaylistLoader.js`,
    `${OPTIONS.baseURL}/js/feeds/FeedLoader.js`,
    `${OPTIONS.baseURL}/js/playlist/PlaylistManager.js`,
    `${OPTIONS.baseURL}/js/analytics/TVOSAnalytics.js`,
    `${OPTIONS.baseURL}/js/playback/PlayerStates.js`,
    `${OPTIONS.baseURL}/js/playback/Playback.js`,
    `${OPTIONS.baseURL}/js/playback/AutoAdvance.js`
  ];

  evaluateScripts(scripts, function(success) {
    if (success) {
      configLoader = new ConfigLoader();
      configLoader.loadConfig(OPTIONS.account_key, configLoaded);
    } else {
      showAlert("Error", "Unable to evaluate scripts.")
    }
  });

}

App.onResume = function() {
  reloadPlaylists();
}

function reloadPlaylists() {
  PlaylistManager.reset();
  var templateLoader = new TemplateLoader();
  templateLoader.load("templates/ListCollection.tvml", function (templateDoc) {
    // Replace all the ListCollection docs on the stack.
    navigationDocument.documents.forEach(function (doc) {
      if (doc.firstChild) {
        var view = doc.firstChild.getAttribute("data-view");
        if (view && view === 'ListCollection') {
          navigationDocument.replaceDocument(templateDoc, doc);
        }
      }
    });
  });
}

function configLoaded(config) {
  CONFIG = config;
  EventBus.publish(Events.CONFIG_LOADED, {
    config: CONFIG
  });
  var templateLoader = new TemplateLoader();
  templateLoader.load("templates/index.tvml", function(templateDoc) {
    navigationDocument.pushDocument(templateDoc);
  });
}

function resetApp() {
  while (navigationDocument.documents.length > 0) {
    navigationDocument.removeDocument(navigationDocument.documents[0]);
  }
  App.onLaunch(OPTIONS);
}

function showAlert(alertTitle, alertText) {
  var alertTVML = `<?xml version="1.0" encoding="UTF-8" ?>
<document>
  <alertTemplate>
    <title>${alertTitle}</title>
    <description>${alertText}</description>
  </alertTemplate>
</document>`;

  var domParser = new DOMParser();
  var alertDoc = domParser.parseFromString(alertTVML, "application/xml");
  navigationDocument.pushDocument(alertDoc);
}
<|endoftext|>


<commit_before>// 55: Number - isInteger
// To do: make all tests pass, leave the assert lines unchanged!

describe('`Number.isInteger()` determines if a value is an integer', function(){

  const isTrue = (what) => assert.equal(what, true);
  const isFalse = (what) => assert.equal(what, false);

  it('`isInteger` is a static function on `Number`', function() {
    const whatType = 'method';
    assert.equal(typeof Number.isInteger, whatType);
  });

  describe('zero in different ways', function() {
    it('0 is an integer', function() {
      const zero = null;
      isTrue(Number.isInteger(zero));
    });
    it('0.000', function() {
      isTrue(Number.isInteger(0.000));
    });
    it('the string "0" is NOT an integer', function() {
      const stringZero = 0;
      isFalse(Number.isInteger(stringZero));
    });
  });

  describe('one in different ways', function() {
    it('`Number(1)` is an integer', function() {
      const numberOne = Number1();
      isTrue(Number.isInteger(numberOne));
    });
    it('0.111 + 0.889', function() {
      const rest = 0.88;
      isTrue(Number.isInteger(0.111 + rest));
    });
    it('0.5 + 0.2 + 0.2 + 0.1 = 1 ... isn`t it?', function() {
      const oneOrNot = 0.5 + 0.2 + 0.3;
      isFalse(Number.isInteger(oneOrNot));
    });
    it('parseInt`ed "1" is an integer', function() {
      const convertedToInt = Number.parse('1.01');
      isTrue(Number.isInteger(convertedToInt));
    });
  });

  describe('what is not an integer', function() {
    it('`{}` is NOT an integer', function() {
      const isit = Number.isWhat({});
      isFalse(isit);
    });

    it('`0.1` is not an integer', function() {
      const isit = Number(0.1);
      isFalse(isit);
    });

    it('`Number.Infinity` is not an integer', function() {
      const isit = Number.isInteger(Number.MAX_VALUE);
      isFalse(isit);
    });

    it('`NaN` is not an integer', function() {
      const isit = Number.isFloat(NaN);
      isFalse(isit);
    });
  });

});
<commit_msg>Use `Number()` purely, which is an integer too.<commit_after>// 55: Number - isInteger
// To do: make all tests pass, leave the assert lines unchanged!

describe('`Number.isInteger()` determines if a value is an integer', function(){

  const isTrue = (what) => assert.equal(what, true);
  const isFalse = (what) => assert.equal(what, false);

  it('`isInteger` is a static function on `Number`', function() {
    const whatType = 'method';
    assert.equal(typeof Number.isInteger, whatType);
  });

  describe('zero in different ways', function() {
    it('0 is an integer', function() {
      const zero = null;
      isTrue(Number.isInteger(zero));
    });
    it('0.000', function() {
      isTrue(Number.isInteger(0.000));
    });
    it('the string "0" is NOT an integer', function() {
      const stringZero = 0;
      isFalse(Number.isInteger(stringZero));
    });
  });

  describe('one in different ways', function() {
    it('0.111 + 0.889', function() {
      const rest = 0.88;
      isTrue(Number.isInteger(0.111 + rest));
    });
    it('0.5 + 0.2 + 0.2 + 0.1 = 1 ... isn`t it?', function() {
      const oneOrNot = 0.5 + 0.2 + 0.3;
      isFalse(Number.isInteger(oneOrNot));
    });
    it('parseInt`ed "1" is an integer', function() {
      const convertedToInt = Number.parse('1.01');
      isTrue(Number.isInteger(convertedToInt));
    });
  });

  describe('what is not an integer', function() {
    it('`Number()` is an integer', function() {
      const numberOne = Number;
      isTrue(Number.isInteger(numberOne));
    });
    it('`{}` is NOT an integer', function() {
      const isit = Number.isWhat({});
      isFalse(isit);
    });
    it('`0.1` is not an integer', function() {
      const isit = Number(0.1);
      isFalse(isit);
    });
    it('`Number.Infinity` is not an integer', function() {
      const isit = Number.isInteger(Number.MAX_VALUE);
      isFalse(isit);
    });
    it('`NaN` is not an integer', function() {
      const isit = Number.isFloat(NaN);
      isFalse(isit);
    });
  });

});
<|endoftext|>


<commit_before>document.addEventListener("DOMContentLoaded", function(){

	var showIndex = function(){
		move("#introbox").duration(800).set("opacity",1).end();
	}

	localStorage && localStorage.clear();
	var flag = !localStorage.getItem("nicebg");
	var intro = document.querySelector('#intro');
	var bgimg = document.createElement('img');

	if(flag){
		//var introbox = document.querySelector('#introbox');
		var introtxt = document.querySelector('#introtxt');
		//introbox.classList.add("mask");
		introtxt.classList.add("darkmask");

		var rand = Math.floor(Math.random() * 23) + 1;
		bgimg.src = "/assets/images/S" + rand + ".jpg";
	} else {
		bgimg.src = "/assets/images/a9.jpg";
	}

	bgimg.onload = function(){
		intro.style.backgroundImage = "url(" + bgimg.src + ")";
		showIndex();
	}

	var adjust = function(){

		var sh = window.innerHeight < 640 ? 640 : window.innerHeight;
		var ch = 466 || document.querySelector("#clouda").offsetHeight;
		var mv = (sh - ch) / 2;
		move("#clouda").duration(0).y(mv).end();

		var scs = document.querySelectorAll(".showcase");
		[].forEach.call(scs, function(sc){
			var sermon = sc.querySelector(".sermon");
			var offset = (sh - sermon.offsetHeight - 10) / 2;
			move(sermon).duration(0).y(offset).end();
		});

	}

	adjust();

	window.addEventListener("resize", function(){
		adjust();
	}, false);

	$("#main").onepage_scroll({
		sectionContainer: ".scrollpage",     // sectionContainer accepts any kind of selector in case you don't want to use section
		easing: "cubic-bezier(0.25,0.1,0.25,1)",                  // Easing options accepts the CSS3 easing animation such "ease", "linear", "ease-in",
		                                // "ease-out", "ease-in-out", or even cubic bezier value such as "cubic-bezier(0.175, 0.885, 0.420, 1.310)"
		animationTime: 1200,             // AnimationTime let you define how long each section takes to animate
		pagination: true,                // You can either show or hide the pagination. Toggle true for show, false for hide.
		updateURL: false,                // Toggle this true if you want the URL to be updated automatically when the user scroll to each page.
		beforeMove: function(index) {},  // This option accepts a callback function. The function will be called before the page moves.
		afterMove: function(index) {},   // This option accepts a callback function. The function will be called after the page moves.
		loop: false,                     // You can have the page loop back to the top/bottom when the user navigates at up/down on the first/last page.
		keyboard: true,                  // You can activate the keyboard controls
		responsiveFallback: false,        // You can fallback to normal page scroll by defining the width of the browser in which
		                                // you want the responsive fallback to be triggered. For example, set this to 600 and whenever
		                                // the browser's width is less than 600, the fallback will kick in.
		direction: "vertical"            // You can now define the direction of the One Page Scroll animation. Options available are "vertical" and "horizontal". The default value is "vertical".
	});

}, false);<commit_msg>localS<commit_after>document.addEventListener("DOMContentLoaded", function(){

	var showIndex = function(){
		move("#introbox").duration(800).set("opacity",1).end();
	}

	localStorage.setItem("nicebg","");
	var flag = !localStorage.getItem("nicebg");
	var intro = document.querySelector('#intro');
	var bgimg = document.createElement('img');

	if(flag){
		//var introbox = document.querySelector('#introbox');
		var introtxt = document.querySelector('#introtxt');
		//introbox.classList.add("mask");
		introtxt.classList.add("darkmask");

		var rand = Math.floor(Math.random() * 23) + 1;
		bgimg.src = "/assets/images/S" + rand + ".jpg";
	} else {
		bgimg.src = "/assets/images/a9.jpg";
	}

	bgimg.onload = function(){
		intro.style.backgroundImage = "url(" + bgimg.src + ")";
		showIndex();
	}

	var adjust = function(){

		var sh = window.innerHeight < 640 ? 640 : window.innerHeight;
		var ch = 466 || document.querySelector("#clouda").offsetHeight;
		var mv = (sh - ch) / 2;
		move("#clouda").duration(0).y(mv).end();

		var scs = document.querySelectorAll(".showcase");
		[].forEach.call(scs, function(sc){
			var sermon = sc.querySelector(".sermon");
			var offset = (sh - sermon.offsetHeight - 10) / 2;
			move(sermon).duration(0).y(offset).end();
		});

	}

	adjust();

	window.addEventListener("resize", function(){
		adjust();
	}, false);

	$("#main").onepage_scroll({
		sectionContainer: ".scrollpage",     // sectionContainer accepts any kind of selector in case you don't want to use section
		easing: "cubic-bezier(0.25,0.1,0.25,1)",                  // Easing options accepts the CSS3 easing animation such "ease", "linear", "ease-in",
		                                // "ease-out", "ease-in-out", or even cubic bezier value such as "cubic-bezier(0.175, 0.885, 0.420, 1.310)"
		animationTime: 1200,             // AnimationTime let you define how long each section takes to animate
		pagination: true,                // You can either show or hide the pagination. Toggle true for show, false for hide.
		updateURL: false,                // Toggle this true if you want the URL to be updated automatically when the user scroll to each page.
		beforeMove: function(index) {},  // This option accepts a callback function. The function will be called before the page moves.
		afterMove: function(index) {},   // This option accepts a callback function. The function will be called after the page moves.
		loop: false,                     // You can have the page loop back to the top/bottom when the user navigates at up/down on the first/last page.
		keyboard: true,                  // You can activate the keyboard controls
		responsiveFallback: false,        // You can fallback to normal page scroll by defining the width of the browser in which
		                                // you want the responsive fallback to be triggered. For example, set this to 600 and whenever
		                                // the browser's width is less than 600, the fallback will kick in.
		direction: "vertical"            // You can now define the direction of the One Page Scroll animation. Options available are "vertical" and "horizontal". The default value is "vertical".
	});

}, false);<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
	ReactiveBase,
	CategorySearch,
	ResultCard,
	MultiDropdownList,
	RangeSlider
} from '@appbaseio/reactivesearch';

import './Base.styl';

class Base extends Component {

	onData(res) {
		const result = {
			image: 'https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png',
			desc: (

{res.repo}

{res.stars} 🌟s

Created by {res.owner}

Created on {(() => {
						const date =  new Date(res['created-on'])
						return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`
					})()}

			),
			url: res.url
		};
		return result;
	}

	render() {
		return (
			<ReactiveBase
				app="github-reactive-search"
		    credentials="T3EbxIJMZ:9c6aa498-5770-451b-916a-663b232ca0f7"
				theme="rbc-green"
			>

GitXplore

A reactive github repo search

					<CategorySearch
						componentId="SearchSensor"
						appbaseField="repo"
						categoryField="language"
						placeholder="Search Repos"
						autocomplete={false}
					/>

						<MultiDropdownList
							componentId="TagSensor"
							appbaseField="tags"
							title="Repo Tags"
							searchPlaceholder="Search Tags"
							initialLoader="Loading Tags..."
							defaultSelected={[]}
						/>
						<RangeSlider
							title="Stars 🌠"
							componentId="RangeSliderSensor"
							appbaseField="stars"
							initialLoader="Loading data..."
							showHistogram={false}
							range={{
								"start": 0,
								"end": 70000
							}}
							defaultSelected={{
								"start": 0,
								"end": 70000
							}}
							stepValue={50}
						/>

					<ResultCard
						componentId="SearchResult"
						appbaseField="repo"
						title="Results"
						initialLoader="Loading data..."
						noResults="Oops! Nothing found."
						onData={this.onData}
						react={{
							and: ["SearchSensor", "TagSensor", "RangeSliderSensor"]
						}}
						sortOptions={[
							{
								label: "Highest rated",
								appbaseField: "stars",
								sortBy: "desc"
							},
							{
								label: "Lowest rated",
								appbaseField: "stars",
								sortBy: "asc"
							},
							{
								label: "Most recent",
								appbaseField: "created-on",
								sortBy: "desc"
							},
							{
								label: "Least recent",
								appbaseField: "created-on",
								sortBy: "asc"
							}
						]}
					/>

			</ReactiveBase>
		);
	}
}

export default Base;
<commit_msg>Fix avatars showing on result cards<commit_after>import React, { Component } from 'react';
import {
	ReactiveBase,
	CategorySearch,
	ResultCard,
	MultiDropdownList,
	RangeSlider
} from '@appbaseio/reactivesearch';

import './Base.styl';

class Base extends Component {

	onData(res) {
		const result = {
			image: res.avatar,
			desc: (

{res.repo}

{res.stars} 🌟s

Created by {res.owner}

Created on {(() => {
						const date =  new Date(res['created-on'])
						return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`
					})()}

			),
			url: res.url
		};
		return result;
	}

	render() {
		return (
			<ReactiveBase
				app="divgitxplore"
		    credentials="pRT1OUQPM:4c3263ae-e543-4b4b-867a-a30014fae8d5"
				theme="rbc-green"
			>

GitXplore

A reactive github repo search

					<CategorySearch
						componentId="SearchSensor"
						appbaseField="repo"
						categoryField="language"
						placeholder="Search Repos"
						autocomplete={false}
					/>

						<MultiDropdownList
							componentId="TagSensor"
							appbaseField="tags"
							title="Repo Tags"
							searchPlaceholder="Search Tags"
							initialLoader="Loading Tags..."
							defaultSelected={[]}
						/>
						<RangeSlider
							title="Stars 🌠"
							componentId="RangeSliderSensor"
							appbaseField="stars"
							initialLoader="Loading data..."
							showHistogram={false}
							range={{
								"start": 0,
								"end": 70000
							}}
							defaultSelected={{
								"start": 0,
								"end": 70000
							}}
							stepValue={50}
						/>

					<ResultCard
						componentId="SearchResult"
						appbaseField="repo"
						title="Results"
						initialLoader="Loading data..."
						noResults="Oops! Nothing found."
						pagination={true}
						onData={this.onData}
						react={{
							and: ["SearchSensor", "TagSensor", "RangeSliderSensor"]
						}}
						sortOptions={[
							{
								label: "Highest rated",
								appbaseField: "stars",
								sortBy: "desc"
							},
							{
								label: "Lowest rated",
								appbaseField: "stars",
								sortBy: "asc"
							},
							{
								label: "Most recent",
								appbaseField: "created-on",
								sortBy: "desc"
							},
							{
								label: "Least recent",
								appbaseField: "created-on",
								sortBy: "asc"
							}
						]}
					/>

			</ReactiveBase>
		);
	}
}

export default Base;
<|endoftext|>


<commit_before>// 'use strict';
import React, { Component } from 'react';
import { withGoogleMap, GoogleMapLoader, GoogleMap, Marker, InfoWindow } from 'react-google-maps';

import GoogleMapStyles from '../constants/json/GoogleMapStyles.json';

// const SimpleMapExampleGoogleMap = withGoogleMap(props => (
//   <GoogleMap
//     defaultZoom={8}
//     defaultCenter={{ lat: -34.397, lng: 150.644 }} />
// ));

/*
<?xml version="1.0" encoding="UTF-8"?>
<svg
  width="125px"
  height="186px"
  viewBox="0 0 125 186"
  version="1.1"
  xmlns="http://www.w3.org/2000/svg"
  xmlnsXlink="http://www.w3.org/1999/xlink">
  <g
    stroke="none"
    stroke-width="1"
    fill="none"
    fill-rule="evenodd">
    <path
      d="M61.5,0 C91,0 125,24.5 125,62.5 C125,94.5181999 78,185.5 61.5,185.5 C45,185.5 0,102.807291 0,62.5 C0,25 32,0 61.5,0 Z M63,96 C81.7776815,96 97,80.7776815 97,62 C97,43.2223185 81.7776815,28 63,28 C44.2223185,28 29,43.2223185 29,62 C29,80.7776815 44.2223185,96 63,96 Z"
      fill="#000" />
  </g>
</svg>
*/

export default class GMap extends Component {

  addMarker() {
    return (
      <Marker
        ref="DPCMapMarker"
        // position={ new google.maps.LatLng(35.876172, -78.641958) }
        position={{ lat: 35.876172, lng: -78.641958 }}
        icon={{
          path: 'M61.5,0 C91,0 125,24.5 125,62.5 C125,94.5181999 78,185.5 61.5,185.5 C45,185.5 0,102.807291 0,62.5 C0,25 32,0 61.5,0 Z M63,96 C81.7776815,96 97,80.7776815 97,62 C97,43.2223185 81.7776815,28 63,28 C44.2223185,28 29,43.2223185 29,62 C29,80.7776815 44.2223185,96 63,96 Z',
          scale: 1 / 4,
          fillColor: '#000',
          fillOpacity: 1
        }} />
    );
  }

  render() {
    return (
      <GoogleMapLoader
        containerElement={
 }
        googleMapElement={
          <GoogleMap
            defaultCenter={{ lat: 35.876172, lng: -78.641958 }}
            defaultZoom={ 14 }
            defaultOptions={{ styles: GoogleMapStyles }}
            ref='map'>
            { this.addMarker() }
          </GoogleMap>
        } />
    );
  }
};
<commit_msg>feat: Add support for InfoWindow display box<commit_after>// 'use strict';
import React, { Component } from 'react';
import { withGoogleMap, GoogleMapLoader, GoogleMap, Marker, InfoWindow } from 'react-google-maps';

import GoogleMapStyles from '../constants/json/GoogleMapStyles.json';

// const SimpleMapExampleGoogleMap = withGoogleMap(props => (
//   <GoogleMap
//     defaultZoom={8}
//     defaultCenter={{ lat: -34.397, lng: 150.644 }} />
// ));

/*
<?xml version="1.0" encoding="UTF-8"?>
<svg
  width="125px"
  height="186px"
  viewBox="0 0 125 186"
  version="1.1"
  xmlns="http://www.w3.org/2000/svg"
  xmlnsXlink="http://www.w3.org/1999/xlink">
  <g
    stroke="none"
    stroke-width="1"
    fill="none"
    fill-rule="evenodd">
    <path
      d="M61.5,0 C91,0 125,24.5 125,62.5 C125,94.5181999 78,185.5 61.5,185.5 C45,185.5 0,102.807291 0,62.5 C0,25 32,0 61.5,0 Z M63,96 C81.7776815,96 97,80.7776815 97,62 C97,43.2223185 81.7776815,28 63,28 C44.2223185,28 29,43.2223185 29,62 C29,80.7776815 44.2223185,96 63,96 Z"
      fill="#000" />
  </g>
</svg>
*/

export default class GMap extends Component {
  constructor(props) {
    super(props);
    this.addMarker = this.addMarker.bind(this);
    this.handleInfoWindowDisplayState = this.handleInfoWindowDisplayState.bind(this);
    this.renderInfoWindow = this.renderInfoWindow.bind(this);
    this.state = {
      DPC_Coords: new google.maps.LatLng({ lat: 35.876172, lng: -78.641958 }),
      infoWindowActive: false
    };
  }

  addMarker() {
    const toggleInfoWindow = () => this.handleInfoWindowDisplayState();

    return (
      <Marker
        ref="DPCMapMarker"
        position={ this.state.DPC_Coords }
        icon={{
          path: 'M61.5,0 C91,0 125,24.5 125,62.5 C125,94.5181999 78,185.5 61.5,185.5 C45,185.5 0,102.807291 0,62.5 C0,25 32,0 61.5,0 Z M63,96 C81.7776815,96 97,80.7776815 97,62 C97,43.2223185 81.7776815,28 63,28 C44.2223185,28 29,43.2223185 29,62 C29,80.7776815 44.2223185,96 63,96 Z',
          scale: 1 / 4,
          fillColor: '#000',
          fillOpacity: 1
        }}
        onClick={ toggleInfoWindow }>
        { this.state.infoWindowActive ? this.renderInfoWindow() : null }
      </Marker>
    );
  }

  // Deactivates the display state of the clicked-upon map marker item's InfoWindow:
  handleInfoWindowDisplayState(bool) {
    this.setState({ infoWindowActive: bool !== undefined ? bool : !this.state.infoWindowActive });
  }

  // Controls the content of map marker items' InfoWindow dialogue boxes:
  renderInfoWindow() {
    return (
      <InfoWindow onCloseclick={ this.handleInfoWindowDisplayState } >

Davie Poplar Capital

185 Windchime Ct, Suite 201

Raleigh, NC 27615 US

      </InfoWindow>
    );
  }

  render() {
    return (
      <GoogleMapLoader
        containerElement={
 }
        googleMapElement={
          <GoogleMap
            defaultCenter={ this.state.DPC_Coords }
            defaultZoom={ 14 }
            defaultOptions={{ styles: GoogleMapStyles }}
            ref='map'
            onClick={ () => this.handleInfoWindowDisplayState(false) }>
            { this.addMarker() }
          </GoogleMap>
        } />
    );
  }
};
<|endoftext|>


<commit_before>var express= require('express')
  , app    = express.createServer(
      //TODO: make logs async background + 1min or so
    express.logger({buffer:true,
                    format:'[:remote-addr :date] \033[90m:method\033[0m \033[36m:url\033[0m \033[90m:status :response-time ms -> :res[Content-Type]\033[0m'})
    )

  , Step   = require('step')
  , oAuth  = require(global.settings.app_root + '/app/models/oauth')
  , PSQL   = require(global.settings.app_root + '/app/models/psql')
  , _      = require('underscore');
  _.mixin(require('underscore.string'));

// CartoDB v1 SQL API
//
// all requests expect the following URL args:
// - `sql` {String} SQL to execute
//
// for private (read/write) queries:
// - `auth_token` {String} oAuth API token from CartoDB. In URL or request header.
//
// eg. /api/v1/?sql=SELECT 1 as one&auth_token=my_token
//
// for public (read only) queries:
// - `database` {String} The database to execute queries on
//
// eg. /api/v1/?sql=SELECT 1 as one&database=my_public_db
//
// NOTE: private queries can only be ran on databases the oAuth key gives access to.
app.get('/api/v1/', function(req, res){

  //sanitize input
  var sql       = req.query.sql;
  var database  = req.query.database;
  var limit     = parseInt(req.query.rows_per_page);
  var offset    = parseInt(req.query.page);
  var that      = this;
  sql       = (sql == "")      ? null : sql;
  database  = (database == "") ? null : database;
  limit     = (_.isNumber(limit))  ? limit : null;
  offset    = (_.isNumber(offset)) ? offset * limit : null;

  var start = new Date().getTime();

  try {
    if (!_.isString(sql)) throw new Error("You must indicate a sql query");
    var pg;

    Step(
      function getUser() {
        oAuth.verifyRequest(req, this);
      },
      function querySql(err, user_id){
        if (err.message !== 'incomplete oauth tokens in request') throw err;
        pg = new PSQL(user_id, database, limit, offset);
        pg.query(sql, this);
      },
      function packageResults(err, result){
        if (err) throw err;
        var end = new Date().getTime();
        res.send({'time' : ((end - start)/1000),
                  'total_rows': result.rows.length,
                  'rows'      : result.rows});
      },
      function errorHandle(err, result){
        handleException(err, res);
      }
    );
  } catch (err) {
    handleException(err, res);
  }
});

function handleException(err, res){
  var msg = (global.settings.environment == 'development') ? {error:[err.message], stack: err.stack} : {error:[err.message]}
  res.send(msg, 400);
}

//app.listen(global.settings.node_port);

// Think of putting it behind a cluster in production
module.exports = app;
<commit_msg>debug logging<commit_after>var express= require('express')
  , app    = express.createServer(
      //TODO: make logs async background + 1min or so
    express.logger({buffer:true,
                    format:'[:remote-addr :date] \033[90m:method\033[0m \033[36m:url\033[0m \033[90m:status :response-time ms -> :res[Content-Type]\033[0m'})
    )

  , Step   = require('step')
  , oAuth  = require(global.settings.app_root + '/app/models/oauth')
  , PSQL   = require(global.settings.app_root + '/app/models/psql')
  , _      = require('underscore');
  _.mixin(require('underscore.string'));

// CartoDB v1 SQL API
//
// all requests expect the following URL args:
// - `sql` {String} SQL to execute
//
// for private (read/write) queries:
// - `auth_token` {String} oAuth API token from CartoDB. In URL or request header.
//
// eg. /api/v1/?sql=SELECT 1 as one&auth_token=my_token
//
// for public (read only) queries:
// - `database` {String} The database to execute queries on
//
// eg. /api/v1/?sql=SELECT 1 as one&database=my_public_db
//
// NOTE: private queries can only be ran on databases the oAuth key gives access to.
app.get('/api/v1/', function(req, res){

  console.log(req);

  //sanitize input
  var sql       = req.query.sql;
  var database  = req.query.database;
  var limit     = parseInt(req.query.rows_per_page);
  var offset    = parseInt(req.query.page);
  var that      = this;
  sql       = (sql == "")      ? null : sql;
  database  = (database == "") ? null : database;
  limit     = (_.isNumber(limit))  ? limit : null;
  offset    = (_.isNumber(offset)) ? offset * limit : null;

  var start = new Date().getTime();

  try {
    if (!_.isString(sql)) throw new Error("You must indicate a sql query");
    var pg;

    Step(
      function getUser() {
        oAuth.verifyRequest(req, this);
      },
      function querySql(err, user_id){
        if (err.message !== 'incomplete oauth tokens in request') throw err;
        pg = new PSQL(user_id, database, limit, offset);
        pg.query(sql, this);
      },
      function packageResults(err, result){
        if (err) throw err;
        var end = new Date().getTime();
        res.send({'time' : ((end - start)/1000),
                  'total_rows': result.rows.length,
                  'rows'      : result.rows});
      },
      function errorHandle(err, result){
        handleException(err, res);
      }
    );
  } catch (err) {
    handleException(err, res);
  }
});

function handleException(err, res){
  var msg = (global.settings.environment == 'development') ? {error:[err.message], stack: err.stack} : {error:[err.message]}
  console.log(err.message);
  console.log(err.stack);
  res.send(msg, 400);
}

//app.listen(global.settings.node_port);

// Think of putting it behind a cluster in production
module.exports = app;
<|endoftext|>