<commit_before>// Class: Loki.Runner
// Runs Crucible tests.
Loki.Runner = Loki.Class.create({
	tests: null,

	events: null,

	// Constructor: Runner
	// Creates a new test runner.
	//
	// Parameters:
	//     (Crucible.Test[]) tests - the tests to be run
	initialize: function Runner(tests) {
		this.tests = tests;

		this.events = {
			run: new Crucible.Delegator("test started"),
			pass: new Crucible.Delegator("test passed"),
			fail: new Crucible.Delegator("test failed"),
			exception: new Crucible.Delegator("test threw an exception"),
			result: new Crucible.Delegator("test finished"),
			finish: new Crucible.Delegator("finished testing")
		};
	}
});
<commit_msg>Implement Runner.<commit_after>// Class: Crucible.Runner
// Runs Crucible tests.
Crucible.Runner = Crucible.Class.create({
	product: null,
	tests: null,

	events: null,

	// Constructor: Runner
	// Creates a new test runner.
	//
	// Parameters:
	//     (Crucible.Test[]) tests - the tests to be run
	initialize: function Runner(product, tests) {
		this.product = product || '(unknown product)';
		this.tests = [];
		if (tests) {
			Crucible.forEach(tests, this.add, this);
		}

		this.events = {
			start: new Crucible.Delegator("started testing"),
			run: new Crucible.Delegator("test started"),
			pass: new Crucible.Delegator("test passed"),
			fail: new Crucible.Delegator("test failed"),
			exception: new Crucible.Delegator("test threw an exception"),
			result: new Crucible.Delegator("test finished"),
			finish: new Crucible.Delegator("finished testing")
		};
	},

	// Method: add
	// Adds a test to the runner.
	//
	// Parameters:
	//     (Crucible.Test) test - the test to add
	add: function add_to_runner(test) {
		test.events.result.add(this, '_processResult');
		this.tests.push(test);
	},

	// Method: run
	// Runs the tests.
	run: function run_tests() {
		if (this.running) {
			throw new Error('Already running!');
		}

		this.queue = this.tests.slice(0); // clone
		this.queue.reverse();
		this.running = true;

		this.events.start.call();
		this._runTest();
	},

	_runTest: function _runner_run_test() {
		if (this.queue.length == 0) {
			this.events.finish.call();
			this.running = false;
			delete this.queue;
			return;
		}

		var test = this.queue.pop();
		this.events.run.call(test);
		Crucible.defer(function() {
			test.run();
		});
	},

	_processResult: function _process_test_result(test, status, result) {
		this.events[status].call(test, result || null);
		this.events.result.call(test, status, result || null);
		Crucible.defer(function() {
			this._runTest();
		});
	}
});
<|endoftext|>


<commit_before>/*
MIT License
Copyright (c) 2016 Knowledgeable Mammoth
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

data['MarathonList']

*/

