<commit_before>/*
 * Orangevolt Macrop processor implementing creole style extension parsing
 *
 * http://github.com/lgersman
 * http://www.orangevolt.com
 *
 * Copyright 2013, Lars Gersmann <lars.gersmann@gmail.com>
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */

;(function( ov, context) {

	var TAG_REGEXP = /<<(\/?)((\w+[\:\-])*(\w+))((\s+((\w|\:|\-|\w[\w-]*\w)+)(\s*=\s*(?:\"[^\"]*?\"|'[^\"]*?'|[^'\">\s]+))?)+\s*|\s*)(\/?)>>/i,
		ATTR_REGEX = /((\w|\:|\-|\w[\w-]*\w)+)(\s*=\s*(?:\"([^\"]*?)\"|'([^\"]*?)'|([^'\">\s]+)))?/i
	;

		/**
		 * parse the attribute string
		 *
		 * @param  {string} input the attribute string
		 * @return {object} Object representing the string
		 */
	function parseAttributes( input) {
		var attrs = {},
			match
		;

		while( match = input.match( ATTR_REGEX)) {
				// adjust import
			input = input.substring( match.index + match[0].length);
			var name	= match[ 1],
				val		= match[ 4]!=null || match[ 5]!=null || match[ 6]!=null ?
					(match[ 4] || match[ 5] || match[ 6]).replace(/^[\r\n]+|\s+$/g, '')
					: true
			;

			if( name in attrs) {
				attrs[ name] = (Array.isArray( attrs[ name]) ? attrs[ name] : [ attrs[ name]]);
				attrs[ name].push( val);
			} else {
				attrs[ name] = val;
			}
		}

		return attrs;
	}

		/**
		 * parse a string into an ast
		 *
		 * @param  {string} the string to parse
		 * @return {array}  Array of strings (non macro text) and objects representing the parsed macros
		 */
	function parse( input) {
		var nodes = [],
			match
		;

		input = input || '';

		while( match = input.match( TAG_REGEXP)) {
			var node = {
				source		: match[0],
				namespace   : match[2] || '',
				name		: match[4],
				attributes	: parseAttributes( match[5]),
				content		: ''
			};

				// strip name from namespace
			if( node.namespace.length) {
				node.namespace = node.namespace.substring( 0, node.namespace.length - node.name.length);
			}

				// push text before macro
			nodes.push( input.substring( 0, match.index));
				// adjust input
			input = input.substring( match.index + match[0].length);

				// if macro has end tag
			if( !match[10]) {
					// scan for end tag
				match = input.match( new RegExp( '<<\/' + (node.namespace + node.name).replace( /\:/g, '\\:').replace( /\-/g, '\\-') + '>>'));
				if( match) {
					var content = input.substr( 0, match.index);
					node.source += content;

						// strip leading / trailing \r\n
					node.content = content.replace(/^[\r\n]+|\s+$/g, '');
						// adjust input
					input = input.substr( match.index + match[ 0].length);
				} else {
					node.content = input;
					input='';
				}

				node.source += (match && match[0] || '');
			}

			nodes.push( node);
		}

		input && nodes.push( input);

		return nodes;
	}

		/**
		 * process the nodes provided as argument and return the processed output.
		 * if an macro with no matching pendant in macros was found, the fallback macro handler get called.
		 *
		 * @param  {array} nodes array of string and objects returned by the parse function
		 * @param  {object} macros object with keys naming the supported macros and functions handling the macros processing
		 * if macros has a property '*' the function value will be taken as fallback for unknown macros.
		 * if no fallback macro handle was provided the default macro handler will be be called (which will throw an exeption)
		 * @param {object} options additional prosessing options
		 *
		 * @return {array} the processing result
		 *
		 * @see parse
		 */
	function process( nodes, macros, options) {
		if( !macros['*']) {
			macros['*'] = function( node, index) {
				throw new Error( 'No macro "' + node.name + '" found');
			};
		}

		options = options || {};

		var result	= [],
			context = {
				result : result,
				nodes  : nodes,
				macros : macros,
				options: options
			}
		;

		for( var i=0; i<nodes.length; i++) {
			var node = nodes[i];

			if( typeof( node)=='string') {
				result.push( node);
			} else {
				var macroFn = macros[ node.name] || macros[ '*'];
				result.push( macroFn.call( context, node, i));
			}
		}

		return result;
	}

		/**
		 * creates a reusable function encapsuulating the given macros and the parse/process chain
		 *
		 * @param  {object} macros object with keys naming the supported macros and functions handling the macros processing
		 * if macros has a property '*' the function value will be taken as fallback for unknown macros.
		 * if no fallback macro handle was provided the default macro handler will be be called (which will throw an exeption)
		 * @param {object} options additional prosessing options
		 *
		 * @return {array}
		 *
		 * @see process
		 */
	ov.macrop = function( macros, options) {
		return function( input) {
			return process( parse( input), macros, options);
		};
	};
	ov.macrop.parse = parse;
	ov.macrop.process = process;

	context.orangevolt = ov;
})(
	((typeof( require)=='function' && {}) || (typeof( window)=='object' && window.orangevolt)) || {},
	(typeof( require)=='function' && module.exports) || (typeof( window)=='object' && window)
);<commit_msg>parser fixed : attributes may now also contain JSON<commit_after>/*
 * Orangevolt Macrop processor implementing creole style extension parsing
 *
 * http://github.com/lgersman
 * http://www.orangevolt.com
 *
 * Copyright 2013, Lars Gersmann <lars.gersmann@gmail.com>
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */

;(function( ov, context) {

	var TAG_REGEXP = /<<(\/?)((\w+[\:\-])*(\w+))((\s+((\w|\:|\-|\w[\w-]*\w)+)(\s*=\s*(?:\"[^\"]*?\"|'[^\']*?'|[^'\">\s]+))?)+\s*|\s*)(\/?)>>/i,
		ATTR_REGEX = /((\w|\:|\-|\w[\w-]*\w)+)(\s*=\s*(?:\"([^\"]*?)\"|'([^\']*?)'|([^'\">\s]+)))?/i
	;

		/**
		 * parse the attribute string
		 *
		 * @param  {string} input the attribute string
		 * @return {object} Object representing the string
		 */
	function parseAttributes( input) {
		var attrs = {},
			match
		;

		while( match = input.match( ATTR_REGEX)) {
				// adjust import
			input = input.substring( match.index + match[0].length);
			var name	= match[ 1],
				val		= match[ 4]!=null || match[ 5]!=null || match[ 6]!=null ?
					(match[ 4] || match[ 5] || match[ 6]).replace(/^[\r\n]+|\s+$/g, '')
					: true
			;

			if( name in attrs) {
				attrs[ name] = (Array.isArray( attrs[ name]) ? attrs[ name] : [ attrs[ name]]);
				attrs[ name].push( val);
			} else {
				attrs[ name] = val;
			}
		}

		return attrs;
	}

		/**
		 * parse a string into an ast
		 *
		 * @param  {string} the string to parse
		 * @return {array}  Array of strings (non macro text) and objects representing the parsed macros
		 */
	function parse( input) {
		var nodes = [],
			match
		;

		input = input || '';

		while( match = input.match( TAG_REGEXP)) {
			var node = {
				source		: match[0],
				namespace   : match[2] || '',
				name		: match[4],
				attributes	: parseAttributes( match[5]),
				content		: ''
			};

				// strip name from namespace
			if( node.namespace.length) {
				node.namespace = node.namespace.substring( 0, node.namespace.length - node.name.length);
			}

				// push text before macro
			nodes.push( input.substring( 0, match.index));
				// adjust input
			input = input.substring( match.index + match[0].length);

				// if macro has end tag
			if( !match[10]) {
					// scan for end tag
				match = input.match( new RegExp( '<<\/' + (node.namespace + node.name).replace( /\:/g, '\\:').replace( /\-/g, '\\-') + '>>'));
				if( match) {
					var content = input.substr( 0, match.index);
					node.source += content;

						// strip leading / trailing \r\n
					node.content = content.replace(/^[\r\n]+|\s+$/g, '');
						// adjust input
					input = input.substr( match.index + match[ 0].length);
				} else {
					node.content = input;
					input='';
				}

				node.source += (match && match[0] || '');
			}

			nodes.push( node);
		}

		input && nodes.push( input);

		return nodes;
	}

		/**
		 * process the nodes provided as argument and return the processed output.
		 * if an macro with no matching pendant in macros was found, the fallback macro handler get called.
		 *
		 * @param  {array} nodes array of string and objects returned by the parse function
		 * @param  {object} macros object with keys naming the supported macros and functions handling the macros processing
		 * if macros has a property '*' the function value will be taken as fallback for unknown macros.
		 * if no fallback macro handle was provided the default macro handler will be be called (which will throw an exeption)
		 * @param {object} options additional prosessing options
		 *
		 * @return {array} the processing result
		 *
		 * @see parse
		 */
	function process( nodes, macros, options) {
		if( !macros['*']) {
			macros['*'] = function( node, index) {
				throw new Error( 'No macro "' + node.name + '" found');
			};
		}

		options = options || {};

		var result	= [],
			context = {
				result : result,
				nodes  : nodes,
				macros : macros,
				options: options
			}
		;

		for( var i=0; i<nodes.length; i++) {
			var node = nodes[i];

			if( typeof( node)=='string') {
				result.push( node);
			} else {
				var macroFn = macros[ node.name] || macros[ '*'];
				result.push( macroFn.call( context, node, i));
			}
		}

		return result;
	}

		/**
		 * creates a reusable function encapsuulating the given macros and the parse/process chain
		 *
		 * @param  {object} macros object with keys naming the supported macros and functions handling the macros processing
		 * if macros has a property '*' the function value will be taken as fallback for unknown macros.
		 * if no fallback macro handle was provided the default macro handler will be be called (which will throw an exeption)
		 * @param {object} options additional prosessing options
		 *
		 * @return {array}
		 *
		 * @see process
		 */
	ov.macrop = function( macros, options) {
		return function( input) {
			return process( parse( input), macros, options);
		};
	};
	ov.macrop.parse = parse;
	ov.macrop.process = process;

	context.orangevolt = ov;
})(
	((typeof( require)=='function' && {}) || (typeof( window)=='object' && window.orangevolt)) || {},
	(typeof( require)=='function' && module.exports) || (typeof( window)=='object' && window)
);<|endoftext|>


<commit_before>import { LineSegments } from '../../objects/LineSegments';
import { Matrix4 } from '../../math/Matrix4';
import { VertexColors } from '../../constants';
import { LineBasicMaterial } from '../../materials/LineBasicMaterial';
import { Color } from '../../math/Color';
import { Vector3 } from '../../math/Vector3';
import { BufferGeometry } from '../../core/BufferGeometry';
import { Float32BufferAttribute } from '../../core/BufferAttribute';

/**
 * @author Sean Griffin / http://twitter.com/sgrif
 * @author Michael Guerrero / http://realitymeltdown.com
 * @author mrdoob / http://mrdoob.com/
 * @author ikerr / http://verold.com
 * @author Mugen87 / https://github.com/Mugen87
 */

function SkeletonHelper( object ) {

	this.bones = this.getBoneList( object );

	var geometry = new BufferGeometry();

	var vertices = [];
	var colors = [];

	var color1 = new Color( 0, 0, 1 );
	var color2 = new Color( 0, 1, 0 );

	for ( var i = 0; i < this.bones.length; i ++ ) {

		var bone = this.bones[ i ];

		if ( bone.parent && bone.parent.isBone ) {

			vertices.push( 0, 0, 0 );
			vertices.push( 0, 0, 0 );
			colors.push( color1.r, color1.g, color1.b );
			colors.push( color2.r, color2.g, color2.b );

		}

	}

	geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

	var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );

	LineSegments.call( this, geometry, material );

	this.root = object;

	this.matrix = object.matrixWorld;
	this.matrixAutoUpdate = false;

	this.update();

}

SkeletonHelper.prototype = Object.create( LineSegments.prototype );
SkeletonHelper.prototype.constructor = SkeletonHelper;

SkeletonHelper.prototype.getBoneList = function( object ) {

	var boneList = [];

	if ( object && object.isBone ) {

		boneList.push( object );

	}

	for ( var i = 0; i < object.children.length; i ++ ) {

		boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );

	}

	return boneList;

};

SkeletonHelper.prototype.update = function () {

	var vector = new Vector3();

	var boneMatrix = new Matrix4();
	var matrixWorldInv = new Matrix4();

	return function update() {

		var geometry = this.geometry;
		var position = geometry.getAttribute( 'position' );

		matrixWorldInv.getInverse( this.root.matrixWorld );

		for ( var i = 0, j = 0; i < this.bones.length; i ++, j += 2 ) {

			var bone = this.bones[ i ];

			if ( bone.parent && bone.parent.isBone ) {

				boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
				vector.setFromMatrixPosition( boneMatrix );
				position.setXYZ( j, vector.x, vector.y, vector.z );

				boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
				vector.setFromMatrixPosition( boneMatrix );
				position.setXYZ( j + 1, vector.x, vector.y, vector.z );

			}

		}

		geometry.getAttribute( 'position' ).needsUpdate = true;

	};

}();

export { SkeletonHelper };
<commit_msg>SkeletonHelper: Fixed update method<commit_after>import { LineSegments } from '../../objects/LineSegments';
import { Matrix4 } from '../../math/Matrix4';
import { VertexColors } from '../../constants';
import { LineBasicMaterial } from '../../materials/LineBasicMaterial';
import { Color } from '../../math/Color';
import { Vector3 } from '../../math/Vector3';
import { BufferGeometry } from '../../core/BufferGeometry';
import { Float32BufferAttribute } from '../../core/BufferAttribute';

/**
 * @author Sean Griffin / http://twitter.com/sgrif
 * @author Michael Guerrero / http://realitymeltdown.com
 * @author mrdoob / http://mrdoob.com/
 * @author ikerr / http://verold.com
 * @author Mugen87 / https://github.com/Mugen87
 */

function SkeletonHelper( object ) {

	this.bones = this.getBoneList( object );

	var geometry = new BufferGeometry();

	var vertices = [];
	var colors = [];

	var color1 = new Color( 0, 0, 1 );
	var color2 = new Color( 0, 1, 0 );

	for ( var i = 0; i < this.bones.length; i ++ ) {

		var bone = this.bones[ i ];

		if ( bone.parent && bone.parent.isBone ) {

			vertices.push( 0, 0, 0 );
			vertices.push( 0, 0, 0 );
			colors.push( color1.r, color1.g, color1.b );
			colors.push( color2.r, color2.g, color2.b );

		}

	}

	geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

	var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );

	LineSegments.call( this, geometry, material );

	this.root = object;

	this.matrix = object.matrixWorld;
	this.matrixAutoUpdate = false;

	this.update();

}

SkeletonHelper.prototype = Object.create( LineSegments.prototype );
SkeletonHelper.prototype.constructor = SkeletonHelper;

SkeletonHelper.prototype.getBoneList = function( object ) {

	var boneList = [];

	if ( object && object.isBone ) {

		boneList.push( object );

	}

	for ( var i = 0; i < object.children.length; i ++ ) {

		boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );

	}

	return boneList;

};

SkeletonHelper.prototype.update = function () {

	var vector = new Vector3();

	var boneMatrix = new Matrix4();
	var matrixWorldInv = new Matrix4();

	return function update() {

		var geometry = this.geometry;
		var position = geometry.getAttribute( 'position' );

		matrixWorldInv.getInverse( this.root.matrixWorld );

		for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {

			var bone = this.bones[ i ];

			if ( bone.parent && bone.parent.isBone ) {

				boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
				vector.setFromMatrixPosition( boneMatrix );
				position.setXYZ( j, vector.x, vector.y, vector.z );

				boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
				vector.setFromMatrixPosition( boneMatrix );
				position.setXYZ( j + 1, vector.x, vector.y, vector.z );

				j += 2

			}

		}

		geometry.getAttribute( 'position' ).needsUpdate = true;

	};

}();

export { SkeletonHelper };
<|endoftext|>


<commit_before>var should = require( 'chai' ).should();
var calc = require( '../app/Calculator' );

describe("Calculator", function() {
  describe("Add", function() {
    it('should add together two numbers', function() {
      calc.add( 1, 1 ).should.equal( 2 );
      calc.add( 2, 4 ).should.equal( 6 );
      calc.add( 10, 10 ).should.equal( 20 );
      calc.add( 73, 27 ).should.equal( 100 );
    });

    it('should add together all arguments passed', function() {
      calc.add( 1, 3, 5 ).should.equal( 9 );
      calc.add( 2, 4, 6 ).should.equal( 12 );
      calc.add( 1, 1, 1, 1 ).should.equal( 4 );
      calc.add( 3 , 10, 8, 1 ).should.equal( 22 );
    });

    it('should add together contents of an array as an argument', function() {
      calc.add([ 1, 1 ]).should.equal( 2 );
      calc.add([ 1, 1, 1, 1, 1 ]).should.equal( 5 );
      calc.add([ 3, 4, 5 ]).should.equal( 12 );
      calc.add([ 7, 2, 1 ]).should.equal( 10 );
    });
  });
});
<commit_msg>add test for #Add when method is called with a mixture or arrays and single elements as arguments. Tests passed with no changes to src file<commit_after>var should = require( 'chai' ).should();
var calc = require( '../app/Calculator' );

describe("Calculator", function() {
  describe("#Add", function() {
    it('should add together two numbers', function() {
      calc.add( 1, 1 ).should.equal( 2 );
      calc.add( 2, 4 ).should.equal( 6 );
      calc.add( 10, 10 ).should.equal( 20 );
      calc.add( 73, 27 ).should.equal( 100 );
    });

    it('should add together all arguments passed', function() {
      calc.add( 1, 3, 5 ).should.equal( 9 );
      calc.add( 2, 4, 6 ).should.equal( 12 );
      calc.add( 1, 1, 1, 1 ).should.equal( 4 );
      calc.add( 3 , 10, 8, 1 ).should.equal( 22 );
    });

    it('should add together contents of an array as an argument', function() {
      calc.add([ 1, 1 ]).should.equal( 2 );
      calc.add([ 1, 1, 1, 1, 1 ]).should.equal( 5 );
      calc.add([ 3, 4, 5 ]).should.equal( 12 );
      calc.add([ 7, 2, 1 ]).should.equal( 10 );
    });

    it('should add arguments when arrays are mixed with single elements', function() {
      calc.add(1, [1, 1]).should.equal( 3 );
      calc.add(1, 1, [1]).should.equal( 3 );
      calc.add([ 1, 1, 1], 1 ).should.equal( 4 );
      calc.add([ 1, 1 ], [ 1, 1 ]).should.equal( 4 );
    });

  });
});
<|endoftext|>


<commit_before>import {FlightStateMapper} from "./FlightsServices";

export default class FlightStatusDirective {
    static factory() {
        return {
            template: require("./flight-status-icon.html"),
            scope: {
                flight: "=",
                mode: "="
            },
            controller: ($scope) => {
                let flight = $scope.flight;

                $scope.status = {
                    glider: FlightStateMapper.processedState(flight.ProcessState) || FlightStateMapper.statusOfFlight(flight.AirState)
                };
                if ($scope.mode !== "MOTOR") {
                    $scope.status.tow = FlightStateMapper.processedState(flight.ProcessState) || flight.TowFlightId && FlightStateMapper.statusOfFlight(flight.TowFlightAirState);
                }
            }
        }
    }
}

<commit_msg>Fixed tow flight process state icon issue in flight overview page<commit_after>import {FlightStateMapper} from "./FlightsServices";

export default class FlightStatusDirective {
    static factory() {
        return {
            template: require("./flight-status-icon.html"),
            scope: {
                flight: "=",
                mode: "="
            },
            controller: ($scope) => {
                let flight = $scope.flight;

                $scope.status = {
                    glider: FlightStateMapper.processedState(flight.ProcessState) || FlightStateMapper.statusOfFlight(flight.AirState)
                };
                if ($scope.mode !== "MOTOR") {
                    $scope.status.tow = FlightStateMapper.processedState(flight.TowFlightProcessState) || flight.TowFlightId && FlightStateMapper.statusOfFlight(flight.TowFlightAirState);
                }
            }
        }
    }
}

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.comics.v2',
  name: 'DAOSummaryView',
  extends: 'foam.u2.View',

  documentation: `
    A configurable summary view for a specific instance
  `,

  topics: [
    'finished',
    'throwError'
  ],

  axioms: [
    foam.pattern.Faceted.create()
  ],

  css:`
    ^ {
      padding: 32px
    }

    ^ .foam-u2-ActionView-back {
      display: flex;
      align-items: center;
      width: 30%;
    }

    ^account-name {
      font-size: 36px;
      font-weight: 600;
    }

    ^actions-header .foam-u2-ActionView {
      margin-right: 24px;
      line-height: 1.5
    }

    ^view-container {
      margin: auto;
    }
  `,

  requires: [
    'foam.u2.layout.Cols',
    'foam.u2.layout.Rows',
    'foam.u2.ControllerMode',
    'foam.u2.dialog.NotificationMessage',
    'foam.u2.dialog.Popup',
  ],

  imports: [
    'stack'
  ],

  exports: [
    'controllerMode'
  ],

  properties: [
    {
      class: 'FObjectProperty',
      name: 'data'
    },
    {
      class: 'FObjectProperty',
      of: 'foam.comics.v2.DAOControllerConfig',
      name: 'config'
    },
    {
      name: 'controllerMode',
      factory: function() {
        return this.ControllerMode.VIEW;
      }
    },
    {
      name: 'primary',
      expression: function(config$of) {
        var allActions = config$of.getAxiomsByClass(foam.core.Action);
        var defaultAction = allActions.filter((a) => a.isDefault);
        return defaultAction.length >= 1 ? defaultAction[0] : allActions[0];
      }
    },
    {
      class: 'foam.u2.ViewSpecWithJava',
      name: 'viewView',
      expression: function() {
        return foam.u2.detail.SectionedDetailView;
      }
    }
  ],

  actions: [
    {
      name: 'edit',
      isAvailable: function(config$editEnabled) {
        return config$editEnabled;
      },
      code: function() {
        if ( ! this.stack ) return;
        this.stack.push({
          class: 'foam.comics.v2.DAOUpdateView',
          data: this.data,
          config: this.config,
          of: this.config.of
        });
      }
    },
    {
      name: 'delete',
      isAvailable: function(config$deleteEnabled) {
        return config$deleteEnabled;
      },
      code: function() {
        this.add(this.Popup.create().tag({
          class: 'foam.u2.DeleteModal',
          dao: this.config.dao,
          onDelete: () => {
            this.finished.pub();
            this.stack.back();
          },
          data: this.data
        }));
      }
    }
  ],

  methods: [
    function initE() {
      var self = this;
      this.SUPER();
      this
        .addClass(this.myClass())
        .add(self.slot(function(data, data$id, config$CRUDActionsAuth$update, config$CRUDActionsAuth$delete,config$browseTitle, config$viewBorder, viewView) {

          // iterate through permissions and replace % with data$id
          var editAction = self.EDIT;
          var deleteAction = self.DELETE;

          if ( config$CRUDActionsAuth$update ){
            var editArray = config$CRUDActionsAuth$update;

            editArray = editArray.map(permission => {
              return permission.replace("%", data$id);
            });

            editAction = self.EDIT.copyFrom({
              availablePermissions: editArray
            });
          }

          if ( config$CRUDActionsAuth$delete ){
            var deleteArray = config$CRUDActionsAuth$delete;

            deleteArray = deleteArray.map(permission => {
              return permission.replace("%", data$id);
            });

            deleteAction = self.DELETE.copyFrom({
              availablePermissions: deleteArray
            });
          }

          return self.E()
            .start(self.Rows)
              .start(self.Rows)
                // we will handle this in the StackView instead
                .startContext({ data: self.stack })
                  .tag(self.stack.BACK, {
                    buttonStyle: foam.u2.ButtonStyle.TERTIARY,
                    icon: 'images/back-icon.svg',
                    label: `All ${config$browseTitle}`
                  })
                .endContext()
                .start(self.Cols).style({ 'align-items': 'center' })
                  .start()
                    .add(data.toSummary())
                    .addClass(this.myClass('account-name'))
                  .end()
                  .startContext({ data }).add(self.primary).endContext()
                .end()
              .end()

              .start(self.Cols)
                .start(self.Cols).addClass(this.myClass('actions-header'))
                  .startContext({ data: self })
                    .tag(editAction, {
                      buttonStyle: foam.u2.ButtonStyle.TERTIARY,
                      icon: 'images/edit-icon.svg'
                    })
                    .tag(deleteAction, {
                      buttonStyle: foam.u2.ButtonStyle.TERTIARY,
                      icon: 'images/delete-icon.svg'
                    })
                  .endContext()
                .end()
              .end()

              .start(config$viewBorder)
                .start(viewView, { data }).addClass(this.myClass('view-container')).end()
              .end()
            .end();
        }));
    }
  ]
});
<commit_msg>Update src/foam/comics/v2/DAOSummaryView.js<commit_after>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.comics.v2',
  name: 'DAOSummaryView',
  extends: 'foam.u2.View',

  documentation: `
    A configurable summary view for a specific instance
  `,

  topics: [
    'finished',
    'throwError'
  ],

  axioms: [
    foam.pattern.Faceted.create()
  ],

  css:`
    ^ {
      padding: 32px
    }

    ^ .foam-u2-ActionView-back {
      display: flex;
      align-items: center;
      width: 30%;
    }

    ^account-name {
      font-size: 36px;
      font-weight: 600;
    }

    ^actions-header .foam-u2-ActionView {
      margin-right: 24px;
      line-height: 1.5
    }

    ^view-container {
      margin: auto;
    }
  `,

  requires: [
    'foam.u2.layout.Cols',
    'foam.u2.layout.Rows',
    'foam.u2.ControllerMode',
    'foam.u2.dialog.NotificationMessage',
    'foam.u2.dialog.Popup',
  ],

  imports: [
    'stack'
  ],

  exports: [
    'controllerMode'
  ],

  properties: [
    {
      class: 'FObjectProperty',
      name: 'data'
    },
    {
      class: 'FObjectProperty',
      of: 'foam.comics.v2.DAOControllerConfig',
      name: 'config'
    },
    {
      name: 'controllerMode',
      factory: function() {
        return this.ControllerMode.VIEW;
      }
    },
    {
      name: 'primary',
      expression: function(config$of) {
        var allActions = config$of.getAxiomsByClass(foam.core.Action);
        var defaultAction = allActions.filter((a) => a.isDefault);
        return defaultAction.length >= 1 ? defaultAction[0] : allActions[0];
      }
    },
    {
      class: 'foam.u2.ViewSpecWithJava',
      name: 'viewView',
      expression: function() {
        return foam.u2.detail.SectionedDetailView;
      }
    }
  ],

  actions: [
    {
      name: 'edit',
      isAvailable: function(config$editEnabled) {
        return config$editEnabled;
      },
      code: function() {
        if ( ! this.stack ) return;
        this.stack.push({
          class: 'foam.comics.v2.DAOUpdateView',
          data: this.data,
          config: this.config,
          of: this.config.of
        });
      }
    },
    {
      name: 'delete',
      isAvailable: function(config$deleteEnabled) {
        return config$deleteEnabled;
      },
      code: function() {
        this.add(this.Popup.create().tag({
          class: 'foam.u2.DeleteModal',
          dao: this.config.dao,
          onDelete: () => {
            this.finished.pub();
            this.stack.back();
          },
          data: this.data
        }));
      }
    }
  ],

  methods: [
    function initE() {
      var self = this;
      this.SUPER();
      this
        .addClass(this.myClass())
        .add(self.slot(function(data, data$id, config$CRUDActionsAuth$update, config$CRUDActionsAuth$delete,config$browseTitle, config$viewBorder, viewView) {

          // iterate through permissions and replace % with data$id
          var editAction = self.EDIT;
          var deleteAction = self.DELETE;

          if ( config$CRUDActionsAuth$update ){
            var editArray = config$CRUDActionsAuth$update;

            editArray = editArray.map(permission => {
              return permission.replace("%", data$id);
            });

            editAction = self.EDIT.clone().copyFrom({
              availablePermissions: editArray
            });
          }

          if ( config$CRUDActionsAuth$delete ){
            var deleteArray = config$CRUDActionsAuth$delete;

            deleteArray = deleteArray.map(permission => {
              return permission.replace("%", data$id);
            });

            deleteAction = self.DELETE.copyFrom({
              availablePermissions: deleteArray
            });
          }

          return self.E()
            .start(self.Rows)
              .start(self.Rows)
                // we will handle this in the StackView instead
                .startContext({ data: self.stack })
                  .tag(self.stack.BACK, {
                    buttonStyle: foam.u2.ButtonStyle.TERTIARY,
                    icon: 'images/back-icon.svg',
                    label: `All ${config$browseTitle}`
                  })
                .endContext()
                .start(self.Cols).style({ 'align-items': 'center' })
                  .start()
                    .add(data.toSummary())
                    .addClass(this.myClass('account-name'))
                  .end()
                  .startContext({ data }).add(self.primary).endContext()
                .end()
              .end()

              .start(self.Cols)
                .start(self.Cols).addClass(this.myClass('actions-header'))
                  .startContext({ data: self })
                    .tag(editAction, {
                      buttonStyle: foam.u2.ButtonStyle.TERTIARY,
                      icon: 'images/edit-icon.svg'
                    })
                    .tag(deleteAction, {
                      buttonStyle: foam.u2.ButtonStyle.TERTIARY,
                      icon: 'images/delete-icon.svg'
                    })
                  .endContext()
                .end()
              .end()

              .start(config$viewBorder)
                .start(viewView, { data }).addClass(this.myClass('view-container')).end()
              .end()
            .end();
        }));
    }
  ]
});
<|endoftext|>


<commit_before>var webrtc;
$(window).load(function() {
	// Create a new room
	$('#oca-spreedme-add-room > input[type="submit"]').click(function() {
		OCA.SpreedMe.Rooms.create($('#oca-spreedme-add-room > input[type="text"]').val());
	});

	// Load the list of rooms all 10 seconds
	OCA.SpreedMe.Rooms.list();
	setInterval(function() {
		OCA.SpreedMe.Rooms.list();
	}, 10000);

	// Send a ping to the server all 5 seconds to ensure that the connection is
	// still alive.
	setInterval(function() {
		$.post(
			OC.generateUrl('/apps/spreedme/api/ping'),
			{
				currentRoom: OCA.SpreedMe.Rooms.currentRoom()
			}
		);
	}, 5000);

	// If page is opened already with a hash in the URL redirect to plain URL
	if(window.location.hash !== '') {
		window.location.replace(window.location.href.slice(0, -window.location.hash.length));
	}

	var videoHidden = false;
	$('#hideVideo').click(function() {
		if(videoHidden) {
			webrtc.resumeVideo();
			$(this).text('Pause video');
			videoHidden = false;
		} else {
			webrtc.pauseVideo();
			$(this).text('Enable video');
			videoHidden = true;
		}
	});
	var audioMuted = false;
	$('#mute').click(function() {
		if(audioMuted) {
			webrtc.unmute();
			$(this).text('Mute audio');
			audioMuted = false;
		} else {
			webrtc.mute();
			$(this).text('Enable audio');
			audioMuted = true;
		}
	});

	// If the hash changes a room gets joined
	$(window).on('hashchange', function() {
		OCA.SpreedMe.Rooms.join(window.location.hash.substring(1));
		$('#emptycontent').hide();
		$('#app-content').addClass('icon-loading');
	});

});
<commit_msg>Hide video when loading new channel<commit_after>var webrtc;
$(window).load(function() {
	// Create a new room
	$('#oca-spreedme-add-room > input[type="submit"]').click(function() {
		OCA.SpreedMe.Rooms.create($('#oca-spreedme-add-room > input[type="text"]').val());
	});

	// Load the list of rooms all 10 seconds
	OCA.SpreedMe.Rooms.list();
	setInterval(function() {
		OCA.SpreedMe.Rooms.list();
	}, 10000);

	// Send a ping to the server all 5 seconds to ensure that the connection is
	// still alive.
	setInterval(function() {
		$.post(
			OC.generateUrl('/apps/spreedme/api/ping'),
			{
				currentRoom: OCA.SpreedMe.Rooms.currentRoom()
			}
		);
	}, 5000);

	// If page is opened already with a hash in the URL redirect to plain URL
	if(window.location.hash !== '') {
		window.location.replace(window.location.href.slice(0, -window.location.hash.length));
	}

	var videoHidden = false;
	$('#hideVideo').click(function() {
		if(videoHidden) {
			webrtc.resumeVideo();
			$(this).text('Pause video');
			videoHidden = false;
		} else {
			webrtc.pauseVideo();
			$(this).text('Enable video');
			videoHidden = true;
		}
	});
	var audioMuted = false;
	$('#mute').click(function() {
		if(audioMuted) {
			webrtc.unmute();
			$(this).text('Mute audio');
			audioMuted = false;
		} else {
			webrtc.mute();
			$(this).text('Enable audio');
			audioMuted = true;
		}
	});

	// If the hash changes a room gets joined
	$(window).on('hashchange', function() {
		OCA.SpreedMe.Rooms.join(window.location.hash.substring(1));
		$('#emptycontent').hide();
		$('.videoView').addClass('hidden');
		$('#app-content').addClass('icon-loading');
	});

});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */
foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnsConfigView',
  extends: 'foam.u2.View',

  documentation: 'A view for configuring table columns.',

  requires: [
    'foam.u2.view.ColumnConfigPropView',
    'foam.u2.view.ColumnOptionsSelectConfig',
  ],

  properties: [
    'of',
    'allColumns',
    'selectedColumns',
    {
      name: 'allProperties',
      expression: function(allColumns, of) {
        var props = [];
        allColumns.map(axiomName => {//what is overridesMap??? can't find
          props.push(this.of.getAxiomByName(axiomName[0]));
          });

        return props;
      }
    },
    'isColumnChanged',
    {
      name: 'columns',
      value: []
    }
  ],

  css: `
    ^ {
      font-size: 18px;
      padding: 8px 0;
      //display: grid;
      grid-template-columns: 1fr 1fr;
    }
    ^ > * {
      align-self: center;
    }
  `,

  methods: [
    function initE() {
      this.SUPER();
      var self = this;
      for (var i = 0; i < this.data.selectedColumnNames.length; i++) {
        self.columns.push(self.ColumnOptionsSelectConfig.create({selectedColumns: self.data.selectedColumnNames[i], of:self.data.of}));
      }

      this
        .addClass(this.myClass())
        .forEach(this.columns, function(c) {
          self.add(foam.u2.ViewSpec.createView(self.ColumnConfigPropView, {data:c},  this, this.__subSubContext__));
        });
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnConfigPropView',
  extends: 'foam.u2.View',
  requires: [
    'foam.u2.view.ColumnViewHeader',
    'foam.u2.view.ColumnViewBody',
    'foam.u2.view.RootColumnConfigPropView',

  ],
  css: `
    ^move-right {
      margin-left: 15px;
    }
  `,
  methods: [
    function initE() {
      this.SUPER();
      var self = this;

      this.start()//.addClass(self.data.myClass('container-handle'))
          .add(this.slot(function(data, data$isPropertySelected, data$columnOptions, data$rootProperty, data$rootProperty$expanded) {
            return this.E()
            .start()
              .add(foam.u2.ViewSpec.createView(self.ColumnViewHeader, {data$:self.data.rootProperty$},  self, self.__subSubContext__))
            .end()
            .start()
              //.show(self.data.rootProperty.parentExpanded$)
              .start()
                .add(foam.u2.ViewSpec.createView(self.ColumnViewBody, {data$:self.data.rootProperty$},  self, self.__subSubContext__))
              .end()
              .forEach(self.data.columnOptions, function(o) {
                this
                  .start()
                    .show(self.data.rootProperty.expanded$)
                    .addClass(self.myClass('move-right'))
                      .add(foam.u2.ViewSpec.createView(self.RootColumnConfigPropView, {data:o},  self, self.__subSubContext__))
                  .end();
              })
            .end();
          }))
        .end();
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'RootColumnConfigPropView',
  extends: 'foam.u2.View',
  properties: [
    {
      class: 'foam.u2.ViewSpec',
      name: 'head',
      value: { class:'foam.u2.view.ColumnViewHeader'}
    },
    {
      class: 'foam.u2.ViewSpec',
      name: 'body',
      value: { class:'foam.u2.view.ColumnViewBody'}
    }
  ],
  methods: [
    function initE() {
      this.SUPER();
      this
      .start()
          .add(foam.u2.ViewSpec.createView(this.head, {data$:this.data$},  this, this.__subSubContext__))
        .end()
        .start()
          .add(foam.u2.ViewSpec.createView(this.body, {data$:this.data$},  this, this.__subSubContext__))
        .end();
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnOptionsSelectConfig',
  requires: [
    'foam.u2.view.SubColumnSelectConfig'
  ],
  properties: [
    'selectedColumns',
    'of',
    {
      name: 'rootProperty',
      class: 'FObjectProperty',
      of: 'foam.u2.view.SubColumnSelectConfig',
      expression: function(of, selectedColumns, isPropertySelected) {
        return this.updateRootProperty();
      }
    },
    {
      name: 'columnOptions',
      class: 'FObjectArray',
      of: 'foam.u2.view.SubColumnSelectConfig',
      factory: function() {
        return this.updateOptionsProperty();
      }
    },
    {
      name: 'isPropertySelected',
      class: 'Boolean',
      value: true,
      postSet: function() {
        if ( this.isPropertySelected) {
          this.rootProperty = this.updateRootProperty();
          this.columnOptions = this.updateOptionsProperty();
          this.isPropertySelected = false;
        }
      }
    }
  ],
  methods: [
    function updateRootProperty() {
      var p = this.of.getAxiomByName(this.selectedColumns[0]);
      return this.SubColumnSelectConfig.create({ rootProperty: p, hasOtherOptions:true, selectedColumns$:this.selectedColumns$, level:0, isPathSelected$:this.isPropertySelected$ });
    },
    function updateOptionsProperty() {
      var props = this.of.getAxiomsByClass(foam.core.Property);
      var propViews = [];
      props = props.filter(p => p.name !== this.selectedColumns[0]);
      for ( var i = 0; i < props.length; i++) {
        propViews.push(this.SubColumnSelectConfig.create({ rootProperty: props[i], hasOtherOptions:false, selectedColumns$:this.selectedColumns$, level:0, isPathSelected$:this.isPropertySelected$ }));
      }
      this.isPropertySelected = false;
      return propViews;
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnViewHeader',
  extends: 'foam.u2.View',
  css: `

  ^selected {
    background: lightblue;
  }
  `,

  methods: [
    function initE() {
      this.SUPER();
      this.start()
        //.style({'margin-right': '20px'})
        .enableClass(this.myClass('selected'), this.data.level < this.data.selectedColumns.length && this.data.selectedColumns[this.data.level] == this.data.rootProperty.name)
        .on('click', this.toggleExpanded)
        .start()
          .add(this.data.rootProperty.name)
          .start('span')
            .show(this.data.hasOtherOptions || this.data.hasSubProperties)
            .style({
              'vertical-align': 'middle',
              'font-weight':    'bold',
              'visibility':     'visible',
              'font-size':      '16px',
              'float':          'right',
              'transform':      this.data.expanded$.map(function(c) { return c ? 'rotate(180deg)' : 'rotate(90deg)'; })
            })
            .on('click', this.toggleExpanded)
            .add('\u2303')
          .end()
        .end()
      .end();
    }
  ],
  listeners: [
    function toggleExpanded(e) {
      this.data.expanded = !this.data.expanded;
      if ( !this.data.expanded || !(this.data.hasSubProperties || this.data.hasOtherOptions)) {
        if ( !this.data.hasSubProperties ) {
          this.data.parentExpanded = !this.data.parentExpanded;
        }
        this.data.isPropertySelected = true;
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnViewBody',
  extends: 'foam.u2.View',
  requires: [
    'foam.u2.view.RootColumnConfigPropView',
    'foam.u2.view.SubColumnSelectConfig'
  ],
  css: `
  ^move-right {
    margin-left: 20px;
  }
  `,
  methods: [
    function initE() {
      this.SUPER();
      var self = this;

      // self.data.rootProperty.parentExpanded$.sub(function() {
      //   console.log(self.data.rootProperty.expanded);
      // });

      this
        .start()
            .forEach(this.data.subColumnSelectConfig, function(p) {
            self
              .addClass(self.myClass('move-right'))
              .show(self.data.expanded$)
              .add(foam.u2.ViewSpec.createView(self.RootColumnConfigPropView, {data:p}, self, self.__subSubContext__));
          })
        .end();
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'SubColumnSelectConfig',
  properties: [
    {
      name: 'hasSubProperties',
      class: 'Boolean',
      expression: function(rootProperty) {
        if ( rootProperty.cls_.name === 'FObjectProperty' )
          return true;
        return false;
      }
    },
    {
      name: 'selectedColumns',
      documentation: 'array of names of selected proprties'
    },
    {
      name: 'subProperties',
      expression: function(rootProperty) {
        if ( rootProperty.cls_.name === 'FObjectProperty' )
          return rootProperty.of.getAxiomsByClass(foam.core.Property);
        return [];
      }
    },
    {
      name: 'subColumnSelectConfig',
      expression: function(subProperties, level) {
        var arr = [];
        var l = level + 1;
        for ( var i = 0; i < subProperties.length; i++ )
          arr.push(this.cls_.create({ rootProperty: subProperties[i], selectedColumns$:this.selectedColumns$, level:l, isPathSelected$:this.isPropertySelected$, parentExpanded$:this.expanded$ }));
        return arr;
      }
    },
    {
      name: 'rootProperty'
    },
    {
      name: 'isPropertySelected',
      class: 'Boolean',
      postSet: function() {
        if ( this.isPropertySelected ) {
          while ( this.level > this.selectedColumns.length - 1 ) {
            this.selectedColumns.push(undefined);
          }
          if ( this.selectedColumns[this.level] !== this.rootProperty.name )
            this.selectedColumns[this.level] = this.rootProperty.name;

            //if level higher then previous one
          if ( !this.hasSubProperties && this.level !== this.selectedColumns.length - 1 ) {
            this.selectedColumns.splice(0, this.selectedColumns.length - 1 - this.level);
          }
          this.isPathSelected = true;
        }
      }
    },
    {
      name: 'isPathSelected',
      class: 'Boolean',
      value: false
    },
    {
      name: 'level',
      class: 'Int',
    },
    {
      name: 'parentExpanded',
      class: 'Boolean',
      value: false
    },
    {
      name: 'expanded',
      class: 'Boolean',
      value: false
    },
    // {
    //   name: 'parentExpanded',
    //   class: 'Boolean',
    //   value: false
    // },
    {
      name: 'hasOtherOptions',
      class: 'Boolean',
      value: false
    }
  ]
});
<commit_msg>Fixing bug<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */
foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnsConfigView',
  extends: 'foam.u2.View',

  documentation: 'A view for configuring table columns.',

  requires: [
    'foam.u2.view.ColumnConfigPropView',
    'foam.u2.view.ColumnOptionsSelectConfig',
  ],

  properties: [
    'of',
    'allColumns',
    'selectedColumns',
    {
      name: 'allProperties',
      expression: function(allColumns, of) {
        var props = [];
        allColumns.map(axiomName => {//what is overridesMap??? can't find
          props.push(this.of.getAxiomByName(axiomName[0]));
          });

        return props;
      }
    },
    {
      name: 'columns',
      value: []
    }
  ],

  css: `
    ^ {
      font-size: 18px;
      padding: 8px 0;
      //display: grid;
      grid-template-columns: 1fr 1fr;
    }
    ^ > * {
      align-self: center;
    }
  `,

  methods: [
    function initE() {
      this.SUPER();
      var self = this;
      for (var i = 0; i < this.data.selectedColumnNames.length; i++) {
        self.columns.push(self.ColumnOptionsSelectConfig.create({selectedColumns: self.data.selectedColumnNames[i], of:self.data.of}));
      }

      this
        .addClass(this.myClass())
        .forEach(this.columns, function(c) {
          self.add(foam.u2.ViewSpec.createView(self.ColumnConfigPropView, {data:c},  this, this.__subSubContext__));
        });
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnConfigPropView',
  extends: 'foam.u2.View',
  requires: [
    'foam.u2.view.ColumnViewHeader',
    'foam.u2.view.ColumnViewBody',
    'foam.u2.view.RootColumnConfigPropView',

  ],
  css: `
    ^move-right {
      margin-left: 15px;
    }
  `,
  methods: [
    function initE() {
      this.SUPER();
      var self = this;

      this.start()//.addClass(self.data.myClass('container-handle'))
          .add(this.slot(function(data, data$isPropertySelected, data$columnOptions, data$rootProperty, data$rootProperty$expanded) {
            return this.E()
            .start()
              .add(foam.u2.ViewSpec.createView(self.ColumnViewHeader, {data$:self.data.rootProperty$},  self, self.__subSubContext__))
            .end()
            .start()
              //.show(self.data.rootProperty.parentExpanded$)
              .start()
                .add(foam.u2.ViewSpec.createView(self.ColumnViewBody, {data$:self.data.rootProperty$},  self, self.__subSubContext__))
              .end()
              .forEach(self.data.columnOptions, function(o) {
                this
                  .start()
                    .show(self.data.rootProperty.expanded$)
                    .addClass(self.myClass('move-right'))
                      .add(foam.u2.ViewSpec.createView(self.RootColumnConfigPropView, {data:o},  self, self.__subSubContext__))
                  .end();
              })
            .end();
          }))
        .end();
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'RootColumnConfigPropView',
  extends: 'foam.u2.View',
  properties: [
    {
      class: 'foam.u2.ViewSpec',
      name: 'head',
      value: { class:'foam.u2.view.ColumnViewHeader'}
    },
    {
      class: 'foam.u2.ViewSpec',
      name: 'body',
      value: { class:'foam.u2.view.ColumnViewBody'}
    }
  ],
  methods: [
    function initE() {
      this.SUPER();
      this
      .start()
          .add(foam.u2.ViewSpec.createView(this.head, {data$:this.data$},  this, this.__subSubContext__))
        .end()
        .start()
          .add(foam.u2.ViewSpec.createView(this.body, {data$:this.data$},  this, this.__subSubContext__))
        .end();
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnOptionsSelectConfig',
  requires: [
    'foam.u2.view.SubColumnSelectConfig'
  ],
  properties: [
    'selectedColumns',
    'of',
    {
      name: 'rootProperty',
      class: 'FObjectProperty',
      of: 'foam.u2.view.SubColumnSelectConfig',
      expression: function(of, selectedColumns, isPropertySelected) {
        return this.updateRootProperty();
      }
    },
    {
      name: 'columnOptions',
      class: 'FObjectArray',
      of: 'foam.u2.view.SubColumnSelectConfig',
      factory: function() {
        return this.updateOptionsProperty();
      }
    },
    {
      name: 'isPropertySelected',
      class: 'Boolean',
      value: true,
      postSet: function() {
        if ( this.isPropertySelected) {
          this.rootProperty = this.updateRootProperty();
          this.columnOptions = this.updateOptionsProperty();
          this.isPropertySelected = false;
        }
      }
    }
  ],
  methods: [
    function updateRootProperty() {
      var p = this.of.getAxiomByName(this.selectedColumns[0]);
      return this.SubColumnSelectConfig.create({ rootProperty: p, hasOtherOptions:true, selectedColumns$:this.selectedColumns$, level:0, isPathSelected$:this.isPropertySelected$ });
    },
    function updateOptionsProperty() {
      var props = this.of.getAxiomsByClass(foam.core.Property);
      var propViews = [];
      props = props.filter(p => p.name !== this.selectedColumns[0]);
      for ( var i = 0; i < props.length; i++) {
        propViews.push(this.SubColumnSelectConfig.create({ rootProperty: props[i], hasOtherOptions:false, selectedColumns$:this.selectedColumns$, level:0, isPathSelected$:this.isPropertySelected$ }));
      }
      this.isPropertySelected = false;
      return propViews;
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnViewHeader',
  extends: 'foam.u2.View',
  css: `

  ^selected {
    background: lightblue;
  }
  `,

  methods: [
    function initE() {
      this.SUPER();
      this.start()
        //.style({'margin-right': '20px'})
        .enableClass(this.myClass('selected'), this.data.level < this.data.selectedColumns.length && this.data.selectedColumns[this.data.level] == this.data.rootProperty.name)
        .on('click', this.toggleExpanded)
        .start()
          .add(this.data.rootProperty.name)
          .start('span')
            .show(this.data.hasOtherOptions || this.data.hasSubProperties)
            .style({
              'vertical-align': 'middle',
              'font-weight':    'bold',
              'visibility':     'visible',
              'font-size':      '16px',
              'float':          'right',
              'transform':      this.data.expanded$.map(function(c) { return c ? 'rotate(180deg)' : 'rotate(90deg)'; })
            })
            .on('click', this.toggleExpanded)
            .add('\u2303')
          .end()
        .end()
      .end();
    }
  ],
  listeners: [
    function toggleExpanded(e) {
      this.data.expanded = !this.data.expanded;
      if ( !this.data.expanded && !(this.data.hasSubProperties || this.data.hasOtherOptions)) {
        if ( !this.data.hasSubProperties ) {
          this.data.parentExpanded = !this.data.parentExpanded;
        }
        this.data.isPropertySelected = true;
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'ColumnViewBody',
  extends: 'foam.u2.View',
  requires: [
    'foam.u2.view.RootColumnConfigPropView',
    'foam.u2.view.SubColumnSelectConfig'
  ],
  css: `
  ^move-right {
    margin-left: 20px;
  }
  `,
  methods: [
    function initE() {
      this.SUPER();
      var self = this;

      // self.data.rootProperty.parentExpanded$.sub(function() {
      //   console.log(self.data.rootProperty.expanded);
      // });

      this
        .start()
            .forEach(this.data.subColumnSelectConfig, function(p) {
            self
              .addClass(self.myClass('move-right'))
              .show(self.data.expanded$)
              .add(foam.u2.ViewSpec.createView(self.RootColumnConfigPropView, {data:p}, self, self.__subSubContext__));
          })
        .end();
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'SubColumnSelectConfig',
  properties: [
    {
      name: 'hasSubProperties',
      class: 'Boolean',
      expression: function(rootProperty) {
        if ( rootProperty.cls_.name === 'FObjectProperty' )
          return true;
        return false;
      }
    },
    {
      name: 'selectedColumns',
      documentation: 'array of names of selected proprties'
    },
    {
      name: 'subProperties',
      expression: function(rootProperty) {
        if ( rootProperty.cls_.name === 'FObjectProperty' )
          return rootProperty.of.getAxiomsByClass(foam.core.Property);
        return [];
      }
    },
    {
      name: 'subColumnSelectConfig',
      expression: function(subProperties, level) {
        var arr = [];
        var l = level + 1;
        for ( var i = 0; i < subProperties.length; i++ )
          arr.push(this.cls_.create({ rootProperty: subProperties[i], selectedColumns$:this.selectedColumns$, level:l, isPathSelected$:this.isPropertySelected$, parentExpanded$:this.expanded$ }));
        return arr;
      }
    },
    {
      name: 'rootProperty'
    },
    {
      name: 'isPropertySelected',
      class: 'Boolean',
      postSet: function() {
        if ( this.isPropertySelected ) {
          while ( this.level > this.selectedColumns.length - 1 ) {
            this.selectedColumns.push(undefined);
          }
          if ( this.selectedColumns[this.level] !== this.rootProperty.name )
            this.selectedColumns[this.level] = this.rootProperty.name;

            //if level higher then previous one
          if ( !this.hasSubProperties && this.level !== this.selectedColumns.length - 1 ) {
            this.selectedColumns.splice(0, this.selectedColumns.length - 1 - this.level);
          }
          this.isPathSelected = true;
        }
      }
    },
    {
      name: 'isPathSelected',
      class: 'Boolean',
      value: false
    },
    {
      name: 'level',
      class: 'Int',
    },
    {
      name: 'parentExpanded',
      class: 'Boolean',
      value: false
    },
    {
      name: 'expanded',
      class: 'Boolean',
      value: false
    },
    // {
    //   name: 'parentExpanded',
    //   class: 'Boolean',
    //   value: false
    // },
    {
      name: 'hasOtherOptions',
      class: 'Boolean',
      value: false
    }
  ]
});
<|endoftext|>


<commit_before>var canvas = document.getElementById('canvas');
var shapes = 5000;
var ctx, left;

$(function(){
    if (canvas.getContext) {
        ctx = canvas.getContext('2d');
        left = true;

        canvas.height = screen.height - 60;
    	canvas.width = screen.width + 20;

        drawShapes();

        var timer = setInterval(function () {
            drawShapes();
        }, 5000);
    }
});

function drawShapes(){
    for (var i = 1; i <= shapes; i++) {
        ctx.beginPath();
        if (left) {
            ctx.moveTo(-10, randomize(canvas.height + 10));
            left = false;
        } else {
            ctx.moveTo(randomize(canvas.width+ 10), -10);
            left = true;
        }
        ctx.lineTo(randomize(canvas.width + 50), randomize(canvas.height  + 50));
        ctx.lineTo(randomize(canvas.width + 50), randomize(canvas.height + 50));
        ctx.fillStyle = getRndColor();
        ctx.fill();
    }
}

function randomize(num) {
    var a = Math.floor(Math.random() * num);
    return a;
}

function sides() {
    var a = Math.floor(Math.random() * 10);
    return a;
}

function getRndColor() {
    var r = 255 * Math.random() | 0,
        g = 255 * Math.random() | 0,
        b = 255 * Math.random() | 0,
        alpha = 0.01;
    var final = 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')';
    return final;
}

$('#save').click(function () {
    clearInterval(timer);

    //Convert canvas to image
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var dataURL = canvas.toDataURL();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    document.getElementById('canvasImg').src = dataURL;
    $('#canvas').hide();
    $('#canvasImg').show();

    // //Download image
    // var a = document.createElement('a');
    // a.href = dataURL;
    // a.download = "output.png";
    // document.body.appendChild(a);
    // console.log(a)
    // a.click();
    $('h4').text("Right click on the image to save a beautiful wallpaper!")
});
<commit_msg>Fixes edge coloring issues<commit_after>var canvas = document.getElementById('canvas');
var shapes = 5000;
var ctx, left;

$(function(){
    if (canvas.getContext) {
        ctx = canvas.getContext('2d');
        left = true;

        canvas.height = screen.height - 60;
    	canvas.width = screen.width + 20;

        drawShapes();
        drawShapes();

        var timer = setInterval(function () {
            drawShapes();
        }, 5000);
    }
});

function drawShapes(){
    for (var i = 1; i <= shapes; i++) {
        ctx.beginPath();
        if (left) {
            ctx.moveTo(-10, randomize(canvas.height + 10));
            left = false;
        } else {
            ctx.moveTo(randomize(canvas.width+ 10), -10);
            left = true;
        }
        ctx.lineTo(randomize(canvas.width + 50), randomize(canvas.height  + 50));
        ctx.lineTo(randomize(canvas.width + 50), randomize(canvas.height + 50));
        ctx.fillStyle = getRndColor();
        ctx.fill();
    }
}

function randomize(num) {
    var a = Math.floor(Math.random() * num);
    return a;
}

function sides() {
    var a = Math.floor(Math.random() * 10);
    return a;
}

function getRndColor() {
    var r = 255 * Math.random() | 0,
        g = 255 * Math.random() | 0,
        b = 255 * Math.random() | 0,
        alpha = 0.01;
    var final = 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')';
    return final;
}

$('#save').click(function () {
    clearInterval(timer);

    //Convert canvas to image
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var dataURL = canvas.toDataURL();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    document.getElementById('canvasImg').src = dataURL;
    $('#canvas').hide();
    $('#canvasImg').show();

    // //Download image
    // var a = document.createElement('a');
    // a.href = dataURL;
    // a.download = "output.png";
    // document.body.appendChild(a);
    // console.log(a)
    // a.click();
    $('h4').text("Right click on the image to save a beautiful wallpaper!")
});
<|endoftext|>


<commit_before>var xmlhttp = new XMLHttpRequest();

function Message () {
	this.from;
	this.to;
	this.subject;
	this.message;
}

function changeTitle () {
	var subject = document.getElementById('mail_subject').value;

	if ((subject == null) || (subject == "")) {
		document.title = "SendMail";
		document.getElementById('message_title').innerHTML = "New Message";
	}
	else {
		document.title = "SendMail - " + subject;
		document.getElementById('message_title').innerHTML = subject;
	}
}

function showSignature () {
	document.getElementById('overlay_background').style.display = "block";
	document.getElementById('overlay_body').style.display = "block";
}

function hideSignature () {
	var signature = document.getElementById('signature_text').value;
	var message = document.getElementById('message_text').value;

	if (!((message == null) || (message == ""))) {
		document.getElementById('message_text').value = message + "\n\n" + signature;
	}

	document.getElementById('overlay_background').style.display = "none";
	document.getElementById('overlay_body').style.display = "none";
}

function messageSend () {
	var message_form = document.getElementById('message_form');
	var email = new Message();

	email.from = message_form.elements[0].value;
	email.to = message_form.elements[1].value;
	email.subject = message_form.elements[2].value;
	email.message = message_form.elements[3].value;

	var jsonified = JSON.stringify(email);

	var params = "json=" + jsonified;
	xmlhttp.open("POST", "scripts/sendmail.php", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			document.getElementById("response_message").innerHTML = xmlhttp.responseText;
		}
	}
	xmlhttp.send(params);

	document.getElementById('response_message_div').style.display = "block";
}<commit_msg>JS posting data now works<commit_after>var xmlhttp = new XMLHttpRequest();

function Message () {
	this.from;
	this.to;
	this.subject;
	this.message;
}

function changeTitle () {
	var subject = document.getElementById('mail_subject').value;

	if ((subject == null) || (subject == "")) {
		document.title = "SendMail";
		document.getElementById('message_title').innerHTML = "New Message";
	}
	else {
		document.title = "SendMail - " + subject;
		document.getElementById('message_title').innerHTML = subject;
	}
}

function showSignature () {
	document.getElementById('overlay_background').style.display = "block";
	document.getElementById('overlay_body').style.display = "block";
}

function hideSignature () {
	var signature = document.getElementById('signature_text').value;
	var message = document.getElementById('message_text').value;

	if (!((message == null) || (message == ""))) {
		document.getElementById('message_text').value = message + "\n\n" + signature;
	}

	document.getElementById('overlay_background').style.display = "none";
	document.getElementById('overlay_body').style.display = "none";
}

function messageSend () {
	var message_form = document.getElementById('message_form');
	var email = new Message();

	for (var i = 0; i < message_form.length; i++) {
		if (message_form.elements[i].value == null || message_form.elements[i].value == "") {
			alert("No fields can be blank");
			return false;
		}
	}

	email.from = message_form.elements[0].value;
	email.to = message_form.elements[1].value;
	email.subject = message_form.elements[2].value;
	email.message = message_form.elements[3].value;

	var jsonified = JSON.stringify(email);

	var params = "json=" + jsonified;
	xmlhttp.open("POST", "scripts/sendmail.php", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			document.getElementById("response_message").innerHTML = xmlhttp.responseText;
		}
	}
	xmlhttp.send(params);

	document.getElementById('response_message_div').style.display = "block";
}<|endoftext|>


<commit_before>(function($){
    var TX = {
        bars: null,
        set_bars: function(bars) {
            this.bars = [];
            for (i=0; i<bars; i++) {
                bars.push({
                    height: (Math.random() * 30) + 10
                });
            }
        },
        build_bars: function(container, bars) {
            var container = $(container),
            this.set_bars(bars);

            $.each(this.bars, function() {
                container.append(this.build_html(this));
            });
        },
        build_html: function(bar) {
            return $('<div>').addClass('bar').css({height: bar.height * 10});
        }
    };
})(jQuery);<commit_msg>fix js error.<commit_after>(function($){
    TX = {
        bars: null,
        set_bars: function(bars) {
            this.bars = [];
            for (i=0; i<bars; i++) {
                this.bars.push({
                    height: (Math.random() * 30) + 10
                });
            }
        },
        build_bars: function(container, bars) {
            var container = $(container), that = this;
            this.set_bars(bars);

            $.each(this.bars, function() {
                container.append(that.build_html(this));
            });
        },
        build_html: function(bar) {
            return $('<div>').addClass('bar').css({height: bar.height * 10});
        }
    };
})(jQuery);<|endoftext|>


<commit_before>$(".document").ready(function() {

  let timerID;

  let data = {
    sequence: null,
    compSeq: [],
    humanSeq: [],
    ms: [1200, 1000, 800],
    colors: [green, red, yellow, blue],
    turns: 0
  };

  let controller = {

    init: function() {
      view.init();
    },
/*
    play: function(){
      // Add function: check for winner, call victory() and return true
      simon.playSeq(data.compSeq);
      events.activateHumanEvents();
    },
*/

    start: function() {
      data.sequence = simon.makeSequence();
      //data.compSeq.push(data.sequence[0]);
      simon.turn();
    },

    strict: function() {
      $('#strict-display').toggleClass('strict-on');
    }
  };

  // This function should togggle all event listeners on and off
  let events = {

    activateEvents: function() {
      $('#start-button').on('mousedown', controller.start);
      $('#strict-button').on('click', controller.strict);
      $('#green').on('mousedown', press.green);
      $('#red').on('mousedown', press.red);
      $('#yellow').on('mousedown', press.yellow);
      $('#blue').on('mousedown', press.blue);
    },

    deactivateEvents: function() {
      $('#test').off('click', controller.init);
      $('#start-button').off('click', controller.start);
      $('#strict-button').off('click', controller.strict);
      $('#green').off('mousedown', press.green);
      $('#red').off('mousedown', press.red);
      $('#yellow').off('mousedown', press.yellow);
      $('#blue').off('mousedown', press.blue);
    },

    activateHumanEvents: function() {
      $('.button').on('mousedown', simon.humanResponse);
      $('.button').toggleClass('lockout');
    },

    deactivateHumanEvents: function() {
      $('.button').off('mousedown', simon.humanResponse);
      $('.button').toggleClass('lockout');
    },

    togglePower: function() {
      this.checked ? events.activateEvents() : events.deactivateEvents();
    }

  };

  let press = {
    green: function() {
      let greenSound = document.getElementById('green-sound');
      let newSound = greenSound.cloneNode();
      newSound.play();
      newSound.remove();
      $('#green').addClass('press');
      setTimeout(() => {press.removeOpacity('#green')}, 200);
    },

    red: function() {
      let redSound = document.getElementById('red-sound');
      let newSound = redSound.cloneNode();
      newSound.play();
      newSound.remove();
      $('#red').addClass('press');
      setTimeout(() => {press.removeOpacity('#red')}, 200)
    },

    yellow: function() {
      let yellowSound = document.getElementById('yellow-sound');
      let newSound = yellowSound.cloneNode();
      newSound.play();
      newSound.remove();
      $('#yellow').addClass('press');
      setTimeout(() => {press.removeOpacity('#yellow')}, 200)
    },

    blue: function() {
      let blueSound = document.getElementById('blue-sound');
      let newSound = blueSound.cloneNode();
      newSound.play();
      newSound.remove();
      $('#blue').addClass('press');
      setTimeout(() => {press.removeOpacity('#blue')}, 200)
    },

    removeOpacity: function(x) {
      $(x).removeClass('press').bind(press.green);
    },
  };

  // The 'simon' object contains helper functions
  let simon = {

    getColorCode: function(button){
      return $(button).data().button;
    },

    hasWinner: function(humArr, compArr){
      return humArr.every((value, index) => compArr[index] === humArr[index]);
    },

    humanResponse: function(){
      let x = simon.getColorCode(this);
      data.humanSeq.push(x);
      console.log("humanResponse", "compSeq", data.compSeq);
      console.log("humanResponse", "humanSeq", data.humanSeq);
      console.log("humanResponse", "turns", data.turns);
      // If both arrays are equal...
      if (data.humanSeq.every(function isMatching(el, i) {
        return el === data.compSeq[i];
      })) {
        console.log('match');
        if (data.humanSeq.length === data.compSeq.length) {
          console.log('nice!');
          data.turns++;
          console.log('turns', data.turns)
          data.humanSeq = [];
          return controller.play();
        }
        /*
        if (data.humanSeq.length === data.turns) {
          console.log('nice!');
          data.turns++;
          data.humanSeq = [];
          events.deactivateHumanEvents();
          controller.play();
        }
        } else {
        data.humanSeq = [];
        events.deactivateHumanEvents();
        controller.play();*/
      }

      // Reset humanSeq
    },

    makeSequence: function() {
      //Return an array of 20 numbers between 0 and 3
      let arr = new Array(20);
      for (let i = 0; i < arr.length; i++) {
        let rand = Math.floor(Math.random() * 4);
        arr[i] = rand;
      }
      return arr;
    },

    playback: function(){

    },

    pushButton: function(value, index, array) {
      if (value === 0) press.green();
      else if (value === 1) press.red();
      else if (value === 2) press.yellow()
      else press.blue();
    },

    translateToColor: function(num) {
      return data.colors[num];
    },

    turn: function(arr) { // arr is data.compSeq
      let index = 0;
      data.compSeq.push(data.sequence[data.turns]); // Push new number to compSeq
      // Adjust playback speed, depending on number of turns
      events.deactivateHumanEvents(); // Turn off human input during playback
      timerID = setInterval(function(){
        index++;
        console.log('turns', data.turns, 'index', index);
        // Playback logic
        simon.pushButton(data.compSeq[index]);
        if (index === data.turns + 1) {
          clearInterval(timerID);
        }
      }, 1000);
    }
  }

  let view = {
    init: function() {
      $('#power').change(events.togglePower);
    }
  };

  controller.init();
});
<commit_msg>Allow human input after sequence playback<commit_after>$(".document").ready(function() {

  let timerID;

  let data = {
    sequence: null,
    compSeq: [],
    humanSeq: [],
    ms: [1200, 1000, 800],
    colors: [green, red, yellow, blue],
    turns: 0
  };

  let controller = {

    init: function() {
      view.init();
    },
/*
    play: function(){
      // Add function: check for winner, call victory() and return true
      simon.playSeq(data.compSeq);
      events.activateHumanEvents();
    },
*/

    start: function() {
      data.sequence = simon.makeSequence();
      //data.compSeq.push(data.sequence[0]);
      simon.turn();
    },

    strict: function() {
      $('#strict-display').toggleClass('strict-on');
    }
  };

  // This function should togggle all event listeners on and off
  let events = {

    activateEvents: function() {
      $('#start-button').on('mousedown', controller.start);
      $('#strict-button').on('click', controller.strict);
      $('#green').on('mousedown', press.green);
      $('#red').on('mousedown', press.red);
      $('#yellow').on('mousedown', press.yellow);
      $('#blue').on('mousedown', press.blue);
    },

    deactivateEvents: function() {
      $('#test').off('click', controller.init);
      $('#start-button').off('click', controller.start);
      $('#strict-button').off('click', controller.strict);
      $('#green').off('mousedown', press.green);
      $('#red').off('mousedown', press.red);
      $('#yellow').off('mousedown', press.yellow);
      $('#blue').off('mousedown', press.blue);
    },

    activateHumanEvents: function() {
      $('.button').on('mousedown', simon.humanResponse);
      $('.button').toggleClass('lockout');
    },

    deactivateHumanEvents: function() {
      $('.button').off('mousedown', simon.humanResponse);
      $('.button').toggleClass('lockout');
    },

    togglePower: function() {
      this.checked ? events.activateEvents() : events.deactivateEvents();
    }

  };

  let press = {
    green: function() {
      let greenSound = document.getElementById('green-sound');
      let newSound = greenSound.cloneNode();
      newSound.play();
      newSound.remove();
      $('#green').addClass('press');
      setTimeout(() => {press.removeOpacity('#green')}, 200);
    },

    red: function() {
      let redSound = document.getElementById('red-sound');
      let newSound = redSound.cloneNode();
      newSound.play();
      newSound.remove();
      $('#red').addClass('press');
      setTimeout(() => {press.removeOpacity('#red')}, 200)
    },

    yellow: function() {
      let yellowSound = document.getElementById('yellow-sound');
      let newSound = yellowSound.cloneNode();
      newSound.play();
      newSound.remove();
      $('#yellow').addClass('press');
      setTimeout(() => {press.removeOpacity('#yellow')}, 200)
    },

    blue: function() {
      let blueSound = document.getElementById('blue-sound');
      let newSound = blueSound.cloneNode();
      newSound.play();
      newSound.remove();
      $('#blue').addClass('press');
      setTimeout(() => {press.removeOpacity('#blue')}, 200)
    },

    removeOpacity: function(x) {
      $(x).removeClass('press').bind(press.green);
    },
  };

  // The 'simon' object contains helper functions
  let simon = {

    getColorCode: function(button){
      return $(button).data().button;
    },

    hasWinner: function(humArr, compArr){
      return humArr.every((value, index) => compArr[index] === humArr[index]);
    },

    humanResponse: function(){
      let x = simon.getColorCode(this);
      data.humanSeq.push(x);
      console.log("humanResponse", "compSeq", data.compSeq);
      console.log("humanResponse", "humanSeq", data.humanSeq);
      console.log("humanResponse", "turns", data.turns);
      // If both arrays are equal...
      if (data.humanSeq.every(function isMatching(el, i) {
        return el === data.compSeq[i];
      })) {
        console.log('match');
        /*
        if (data.humanSeq.length === data.compSeq.length) {
          console.log('nice!');
          data.turns++;
          console.log('turns', data.turns)
          data.humanSeq = [];
          return controller.play();

        }*/
        /*
        if (data.humanSeq.length === data.turns) {
          console.log('nice!');
          data.turns++;
          data.humanSeq = [];
          events.deactivateHumanEvents();
          controller.play();
        }
        } else {
        data.humanSeq = [];
        events.deactivateHumanEvents();
        controller.play();*/
      }

      // Reset humanSeq
    },

    makeSequence: function() {
      //Return an array of 20 numbers between 0 and 3
      let arr = new Array(20);
      for (let i = 0; i < arr.length; i++) {
        let rand = Math.floor(Math.random() * 4);
        arr[i] = rand;
      }
      return arr;
    },

    playback: function(){

    },

    pushButton: function(value, index, array) {
      if (value === 0) press.green();
      else if (value === 1) press.red();
      else if (value === 2) press.yellow()
      else press.blue();
    },

    translateToColor: function(num) {
      return data.colors[num];
    },

    turn: function(arr) { // arr is data.compSeq
      let index = 0;
      data.compSeq.push(data.sequence[data.turns]); // Push new number to compSeq
      // Adjust playback speed, depending on number of turns
      events.deactivateHumanEvents(); // Turn off human input during playback
      timerID = setInterval(function(){
        index++;
        console.log('turns', data.turns, 'index', index);
        // Playback logic
        simon.pushButton(data.compSeq[index]);
        if (index === data.turns + 1) {
          clearInterval(timerID);
        }
      }, 1000);
      events.activateHumanEvents();
      simon.humanResponse();
    }
  }

  let view = {
    init: function() {
      $('#power').change(events.togglePower);
    }
  };

  controller.init();
});
<|endoftext|>


<commit_before>var alexa = require("alexa-app");
var search = require('youtube-search');
var ytdl = require('ytdl-core');
var s3 = require('s3');

global.__bucket = process.env.S3_BUCKET;

var app = new alexa.app("youtube");

var s3Client = s3.createClient({
    s3Options: {
        accessKeyId: process.env.S3_ACCESS_KEY,
        secretAccessKey: process.env.S3_SECRET_ACCESS_KEY
    }
});

var searchOpts = {
    maxResults: 1,
    type: 'video',
    key: process.env.YOUTUBE_API_KEY
};

var constants = {
    'token': 'string',
    'expectedPreviousToken': 'string'
};

var lastSearch;

app.pre = function(request, response, type) {
    if (request.applicationId != "amzn1.ask.skill.e252ffe0-987b-43c2-abec-58050fd7153b") {
        response.fail("Invalid application");
    }
};

app.intent("GetVideoIntent", {
        "slots": {
            "VideoQuery": "VIDEOS",
        },
        "utterances": [
            "search for {-|VideoQuery}",
            "find {-|VideoQuery}",
            "play {-|VideoQuery}",
            "start playing {-|VideoQuery}",
            "put on {-|VideoQuery}"
        ]
    },
    function(request, response) {
        var query = request.slot("VideoQuery");

        search(query, searchOpts, function(err, results) {
            if (err || results.length !== 1) {
                response.say('I could not complete your request at this moment.').send();
            } else {
                var metadata = results[0];
                if (metadata.link === undefined) {
                    response.say(query + ' did not return any results on YouTube.').send();
                } else {
                    response.say('I found a relevant video called '+metadata.title+'.');

                    var tmpfile = require('path').join('/tmp', metadata.id+'.mp3');
                    var key = require('path').join('audio', metadata.id);

                    ytdl(metadata.link, {
                        filter: function(format) {
                            return format.container === 'mp3';
                        }
                    }).pipe(fs.createWriteStream(tmpfile).on('finish', function () {
                        var params = {
                            localFile: tmpfile,
                            s3Params: {
                                Bucket: __bucket,
                                Key: key
                            }
                        };
                        var uploader = s3Client.uploadFile(params);
                        uploader.on('error', function(err) {
                            response.say('I had trouble downloading this video.').send();
                        });
                        uploader.on('end', function() {
                            lastSearch = s3.getPublicUrl(__bucket, key);
                            response.card({
                                'type': 'Simple',
                                'title': metadata.title,
                                'content': metadata.link
                            }).audioPlayerPlayStream('REPLACE_ALL', {
                                'url': lastSearch,
                                'streamFormat': 'AUDIO_MPEG',
                                'token': constants.token,
                                'expectedPreviousToken': constants.expectedPreviousToken
                            }).send();
                        });
                    }));
                }
            }
        });

        return false;
    }
);

app.intent("AMAZON.PauseIntent", {}, function(request, response) {
    response.audioPlayerStop();
});

app.intent("AMAZON.ResumeIntent", {}, function(request, response) {
    if (lastSearch === undefined) {
        response.say('You were not playing any video previously.');
    } else {
        response.audioPlayerPlayStream('REPLACE_ALL', {
            'url': lastSearch,
            'streamFormat': 'AUDIO_MPEG',
            'token': constants.token,
            'expectedPreviousToken': constants.expectedPreviousToken
        });
    }
});

app.intent("AMAZON.StopIntent", {}, function(request, response) {
    lastSearch = undefined;
    response.audioPlayerStop();
    response.audioPlayerClearQueue();
});

exports.handler = app.lambda();
<commit_msg>Restructure<commit_after>var alexa = require("alexa-app");
var search = require('youtube-search');
var ytdl = require('ytdl-core');
var s3 = require('s3');

global.__bucket = process.env.S3_BUCKET;

var app = new alexa.app("youtube");

var s3Client = s3.createClient({
    s3Options: {
        accessKeyId: process.env.S3_ACCESS_KEY,
        secretAccessKey: process.env.S3_SECRET_ACCESS_KEY
    }
});

var searchOpts = {
    maxResults: 1,
    type: 'video',
    key: process.env.YOUTUBE_API_KEY
};

var constants = {
    'token': 'string',
    'expectedPreviousToken': 'string'
};

var lastSearch;

app.pre = function(request, response, type) {
    if (request.applicationId != "amzn1.ask.skill.e252ffe0-987b-43c2-abec-58050fd7153b") {
        response.fail("Invalid application");
    }
};

app.intent("GetVideoIntent", {
        "slots": {
            "VideoQuery": "VIDEOS",
        },
        "utterances": [
            "search for {-|VideoQuery}",
            "find {-|VideoQuery}",
            "play {-|VideoQuery}",
            "start playing {-|VideoQuery}",
            "put on {-|VideoQuery}"
        ]
    },
    function(request, response) {
        var query = request.slot("VideoQuery");

        search(query, searchOpts, function(err, results) {
            if (err || results.length !== 1) {
                response.say('I could not complete your request at this moment.').send();
            } else {
                var metadata = results[0];
                if (metadata.link === undefined) {
                    response.say(query + ' did not return any results on YouTube.').send();
                } else {
                    response.say('I found a relevant video called '+metadata.title+'.');

                    var tmpfile = require('path').join('/tmp', metadata.id+'.mp3');
                    var key = require('path').join('audio', metadata.id);

                    var writer = fs.createWriteStream(tmpfile);
                    writer.on('finish', function () {
                        var uploader = s3Client.uploadFile({
                            localFile: tmpfile,
                            s3Params: {
                                Bucket: __bucket,
                                Key: key
                            }
                        });
                        uploader.on('error', function(err) {
                            response.say('I had trouble downloading this video.').send();
                        });
                        uploader.on('end', function() {
                            lastSearch = s3.getPublicUrl(__bucket, key);
                            response.card({
                                'type': 'Simple',
                                'title': metadata.title,
                                'content': metadata.link
                            }).audioPlayerPlayStream('REPLACE_ALL', {
                                'url': lastSearch,
                                'streamFormat': 'AUDIO_MPEG',
                                'token': constants.token,
                                'expectedPreviousToken': constants.expectedPreviousToken
                            }).send();
                        });
                    });

                    ytdl(metadata.link, {
                        filter: function(format) {
                            return format.container === 'mp3';
                        }
                    }).pipe(writer);
                }
            }
        });

        return false;
    }
);

app.intent("AMAZON.PauseIntent", {}, function(request, response) {
    response.audioPlayerStop();
});

app.intent("AMAZON.ResumeIntent", {}, function(request, response) {
    if (lastSearch === undefined) {
        response.say('You were not playing any video previously.');
    } else {
        response.audioPlayerPlayStream('REPLACE_ALL', {
            'url': lastSearch,
            'streamFormat': 'AUDIO_MPEG',
            'token': constants.token,
            'expectedPreviousToken': constants.expectedPreviousToken
        });
    }
});

app.intent("AMAZON.StopIntent", {}, function(request, response) {
    lastSearch = undefined;
    response.audioPlayerStop();
    response.audioPlayerClearQueue();
});

exports.handler = app.lambda();
<|endoftext|>


<commit_before>$(document).ready(function() {

  $('.social li:nth-child(1)').mouseenter(function() {
    $('.hint').empty().css('color', 'inherit').html("
+  Contribute
");
  });
  $('.social li:nth-child(2)').mouseenter(function() {
    $('.hint').empty().css('color', '#55acee').html("
Tweet my work
");
  });
  $('.social li:nth-child(3)').mouseenter(function() {
    $('.hint').empty().css('color', '#dd4b39').html("
Lets Talk
");
  });
  $('.social').mouseleave(function() {
    $('.hint').css('color', '#efefef');
  });

  $(".grad").each(function() {

    var rgb = [Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256)];
    console.log(rgb + " rgb");
    var color1 = 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')';
    console.log(color1 + " color1");
    var color2 = 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')';
    console.log(color2 + " color2");

    $(this).css("background", "linear-gradient(" + color1 + "," + color2 + ")");
  });
});<commit_msg>Master: Beautify the js script and remove unused functions.<commit_after>$(document).ready(function() {

    $(".grad").each(function() {

        var rgb = [Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256)];
        //console.log(rgb + " rgb");
        var color1 = 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')';
        //console.log(color1 + " color1");
        var color2 = 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')';
        //console.log(color2 + " color2");

        $(this).css("background", "linear-gradient(" + color1 + "," + color2 + ")");
    });
});
<|endoftext|>


<commit_before>const slice = (() => {
    const splitAt = (array, n) => [array.slice(0, n), array.slice(n)];
    const reduceConcat = a => a.length ? a.reduce((a, b) => [a].concat(reduceConcat(b))) : [];

    return (array, n) => {
        const splitted = splitAt(array, n);
        var p = splitted;
        while (p[1].length !== 0) {
            p[1] = splitAt(p[1], n);
            p = p[1];
        }
        return reduceConcat(splitted);
    };
})();

const rootVm = new Vue({
    el: '#app-sudoku',
    template: `

                    {{
                        n || ''
                    }}

                    {{ n }}

`,
    computed: {
        boxes: function() {
            const rows = this.rows;
            const sliced = rows.map(row => slice(row, 3));
            return [
                [].concat(sliced[0][0], sliced[1][0], sliced[2][0]),
                [].concat(sliced[0][1], sliced[1][1], sliced[2][1]),
                [].concat(sliced[0][2], sliced[1][2], sliced[2][2]),

                [].concat(sliced[3][0], sliced[4][0], sliced[5][0]),
                [].concat(sliced[3][1], sliced[4][1], sliced[5][1]),
                [].concat(sliced[3][2], sliced[4][2], sliced[5][2]),

                [].concat(sliced[6][0], sliced[7][0], sliced[8][0]),
                [].concat(sliced[6][1], sliced[7][1], sliced[8][1]),
                [].concat(sliced[6][2], sliced[7][2], sliced[8][2]),
            ];
        },
    },
    created: function() {
        this.rows = slice(Array.from(this.board).map(Number), 9);
        this.memo.data = Array.from({length: 81}).map(_ => [1,2,3,4,5,6,7,8,9,]);
    },
    data: () => new Object({
        board: '060003001200500600007090500000400090800000006010005000002010700004009003700200040', // 朝日新聞beパズル 2017/10/07 掲載分
        rows: undefined,
        memo: { hidden: false, },
    }),
});
<commit_msg>Move boxes calculation on created lifecycle hook.<commit_after>const slice = (() => {
    const splitAt = (array, n) => [array.slice(0, n), array.slice(n)];
    const reduceConcat = a => a.length ? a.reduce((a, b) => [a].concat(reduceConcat(b))) : [];

    return (array, n) => {
        const splitted = splitAt(array, n);
        var p = splitted;
        while (p[1].length !== 0) {
            p[1] = splitAt(p[1], n);
            p = p[1];
        }
        return reduceConcat(splitted);
    };
})();

const rootVm = new Vue({
    el: '#app-sudoku',
    template: `

                    {{
                        n || ''
                    }}

                    {{ n }}

`,
    created: function() {
        const rows = slice(Array.from(this.board).map(Number), 9);
        this.rows = rows;

        const sliced = rows.map(row => slice(row, 3));
        this.boxes = [
            [].concat(sliced[0][0], sliced[1][0], sliced[2][0]),
            [].concat(sliced[0][1], sliced[1][1], sliced[2][1]),
            [].concat(sliced[0][2], sliced[1][2], sliced[2][2]),

            [].concat(sliced[3][0], sliced[4][0], sliced[5][0]),
            [].concat(sliced[3][1], sliced[4][1], sliced[5][1]),
            [].concat(sliced[3][2], sliced[4][2], sliced[5][2]),

            [].concat(sliced[6][0], sliced[7][0], sliced[8][0]),
            [].concat(sliced[6][1], sliced[7][1], sliced[8][1]),
            [].concat(sliced[6][2], sliced[7][2], sliced[8][2]),
        ];

        this.memo.data = Array.from({length: 81}).map(_ => [1,2,3,4,5,6,7,8,9,]);
    },
    data: () => new Object({
        board: '060003001200500600007090500000400090800000006010005000002010700004009003700200040', // 朝日新聞beパズル 2017/10/07 掲載分
        rows: undefined,
        boxes: undefined,
        memo: { hidden: false, },
    }),
});
<|endoftext|>