'use strict';
(function () {
    var marathons = "";
    $(document).ready(function () {
        var evenhtml = '';
        var oddhtml = '';

        var htmlcode = '';

        $.when(
            $.get('HTML/evenlistitem.html', function (data) { evenhtml = data; }),
            $.get('HTML/oddlistitem.html', function (data) { oddhtml = data; }),
            $.get('Data/marathons.json', function (data) {
                marathons = JSON.parse(data);
                marathons.sort(function (a, b) {
                    if (a.MarathonName  b.MarathonName) return 1;
                    return 0;
                });
            })).done(
            function () {
                var i = 0;
                for (i = 0; i < marathons.length; i++) {
                    if (i % 2 == 0) {
                        htmlcode += createRow(evenhtml, i);
                    } else {
                        htmlcode += createRow(oddhtml, i);
                    }
                }
                $('#list').append(htmlcode);

            }
            );

    });

    function createRow(code, index) {
        var tempcode = '';
        var listcode = '';
        var zindex = 'z-index:' + (marathons.length - index) + ';';
        tempcode = code;

        var $tempcode = $(tempcode);

        $tempcode.find('.MarathonName').text(marathons[index].MarathonName);
        var i = 0;
        for (i = 1; i < marathons[index].Movies.length; i++) {
            listcode += '
' + marathons[index].Movies[i] + '
\n';

        }
        $tempcode.find('.centercol').attr('style', zindex);
        $tempcode.find('.MovieName').text(marathons[index].Movies[0]);
        $tempcode.find('.MovieName').append('

');
        $tempcode.find('.ShowList').attr('style', zindex);
        $tempcode.find(".ShowList").html(listcode);

        $tempcode.find(".Length").text(marathons[index].Length);
        return $tempcode.html();
    }

})();

function scrollDropDown(a) {
    var h1 = $(document).height();
    $(a).toggleClass('show');
    $(a).find('.Arrow').toggleClass('show');
    $(a).find('.ShowList').toggleClass('show');
    var h2 = $(document).height();
    if (h2 > h1 && $(window).width() > 1400) {
        $("html, body").animate({ scrollTop: $(document).height() }, 500);
    }
};
<commit_msg>JS Fix<commit_after>/*
MIT License
Copyright (c) 2016 Knowledgeable Mammoth
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

data['MarathonList']

*/

'use strict';
(function () {
    var marathons = "";
    $(document).ready(function () {
        var evenhtml = '';
        var oddhtml = '';

        var htmlcode = '';

        $.when(
            $.get('HTML/evenlistitem.html', function (data) { evenhtml = data; }),
            $.get('HTML/oddlistitem.html', function (data) { oddhtml = data; }),
            $.get('Data/marathons.json', function (data) {
                marathons = JSON.parse(data['MarathonList']);
                marathons.sort(function (a, b) {
                    if (a.MarathonName  b.MarathonName) return 1;
                    return 0;
                });
            })).done(
            function () {
                var i = 0;
                for (i = 0; i < marathons.length; i++) {
                    if (i % 2 == 0) {
                        htmlcode += createRow(evenhtml, i);
                    } else {
                        htmlcode += createRow(oddhtml, i);
                    }
                }
                $('#list').append(htmlcode);

            }
            );

    });

    function createRow(code, index) {
        var tempcode = '';
        var listcode = '';
        var zindex = 'z-index:' + (marathons.length - index) + ';';
        tempcode = code;

        var $tempcode = $(tempcode);

        $tempcode.find('.MarathonName').text(marathons[index].MarathonName);
        var i = 0;
        for (i = 1; i < marathons[index].Movies.length; i++) {
            listcode += '
' + marathons[index].Movies[i] + '
\n';

        }
        $tempcode.find('.centercol').attr('style', zindex);
        $tempcode.find('.MovieName').text(marathons[index].Movies[0]);
        $tempcode.find('.MovieName').append('

');
        $tempcode.find('.ShowList').attr('style', zindex);
        $tempcode.find(".ShowList").html(listcode);

        $tempcode.find(".Length").text(marathons[index].Length);
        return $tempcode.html();
    }

})();

function scrollDropDown(a) {
    var h1 = $(document).height();
    $(a).toggleClass('show');
    $(a).find('.Arrow').toggleClass('show');
    $(a).find('.ShowList').toggleClass('show');
    var h2 = $(document).height();
    if (h2 > h1 && $(window).width() > 1400) {
        $("html, body").animate({ scrollTop: $(document).height() }, 500);
    }
};
<|endoftext|>


<commit_before>Package.describe({
  name: 'trepafi:mapbox',
  summary: 'Integrating MapBox.js with Meteor  ',
  version: '0.1.0',
  git: 'https://github.com/trepafi/meteor-mapbox.git'
});

Package.onUse(function(api) {
  api.versionsFrom('METEOR@1.0');
  api.use("jquery", 'client');
  api.use("mizzao:build-fetcher@0.2.0", 'client');
  api.addFiles('mapbox.fetch.json', 'client');
});<commit_msg>Updating version<commit_after>Package.describe({
  name: 'trepafi:mapbox',
  summary: 'Integrating MapBox.js with Meteor  ',
  version: '0.1.1',
  git: 'https://github.com/trepafi/meteor-mapbox.git'
});

Package.onUse(function(api) {
  api.versionsFrom('METEOR@1.0');
  api.use("jquery", 'client');
  api.use("mizzao:build-fetcher@0.2.0", 'client');
  api.addFiles('mapbox.fetch.json', 'client');
});
<|endoftext|>


<commit_before>// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Provides utility methods to render soy template.
 * @author chrishenry@google.com (Chris Henry)
 */

goog.provide('goog.soy');

goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.TagName');
goog.require('goog.dom.safe');
goog.require('goog.html.uncheckedconversions');
goog.require('goog.soy.data.SanitizedContent');
goog.require('goog.soy.data.SanitizedContentKind');
goog.require('goog.string');

/**
 * @define {boolean} Whether to require all Soy templates to be "strict html".
 * Soy templates that use strict autoescaping forbid noAutoescape along with
 * many dangerous directives, and return a runtime type SanitizedContent that
 * marks them as safe.
 *
 * If this flag is enabled, Soy templates will fail to render if a template
 * returns plain text -- indicating it is a non-strict template.
 */
goog.soy.REQUIRE_STRICT_AUTOESCAPE =
    goog.define('goog.soy.REQUIRE_STRICT_AUTOESCAPE', false);

/**
 * Type definition for strict Soy templates. Very useful when passing a template
 * as an argument.
 * @typedef {function(?, null=, ?Object<string, *>=):
 *     !goog.soy.data.SanitizedContent}
 */
goog.soy.StrictTemplate;

/**
 * Type definition for strict Soy HTML templates. Very useful when passing
 * a template as an argument.
 * @typedef {function(?, null=, ?Object<string, *>=):
 *     !goog.soy.data.SanitizedHtml}
 */
goog.soy.StrictHtmlTemplate;

/**
 * Sets the processed template as the innerHTML of an element. It is recommended
 * to use this helper function instead of directly setting innerHTML in your
 * hand-written code, so that it will be easier to audit the code for cross-site
 * scripting vulnerabilities.
 *
 * @param {?Element} element The element whose content we are rendering into.
 * @param {!goog.soy.data.SanitizedContent} templateResult The processed
 *     template of kind HTML or TEXT (which will be escaped).
 * @template ARG_TYPES
 */
goog.soy.renderHtml = function(element, templateResult) {
  goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse(
      goog.asserts.assert(element),
      goog.html.uncheckedconversions
          .safeHtmlFromStringKnownToSatisfyTypeContract(
              goog.string.Const.from('Soy HTML template.'),
              goog.soy.ensureTemplateOutputHtml_(templateResult)));
};

/**
 * Renders a Soy template and then set the output string as
 * the innerHTML of an element. It is recommended to use this helper function
 * instead of directly setting innerHTML in your hand-written code, so that it
 * will be easier to audit the code for cross-site scripting vulnerabilities.
 *
 * @param {Element} element The element whose content we are rendering into.
 * @param {?function(ARG_TYPES, Object<string, *>=):*|
 *     ?function(ARG_TYPES, null=, Object<string, *>=):*} template
 *     The Soy template defining the element's content.
 * @param {ARG_TYPES=} opt_templateData The data for the template.
 * @param {Object=} opt_injectedData The injected data for the template.
 * @template ARG_TYPES
 */
goog.soy.renderElement = function(
    element, template, opt_templateData, opt_injectedData) {
  // Soy template parameter is only nullable for historical reasons.
  goog.asserts.assert(template, 'Soy template may not be null.');
  var html = goog.soy.ensureTemplateOutputHtml_(template(
      opt_templateData || goog.soy.defaultTemplateData_, undefined,
      opt_injectedData));
  goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse(
      goog.asserts.assert(element),
      goog.html.uncheckedconversions
          .safeHtmlFromStringKnownToSatisfyTypeContract(
              goog.string.Const.from('Soy HTML template.'), html));
};

/**
 * Renders a Soy template into a single node or a document
 * fragment. If the rendered HTML string represents a single node, then that
 * node is returned (note that this is *not* a fragment, despite them name of
 * the method). Otherwise a document fragment is returned containing the
 * rendered nodes.
 *
 * @param {
 *     ?function(ARG_TYPES, Object<string, *>=):goog.soy.data.SanitizedContent|
 *     ?function(ARG_TYPES, null=, Object<string, *>=):
 *     goog.soy.data.SanitizedContent} template The Soy template defining the
 *     element's content. The kind of the template must be "html" or "text".
 * @param {ARG_TYPES=} opt_templateData The data for the template.
 * @param {Object=} opt_injectedData The injected data for the template.
 * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper used to
 *     create DOM nodes; defaults to `goog.dom.getDomHelper`.
 * @return {!Node} The resulting node or document fragment.
 * @template ARG_TYPES
 */
goog.soy.renderAsFragment = function(
    template, opt_templateData, opt_injectedData, opt_domHelper) {
  // Soy template parameter is only nullable for historical reasons.
  goog.asserts.assert(template, 'Soy template may not be null.');
  var dom = opt_domHelper || goog.dom.getDomHelper();
  var output = template(
      opt_templateData || goog.soy.defaultTemplateData_, undefined,
      opt_injectedData);
  var html = goog.soy.ensureTemplateOutputHtml_(output);
  goog.soy.assertFirstTagValid_(html);
  var safeHtml = output.toSafeHtml();
  return dom.safeHtmlToNode(safeHtml);
};

/**
 * Renders a Soy template into a single node. If the rendered
 * HTML string represents a single node, then that node is returned. Otherwise,
 * a DIV element is returned containing the rendered nodes.
 *
 * @param {?function(ARG_TYPES, Object<string, *>=):*|
 *     ?function(ARG_TYPES, null=, Object<string, *>=):*} template
 *     The Soy template defining the element's content.
 * @param {ARG_TYPES=} opt_templateData The data for the template.
 * @param {Object=} opt_injectedData The injected data for the template.
 * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper used to
 *     create DOM nodes; defaults to `goog.dom.getDomHelper`.
 * @return {!Element} Rendered template contents, wrapped in a parent DIV
 *     element if necessary.
 * @template ARG_TYPES
 */
goog.soy.renderAsElement = function(
    template, opt_templateData, opt_injectedData, opt_domHelper) {
  // Soy template parameter is only nullable for historical reasons.
  goog.asserts.assert(template, 'Soy template may not be null.');
  return goog.soy.convertToElement_(
      template(
          opt_templateData || goog.soy.defaultTemplateData_, undefined,
          opt_injectedData),
      opt_domHelper);
};

/**
 * Converts a processed Soy template into a single node. If the rendered
 * HTML string represents a single node, then that node is returned. Otherwise,
 * a DIV element is returned containing the rendered nodes.
 *
 * @param {!goog.soy.data.SanitizedContent} templateResult The processed
 *     template of kind HTML or TEXT (which will be escaped).
 * @param {?goog.dom.DomHelper=} opt_domHelper The DOM helper used to
 *     create DOM nodes; defaults to `goog.dom.getDomHelper`.
 * @return {!Element} Rendered template contents, wrapped in a parent DIV
 *     element if necessary.
 */
goog.soy.convertToElement = function(templateResult, opt_domHelper) {
  return goog.soy.convertToElement_(templateResult, opt_domHelper);
};

/**
 * Non-strict version of `goog.soy.convertToElement`.
 *
 * @param {*} templateResult The processed template.
 * @param {?goog.dom.DomHelper=} opt_domHelper The DOM helper used to
 *     create DOM nodes; defaults to `goog.dom.getDomHelper`.
 * @return {!Element} Rendered template contents, wrapped in a parent DIV
 *     element if necessary.
 * @private
 */
goog.soy.convertToElement_ = function(templateResult, opt_domHelper) {
  var dom = opt_domHelper || goog.dom.getDomHelper();
  var wrapper = dom.createElement(goog.dom.TagName.DIV);
  var html = goog.soy.ensureTemplateOutputHtml_(templateResult);
  goog.soy.assertFirstTagValid_(html);
  goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse(
      wrapper,
      goog.html.uncheckedconversions
          .safeHtmlFromStringKnownToSatisfyTypeContract(
              goog.string.Const.from('Soy HTML template.'), html));

  // If the template renders as a single element, return it.
  if (wrapper.childNodes.length == 1) {
    var firstChild = wrapper.firstChild;
    if (firstChild.nodeType == goog.dom.NodeType.ELEMENT) {
      return /** @type {!Element} */ (firstChild);
    }
  }

  // Otherwise, return the wrapper DIV.
  return wrapper;
};

/**
 * Ensures the result is "safe" to insert as HTML.
 *
 * Note if the template has non-strict autoescape, the guarantees here are very
 * weak. It is recommended applications switch to requiring strict
 * autoescaping over time by tweaking goog.soy.REQUIRE_STRICT_AUTOESCAPE.
 *
 * In the case the argument is a SanitizedContent object, it either must
 * already be of kind HTML, or if it is kind="text", the output will be HTML
 * escaped.
 *
 * @param {*} templateResult The template result.
 * @return {string} The assumed-safe HTML output string.
 * @private
 */
goog.soy.ensureTemplateOutputHtml_ = function(templateResult) {
  // Allow strings as long as strict autoescaping is not mandated. Note we
  // allow everything that isn't an object, because some non-escaping templates
  // end up returning non-strings if their only print statement is a
  // non-escaped argument, plus some unit tests spoof templates.
  // TODO(gboyer): Track down and fix these cases.
  if (!goog.soy.REQUIRE_STRICT_AUTOESCAPE && !goog.isObject(templateResult)) {
    return String(templateResult);
  }

  // Allow SanitizedContent of kind HTML.
  if (templateResult instanceof goog.soy.data.SanitizedContent) {
    templateResult =
        /** @type {!goog.soy.data.SanitizedContent} */ (templateResult);
    var ContentKind = goog.soy.data.SanitizedContentKind;
    if (templateResult.contentKind === ContentKind.HTML) {
      return goog.asserts.assertString(templateResult.getContent());
    }
    if (templateResult.contentKind === ContentKind.TEXT) {
      // Allow text to be rendered, as long as we escape it. Other content
      // kinds will fail, since we don't know what to do with them.
      // TODO(gboyer): Perhaps also include URI in this case.
      return goog.string.htmlEscape(templateResult.getContent());
    }
  }

  goog.asserts.fail(
      'Soy template output is unsafe for use as HTML: ' + templateResult);

  // In production, return a safe string, rather than failing hard.
  return 'zSoyz';
};

/**
 * Checks that the rendered HTML does not start with an invalid tag that would
 * likely cause unexpected output from renderAsElement or renderAsFragment.
 * See {@link http://www.w3.org/TR/html5/semantics.html#semantics} for reference
 * as to which HTML elements can be parents of each other.
 * @param {string} html The output of a template.
 * @private
 */
goog.soy.assertFirstTagValid_ = function(html) {
  if (goog.asserts.ENABLE_ASSERTS) {
    var matches = html.match(goog.soy.INVALID_TAG_TO_RENDER_);
    goog.asserts.assert(
        !matches, 'This template starts with a %s, which ' +
            'cannot be a child of a <div>, as required by soy internals. ' +
            'Consider using goog.soy.renderElement instead.\nTemplate output: %s',
        matches && matches[0], html);
  }
};

/**
 * A pattern to find templates that cannot be rendered by renderAsElement or
 * renderAsFragment, as these elements cannot exist as the child of a <div>.
 * @type {!RegExp}
 * @private
 */
goog.soy.INVALID_TAG_TO_RENDER_ =
    /^<(body|caption|col|colgroup|head|html|tr|td|th|tbody|thead|tfoot)>/i;

/**
 * Immutable object that is passed into templates that are rendered
 * without any data.
 * @private @const
 */
goog.soy.defaultTemplateData_ = {};
<commit_msg>RELNOTES[NEW]: Add type for text template.<commit_after>// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Provides utility methods to render soy template.
 * @author chrishenry@google.com (Chris Henry)
 */

goog.provide('goog.soy');

goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.TagName');
goog.require('goog.dom.safe');
goog.require('goog.html.uncheckedconversions');
goog.require('goog.soy.data.SanitizedContent');
goog.require('goog.soy.data.SanitizedContentKind');
goog.require('goog.string');

/**
 * @define {boolean} Whether to require all Soy templates to be "strict html".
 * Soy templates that use strict autoescaping forbid noAutoescape along with
 * many dangerous directives, and return a runtime type SanitizedContent that
 * marks them as safe.
 *
 * If this flag is enabled, Soy templates will fail to render if a template
 * returns plain text -- indicating it is a non-strict template.
 */
goog.soy.REQUIRE_STRICT_AUTOESCAPE =
    goog.define('goog.soy.REQUIRE_STRICT_AUTOESCAPE', false);

/**
 * Type definition for strict Soy templates. Very useful when passing a template
 * as an argument.
 * @typedef {function(?, null=, ?Object<string, *>=):
 *     !goog.soy.data.SanitizedContent}
 */
goog.soy.StrictTemplate;

/**
 * Type definition for strict Soy HTML templates. Very useful when passing
 * a template as an argument.
 * @typedef {function(?, null=, ?Object<string, *>=):
 *     !goog.soy.data.SanitizedHtml}
 */
goog.soy.StrictHtmlTemplate;

/**
 * Type definition for text templates.
 * @typedef {function(?, null=, ?Object<string, *>=):
 *     (!goog.soy.data.UnsanitizedText|string)}
 */
goog.soy.TextTemplate;

/**
 * Sets the processed template as the innerHTML of an element. It is recommended
 * to use this helper function instead of directly setting innerHTML in your
 * hand-written code, so that it will be easier to audit the code for cross-site
 * scripting vulnerabilities.
 *
 * @param {?Element} element The element whose content we are rendering into.
 * @param {!goog.soy.data.SanitizedContent} templateResult The processed
 *     template of kind HTML or TEXT (which will be escaped).
 * @template ARG_TYPES
 */
goog.soy.renderHtml = function(element, templateResult) {
  goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse(
      goog.asserts.assert(element),
      goog.html.uncheckedconversions
          .safeHtmlFromStringKnownToSatisfyTypeContract(
              goog.string.Const.from('Soy HTML template.'),
              goog.soy.ensureTemplateOutputHtml_(templateResult)));
};

/**
 * Renders a Soy template and then set the output string as
 * the innerHTML of an element. It is recommended to use this helper function
 * instead of directly setting innerHTML in your hand-written code, so that it
 * will be easier to audit the code for cross-site scripting vulnerabilities.
 *
 * @param {Element} element The element whose content we are rendering into.
 * @param {?function(ARG_TYPES, Object<string, *>=):*|
 *     ?function(ARG_TYPES, null=, Object<string, *>=):*} template
 *     The Soy template defining the element's content.
 * @param {ARG_TYPES=} opt_templateData The data for the template.
 * @param {Object=} opt_injectedData The injected data for the template.
 * @template ARG_TYPES
 */
goog.soy.renderElement = function(
    element, template, opt_templateData, opt_injectedData) {
  // Soy template parameter is only nullable for historical reasons.
  goog.asserts.assert(template, 'Soy template may not be null.');
  var html = goog.soy.ensureTemplateOutputHtml_(template(
      opt_templateData || goog.soy.defaultTemplateData_, undefined,
      opt_injectedData));
  goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse(
      goog.asserts.assert(element),
      goog.html.uncheckedconversions
          .safeHtmlFromStringKnownToSatisfyTypeContract(
              goog.string.Const.from('Soy HTML template.'), html));
};

/**
 * Renders a Soy template into a single node or a document
 * fragment. If the rendered HTML string represents a single node, then that
 * node is returned (note that this is *not* a fragment, despite them name of
 * the method). Otherwise a document fragment is returned containing the
 * rendered nodes.
 *
 * @param {
 *     ?function(ARG_TYPES, Object<string, *>=):goog.soy.data.SanitizedContent|
 *     ?function(ARG_TYPES, null=, Object<string, *>=):
 *     goog.soy.data.SanitizedContent} template The Soy template defining the
 *     element's content. The kind of the template must be "html" or "text".
 * @param {ARG_TYPES=} opt_templateData The data for the template.
 * @param {Object=} opt_injectedData The injected data for the template.
 * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper used to
 *     create DOM nodes; defaults to `goog.dom.getDomHelper`.
 * @return {!Node} The resulting node or document fragment.
 * @template ARG_TYPES
 */
goog.soy.renderAsFragment = function(
    template, opt_templateData, opt_injectedData, opt_domHelper) {
  // Soy template parameter is only nullable for historical reasons.
  goog.asserts.assert(template, 'Soy template may not be null.');
  var dom = opt_domHelper || goog.dom.getDomHelper();
  var output = template(
      opt_templateData || goog.soy.defaultTemplateData_, undefined,
      opt_injectedData);
  var html = goog.soy.ensureTemplateOutputHtml_(output);
  goog.soy.assertFirstTagValid_(html);
  var safeHtml = output.toSafeHtml();
  return dom.safeHtmlToNode(safeHtml);
};

/**
 * Renders a Soy template into a single node. If the rendered
 * HTML string represents a single node, then that node is returned. Otherwise,
 * a DIV element is returned containing the rendered nodes.
 *
 * @param {?function(ARG_TYPES, Object<string, *>=):*|
 *     ?function(ARG_TYPES, null=, Object<string, *>=):*} template
 *     The Soy template defining the element's content.
 * @param {ARG_TYPES=} opt_templateData The data for the template.
 * @param {Object=} opt_injectedData The injected data for the template.
 * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper used to
 *     create DOM nodes; defaults to `goog.dom.getDomHelper`.
 * @return {!Element} Rendered template contents, wrapped in a parent DIV
 *     element if necessary.
 * @template ARG_TYPES
 */
goog.soy.renderAsElement = function(
    template, opt_templateData, opt_injectedData, opt_domHelper) {
  // Soy template parameter is only nullable for historical reasons.
  goog.asserts.assert(template, 'Soy template may not be null.');
  return goog.soy.convertToElement_(
      template(
          opt_templateData || goog.soy.defaultTemplateData_, undefined,
          opt_injectedData),
      opt_domHelper);
};

/**
 * Converts a processed Soy template into a single node. If the rendered
 * HTML string represents a single node, then that node is returned. Otherwise,
 * a DIV element is returned containing the rendered nodes.
 *
 * @param {!goog.soy.data.SanitizedContent} templateResult The processed
 *     template of kind HTML or TEXT (which will be escaped).
 * @param {?goog.dom.DomHelper=} opt_domHelper The DOM helper used to
 *     create DOM nodes; defaults to `goog.dom.getDomHelper`.
 * @return {!Element} Rendered template contents, wrapped in a parent DIV
 *     element if necessary.
 */
goog.soy.convertToElement = function(templateResult, opt_domHelper) {
  return goog.soy.convertToElement_(templateResult, opt_domHelper);
};

/**
 * Non-strict version of `goog.soy.convertToElement`.
 *
 * @param {*} templateResult The processed template.
 * @param {?goog.dom.DomHelper=} opt_domHelper The DOM helper used to
 *     create DOM nodes; defaults to `goog.dom.getDomHelper`.
 * @return {!Element} Rendered template contents, wrapped in a parent DIV
 *     element if necessary.
 * @private
 */
goog.soy.convertToElement_ = function(templateResult, opt_domHelper) {
  var dom = opt_domHelper || goog.dom.getDomHelper();
  var wrapper = dom.createElement(goog.dom.TagName.DIV);
  var html = goog.soy.ensureTemplateOutputHtml_(templateResult);
  goog.soy.assertFirstTagValid_(html);
  goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse(
      wrapper,
      goog.html.uncheckedconversions
          .safeHtmlFromStringKnownToSatisfyTypeContract(
              goog.string.Const.from('Soy HTML template.'), html));

  // If the template renders as a single element, return it.
  if (wrapper.childNodes.length == 1) {
    var firstChild = wrapper.firstChild;
    if (firstChild.nodeType == goog.dom.NodeType.ELEMENT) {
      return /** @type {!Element} */ (firstChild);
    }
  }

  // Otherwise, return the wrapper DIV.
  return wrapper;
};

/**
 * Ensures the result is "safe" to insert as HTML.
 *
 * Note if the template has non-strict autoescape, the guarantees here are very
 * weak. It is recommended applications switch to requiring strict
 * autoescaping over time by tweaking goog.soy.REQUIRE_STRICT_AUTOESCAPE.
 *
 * In the case the argument is a SanitizedContent object, it either must
 * already be of kind HTML, or if it is kind="text", the output will be HTML
 * escaped.
 *
 * @param {*} templateResult The template result.
 * @return {string} The assumed-safe HTML output string.
 * @private
 */
goog.soy.ensureTemplateOutputHtml_ = function(templateResult) {
  // Allow strings as long as strict autoescaping is not mandated. Note we
  // allow everything that isn't an object, because some non-escaping templates
  // end up returning non-strings if their only print statement is a
  // non-escaped argument, plus some unit tests spoof templates.
  // TODO(gboyer): Track down and fix these cases.
  if (!goog.soy.REQUIRE_STRICT_AUTOESCAPE && !goog.isObject(templateResult)) {
    return String(templateResult);
  }

  // Allow SanitizedContent of kind HTML.
  if (templateResult instanceof goog.soy.data.SanitizedContent) {
    templateResult =
        /** @type {!goog.soy.data.SanitizedContent} */ (templateResult);
    var ContentKind = goog.soy.data.SanitizedContentKind;
    if (templateResult.contentKind === ContentKind.HTML) {
      return goog.asserts.assertString(templateResult.getContent());
    }
    if (templateResult.contentKind === ContentKind.TEXT) {
      // Allow text to be rendered, as long as we escape it. Other content
      // kinds will fail, since we don't know what to do with them.
      // TODO(gboyer): Perhaps also include URI in this case.
      return goog.string.htmlEscape(templateResult.getContent());
    }
  }

  goog.asserts.fail(
      'Soy template output is unsafe for use as HTML: ' + templateResult);

  // In production, return a safe string, rather than failing hard.
  return 'zSoyz';
};

/**
 * Checks that the rendered HTML does not start with an invalid tag that would
 * likely cause unexpected output from renderAsElement or renderAsFragment.
 * See {@link http://www.w3.org/TR/html5/semantics.html#semantics} for reference
 * as to which HTML elements can be parents of each other.
 * @param {string} html The output of a template.
 * @private
 */
goog.soy.assertFirstTagValid_ = function(html) {
  if (goog.asserts.ENABLE_ASSERTS) {
    var matches = html.match(goog.soy.INVALID_TAG_TO_RENDER_);
    goog.asserts.assert(
        !matches, 'This template starts with a %s, which ' +
            'cannot be a child of a <div>, as required by soy internals. ' +
            'Consider using goog.soy.renderElement instead.\nTemplate output: %s',
        matches && matches[0], html);
  }
};

/**
 * A pattern to find templates that cannot be rendered by renderAsElement or
 * renderAsFragment, as these elements cannot exist as the child of a <div>.
 * @type {!RegExp}
 * @private
 */
goog.soy.INVALID_TAG_TO_RENDER_ =
    /^<(body|caption|col|colgroup|head|html|tr|td|th|tbody|thead|tfoot)>/i;

/**
 * Immutable object that is passed into templates that are rendered
 * without any data.
 * @private @const
 */
goog.soy.defaultTemplateData_ = {};
<|endoftext|>


<commit_before>// Copyright 2016 Google Inc. All rights reserved.
//
// 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.

(function(internal, scope) {

  function isInt(value) {
    return typeof value == 'number' && value % 1 === 0;
  }

  function CSSColorValue(r, g, b, a) {
    if (a === undefined) {
      a = 1;
    }

    if (!(isInt(r) && isInt(g) && isInt(b))) {
      throw new TypeError('r, g and b must be integers.');
    }

    if (typeof a != 'number') {
      throw new TypeError('a must be a number.');
    }

    if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
      throw new TypeError('r, g and b must be integers between 0 and 255.');
    }

    if (a < 0 || a > 1) {
      throw new TypeError('a must be a number between 0 and 1.');
    }
    this.r = r;
    this.g = g;
    this.b = b;
    this.a = a;
    this.cssText = this._generateCssString();
  }
  internal.inherit(CSSColorValue, CSSStyleValue);

  CSSColorValue.from = function(value) {
    var parsing = internal.parsing;

    var params = parsing.consumeList([
        parsing.consumeToken.bind(null, /^rgba?/i),
        parsing.ignore(parsing.consumeToken.bind(null, /^\(/)),
        parsing.consumeRepeated.bind(null, parsing.consumeNumber, /^,/),
        parsing.ignore(parsing.consumeToken.bind(null, /^\)/)),
    ], value);

    if (!params || params[1].length) {
      // Failure to parse, or trailing characters.
      return null;
    }
    params = params[0];

    var isRGBA = params[0].endsWith('a');
    values = params[1];
    for (var i = 0; i < 3; i++) {
      if (!isInt(values[i]) || values[i] < 0 || values[i] > 255) {
        return null;
      }
    }
    if (isRGBA  && values.length == 4) {
      if (values[3] < 0 || values[3] > 1) {
        return null;
      }
      var result = new CSSColorValue(values[0], values[1], values[2], values[3]);
      return result;
    } else if (!isRGBA && values.length == 3) {
      var result = new CSSColorValue(values[0], values[1], values[2]);
      return result;
    }
    return null;
  };

  CSSColorValue.prototype._generateCssString = function() {
    var cssText = this.a == 1 ? 'rgb(' : 'rgba(';
    cssText = cssText + this.r + ',' + this.g + ',' + this.b;

    if (this.a != 1) {
      cssText  = cssText + ',' + this.a;
    }
    cssText = cssText + ')'
    return cssText;
  };

  scope.CSSColorValue = CSSColorValue;

})(typedOM.internal, window);
<commit_msg>Make _generateCssString more private in CSSColorValue<commit_after>// Copyright 2016 Google Inc. All rights reserved.
//
// 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.

(function(internal, scope) {

  function isInt(value) {
    return typeof value == 'number' && value % 1 === 0;
  }

  function generateCssString(colorValue) {
    var cssText = colorValue.a == 1 ? 'rgb(' : 'rgba(';
    cssText = cssText + colorValue.r + ',' + colorValue.g + ',' + colorValue.b;

    if (colorValue.a != 1) {
      cssText  = cssText + ',' + colorValue.a;
    }
    cssText = cssText + ')'
    return cssText;
  }

  function CSSColorValue(r, g, b, a) {
    if (a === undefined) {
      a = 1;
    }

    if (!(isInt(r) && isInt(g) && isInt(b))) {
      throw new TypeError('r, g and b must be integers.');
    }

    if (typeof a != 'number') {
      throw new TypeError('a must be a number.');
    }

    if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
      throw new TypeError('r, g and b must be integers between 0 and 255.');
    }

    if (a < 0 || a > 1) {
      throw new TypeError('a must be a number between 0 and 1.');
    }
    this.r = r;
    this.g = g;
    this.b = b;
    this.a = a;
    this.cssText = generateCssString(this);
  }
  internal.inherit(CSSColorValue, CSSStyleValue);

  CSSColorValue.from = function(value) {
    var parsing = internal.parsing;

    var params = parsing.consumeList([
        parsing.consumeToken.bind(null, /^rgba?/i),
        parsing.ignore(parsing.consumeToken.bind(null, /^\(/)),
        parsing.consumeRepeated.bind(null, parsing.consumeNumber, /^,/),
        parsing.ignore(parsing.consumeToken.bind(null, /^\)/)),
    ], value);

    if (!params || params[1].length) {
      // Failure to parse, or trailing characters.
      return null;
    }
    params = params[0];

    var isRGBA = params[0].endsWith('a');
    values = params[1];
    for (var i = 0; i < 3; i++) {
      if (!isInt(values[i]) || values[i] < 0 || values[i] > 255) {
        return null;
      }
    }
    if (isRGBA  && values.length == 4) {
      if (values[3] < 0 || values[3] > 1) {
        return null;
      }
      var result = new CSSColorValue(values[0], values[1], values[2], values[3]);
      return result;
    } else if (!isRGBA && values.length == 3) {
      var result = new CSSColorValue(values[0], values[1], values[2]);
      return result;
    }
    return null;
  };

  scope.CSSColorValue = CSSColorValue;

})(typedOM.internal, window);
<|endoftext|>


<commit_before>//
//     Copyright (c) 1979, the Gra projects.
//     Please see the AUTHORS file for details.
//     All rights reserved.
//     Use of this source code is governed by a MIT-style license
//     that can be found in the LICENSE file.
//
//
//     @author Gra <Gołębiewski Radosław A.>
//             https://github.com/golebier or https://golebier.github.io
//             https://google.com/+RadoslawGolebiewski
//             http://www.linkedin.com/pub/rados%C5%82aw-go%C5%82%C4%99biewski/70/832/35
//

var app = angular.module('sp12', ['ngRoute']);

app.config(function ($routeProvider) {
	   $routeProvider
	      .when('/', {
	    	  // TODO read f from file?
	          controller: function($scope, $location, $route) {
	        	  // TODO
                },
	          templateUrl: 'htmls/views/main.html'
	      })
	      // TODO add more, CSM via W3/Mob/...
	      .otherwise({redirectTo: '/'});
});

app.controller('footer', function($scope) {
     $scope.accounts = [
                            { name: "Linkedin",
                               url: "http://pl.linkedin.com/pub/rados%C5%82aw-go%C5%82%C4%99biewski/70/832/35/",
                           iconUrl: "https://github.com/golebier/TemplateTeXCv/raw/master/Icons/linkedin.png"
                            },
                            { name: "Google plus",
                               url: "https://google.com/+RadoslawGolebiewski",
                           iconUrl: "https://github.com/golebier/TemplateTeXCv/raw/master/Icons/gplus.jpg"
                            },
                            { name: "Github",
                               url: "https://github.com/golebier",
                           iconUrl: "https://github.com/golebier/TemplateTeXCv/raw/master/Icons/github.png"
                            }
                        ];
});

app.controller('menu', function($scope) {
     $scope.main = [
                            { name: "Strona Główna",
                               url: "#/", // main
                            },
                            { name: "Fotogaleria",
                               url: "#/fotogallery"
                            },
                            { name: "Cyfrowa Szkola",
                               url: "#/ishool"
                            },
                            { name: "Prawo Szkolne",
                               url: "#/schoollow"
                            },
                            { name: "O Szkole",
                               url: "#/aboutas"
                            },
                            { name: "Kontakt",
                               url: "#/contact"
                            },
                            { name: "Archiwalna",
                               url: "http://www.sp12plock.pl/"
                            }
                        ];

     $scope.parentinfo = [
                            { name: "e-dziennik",
                               url: "#/eRegister/"
                            },
                            { name: "Pierwszak w szkole",
                               url: "#/fromkinderganden/"
                            },
                            { name: "Zebrania",
                               url: "#/meetings/"
                            },
                            { name: "Kalendarz Szkolny",
                               url: "#/schoolCalendar/"
                            },
                            { name: "Konkursy Przedmiotowe",
                               url: "#/subjectCompetitions/"
                            },
                ];

     $scope.school = [
                            { name: "Plan zajęć",
                                url: "#/lessonsPlans/"
                            },
                            { name: "Rada Pedagogiczna",
                                url: "#/radapedadogiczna"
                            },
                            { name: "Samorząd Uczniowski",
                                url: "#/samorzaduczniowski"
                            },
                            { name: "Osiągnięcia",
                                url: "#/osiagniecia"
                            },
                            { name: "Zajęcia Pozalekcyjne",
                                url: "http://www.sp12plock.pl/zajecia_pozalekcyjne.html/"
                            },
                            { name: "Świetlica",
                                url: "#/swietlica/"
                            },
                            { name: "Podręczniki",
                                url: "#/podreczniki/"
                            },
                            { name: "Stypendia",
                                url: "#/stypendia/"
                            },
                            { name: "Stowarzyszenie",
                                url: "#/stowarzyszenie/"
                            }
                      ];

     $scope.library = [
                        { name: "Stara strona",
                           url: "http://www.sp12plock.pl/biblioteka/index.html"
                        },
                        { name: "O bibliotece",
                           url: "#/aboutLibrary/"
                        },
                        { name: "Lektury",
                           url: "#/lectures/"
                        },
                        { name: "Czytelnictwo",
                           url: "#/readRates/"
                        },
                        { name: "Regulaminy",
                           url: "#/regulations/"
                        },
                        { name: "Konkursy",
                           url: "#/competitions/"
                        },
                        { name: "Imprezy",
                           url: "#/events/"
                        },
                        { name: "Złota Lista",
                            url: "#/goldenList/"
                        },
                        { name: "Fotogaleria",
                            url: "#/photoGallery/"
                        },
                        { name: "Przydatne strony",
                            url: "#/usefulWebSides/"
                        }
     ];

     $scope.archive = [
                        // months
                        { name: "Wrzesień",
                           url: "201409",
                           amount: "12"

                        },
                        { name: "Sierpień",
                           url: "201408",
                        amount: "5"
                        },
                        // years, after the calendar new year, above changes to year ...
                        { name: "2013",
                           url: "2013",
                        amount: "144"
                        },
                        { name: "2012",
                            url: "2012",
                         amount: "156"
                        }
     ];

     $scope.sport = [
                        { name: "Program Otwarte Szkolne Obiekty Sportowe",
                           url: "posos"

                        },
                        { name: "ORLEN Szkolna Liga MDK",
                           url: "oslmkd"
                        },
                        { name: "ORLEN Szkolna Liga MDK",
                           url: "http://www.sp12plock.pl/liga-mdk.html"
                        }
     ];
     // deprecated TODO remove after all menus are corrected
     $scope.show = false;
     $scope.prepareClassForSidebarLeft = function () {
         return "sidebar";//$scope.show?"sidebar":"lesssidebar";
     };

     $scope.showState = function (position) {
         return showList[position];
     };

     $scope.showState = function (position, state) {
         return showList[position] = state;
     };
});
<commit_msg>Show states list, initialized.<commit_after>//
//     Copyright (c) 1979, the Gra projects.
//     Please see the AUTHORS file for details.
//     All rights reserved.
//     Use of this source code is governed by a MIT-style license
//     that can be found in the LICENSE file.
//
//
//     @author Gra <Gołębiewski Radosław A.>
//             https://github.com/golebier or https://golebier.github.io
//             https://google.com/+RadoslawGolebiewski
//             http://www.linkedin.com/pub/rados%C5%82aw-go%C5%82%C4%99biewski/70/832/35
//

var app = angular.module('sp12', ['ngRoute']);

app.config(function ($routeProvider) {
	   $routeProvider
	      .when('/', {
	    	  // TODO read f from file?
	          controller: function($scope, $location, $route) {
	        	  // TODO
                },
	          templateUrl: 'htmls/views/main.html'
	      })
	      // TODO add more, CSM via W3/Mob/...
	      .otherwise({redirectTo: '/'});
});

app.controller('footer', function($scope) {
     $scope.accounts = [
                            { name: "Linkedin",
                               url: "http://pl.linkedin.com/pub/rados%C5%82aw-go%C5%82%C4%99biewski/70/832/35/",
                           iconUrl: "https://github.com/golebier/TemplateTeXCv/raw/master/Icons/linkedin.png"
                            },
                            { name: "Google plus",
                               url: "https://google.com/+RadoslawGolebiewski",
                           iconUrl: "https://github.com/golebier/TemplateTeXCv/raw/master/Icons/gplus.jpg"
                            },
                            { name: "Github",
                               url: "https://github.com/golebier",
                           iconUrl: "https://github.com/golebier/TemplateTeXCv/raw/master/Icons/github.png"
                            }
                        ];
});

app.controller('menu', function($scope) {
     $scope.main = [
                            { name: "Strona Główna",
                               url: "#/", // main
                            },
                            { name: "Fotogaleria",
                               url: "#/fotogallery"
                            },
                            { name: "Cyfrowa Szkola",
                               url: "#/ishool"
                            },
                            { name: "Prawo Szkolne",
                               url: "#/schoollow"
                            },
                            { name: "O Szkole",
                               url: "#/aboutas"
                            },
                            { name: "Kontakt",
                               url: "#/contact"
                            },
                            { name: "Archiwalna",
                               url: "http://www.sp12plock.pl/"
                            }
                        ];

     $scope.parentinfo = [
                            { name: "e-dziennik",
                               url: "#/eRegister/"
                            },
                            { name: "Pierwszak w szkole",
                               url: "#/fromkinderganden/"
                            },
                            { name: "Zebrania",
                               url: "#/meetings/"
                            },
                            { name: "Kalendarz Szkolny",
                               url: "#/schoolCalendar/"
                            },
                            { name: "Konkursy Przedmiotowe",
                               url: "#/subjectCompetitions/"
                            },
                ];

     $scope.school = [
                            { name: "Plan zajęć",
                                url: "#/lessonsPlans/"
                            },
                            { name: "Rada Pedagogiczna",
                                url: "#/radapedadogiczna"
                            },
                            { name: "Samorząd Uczniowski",
                                url: "#/samorzaduczniowski"
                            },
                            { name: "Osiągnięcia",
                                url: "#/osiagniecia"
                            },
                            { name: "Zajęcia Pozalekcyjne",
                                url: "http://www.sp12plock.pl/zajecia_pozalekcyjne.html/"
                            },
                            { name: "Świetlica",
                                url: "#/swietlica/"
                            },
                            { name: "Podręczniki",
                                url: "#/podreczniki/"
                            },
                            { name: "Stypendia",
                                url: "#/stypendia/"
                            },
                            { name: "Stowarzyszenie",
                                url: "#/stowarzyszenie/"
                            }
                      ];

     $scope.library = [
                        { name: "Stara strona",
                           url: "http://www.sp12plock.pl/biblioteka/index.html"
                        },
                        { name: "O bibliotece",
                           url: "#/aboutLibrary/"
                        },
                        { name: "Lektury",
                           url: "#/lectures/"
                        },
                        { name: "Czytelnictwo",
                           url: "#/readRates/"
                        },
                        { name: "Regulaminy",
                           url: "#/regulations/"
                        },
                        { name: "Konkursy",
                           url: "#/competitions/"
                        },
                        { name: "Imprezy",
                           url: "#/events/"
                        },
                        { name: "Złota Lista",
                            url: "#/goldenList/"
                        },
                        { name: "Fotogaleria",
                            url: "#/photoGallery/"
                        },
                        { name: "Przydatne strony",
                            url: "#/usefulWebSides/"
                        }
     ];

     $scope.archive = [
                        // months
                        { name: "Wrzesień",
                           url: "201409",
                           amount: "12"

                        },
                        { name: "Sierpień",
                           url: "201408",
                        amount: "5"
                        },
                        // years, after the calendar new year, above changes to year ...
                        { name: "2013",
                           url: "2013",
                        amount: "144"
                        },
                        { name: "2012",
                            url: "2012",
                         amount: "156"
                        }
     ];

     $scope.sport = [
                        { name: "Program Otwarte Szkolne Obiekty Sportowe",
                           url: "posos"

                        },
                        { name: "ORLEN Szkolna Liga MDK",
                           url: "oslmkd"
                        },
                        { name: "ORLEN Szkolna Liga MDK",
                           url: "http://www.sp12plock.pl/liga-mdk.html"
                        }
     ];
     // deprecated TODO remove after all menus are corrected
     $scope.show = false;
     $scope.prepareClassForSidebarLeft = function () {
         return "sidebar";//$scope.show?"sidebar":"lesssidebar";
     };

     $scope.showList['Sport'] = false;
     $scope.showState = function (position) {
         return $scope.showList[position];
     };

     $scope.showState = function (position, state) {
         return $scope.showList[position] = state;
     };
});
<|endoftext|>


<commit_before>// Initial LCD draft based on Andreas Haugstrup Pedersen's
// proof of concept: https://gist.github.com/3200887
//
//
//
var Board = require("../lib/board.js"),
    events = require("events"),
    util = require("util"),
    __ = require("../lib/fn.js"),
    es6 = require("es6-collections"),
    WeakMap = es6.WeakMap;

var DeviceMap,
    characters,
    priv = new WeakMap();

DeviceMap = {

};

function sleep( milliSeconds ) {
  var startTime = Date.now();
  while ( Date.now() < startTime + milliSeconds ) {}
}

/**
 * LCD
 * @param {[type]} opts [description]
 */
function LCD( opts ) {

  if ( !(this instanceof LCD) ) {
    return new LCD( opts );
  }

  opts = Board.options( opts );

  // Hardware instance properties
  this.board = Board.mount( opts );
  this.firmata = this.board.firmata;

  // options
  this.bitMode = opts.bitMode || 4;
  this.lines = opts.lines || 2;
  this.dots = opts.dots || "5x8";

  this.pins = {
    rs: opts.pins[0],
    en: opts.pins[1],
    // TODO: Move to device map profile
    data: [
      opts.pins[5],
      opts.pins[4],
      opts.pins[3],
      opts.pins[2]
    ]
  };
  // Track display state. This can be updated directly by user code
  // Prefixed with underscore exists to avoid shadowing the
  // LCD.prototype.display method
  this._display = LCD.DISPLAYCONTROL | LCD.DISPLAYON;

  priv.set( this, {
    characters: []
  });

  // TODO: ALL OF THIS NEEDS TO BE RE-WRITTEN
  //
  //
  // RS to low (for command mode), EN to low to start
  // TODO: Move to device map profile
  this.board.digitalWrite( this.pins.rs, this.firmata.LOW );
  this.board.digitalWrite( this.pins.en, this.firmata.LOW );

  // Wait 50ms before initializing to make sure LCD is powered up
  // TODO: Don't use sleep
  setTimeout(function() {
    // Send 0011 thrice to make sure LCD is initialized properly
    this.writeBits(0x03);
    sleep(5);
    this.writeBits(0x03);
    sleep(5);
    this.writeBits(0x03);

    // Switch to 4-bit mode
    // TODO: Move to device map profile
    if ( this.bitMode === 4 ) {
      this.writeBits(0x02);
    }

    // Set number of lines and dots
    // TODO: Move to device map profile
    this.command(
      LCD.FUNCTIONSET |
      LCD.LINE[ this.lines ] |
      LCD.DOTS[ this.dots ]
    );

    // Clear display and turn it on
    this.command( this._display );
    this.clear();
    this.home();

    this.emit.call( this, "ready", null );
  }.bind(this), 50);
}

util.inherits( LCD, events.EventEmitter );

// |this| sensitive, must be called as
// LCD.hilo.call( lcd, callback );
LCD.hilo = function( callback ) {
  if ( !(this instanceof LCD) ) {
    throw new Error("Cannot toggle a non-LCD instance");
  }

  // RS High for write mode
  this.board.digitalWrite( this.pins.rs, this.firmata.HIGH );

  // Callback wrapped write this.command( charCode );functionality
  callback.call( this );

  // RS Low for command mode
  this.board.digitalWrite( this.pins.rs, this.firmata.LOW );
};

LCD.prototype.pulse = function() {
  [ "LOW", "HIGH", "LOW" ].forEach(function(val) {
    this.board.digitalWrite(this.pins.en, this.firmata[ val ] );
  }, this);

  return this;
};

LCD.prototype.writeBits = function( value ) {
  var pin, mask;

  pin = 0;
  mask = { 4: 8, 8: 128 }[ this.bitMode ];

  for ( ; mask > 0; mask = mask >> 1 ) {
    this.board.digitalWrite(
      this.pins.data[ pin ],
      this.firmata[ value & mask ? "HIGH" : "LOW" ]
    );
    pin++;
  }

  this.pulse();

  return this;
};

LCD.prototype.command = function( command, callback ) {
  if ( this.bitMode === 4 ) {
    this.writeBits( command >> 4 );
  }

  this.writeBits( command );

  if ( callback ) {
    process.nextTick( callback );
  }

  return this;
};

LCD.prototype.print = function( message ) {
  var chars, msg;

  chars = message.match( /:[a-z0-9\+\-_]+:/g );
  msg = message;

  if ( chars !== null && chars.length ) {
    chars.forEach(function( char ) {

      process.nextTick(function() {

        var parts = msg.split(char),
            location = priv.get(this).characters[ char.replace(/:/g, "") ];

        // Print message chunk and write the character tht appeared
        this.print( parts[0] );
        this.write( location );

        // Update msg
        msg = parts.slice(1).join(char);

        // Ensure message ends are printed
        if ( !/:[a-z0-9\+\-_]+:/g.test( msg ) ) {
          this.print( msg );
          msg = "";
        }

      }.bind(this));
    }, this );

  } else {

    LCD.hilo.call( this, function() {
      [].slice.call( String(message) ).forEach(function( char ) {
        // console.log( char, char.charCodeAt(0) );
        this.command( char.charCodeAt(0), function() {
          sleep(2);
        });
      }, this );
    });
  }

  return this;
};

LCD.prototype.write = function( charCode ) {
  LCD.hilo.call( this, function() {
    this.command( charCode );
  });
  return this;
};

LCD.prototype.clear = function() {
  this.command( LCD.CLEARDISPLAY );

  return this;
};

LCD.prototype.home = function() {
  this.command( LCD.RETURNHOME );
  sleep(2); // Command can be slow

  return this;
};

LCD.prototype.setCursor = function( col, row ) {
  var rowOffsets = [ 0x00, 0x40, 0x14, 0x54 ];
  this.command( LCD.SETDDRAMADDR | ( col + rowOffsets[ row ] ) );

  return this;
};

LCD.prototype.display = function() {
  this._display |= LCD.DISPLAYON;
  this.command( this._display );

  return this;
};

LCD.prototype.noDisplay = function() {
  this._display &= ~LCD.DISPLAYON;
  this.command( this._display );

  return this;
};

LCD.prototype.cursor = function() {
  this._display |= LCD.CURSORON;
  this.command( this._display );

  return this;
};

LCD.prototype.noCursor = function() {
  this._display &= ~LCD.CURSORON;
  this.command( this._display );

  return this;
};

LCD.prototype.blink = function() {
  this._display |= LCD.BLINKON;
  this.command( this._display );

  return this;
};

LCD.prototype.noBlink = function() {
  this._display &= ~LCD.BLINKON;
  this.command( this._display );

  return this;
};

LCD.prototype.createChar = function( number, charMap ) {
  // Ensure location is never above 7
  var state, location;

  location = number & 0x07;
  state = priv.get( this );

  this.command( LCD.SETCGRAMADDR | (location << 3) );

  LCD.hilo.call( this, function() {
    var i;
    for ( i = 0; i < 8; i++ ) {
      this.command( charMap[i] );
    }
  });

  // Fill in location
  state.characters[ location ] = location;

  // Update private state
  priv.set( this, state );

  return this;
};

LCD.prototype.useChar = function( name ) {
  var state, k;

  // Derive the current private state cache
  state = priv.get( this );

  k = 8;

  while ( --k > -2 ) {
    if ( state.characters[ k ] === undefined ) {
      break;
    }
  }

  // Create the character in LCD memory
  this.createChar( k, characters[ name ] );

  // Add character to current LCD character map
  state.characters[ name ] = k;

  // Update private data cache
  priv.set( this, state );

  return this;
};

characters = {
  bell:     [ 0x4, 0xe, 0xe, 0xe, 0x1f, 0x0, 0x4 ],
  note:     [ 0x2, 0x3, 0x2, 0xe, 0x1e, 0xc, 0x0 ],
  clock:    [ 0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0 ],
  heart:    [ 0x0, 0xa, 0x1f, 0x1f, 0xe, 0x4, 0x0 ],
  duck:     [ 0x0, 0xc, 0x1d, 0xf, 0xf, 0x6, 0x0 ],
  check:    [ 0x0, 0x1, 0x3, 0x16, 0x1c, 0x8, 0x0 ],
  cross:    [ 0x0, 0x1b, 0xe, 0x4, 0xe, 0x1b, 0x0 ],
  retarrow: [ 0x1, 0x1, 0x5, 0x9, 0x1f, 0x8, 0x4 ]
};

// createChar resources:
// http://www.hackmeister.dk/2010/08/custom-lcd-characters-with-arduino/
//

/**
 *

TODO:

begin()
burst()
print()
scrollDisplayLeft()
scrollDisplayRight()
autoscroll()
noAutoscroll()
leftToRight()
rightToLeft()

*/

// commands
LCD.CLEARDISPLAY = 0x01;
LCD.RETURNHOME = 0x02;
LCD.ENTRYMODESET = 0x04;
LCD.DISPLAYCONTROL = 0x08;
LCD.CURSORSHIFT = 0x10;
LCD.FUNCTIONSET = 0x20;
LCD.SETCGRAMADDR = 0x40;
LCD.SETDDRAMADDR = 0x80;

// flags for display entry mode
LCD.ENTRYRIGHT = 0x00;
LCD.ENTRYLEFT = 0x02;
LCD.ENTRYSHIFTINCREMENT = 0x01;
LCD.ENTRYSHIFTDECREMENT = 0x00;

// flags for display on/off control
LCD.DISPLAYON = 0x04;
LCD.DISPLAYOFF = 0x00;
LCD.CURSORON = 0x02;
LCD.CURSOROFF = 0x00;
LCD.BLINKON = 0x01;
LCD.BLINKOFF = 0x00;

// flags for display/cursor shift
LCD.DISPLAYMOVE = 0x08;
LCD.CURSORMOVE = 0x00;
LCD.MOVERIGHT = 0x04;
LCD.MOVELEFT = 0x00;

// flags for function set
// Intentionally sparse array
LCD.BITMODE = [ , , , , 0x00, , , , 0x10 ];
// 4 & 8

// Intentionally sparse array
LCD.LINE = [ , 0x00, 0x08 ];
// 1 & 2

LCD.DOTS = {
  "5x10": 0x04,
  "5x8": 0x00
};

// flags for backlight control
LCD.BACKLIGHT = {
  ON: 0x08,
  OFF: 0x00
};

module.exports = LCD;

// http://www.arduino.cc/playground/Code/LCDAPI
<commit_msg>LCD autoscroll/noautoscroll<commit_after>// Initial LCD draft based on Andreas Haugstrup Pedersen's
// proof of concept: https://gist.github.com/3200887
//
//
//
var Board = require("../lib/board.js"),
    events = require("events"),
    util = require("util"),
    __ = require("../lib/fn.js"),
    es6 = require("es6-collections"),
    WeakMap = es6.WeakMap;

var DeviceMap,
    characters,
    priv = new WeakMap();

DeviceMap = {

};

function sleep( milliSeconds ) {
  var startTime = Date.now();
  while ( Date.now() < startTime + milliSeconds ) {}
}

/**
 * LCD
 * @param {[type]} opts [description]
 */
function LCD( opts ) {

  if ( !(this instanceof LCD) ) {
    return new LCD( opts );
  }

  opts = Board.options( opts );

  // Hardware instance properties
  this.board = Board.mount( opts );
  this.firmata = this.board.firmata;

  // options
  this.bitMode = opts.bitMode || 4;
  this.lines = opts.lines || 2;
  this.dots = opts.dots || "5x8";

  this.pins = {
    rs: opts.pins[0],
    en: opts.pins[1],
    // TODO: Move to device map profile
    data: [
      opts.pins[5],
      opts.pins[4],
      opts.pins[3],
      opts.pins[2]
    ]
  };
  // Track display state. This can be updated directly by user code
  // Prefixed with underscore exists to avoid shadowing the
  // LCD.prototype.display method
  this._display = LCD.DISPLAYCONTROL | LCD.DISPLAYON;

  priv.set( this, {
    characters: []
  });

  // TODO: ALL OF THIS NEEDS TO BE RE-WRITTEN
  //
  //
  // RS to low (for command mode), EN to low to start
  // TODO: Move to device map profile
  this.board.digitalWrite( this.pins.rs, this.firmata.LOW );
  this.board.digitalWrite( this.pins.en, this.firmata.LOW );

  // Wait 50ms before initializing to make sure LCD is powered up
  // TODO: Don't use sleep
  setTimeout(function() {
    // Send 0011 thrice to make sure LCD is initialized properly
    this.writeBits(0x03);
    sleep(5);
    this.writeBits(0x03);
    sleep(5);
    this.writeBits(0x03);

    // Switch to 4-bit mode
    // TODO: Move to device map profile
    if ( this.bitMode === 4 ) {
      this.writeBits(0x02);
    }

    // Set number of lines and dots
    // TODO: Move to device map profile
    this.command(
      LCD.FUNCTIONSET |
      LCD.LINE[ this.lines ] |
      LCD.DOTS[ this.dots ]
    );

    // Clear display and turn it on
    this.command( this._display );
    this.clear();
    this.home();

    this.emit.call( this, "ready", null );
  }.bind(this), 50);
}

util.inherits( LCD, events.EventEmitter );

// |this| sensitive, must be called as
// LCD.hilo.call( lcd, callback );
LCD.hilo = function( callback ) {
  if ( !(this instanceof LCD) ) {
    throw new Error("Cannot toggle a non-LCD instance");
  }

  // RS High for write mode
  this.board.digitalWrite( this.pins.rs, this.firmata.HIGH );

  // Callback wrapped write this.command( charCode );functionality
  callback.call( this );

  // RS Low for command mode
  this.board.digitalWrite( this.pins.rs, this.firmata.LOW );
};

LCD.prototype.pulse = function() {
  [ "LOW", "HIGH", "LOW" ].forEach(function(val) {
    this.board.digitalWrite(this.pins.en, this.firmata[ val ] );
  }, this);

  return this;
};

LCD.prototype.writeBits = function( value ) {
  var pin, mask;

  pin = 0;
  mask = { 4: 8, 8: 128 }[ this.bitMode ];

  for ( ; mask > 0; mask = mask >> 1 ) {
    this.board.digitalWrite(
      this.pins.data[ pin ],
      this.firmata[ value & mask ? "HIGH" : "LOW" ]
    );
    pin++;
  }

  this.pulse();

  return this;
};

LCD.prototype.command = function( command, callback ) {
  if ( this.bitMode === 4 ) {
    this.writeBits( command >> 4 );
  }

  this.writeBits( command );

  if ( callback ) {
    process.nextTick( callback );
  }

  return this;
};

LCD.prototype.print = function( message ) {
  var chars, msg;

  chars = message.match( /:[a-z0-9\+\-_]+:/g );
  msg = message;

  if ( chars !== null && chars.length ) {
    chars.forEach(function( char ) {

      process.nextTick(function() {

        var parts = msg.split(char),
            location = priv.get(this).characters[ char.replace(/:/g, "") ];

        // Print message chunk and write the character tht appeared
        this.print( parts[0] );
        this.write( location );

        // Update msg
        msg = parts.slice(1).join(char);

        // Ensure message ends are printed
        if ( !/:[a-z0-9\+\-_]+:/g.test( msg ) ) {
          this.print( msg );
          msg = "";
        }

      }.bind(this));
    }, this );

  } else {

    LCD.hilo.call( this, function() {
      [].slice.call( String(message) ).forEach(function( char ) {
        // console.log( char, char.charCodeAt(0) );
        this.command( char.charCodeAt(0), function() {
          sleep(2);
        });
      }, this );
    });
  }

  return this;
};

LCD.prototype.write = function( charCode ) {
  LCD.hilo.call( this, function() {
    this.command( charCode );
  });
  return this;
};

LCD.prototype.clear = function() {
  this.command( LCD.CLEARDISPLAY );

  return this;
};

LCD.prototype.home = function() {
  this.command( LCD.RETURNHOME );
  sleep(2); // Command can be slow

  return this;
};

LCD.prototype.setCursor = function( col, row ) {
  var rowOffsets = [ 0x00, 0x40, 0x14, 0x54 ];
  this.command( LCD.SETDDRAMADDR | ( col + rowOffsets[ row ] ) );

  return this;
};

LCD.prototype.display = function() {
  this._display |= LCD.DISPLAYON;
  this.command( this._display );

  return this;
};

LCD.prototype.noDisplay = function() {
  this._display &= ~LCD.DISPLAYON;
  this.command( this._display );

  return this;
};

LCD.prototype.cursor = function() {
  this._display |= LCD.CURSORON;
  this.command( this._display );

  return this;
};

LCD.prototype.noCursor = function() {
  this._display &= ~LCD.CURSORON;
  this.command( this._display );

  return this;
};

LCD.prototype.blink = function() {
  this._display |= LCD.BLINKON;
  this.command( this._display );

  return this;
};

LCD.prototype.noBlink = function() {
  this._display &= ~LCD.BLINKON;
  this.command( this._display );

  return this;
};

LCD.prototype.autoscroll = function() {
  this._display |= LCD.ENTRYSHIFTINCREMENT;
  this.command( LCD.ENTRYMODESET | this._display );

  return this;
};

LCD.prototype.noAutoscroll = function() {
  this._display &= ~LCD.ENTRYSHIFTINCREMENT;
  this.command( LCD.ENTRYMODESET | this._display );

  return this;
};

LCD.prototype.createChar = function( number, charMap ) {
  // Ensure location is never above 7
  var state, location;

  location = number & 0x07;
  state = priv.get( this );

  this.command( LCD.SETCGRAMADDR | (location << 3) );

  LCD.hilo.call( this, function() {
    var i;
    for ( i = 0; i < 8; i++ ) {
      this.command( charMap[i] );
    }
  });

  // Fill in location
  state.characters[ location ] = location;

  // Update private state
  priv.set( this, state );

  return this;
};

LCD.prototype.useChar = function( name ) {
  var state, k;

  // Derive the current private state cache
  state = priv.get( this );

  k = 8;

  while ( --k > -2 ) {
    if ( state.characters[ k ] === undefined ) {
      break;
    }
  }

  // Create the character in LCD memory
  this.createChar( k, characters[ name ] );

  // Add character to current LCD character map
  state.characters[ name ] = k;

  // Update private data cache
  priv.set( this, state );

  return this;
};

characters = {
  bell:     [ 0x4, 0xe, 0xe, 0xe, 0x1f, 0x0, 0x4 ],
  note:     [ 0x2, 0x3, 0x2, 0xe, 0x1e, 0xc, 0x0 ],
  clock:    [ 0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0 ],
  heart:    [ 0x0, 0xa, 0x1f, 0x1f, 0xe, 0x4, 0x0 ],
  duck:     [ 0x0, 0xc, 0x1d, 0xf, 0xf, 0x6, 0x0 ],
  check:    [ 0x0, 0x1, 0x3, 0x16, 0x1c, 0x8, 0x0 ],
  cross:    [ 0x0, 0x1b, 0xe, 0x4, 0xe, 0x1b, 0x0 ],
  retarrow: [ 0x1, 0x1, 0x5, 0x9, 0x1f, 0x8, 0x4 ]
};

// createChar resources:
// http://www.hackmeister.dk/2010/08/custom-lcd-characters-with-arduino/
//

/**
 *

TODO:

burst()

scrollDisplayLeft()
scrollDisplayRight()

leftToRight()
rightToLeft()

*/

// commands
LCD.CLEARDISPLAY = 0x01;
LCD.RETURNHOME = 0x02;
LCD.ENTRYMODESET = 0x04;
LCD.DISPLAYCONTROL = 0x08;
LCD.CURSORSHIFT = 0x10;
LCD.FUNCTIONSET = 0x20;
LCD.SETCGRAMADDR = 0x40;
LCD.SETDDRAMADDR = 0x80;

// flags for display entry mode
LCD.ENTRYRIGHT = 0x00;
LCD.ENTRYLEFT = 0x02;
LCD.ENTRYSHIFTINCREMENT = 0x01;
LCD.ENTRYSHIFTDECREMENT = 0x00;

// flags for display on/off control
LCD.DISPLAYON = 0x04;
LCD.DISPLAYOFF = 0x00;
LCD.CURSORON = 0x02;
LCD.CURSOROFF = 0x00;
LCD.BLINKON = 0x01;
LCD.BLINKOFF = 0x00;

// flags for display/cursor shift
LCD.DISPLAYMOVE = 0x08;
LCD.CURSORMOVE = 0x00;
LCD.MOVERIGHT = 0x04;
LCD.MOVELEFT = 0x00;

// flags for function set
// Intentionally sparse array
LCD.BITMODE = [ , , , , 0x00, , , , 0x10 ];
// 4 & 8

// Intentionally sparse array
LCD.LINE = [ , 0x00, 0x08 ];
// 1 & 2

LCD.DOTS = {
  "5x10": 0x04,
  "5x8": 0x00
};

// flags for backlight control
LCD.BACKLIGHT = {
  ON: 0x08,
  OFF: 0x00
};

module.exports = LCD;

// http://www.arduino.cc/playground/Code/LCDAPI
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var pkg = require('../../package.json')
  , agent = 'Anvil Connect/' + pkg.version
  , URL = require('url')
  , util = require('util')
  , Strategy = require('passport-strategy')
  , request = require('superagent')
  , FormUrlencoded = require('form-urlencoded')
  , map = require('../../node_modules/modinha/lib/initialize').map
  ;

/**
 * OAuth2Strategy
 */

function OAuth2Strategy (provider, client, verify) {
  Strategy.call(this);
  this.provider   = provider;
  this.endpoints  = provider.endpoints;
  this.mapping    = provider.mapping;
  this.client     = client;
  this.name       = provider.id;
  this.verify     = verify;
}

util.inherits(OAuth2Strategy, Strategy);

/**
 * Authenticate
 */

function authenticate (req, options) {
  var strategy = this
    , error    = req.query && req.query.error
    , code     = req.query && req.query.code
    , options  = options || {}
    ;

  // Handle authorization endpoint error
  if (error) {
    // handle error response
  }

  // Handle token response
  if (code) {
    // exchange the code for an access token
    strategy.authorizationCodeGrant(code, function (err, response) {
      if (err) {}

      // request user info
      strategy.userInfo(response.access_token, function (err, profile) {
        if (err) {}

        // invoke the callback
        strategy.verify(req, response, profile, function (err, user, info) {
          if (err)   { return strategy.error(err); }
          if (!user) { return strategy.fail(info); }
          strategy.success(user, info);
        });
      });
    });
  }

  // Initiate the OAuth 2.0 Authorization Code Flow
  else {
    strategy.authorizationRequest(options);
  }
}

OAuth2Strategy.prototype.authenticate = authenticate;

/**
 * Base64 Credentials
 *
 * Base64 encodes the user:password value for an HTTP Basic Authorization
 * header from a provider configuration object. The provider object should
 * specify a client_id and client_secret.
 */

function base64credentials () {
  var id          = this.client.client_id
    , secret      = this.client.client_secret
    , credentials = id + ':' + secret
    ;

  return new Buffer(credentials).toString('base64');
}

OAuth2Strategy.prototype.base64credentials = base64credentials;

/**
 * Authorization Request
 */

function authorizationRequest (options) {
  var provider      = this.provider
    , endpoints     = this.endpoints
    , config        = this.client
    , url           = URL.parse(endpoints.authorize.url)
    , response_type = 'code'
    , client_id     = config.client_id
    , redirect_uri  = provider.redirect_uri
    ;

  // required authorization parameters
  url.query = {
    response_type:  response_type,
    client_id:      client_id,
    redirect_uri:   redirect_uri,
  };

  // merge default and configured scopes
  if (provider.scope || config.scope) {
    var s1 = provider.scope || []
      , s2 = config.scope   || []
      , sp = provider.separator
      ;

    url.query.scope = s1.concat(s2).join(sp);
  }

  // redirect to the provider
  this.redirect(URL.format(url))
}

OAuth2Strategy.prototype.authorizationRequest = authorizationRequest;

/**
 * Authorization Code Grant Request
 */

function authorizationCodeGrant (code, done) {
  var endpoint = this.endpoints.token
    , url      = endpoint.url
    , method   = endpoint.method.toLowerCase()
    , auth     = endpoint.auth
    ;

  // required token parameters
  var params = {};
  params.grant_type   = 'authorization_code';
  params.code         = code;
  params.redirect_uri = this.provider.redirect_uri;

  var req = request[method](url);
  req.send(FormUrlencoded.encode(params));

  if (auth === 'client_secret_basic') {
    req.set('Authorization', 'Basic ' + this.base64credentials());
  }

  req.set('accept', 'application/json');
  req.set('user-agent', agent)

  req.end(function (res) {
    done(null, res.body);
  });
}

OAuth2Strategy.prototype.authorizationCodeGrant = authorizationCodeGrant;

/**
 * User Info
 */

function userInfo (token, done) {
  var name     = this.name
    , endpoint = this.endpoints.user
    , mapping  = this.mapping
    , url      = endpoint.url
    , method   = endpoint.method.toLowerCase()
    , auth     = endpoint.auth
    ;

  var req = request[method](url);

  if (auth === 'bearer_token') {
    req.set('Authorization', 'Bearer ' + token);
  }

  if (auth === 'access_token') {
    req.query({
      access_token: token
    });
  }

  req.set('accept', 'application/json');
  req.set('user-agent', agent);

  req.end(function (res) {
    var profile = { provider: name }
    map(mapping, res.body, profile)
    done(null, profile);
  });
}

OAuth2Strategy.prototype.userInfo = userInfo;

/**
 * Exports
 */

module.exports = OAuth2Strategy;
<commit_msg>support client authentication via POST params for authorization code grant<commit_after>/**
 * Module dependencies
 */

var pkg = require('../../package.json')
  , agent = 'Anvil Connect/' + pkg.version
  , URL = require('url')
  , util = require('util')
  , Strategy = require('passport-strategy')
  , request = require('superagent')
  , FormUrlencoded = require('form-urlencoded')
  , map = require('../../node_modules/modinha/lib/initialize').map
  ;

/**
 * OAuth2Strategy
 */

function OAuth2Strategy (provider, client, verify) {
  Strategy.call(this);
  this.provider   = provider;
  this.endpoints  = provider.endpoints;
  this.mapping    = provider.mapping;
  this.client     = client;
  this.name       = provider.id;
  this.verify     = verify;
}

util.inherits(OAuth2Strategy, Strategy);

/**
 * Authenticate
 */

function authenticate (req, options) {
  var strategy = this
    , error    = req.query && req.query.error
    , code     = req.query && req.query.code
    , options  = options || {}
    ;

  // Handle authorization endpoint error
  if (error) {
    // handle error response
  }

  // Handle token response
  if (code) {
    // exchange the code for an access token
    strategy.authorizationCodeGrant(code, function (err, response) {
      if (err) {}

      // request user info
      strategy.userInfo(response.access_token, function (err, profile) {
        if (err) {}

        // invoke the callback
        strategy.verify(req, response, profile, function (err, user, info) {
          if (err)   { return strategy.error(err); }
          if (!user) { return strategy.fail(info); }
          strategy.success(user, info);
        });
      });
    });
  }

  // Initiate the OAuth 2.0 Authorization Code Flow
  else {
    strategy.authorizationRequest(options);
  }
}

OAuth2Strategy.prototype.authenticate = authenticate;

/**
 * Base64 Credentials
 *
 * Base64 encodes the user:password value for an HTTP Basic Authorization
 * header from a provider configuration object. The provider object should
 * specify a client_id and client_secret.
 */

function base64credentials () {
  var id          = this.client.client_id
    , secret      = this.client.client_secret
    , credentials = id + ':' + secret
    ;

  return new Buffer(credentials).toString('base64');
}

OAuth2Strategy.prototype.base64credentials = base64credentials;

/**
 * Authorization Request
 */

function authorizationRequest (options) {
  var provider      = this.provider
    , endpoints     = this.endpoints
    , config        = this.client
    , url           = URL.parse(endpoints.authorize.url)
    , response_type = 'code'
    , client_id     = config.client_id
    , redirect_uri  = provider.redirect_uri
    ;

  // required authorization parameters
  url.query = {
    response_type:  response_type,
    client_id:      client_id,
    redirect_uri:   redirect_uri,
  };

  // merge default and configured scopes
  if (provider.scope || config.scope) {
    var s1 = provider.scope || []
      , s2 = config.scope   || []
      , sp = provider.separator
      ;

    url.query.scope = s1.concat(s2).join(sp);
  }

  // redirect to the provider
  this.redirect(URL.format(url))
}

OAuth2Strategy.prototype.authorizationRequest = authorizationRequest;

/**
 * Authorization Code Grant Request
 */

function authorizationCodeGrant (code, done) {
  var endpoint = this.endpoints.token
    , url      = endpoint.url
    , method   = endpoint.method.toLowerCase()
    , auth     = endpoint.auth
    ;

  // required token parameters
  var params = {};
  params.grant_type   = 'authorization_code';
  params.code         = code;
  params.redirect_uri = this.provider.redirect_uri;

  var req = request[method](url);

  if (auth === 'client_secret_basic') {
    req.set('Authorization', 'Basic ' + this.base64credentials());
  }

  if (auth === 'client_secret_post') {
    params.client_id = this.client.client_id;
    params.client_secret = this.client.client_secret;
  }

  req.send(FormUrlencoded.encode(params));
  req.set('accept', 'application/json');
  req.set('user-agent', agent)

  req.end(function (res) {
    done(null, res.body);
  });
}

OAuth2Strategy.prototype.authorizationCodeGrant = authorizationCodeGrant;

/**
 * User Info
 */

function userInfo (token, done) {
  var name     = this.name
    , endpoint = this.endpoints.user
    , mapping  = this.mapping
    , url      = endpoint.url
    , method   = endpoint.method.toLowerCase()
    , auth     = endpoint.auth
    ;

  var req = request[method](url);

  if (auth === 'bearer_token') {
    req.set('Authorization', 'Bearer ' + token);
  }

  if (auth === 'access_token') {
    req.query({
      access_token: token
    });
  }

  req.set('accept', 'application/json');
  req.set('user-agent', agent);

  req.end(function (res) {
    if (res.statusCode === 401) {
      //return done(new Error('Unauthorized.'))
    }

    var profile = { provider: name }
    map(mapping, res.body, profile)
    done(null, profile);
  });
}

OAuth2Strategy.prototype.userInfo = userInfo;

/**
 * Exports
 */

module.exports = OAuth2Strategy;
<|endoftext|>