<commit_before>// Opening for events
const eventTitles = getElementsByClassName('event-title')
const eventSubtitles = getElementsByClassName('event-subtitle')
const eventDetails = getElementsByClassName('event-details')
for (let i = 0; i < eventTitles.length; i++) {
	// Fade in
	eventTitles[i].classList.add('fade-move')
	eventSubtitles[i].classList.add('fade-move')
	eventDetails[i].classList.add('fade-move')
	// Email signup form
	// If background image is so complex that email signup form needs a dark background instead of a transparent background...
	const emailBox = getElementsByClassName('email-box')[i]
	// emailBox with class `email container background` has conditional visibility in Webflow, so Webflow tags a new class called `w-condition-invisible` if collection determines it’s invisible
	const visible = emailBox.querySelector('div.email-container-background.w-condition-invisible') === null
	changeEmailContainerBackground({ visible })
}

// Reg Form elements
const regFormButtons = getElementsByClassName('button register')
const regFormContainer = getElementByClassName('reg-form-container')

const showRegForm = () => {
	// Prevent background to scroll
	document.body.style.overflow = 'hidden'
	flexElement(regFormContainer)
	setTimeout(() => fadeInElement(regFormContainer), 100)
}

const closeRegForm = () => {
	// Reallow background to scroll
	document.body.style.overflow = 'visible'
	fadeOutElement(regFormContainer)
	setTimeout(() => hideElement(regFormContainer), 200)
}

// Event listener for if reg form is opened...
for (let i = 0; i < regFormButtons.length; i++) {
	onClick(regFormButtons[i], () => showRegForm())
}
// ...and closed.
const regFormClose = getElementByClassName('reg-form-close')
onClick(regFormClose, () => closeRegForm())

// Event summary “Read more...” expansion
getElementByClassName('text read-more').addEventListener('mouseover', () => {
	hideElement(getElementByClassName('text read-more'))
	hideElement(getElementByClassName('text summary'))
	getElementByClassName('text description').classList.add('display')
	setTimeout(() => getElementByClassName('text description display').classList.add('fade'), 100)
})<commit_msg>008 - flex css<commit_after>// Opening for events
const eventTitles = getElementsByClassName('event-title')
const eventSubtitles = getElementsByClassName('event-subtitle')
const eventDetails = getElementsByClassName('event-details')
for (let i = 0; i < eventTitles.length; i++) {
	// Fade in
	eventTitles[i].classList.add('fade-move')
	eventSubtitles[i].classList.add('fade-move')
	eventDetails[i].classList.add('fade-move')
	// Email signup form
	// If background image is so complex that email signup form needs a dark background instead of a transparent background...
	const emailBox = getElementsByClassName('email-box')[i]
	// emailBox with class `email container background` has conditional visibility in Webflow, so Webflow tags a new class called `w-condition-invisible` if collection determines it’s invisible
	const visible = emailBox.querySelector('div.email-container-background.w-condition-invisible') === null
	changeEmailContainerBackground({ visible })
}

// Reg Form elements
const regFormButtons = getElementsByClassName('button register')
const regFormBg = getElementByClassName('reg-form-background')
const regFormContainer = getElementByClassName('reg-form-container')

const showRegForm = () => {
	showElement(regFormBg)
	flexElement(regFormContainer)
	setTimeout(() => {
		fadeInElement(regFormBg)
		fadeInElement(regFormContainer)
		// Prevent background to scroll
		document.body.style.overflow = 'hidden'
	}, 100)
}

const closeRegForm = () => {
	// Reallow background to scroll
	document.body.style.overflow = 'visible'
	fadeOutElement(regFormBg)
	fadeOutElement(regFormContainer)
	setTimeout(() => {
		hideElement(regFormBg)
		hideElement(regFormContainer)
	}, 200)
}

// Event listener for if reg form is opened...
for (let i = 0; i < regFormButtons.length; i++) {
	onClick(regFormButtons[i], () => showRegForm())
}
// ...and closed.
const regFormClose = getElementByClassName('reg-form-close')
onClick(regFormClose, () => closeRegForm())

// Event summary “Read more...” expansion
getElementByClassName('text read-more').addEventListener('mouseover', () => {
	hideElement(getElementByClassName('text read-more'))
	hideElement(getElementByClassName('text summary'))
	getElementByClassName('text description').classList.add('display')
	setTimeout(() => getElementByClassName('text description display').classList.add('fade'), 100)
})<|endoftext|>


<commit_before>angular.module('scharwerk')
.controller('ProofCtrl', [
'$scope',
'$state',
'tasks',
'task',
'$anchorScroll',
'$modal',
function($scope, $state, tasks, task, $anchorScroll, $modal){
  if (!task) {
    $state.go('index');
  }

  var submitModal = function() {
    $modal.open({templateUrl: 'submitModal.html'}).result.then(function () {
      tasks.finish().success(function () {
        $state.go('index');
      });
    }, function () {
      $scope.goto(tasks.current.pages[0].id);
    });
  }

  var updatePage = function(page) {
    if (!page) {
      return submitModal();
    }
    $scope.id = page.id;
    $scope.text = page.text;
    $scope.image = page.image;

    $anchorScroll('text-top');
    $anchorScroll('image-top');
  };

  $scope.task = tasks.current;
  updatePage(tasks.current.current_page);

  $scope.save = function() {
    tasks.savePage($scope.id, $scope.text);
  }

  $scope.goto = function(id) {
    tasks.getPage(id).success(function (data) { updatePage(data) });
  }

  $scope.saveAndContinue = function() {
    tasks.savePage($scope.id, $scope.text, true).success(function() {
      updatePage(tasks.current.current_page);
    });
  }
}]);<commit_msg>redirect if no task<commit_after>angular.module('scharwerk')
.controller('ProofCtrl', [
'$scope',
'$state',
'tasks',
'task',
'$anchorScroll',
'$modal',
function($scope, $state, tasks, task, $anchorScroll, $modal){
  if (!tasks.current.exists) {
    $state.go('index');
    return ;
  }

  var submitModal = function() {
    $modal.open({templateUrl: 'submitModal.html'}).result.then(function () {
      tasks.finish().success(function () {
        $state.go('index');
      });
    }, function () {
      $scope.goto(tasks.current.pages[0].id);
    });
  }

  var updatePage = function(page) {
    if (!page) {
      return submitModal();
    }
    $scope.id = page.id;
    $scope.text = page.text;
    $scope.image = page.image;

    $anchorScroll('text-top');
    $anchorScroll('image-top');
  };

  $scope.task = tasks.current;
  updatePage(tasks.current.current_page);

  $scope.save = function() {
    tasks.savePage($scope.id, $scope.text);
  }

  $scope.goto = function(id) {
    tasks.getPage(id).success(function (data) { updatePage(data) });
  }

  $scope.saveAndContinue = function() {
    tasks.savePage($scope.id, $scope.text, true).success(function() {
      updatePage(tasks.current.current_page);
    });
  }
}]);<|endoftext|>


<commit_before>//If occation is food, set minimum value to 90 minutes

//Formtastic initialises sulten_reservation_reservation_duration selectoren with :collector
$("#sulten_reservation_reservation_type_id").change(function(){
var preValue = parseInt($("#sulten_reservation_reservation_duration").find(":selected").val())
var durationOptions = [30, 60, 90, 120]

  //In prod the values are:
  //mat = 2
  //drikke = 3

  //if testing, change the right hand side to reflect the "Mat/drikke" value in development.
  //remember to change it back to 2 afterwards
  if($(this).val() == 2){
    durationOptions = durationOptions.slice(2,4)
  }

  $("#sulten_reservation_reservation_duration option").remove()
  $.each(durationOptions,function(i,v){
    $("#sulten_reservation_reservation_duration").append($("<option />").val(v).text(v + " minutter"))
  })
  console.log(durationOptions)
  console.log(jQuery.inArray(preValue,durationOptions))
  if (jQuery.inArray(preValue,durationOptions) > -1){
    $("#sulten_reservation_reservation_duration").val(preValue)
  }
});
<commit_msg>Add more documentation for easier testing<commit_after>//If occation is food, set minimum value to 90 minutes

//Formtastic initialises sulten_reservation_reservation_duration selectoren with :collector
$("#sulten_reservation_reservation_type_id").change(function(){
var preValue = parseInt($("#sulten_reservation_reservation_duration").find(":selected").val())
var durationOptions = [30, 60, 90, 120]

  //In prod the values are:
  //mat = 2
  //drikke = 3

  //In testing the values are:
  //drikke = 5
  //mat/drikke = 6

  //if testing, change 'this.val()==' to reflect the "Mat/drikke" value in development.
  //remember to change it back to 2 afterwards
  if($(this).val() == 2){
    durationOptions = durationOptions.slice(2,4)
  }

  $("#sulten_reservation_reservation_duration option").remove()
  $.each(durationOptions,function(i,v){
    $("#sulten_reservation_reservation_duration").append($("<option />").val(v).text(v + " minutter"))
  })
  console.log(durationOptions)
  console.log(jQuery.inArray(preValue,durationOptions))
  if (jQuery.inArray(preValue,durationOptions) > -1){
    $("#sulten_reservation_reservation_duration").val(preValue)
  }
});
<|endoftext|>


<commit_before>Ext.define('sunerp.component.CongViecPicker', {
    extend: 'sunerp.component.core.BasePicker',
    alias: 'widget.congviecpicker',
    searchEmptyText: 'Tìm theo tên hoặc mã công việc',
    storeClass: 'sunerp.store.TaskStore',
    modelName: 'task',
    searchField: 'nameOrCode',
    title: 'Chọn công việc',
    getColumns: function () {
        return [
            {header: 'Mã CV', dataIndex: 'code'},
            {header: 'Tên', dataIndex: 'name', flex: 1},
            {header: 'Đơn vị', dataIndex: 'unit'},
            {header: 'Khối lượng', dataIndex: 'defaultValue', xtype: 'numbercolumn'},
            {header: 'Định mức', dataIndex: 'quota', xtype: 'numbercolumn'}
        ];
    },
    onOk: function () {
        this.getModel().set(this.modelName + "Id", this.getSelect().id);
        this.getModel().set(this.modelName + "Name" , this.getSelect()[this.displayField]);
        this.getWindow().close();
    }
});<commit_msg>Update.<commit_after>Ext.define('sunerp.component.CongViecPicker', {
    extend: 'sunerp.component.core.BasePicker',
    alias: 'widget.congviecpicker',
    searchEmptyText: 'Tìm theo tên hoặc mã công việc',
    storeClass: 'sunerp.store.TaskStore',
    modelName: 'task',
    searchField: 'nameOrCode',
    title: 'Chọn công việc',
    getColumns: function () {
        return [
            {header: 'Mã CV', dataIndex: 'code'},
            {header: 'Tên', dataIndex: 'name', flex: 1},
            {header: 'Đơn vị', dataIndex: 'unit'},
            {header: 'Khối lượng', dataIndex: 'defaultValue', xtype: 'numbercolumn'},
            {header: 'Định mức', dataIndex: 'quota', xtype: 'numbercolumn'}
        ];
    },
    onOk: function () {
        this.getModel().set(this.modelName + "Id", this.getSelect().id);
        this.getModel().set(this.modelName + "Name" , this.getSelect().name);
        this.getModel().set(this.modelName + "Code" , this.getSelect().code);
        this.getModel().set(this.modelName + "Unit" , this.getSelect().unit);
        this.getModel().set(this.modelName + "Quota" , this.getSelect().quota);
        this.getWindow().close();
    }
});<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');

io.emit('chat message', { for: 'everyone' });

io.on('connection', function(socket) {
	console.log('Um usuário se conectou ao server');

	socket.on('disconnect', function() {
		console.log('Usuário se desconectou.');
	});

	socket.on('chat message', function(msg){
    	console.log('message: ' + msg.conteudo);
		io.emit('chat message', msg);
  	});
});

app.use(express.static(path.join(__dirname, '../../')));
app.use(express.static(path.join(__dirname, '../public')));

app.set('port', process.env.PORT || 3000);

var server = http.listen(app.get('port'), function() {
    console.log('Estou escutando na porta ' + app.get('port'));
});
<commit_msg>adicionando configurações para o openshift<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');

io.emit('chat message', { for: 'everyone' });

io.on('connection', function(socket) {
	console.log('Um usuário se conectou ao server');

	socket.on('disconnect', function() {
		console.log('Usuário se desconectou.');
	});

	socket.on('chat message', function(msg){
    	console.log('message: ' + msg.conteudo);
		io.emit('chat message', msg);
  	});
});

app.use(express.static(path.join(__dirname, '../../')));
app.use(express.static(path.join(__dirname, '../public')));

app.set('port', OPENSHIFT_NODEJS_PORT || 3000);

var server = http.listen(app.get('port'), function() {
    console.log('Estou escutando na porta ' + app.get('port'));
});
<|endoftext|>


<commit_before>(function (window, ng) {
	"use strict";

	var app = ng.module("lightGridSamples", ["lightGrid", "lightGridTemplates", "lightGridDataProviders", "lightGridControls", "ngRoute", "ngResource"]);
	window.app = app;

	app.config(function ($routeProvider, $controllerProvider, $compileProvider) {

		$controllerProvider.allowGlobals();
		$compileProvider.debugInfoEnabled(false);

		$routeProvider
			.when("/simplest", {
				templateUrl: "Demos/simplest"
			})
			.when("/local-data", {
				templateUrl: "Demos/localData"
			})
			.when("/expanded-row", {
				templateUrl: "Demos/expandedRow"
			})
			.when("/local-editable-row", {
				templateUrl: "Demos/localEditableRow"
			})
			.when("/sortable-columns", {
				templateUrl: "Demos/sortableColumns"
			})
			.when("/client-side-search", {
				templateUrl: "Demos/clientSideSearch"
			})
			.when("/client-side-paging", {
				templateUrl: "Demos/clientSidePaging"
			})
			.when("/hidden-columns", {
				templateUrl: "Demos/hiddenColumns"
			})
			.when("/fully-featured-local", {
				templateUrl: "Demos/fullyFeaturedLocal"
			})
			.when("/server-side-processing", {
				templateUrl: "Demos/serverSideProcessing"
			})
			.otherwise({
				redirectTo: "/simplest"
			});
	});

	app.constant("sampleModel", [
		{
			make: "Honda",
			model: "CBF 1000F",
			engine: "998cm R4"
		}, {
			make: "BMW",
			model: "F800 GT",
			engine: "800ccm R2"
		}, {
			make: "Suzuki",
			model: "V-Strom 1000",
			engine: "1000ccm V2"
		}, {
			make: "KTM",
			model: "690 Duke",
			engine: "690ccm single"
		}, {
			make: "Kawasaki",
			model: "H2R",
			engine: "998ccm R4 supercharged"
		}
	]);

	app.factory("Zip", function($resource) {
		return $resource("/Demos/SampleData", null, {
			query: {
				action: "GET",
				isArray: true,
				transformResponse: function(data) {
					var parsedResponse = JSON.parse(data);
					var parsedData = parsedResponse.data;
					parsedData.totalRecords = parsedResponse.totalRecords;

					return parsedData;
				}
			}
		});
	});

}(window, window.angular));<commit_msg>Removed an unnecessary $resource definition<commit_after>(function (window, ng) {
	"use strict";

	var app = ng.module("lightGridSamples", ["lightGrid", "lightGridTemplates", "lightGridDataProviders", "lightGridControls", "ngRoute", "ngResource"]);
	window.app = app;

	app.config(function ($routeProvider, $controllerProvider, $compileProvider) {

		$controllerProvider.allowGlobals();
		$compileProvider.debugInfoEnabled(false);

		$routeProvider
			.when("/simplest", {
				templateUrl: "Demos/simplest"
			})
			.when("/local-data", {
				templateUrl: "Demos/localData"
			})
			.when("/expanded-row", {
				templateUrl: "Demos/expandedRow"
			})
			.when("/local-editable-row", {
				templateUrl: "Demos/localEditableRow"
			})
			.when("/sortable-columns", {
				templateUrl: "Demos/sortableColumns"
			})
			.when("/client-side-search", {
				templateUrl: "Demos/clientSideSearch"
			})
			.when("/client-side-paging", {
				templateUrl: "Demos/clientSidePaging"
			})
			.when("/hidden-columns", {
				templateUrl: "Demos/hiddenColumns"
			})
			.when("/fully-featured-local", {
				templateUrl: "Demos/fullyFeaturedLocal"
			})
			.when("/server-side-processing", {
				templateUrl: "Demos/serverSideProcessing"
			})
			.otherwise({
				redirectTo: "/simplest"
			});
	});

	app.constant("sampleModel", [
		{
			make: "Honda",
			model: "CBF 1000F",
			engine: "998cm R4"
		}, {
			make: "BMW",
			model: "F800 GT",
			engine: "800ccm R2"
		}, {
			make: "Suzuki",
			model: "V-Strom 1000",
			engine: "1000ccm V2"
		}, {
			make: "KTM",
			model: "690 Duke",
			engine: "690ccm single"
		}, {
			make: "Kawasaki",
			model: "H2R",
			engine: "998ccm R4 supercharged"
		}
	]);

}(window, window.angular));<|endoftext|>


<commit_before>// create the module and name it multimetro
var multimetro = angular.module('multimetro', ['ngRoute']);

// configure our routes
multimetro.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'pages/contact.html',
            controller  : 'contactController'
        });
});
// create the controller and inject Angular's $scope
multimetro.controller('mainController', function($scope) {
    // create a title to display in our view
    $scope.appName = 'Multimetro';
});

multimetro.controller('aboutController', function($scope) {
});

multimetro.controller('contactController', function($scope) {
});
<commit_msg>added ngProgress<commit_after>// create the module and name it multimetro
var multimetro = angular.module('multimetro', ['ngRoute', 'ngProgress']);

// configure our routes
multimetro.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'pages/contact.html',
            controller  : 'contactController'
        });
});
// create the controller and inject Angular's $scope
multimetro.controller('mainController', function($scope, ngProgress) {
    // create a title to display in our view
    $scope.appName = 'Multimetro';
    ngProgress.start(2);
    ngProgress.complete()
});

multimetro.controller('aboutController', function($scope, ngProgress) {
    ngProgress.start(2);
    ngProgress.complete()
});

multimetro.controller('contactController', function($scope, ngProgress) {
    ngProgress.start(2);
    ngProgress.complete()
});
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
	tagName: 'div',
    classNames: [ 'sl-grid-header-settings' ],
    actions: {
        click: function( action, key, stayOpen ){
            this.sendAction( 'action', action, key );
        }
    },

    open: false,

    eventManager: Ember.Object.create({
        click: function( event, view ){
            if( $( event.target ).closest( '.stay-open' ).length ){
                return false;
            } else {
                view.$( 'button.dropdown-toggle' ).dropdown( 'toggle' );
            }
        }
    }),

    clickableActions: function(){
        var actions = Ember.A([]),
            settings = this.get( 'settings' );

        if( settings.actions ){
            actions.pushObjects( settings.actions );
        }

        return actions;

    }.property( 'settings' ),

    showActions: Ember.computed.bool( 'settings.actions' ),

    hideableColumns: function(){
        var hideableColumns = Ember.A([]),
            settings = this.get( 'settings' ),
            columns = this.get( 'columns' );
        if( settings.hideableColumns ){

            hideableColumns.pushObjects( columns.rejectBy( 'hideable', false ).map( function( column ){
                return {
                    action: 'toggleColumnVisibility',
                    key: column.key,
                    hidden: column.hidden,
                    label: column.title
                };
            }));
        }
        return hideableColumns;

    }.property( 'settings', 'columns.@each.hidden' ),

    columnCheckbox: Ember.Checkbox.extend({
        checked: Ember.computed.not( 'column.hidden' ),
        click: function(){
            this.get( 'parentView' ).send( 'click', this.get( 'column.action'), this.get( 'column.key') );
        }
    }),

    showColumns: Ember.computed.bool( 'settings.hideableColumns' )

});
<commit_msg>removed unused argument<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
	tagName: 'div',
    classNames: [ 'sl-grid-header-settings' ],
    actions: {
        click: function( action, key ){
            this.sendAction( 'action', action, key );
        }
    },

    open: false,

    eventManager: Ember.Object.create({
        click: function( event, view ){
            if( $( event.target ).closest( '.stay-open' ).length ){
                return false;
            } else {
                view.$( 'button.dropdown-toggle' ).dropdown( 'toggle' );
            }
        }
    }),

    clickableActions: function(){
        var actions = Ember.A([]),
            settings = this.get( 'settings' );

        if( settings.actions ){
            actions.pushObjects( settings.actions );
        }

        return actions;

    }.property( 'settings' ),

    showActions: Ember.computed.bool( 'settings.actions' ),

    hideableColumns: function(){
        var hideableColumns = Ember.A([]),
            settings = this.get( 'settings' ),
            columns = this.get( 'columns' );
        if( settings.hideableColumns ){

            hideableColumns.pushObjects( columns.rejectBy( 'hideable', false ).map( function( column ){
                return {
                    action: 'toggleColumnVisibility',
                    key: column.key,
                    hidden: column.hidden,
                    label: column.title
                };
            }));
        }
        return hideableColumns;

    }.property( 'settings', 'columns.@each.hidden' ),

    columnCheckbox: Ember.Checkbox.extend({
        checked: Ember.computed.not( 'column.hidden' ),
        click: function(){
            this.get( 'parentView' ).send( 'click', this.get( 'column.action'), this.get( 'column.key') );
        }
    }),

    showColumns: Ember.computed.bool( 'settings.hideableColumns' )

});
<|endoftext|>


<commit_before>/**
 * Test the repo list item
 */

import { RepoListItem } from './index';
import IssueIcon from 'IssueIcon';
import ListItem from 'ListItem';

import expect from 'expect';
import { shallow, mount } from 'enzyme';
import React from 'react';

describe('<RepoListItem />', () => {
  let item;

  // Before each test reset the item data for safety
  beforeEach(() => {
    item = {
      owner: {
        login: 'mxstbr',
      },
      html_url: 'https://github.com/mxstbr/react-boilerplate',
      name: 'react-boilerplate',
      open_issues_count: 20,
      full_name: 'mxstbr/react-boilerplate',
    };
  });

  it('should render a ListItem', () => {
    const renderedComponent = shallow(
      <RepoListItem item={item} />
    );
    expect(renderedComponent.find(ListItem).length).toEqual(1);
  });

  it('should not render the current username', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} currentUser={item.owner.login} />
    );
    expect(renderedComponent.text().indexOf(item.owner.login)).toBeLessThan(0);
  });

  it('should render usernames that are not the current one', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} currentUser="nikgraf" />
    );
    expect(renderedComponent.text().indexOf(item.owner.login)).toBeGreaterThan(-1);
  });

  it('should render the repo name', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} />
    );
    expect(renderedComponent.text().indexOf(item.name)).toBeGreaterThan(-1);
  });

  it('should render the issue count', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} />
    );
    expect(renderedComponent.text().indexOf(item.open_issues_count)).toBeGreaterThan(1);
  });

  it('should render the IssueIcon', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} />
    );
    console.log(renderedComponent.debug());
    expect(renderedComponent.find('svg').length).toEqual(1);
  });
});
<commit_msg>Fix linting error<commit_after>/**
 * Test the repo list item
 */

import { RepoListItem } from './index';
import ListItem from 'ListItem';

import expect from 'expect';
import { shallow, mount } from 'enzyme';
import React from 'react';

describe('<RepoListItem />', () => {
  let item;

  // Before each test reset the item data for safety
  beforeEach(() => {
    item = {
      owner: {
        login: 'mxstbr',
      },
      html_url: 'https://github.com/mxstbr/react-boilerplate',
      name: 'react-boilerplate',
      open_issues_count: 20,
      full_name: 'mxstbr/react-boilerplate',
    };
  });

  it('should render a ListItem', () => {
    const renderedComponent = shallow(
      <RepoListItem item={item} />
    );
    expect(renderedComponent.find(ListItem).length).toEqual(1);
  });

  it('should not render the current username', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} currentUser={item.owner.login} />
    );
    expect(renderedComponent.text().indexOf(item.owner.login)).toBeLessThan(0);
  });

  it('should render usernames that are not the current one', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} currentUser="nikgraf" />
    );
    expect(renderedComponent.text().indexOf(item.owner.login)).toBeGreaterThan(-1);
  });

  it('should render the repo name', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} />
    );
    expect(renderedComponent.text().indexOf(item.name)).toBeGreaterThan(-1);
  });

  it('should render the issue count', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} />
    );
    expect(renderedComponent.text().indexOf(item.open_issues_count)).toBeGreaterThan(1);
  });

  it('should render the IssueIcon', () => {
    const renderedComponent = mount(
      <RepoListItem item={item} />
    );
    console.log(renderedComponent.debug());
    expect(renderedComponent.find('svg').length).toEqual(1);
  });
});
<|endoftext|>


<commit_before>/**
 * Created by ivar on 1.12.15.
 */

define([
	'angularAMD',
    'service/LexiconService',
    'service/ExtendedSearchModalService'
], function(angularAMD) {

	angularAMD.controller('main/ExtendedSearchCtrl', [ '$scope', '$rootScope', '$q', '$state', '$log', '$http', '$uibModal', '$uibModalInstance', 'wnwbApi',  'spinnerService', 'service/ExtendedSearchModalService', function($scope, $rootScope, $q, $state, $log, $http, $uibModal, $uibModalInstance, wnwbApi,  spinnerService, extendedSearchModalService) {

		$log.log('main/ExternalSearchCtrl');

        var SearchTypes = {
                synset      : 'Synset',
                lexentry    : 'Lexentry',
                sense       : 'Sense'

        };

        var Fields = {
                synset : {},
                sense : {},
                lexentry : {}
        };

        var Types = {
                I : {
                        regexp :'\\d+',
                        errorMessage : 'Only numeric values are allowed.'
                      },
                N : {
                        regexp :'\\d+',
                        errorMessage : 'Only numeric values are allowed.'
                      }
        };

        var SearchResult = null;

        var initSearchParams = function (hash, searchtype)
        {
            var fieldsDict = {};

            $scope.searchTitle[searchtype] = hash.name;
            parameters = hash.parameters;

            relations = {};

            //relations hash
            for (el in hash.relations) {
              relations[hash.relations[el][0]] = hash.relations[el][1];
            }

            //fields from array to hash
            for (el in parameters) {
                if (parameters[el].field) {
                    if (parameters[el].values=='[relations]') {
                          parameters[el].relations = relations;
                    }
                    else if (parameters[el].values && parameters[el].values!='*') {
                       var fixedValues =  (parameters[el].values).split(',');
                        parameters[el].fixedValues = fixedValues;
                    }
                   fieldsDict[parameters[el].field] =  parameters[el];
                }
            }
            $scope.Fields[searchtype] = fieldsDict;
        }

        var RootFilter = {
                type: 'group',
                boolOp: 'OR',
                items : [ {type:'group', boolOp:'AND', items:[]}]
                };

        $scope.filterTree = {};
        $scope.searchTitle = {};

        $scope.filterTree.synset = {};
        $scope.filterTree.sense = {};
        $scope.filterTree.lexentry = {};

        $scope.init = function (qAllResults) {
            if (!$scope.selectedSearchType) {
                $scope.selectedSearchType = 'synset';
                }

            $scope.Fields = Fields;

            initSearchParams(qAllResults[0][0], 'synset');
            initSearchParams(qAllResults[1][0], 'sense');
            initSearchParams(qAllResults[2][0], 'lexentry');

            $scope.TypeValidation = Types;
            $scope.searchTypes = SearchTypes;

            $scope.filterTree.synset = angular.copy(RootFilter);
            $scope.filterTree.sense = angular.copy(RootFilter);
            $scope.filterTree.lexentry = angular.copy(RootFilter);

        };

        $scope.changeSearchType = function(key) {
            $scope.selectedSearchType = key;
        }

        $scope.resetFilter = function(searchType) {
              $scope.filterTree[searchType] =  angular.copy(RootFilter);
        }

        $scope.cancel = function() {
              $uibModalInstance.close(null);
          }

        var evaluateFilterTree = function(items) {
            for (key in items) {
                if (items[key].type =='group') {
                    evaluateFilterTree(items[key].items);
                } else if (items[key].type=='field') {
                    console.debug('items', items[key].field.insertedValue);
                }
            }
            return true;
        }

        $scope.evaluateAndDoSearch = function () {
            if(evaluateFilterTree($scope.filterTree[$scope.selectedSearchType].items)) {
                $scope.doSearch();
            }
        }

        var constructFilter = function (element) {
            if (element.type=='group') {
                var Group = {type:'bool', op: (element.boolOp).toLowerCase(), exps : []};
                for (key in element.items) {
                   Group.exps.push(constructFilter(element.items[key]));
                }
                return Group;
            } else if (element.type=='field') {
                return { type:'simple'
                        , field: element.field.field
                        , op : element.field.selectedOps
                        , value: element.field.insertedValue };
            }
        }

        $scope.doSearch = function() {
            var Filter = constructFilter($scope.filterTree[$scope.selectedSearchType]);
            //console.debug(Filter);
           /* var data = {filter:
                { type:"bool", op: "and", exps: [
                    { type:"simple", field:"date_created", op:">=", value:"2017-05-01T18:50:07.352550Z" },
                    { type:"simple", field:"lemma", op:"like", value:"omp" }
                ]
                }};*/
            var data = {filter:Filter};
            console.debug('request data', data);
            // data = {filter:{}};
            spinnerService.show('searchLemmaSpinner');
            if ($scope.selectedSearchType == 'lexentry') {
                var resultPromise =  wnwbApi.LexicalEntrySearch.query(data).$promise;
            }
            else if ($scope.selectedSearchType == 'sense') {
                var resultPromise =  wnwbApi.SenseSearch.query(data).$promise;
            }
            else {
                var resultPromise =  wnwbApi.SynsetSearch.query(data).$promise;
            }

            //console.log('resultPromise', resultPromise);
            resultPromise.then(function(searchRes) {
                 	console.log("searchRes",searchRes);
                 	$rootScope.extSearchResult = searchRes;
                    //kui tylemus tyhi, j22 sellele lehele
                 	SearchResult = searchRes;
                    extendedSearchModalService.setSearchTitle($scope.searchTitle[$scope.selectedSearchType]);
                    extendedSearchModalService.setSearchType($scope.selectedSearchType);
                    extendedSearchModalService.setSearchResult(SearchResult);
                    $state.go('extsearch');
                    spinnerService.hide('searchLemmaSpinner');
                    $uibModalInstance.close(null);
            });
		};

        var LexentryFieldsPromise =  extendedSearchModalService.getLexentryFilterFieldsPromise();
        var SynsetFieldsPromise = extendedSearchModalService.getSynsetFilterFieldsPromise();
        var SenseFieldsFromise = extendedSearchModalService.getSenseFilterFieldsPromise();
        var PromiseList = [SynsetFieldsPromise, SenseFieldsFromise, LexentryFieldsPromise];

        $q.all(PromiseList).then(function(qAllResults) {
		  $scope.init(qAllResults);
        });

	} ]);
});<commit_msg>op 'isempty' field value is null<commit_after>/**
 * Created by ivar on 1.12.15.
 */

define([
	'angularAMD',
    'service/LexiconService',
    'service/ExtendedSearchModalService'
], function(angularAMD) {

	angularAMD.controller('main/ExtendedSearchCtrl', [ '$scope', '$rootScope', '$q', '$state', '$log', '$http', '$uibModal', '$uibModalInstance', 'wnwbApi',  'spinnerService', 'service/ExtendedSearchModalService', function($scope, $rootScope, $q, $state, $log, $http, $uibModal, $uibModalInstance, wnwbApi,  spinnerService, extendedSearchModalService) {

		$log.log('main/ExternalSearchCtrl');

        var SearchTypes = {
                synset      : 'Synset',
                lexentry    : 'Lexentry',
                sense       : 'Sense'

        };

        var Fields = {
                synset : {},
                sense : {},
                lexentry : {}
        };

        var Types = {
                I : {
                        regexp :'\\d+',
                        errorMessage : 'Only numeric values are allowed.'
                      },
                N : {
                        regexp :'\\d+',
                        errorMessage : 'Only numeric values are allowed.'
                      }
        };

        var SearchResult = null;

        var initSearchParams = function (hash, searchtype)
        {
            var fieldsDict = {};

            $scope.searchTitle[searchtype] = hash.name;
            parameters = hash.parameters;

            relations = {};

            //relations hash
            for (el in hash.relations) {
              relations[hash.relations[el][0]] = hash.relations[el][1];
            }

            //fields from array to hash
            for (el in parameters) {
                if (parameters[el].field) {
                    if (parameters[el].values=='[relations]') {
                          parameters[el].relations = relations;
                    }
                    else if (parameters[el].values && parameters[el].values!='*') {
                       var fixedValues =  (parameters[el].values).split(',');
                        parameters[el].fixedValues = fixedValues;
                    }
                   fieldsDict[parameters[el].field] =  parameters[el];
                }
            }
            $scope.Fields[searchtype] = fieldsDict;
        }

        var RootFilter = {
                type: 'group',
                boolOp: 'OR',
                items : [ {type:'group', boolOp:'AND', items:[]}]
                };

        $scope.filterTree = {};
        $scope.searchTitle = {};

        $scope.filterTree.synset = {};
        $scope.filterTree.sense = {};
        $scope.filterTree.lexentry = {};

        $scope.init = function (qAllResults) {
            if (!$scope.selectedSearchType) {
                $scope.selectedSearchType = 'synset';
                }

            $scope.Fields = Fields;

            initSearchParams(qAllResults[0][0], 'synset');
            initSearchParams(qAllResults[1][0], 'sense');
            initSearchParams(qAllResults[2][0], 'lexentry');

            $scope.TypeValidation = Types;
            $scope.searchTypes = SearchTypes;

            $scope.filterTree.synset = angular.copy(RootFilter);
            $scope.filterTree.sense = angular.copy(RootFilter);
            $scope.filterTree.lexentry = angular.copy(RootFilter);

        };

        $scope.changeSearchType = function(key) {
            $scope.selectedSearchType = key;
        }

        $scope.resetFilter = function(searchType) {
              $scope.filterTree[searchType] =  angular.copy(RootFilter);
        }

        $scope.cancel = function() {
              $uibModalInstance.close(null);
          }

        var evaluateFilterTree = function(items) {
            for (key in items) {
                if (items[key].type =='group') {
                    evaluateFilterTree(items[key].items);
                } else if (items[key].type=='field') {
                    console.debug('items', items[key].field.insertedValue);
                }
            }
            return true;
        }

        $scope.evaluateAndDoSearch = function () {
            if(evaluateFilterTree($scope.filterTree[$scope.selectedSearchType].items)) {
                $scope.doSearch();
            }
        }

        var constructFilter = function (element) {
            if (element.type=='group') {
                var Group = {type:'bool', op: (element.boolOp).toLowerCase(), exps : []};
                for (key in element.items) {
                   Group.exps.push(constructFilter(element.items[key]));
                }
                return Group;
            } else if (element.type=='field') {

                if (element.field.selectedOps == 'isempty')
                {
                    element.field.insertedValue = null;
                }
                return { type:'simple'
                        , field: element.field.field
                        , op : element.field.selectedOps
                        , value: element.field.insertedValue };

            }
        }

        $scope.doSearch = function() {
            var Filter = constructFilter($scope.filterTree[$scope.selectedSearchType]);
            //console.debug(Filter);
           /* var data = {filter:
                { type:"bool", op: "and", exps: [
                    { type:"simple", field:"date_created", op:">=", value:"2017-05-01T18:50:07.352550Z" },
                    { type:"simple", field:"lemma", op:"like", value:"omp" }
                ]
                }};*/
            var data = {filter:Filter};
            console.log('request data', data);
            // data = {filter:{}};
            spinnerService.show('searchLemmaSpinner');
            if ($scope.selectedSearchType == 'lexentry') {
                var resultPromise =  wnwbApi.LexicalEntrySearch.query(data).$promise;
            }
            else if ($scope.selectedSearchType == 'sense') {
                var resultPromise =  wnwbApi.SenseSearch.query(data).$promise;
            }
            else {
                var resultPromise =  wnwbApi.SynsetSearch.query(data).$promise;
            }

            //console.log('resultPromise', resultPromise);
            resultPromise.then(function(searchRes) {
                 	console.log("searchRes",searchRes);
                 	$rootScope.extSearchResult = searchRes;
                    //kui tylemus tyhi, j22 sellele lehele
                 	SearchResult = searchRes;
                    extendedSearchModalService.setSearchTitle($scope.searchTitle[$scope.selectedSearchType]);
                    extendedSearchModalService.setSearchType($scope.selectedSearchType);
                    extendedSearchModalService.setSearchResult(SearchResult);
                    $state.go('extsearch');
                    spinnerService.hide('searchLemmaSpinner');
                    $uibModalInstance.close(null);
            });
		};

        var LexentryFieldsPromise =  extendedSearchModalService.getLexentryFilterFieldsPromise();
        var SynsetFieldsPromise = extendedSearchModalService.getSynsetFilterFieldsPromise();
        var SenseFieldsFromise = extendedSearchModalService.getSenseFilterFieldsPromise();
        var PromiseList = [SynsetFieldsPromise, SenseFieldsFromise, LexentryFieldsPromise];

        $q.all(PromiseList).then(function(qAllResults) {
		  $scope.init(qAllResults);
        });

	} ]);
});<|endoftext|>


<commit_before><commit_msg>commit whatever stupid change i made<commit_after><|endoftext|>


<commit_before>morpheus.ConditionalRenderingUI = function (heatmap) {
	var _this = this;
	this.heatmap = heatmap;
	var $div = $('

');
	$div.on('click', '[data-name=add]', function (e) {
		var $this = $(this);
		var $row = $this.closest('.morpheus-entry');
		// add after
		var index = $row.index();
		var condition = {
			series: null,
			color: 'rgb(0,0,0)',
			shape: null,
			inheritColor: true,
			accept: function (val) {
				return false;
			}

		};

		heatmap.heatmap.getColorScheme().getConditions().insert(index,
			condition);

		$row.after(_this.add(condition));
		e.preventDefault();
	});
	$div.on('click', '[data-name=delete]', function (e) {
		var $this = $(this);
		var $row = $this.closest('.morpheus-entry');
		var index = $row.index() - 1;
		heatmap.heatmap.getColorScheme().getConditions().remove(index);
		heatmap.revalidate();
		$row.remove();
		e.preventDefault();
	});
	var html = [];
	html
	.push('
');
	html.push('
');
	html
	.push('
Add
');

	html.push('
');
	html.push('
');

	$div.append(html.join(''));
	this.$div = $div;
	heatmap.heatmap.getColorScheme().getConditions().getConditions().forEach(
		function (c) {
			_this.add(c).appendTo($div);
		});

};

morpheus.ConditionalRenderingUI.prototype = {
	add: function (condition) {
		var _this = this;
		// shape: shapes and line
		// color: if no color cell is drawn using this shape, otherwise draw
		// shape on top of cell
		// series name
		// value >= x and <= x
		var html = [];
		html.push('
');
		html.push('<form class="form-horizontal">');
		// series
		html.push('
');
		html
		.push('Series');
		html.push('
');
		html
		.push('<select class="form-control morpheus-form-control-inline" id="cond_series">');
		html.push(morpheus.Util.createOptions(morpheus.DatasetUtil
		.getSeriesNames(this.heatmap.getProject().getFullDataset())));
		html.push('</select>');
		html.push('
');
		html.push('
');

		// condition
		html.push('
');
		html.push('Condition');
		html.push('
');
		html
		.push('<select class="form-control morpheus-form-control-inline" name="lower"><option value="gte">>=</option><option value="gt">></option></select>');
		html
		.push('<input class="form-control morpheus-form-control-inline" name="v1" size="5" type="text">');
		html.push('and');
		html
		.push('<select class="form-control morpheus-form-control-inline" name="upper"><option value="lte"><=</option><option value="lt"><</option></select>');
		html
		.push('<input class="form-control morpheus-form-control-inline" name="v2" size="5" type="text">');
		html.push('
');
		html.push('
');

		// shape
		html.push('
');
		html.push('Shape');
		var shapeField = new morpheus.ShapeField(['circle', 'square',
			'diamond', 'triangle-up', 'triangle-down', 'triangle-left',
			'triangle-right']);
		html.push('
');
		html.push('

');
		html.push('
');
		html.push('
');

		// color
		html.push('
');
		html.push('<input name="inherit_color"' +
			' type="checkbox" checked> Inherit' +
			' color');
		html.push('
');

		html.push('
');
		html.push('Color');
		html.push('
');
		html
		.push('<input class="form-control" type="color" name="color" style="display:inline;' +
			' width:6em;" disabled>');
		html.push('
');
		html.push('
');

		// add/delete
		html
		.push('
');

		html.push('
');
		html
		.push('Remove');
		html.push('
');
		html.push('
'); // morpheus-entry
		var $el = $(html.join(''));
		shapeField.$el.appendTo($el.find('[data-name=shapeHolder]'));
		var $color = $el.find('[name=color]');
		var $series = $el.find('[id=cond_series]');
		var $v1 = $el.find('[name=v1]');
		var $v2 = $el.find('[name=v2]');
		var $v1Op = $el.find('[name=lower]');
		var $v2Op = $el.find('[name=upper]');
		var $inherit_color = $el.find('[name=inherit_color]');
		$color.prop('disabled', condition.inheritColor);
		$color.val(condition.color);
		$series.val(condition.series);
		shapeField.setShapeValue(condition.shape);
		$v1.val(condition.v1);
		$v2.val(condition.v2);
		$v1Op.val(condition.v1Op);
		$v2Op.val(condition.v2Op);
		function updateAccept() {
			var v1 = parseFloat($($v1).val());
			if (isNaN(v1)) {
				v1 = -Number.MAX_VALUE;
			}

			var v2 = parseFloat($($v2).val());
			if (isNaN(v2)) {
				v2 = Number.MAX_VALUE;
			}

			var v1Op = $v1Op.val();
			var v2Op = $v2Op.val();
			var gtf = v1Op === 'gt' ? function (val) {
				return val > v1;
			} : function (val) {
				return val >= v1;
			};
			var ltf = v2Op === 'lt' ? function (val) {
				return val < v2;
			} : function (val) {
				return val <= v2;
			};
			condition.v1 = v1;
			condition.v2 = v2;
			condition.v1Op = v1Op;
			condition.v2Op = v2Op;
			condition.accept = function (val) {
				return gtf(val) && ltf(val);
			};
			_this.heatmap.revalidate();
		}

		$v1Op.on('change', function (e) {
			updateAccept();

		});
		$v2Op.on('change', function (e) {
			updateAccept();
		});
		$v1.on('keyup', _.debounce(function (e) {
			updateAccept();
		}, 100));
		$v2.on('keyup', _.debounce(function (e) {
			updateAccept();
		}, 100));
		$inherit_color.on('click', function (e) {
			condition.inheritColor = $(this).prop('checked');
			$color.prop('disabled', condition.inheritColor);
			_this.heatmap.revalidate();
		});
		$color.on('change', function (e) {
			condition.color = $(this).val();
			_this.heatmap.revalidate();
		});
		shapeField.on('change', function (e) {
			condition.shape = e.shape;
			_this.heatmap.revalidate();
		});
		$series.on('change', function (e) {
			condition.series = $(this).val();
			_this.heatmap.revalidate();
		});
		condition.series = $series.val();
		return $el;

	}
};
<commit_msg>borders<commit_after>morpheus.ConditionalRenderingUI = function (heatmap) {
	var _this = this;
	this.heatmap = heatmap;
	var $div = $('

');
	$div.on('click', '[data-name=add]', function (e) {
		var $this = $(this);
		var $row = $this.closest('.morpheus-entry');
		// add after
		var index = $row.index();
		var condition = {
			series: null,
			color: 'rgb(0,0,0)',
			shape: null,
			inheritColor: true,
			accept: function (val) {
				return false;
			}

		};

		heatmap.heatmap.getColorScheme().getConditions().insert(index,
			condition);

		$row.after(_this.add(condition));
		e.preventDefault();
	});
	$div.on('click', '[data-name=delete]', function (e) {
		var $this = $(this);
		var $row = $this.closest('.morpheus-entry');
		var index = $row.index() - 1;
		heatmap.heatmap.getColorScheme().getConditions().remove(index);
		heatmap.revalidate();
		$row.remove();
		e.preventDefault();
	});
	var html = [];
	html
	.push('
');
	html.push('
');
	html
	.push('
Add Condition
');

	html.push('
');
	html.push('
');

	$div.append(html.join(''));
	this.$div = $div;
	heatmap.heatmap.getColorScheme().getConditions().getConditions().forEach(
		function (c) {
			_this.add(c).appendTo($div);
		});

};

morpheus.ConditionalRenderingUI.prototype = {
	add: function (condition) {
		var _this = this;
		// shape: shapes and line
		// color: if no color cell is drawn using this shape, otherwise draw
		// shape on top of cell
		// series name
		// value >= x and <= x
		var html = [];
		html.push('
');
		html.push('<form class="form-horizontal">');
		// series
		html.push('
');
		html
		.push('Series');
		html.push('
');
		html
		.push('<select class="form-control morpheus-form-control-inline" id="cond_series">');
		html.push(morpheus.Util.createOptions(morpheus.DatasetUtil
		.getSeriesNames(this.heatmap.getProject().getFullDataset())));
		html.push('</select>');
		html.push('
');
		html.push('
');

		// condition
		html.push('
');
		html.push('Condition');
		html.push('
');
		html
		.push('<select class="form-control morpheus-form-control-inline" name="lower"><option value="gte">>=</option><option value="gt">></option></select>');
		html
		.push('<input class="form-control morpheus-form-control-inline" name="v1" size="5" type="text">');
		html.push('and');
		html
		.push('<select class="form-control morpheus-form-control-inline" name="upper"><option value="lte"><=</option><option value="lt"><</option></select>');
		html
		.push('<input class="form-control morpheus-form-control-inline" name="v2" size="5" type="text">');
		html.push('
');
		html.push('
');

		// shape
		html.push('
');
		html.push('Shape');
		var shapeField = new morpheus.ShapeField(['circle', 'square',
			'diamond', 'triangle-up', 'triangle-down', 'triangle-left',
			'triangle-right']);
		html.push('
');
		html.push('

');
		html.push('
');
		html.push('
');

		// color
		html.push('
');
		html.push('<input name="inherit_color"' +
			' type="checkbox" checked> Inherit' +
			' color');
		html.push('
');

		html.push('
');
		html.push('Color');
		html.push('
');
		html
		.push('<input class="form-control" type="color" name="color" style="display:inline;' +
			' width:6em;" disabled>');
		html.push('
');
		html.push('
');

		html.push('

');
		html
		.push('Delete Condition');
		html.push('

');
		html.push('
'); // morpheus-entry
		var $el = $(html.join(''));
		shapeField.$el.appendTo($el.find('[data-name=shapeHolder]'));
		var $color = $el.find('[name=color]');
		var $series = $el.find('[id=cond_series]');
		var $v1 = $el.find('[name=v1]');
		var $v2 = $el.find('[name=v2]');
		var $v1Op = $el.find('[name=lower]');
		var $v2Op = $el.find('[name=upper]');
		var $inherit_color = $el.find('[name=inherit_color]');
		$color.prop('disabled', condition.inheritColor);
		$color.val(condition.color);
		$series.val(condition.series);
		shapeField.setShapeValue(condition.shape);
		$v1.val(condition.v1);
		$v2.val(condition.v2);
		$v1Op.val(condition.v1Op);
		$v2Op.val(condition.v2Op);
		function updateAccept() {
			var v1 = parseFloat($($v1).val());
			if (isNaN(v1)) {
				v1 = -Number.MAX_VALUE;
			}

			var v2 = parseFloat($($v2).val());
			if (isNaN(v2)) {
				v2 = Number.MAX_VALUE;
			}

			var v1Op = $v1Op.val();
			var v2Op = $v2Op.val();
			var gtf = v1Op === 'gt' ? function (val) {
				return val > v1;
			} : function (val) {
				return val >= v1;
			};
			var ltf = v2Op === 'lt' ? function (val) {
				return val < v2;
			} : function (val) {
				return val <= v2;
			};
			condition.v1 = v1;
			condition.v2 = v2;
			condition.v1Op = v1Op;
			condition.v2Op = v2Op;
			condition.accept = function (val) {
				return gtf(val) && ltf(val);
			};
			_this.heatmap.revalidate();
		}

		$v1Op.on('change', function (e) {
			updateAccept();

		});
		$v2Op.on('change', function (e) {
			updateAccept();
		});
		$v1.on('keyup', _.debounce(function (e) {
			updateAccept();
		}, 100));
		$v2.on('keyup', _.debounce(function (e) {
			updateAccept();
		}, 100));
		$inherit_color.on('click', function (e) {
			condition.inheritColor = $(this).prop('checked');
			$color.prop('disabled', condition.inheritColor);
			_this.heatmap.revalidate();
		});
		$color.on('change', function (e) {
			condition.color = $(this).val();
			_this.heatmap.revalidate();
		});
		shapeField.on('change', function (e) {
			condition.shape = e.shape;
			_this.heatmap.revalidate();
		});
		$series.on('change', function (e) {
			condition.series = $(this).val();
			_this.heatmap.revalidate();
		});
		condition.series = $series.val();
		return $el;

	}
};
<|endoftext|>


<commit_before>import $ from "jquery"
import {getDefaultSourceCache} from "../resolve-frame"
import async from "async"

export default function saveAndSerializeDOMState(){
    $("*").off()
    var sourceCache = getDefaultSourceCache();

    $("link").each(function(){
        var href = $(this).attr("href")
        $(this).attr("href", _.last(href.split("/")))
    })

    $("#fromjs-initial-html").remove();
    $(".fromjs-outer-container").remove()

    $("html").find("*")
      .contents()
      .filter(function() {
        return this.nodeType === 3; //Node.TEXT_NODE
      }).each(function(){
          if (this.parentElement.tagName ==="SCRIPT") {
              if (this.parentElement.contentElOrigin) {
                  throw "two text nodes inside script tag?"
              }
              this.parentElement.__contentElOrigin = this.__elOrigin
          } else {
              var span = $("")
              span.attr("fromjs-text-node-converted-to-span", "true")
              span[0].textContent = this.textContent
              span[0].__elOrigin = this.__elOrigin

              $(this).replaceWith(span)
          }
      });

    var elsWithOrigin = jQuery("*").filter(function(){
        return this.__elOrigin
    })
    var id=1;

    elsWithOrigin.each(function(){
        var el = this;
        $(el).attr("fromjs-id", id)
        id++;
    })
    var elOrigins = {}
    function storeOrigin(origin, id){
        var serializedElOrigin = {};
        for (var key in origin) {
            if (key === "contents") {
                var contents = origin[key];
                serializedElOrigin[key] = contents.map(function(el){
                    return {elId: $(el).attr("fromjs-id")}
                })
            } else {
                serializedElOrigin[key] = origin[key]
            }
        }
        elOrigins[id] = serializedElOrigin
    }
    elsWithOrigin.each(function(){
        var el = this;
        storeOrigin(el.__elOrigin, $(el).attr("fromjs-id"))
    })
    jQuery("*").filter(function(){
        return this.__contentElOrigin
    }).each(function(){
        var contentOriginId = id++;
        storeOrigin(this.__contentElOrigin, contentOriginId)
        $(this).attr("fromjs-content-origin-id", contentOriginId)
    })

    var additionalFilesToCache = [];
    additionalFilesToCache.push("/demos/index.html?dontprocess=yes")
    $("script:not([type])").each(function(){
        if ($(this).attr("src") === "http://localhost:8080/dist/from.js") {
            return
        }

        var urlParts = location.href.replace(location.hash, "").split("/")
        urlParts.pop(); // remove html file path
        var urlPrefix = urlParts.join("/") + "/"

        additionalFilesToCache.push(urlPrefix + $(this).attr("src"))
        additionalFilesToCache.push(urlPrefix + $(this).attr("src") + ".map")
        additionalFilesToCache.push(urlPrefix + $(this).attr("src") + "?dontprocess=yes")

    })
    async.each(additionalFilesToCache, function(path, callback){
        $.get(path).then(function(res){
            sourceCache[path] = res;
            callback(null, {});
        })
    }, finish)

    function finish(){
        var serializedState = {
            html: document.body.parentElement.innerHTML,
            elOrigins: elOrigins,
            sourceCache: sourceCache,
            fromJSDynamicFileOrigins: window.fromJSDynamicFileOrigins
        }
        console.log("state size", JSON.stringify(serializedState).length)
        window.serializedState = serializedState

        var str = JSON.stringify(serializedState)
        var url = URL.createObjectURL(new Blob([str], {type: 'text/plain'}))

        document.body.innerHTML = "Done"
    }
}
<commit_msg>Fix relying on global Underscore.<commit_after>import $ from "jquery"
import _ from "underscore"
import {getDefaultSourceCache} from "../resolve-frame"
import async from "async"

export default function saveAndSerializeDOMState(){
    $("*").off()
    var sourceCache = getDefaultSourceCache();

    $("link").each(function(){
        var href = $(this).attr("href")
        $(this).attr("href", _.last(href.split("/")))
    })

    $("#fromjs-initial-html").remove();
    $(".fromjs-outer-container").remove()

    $("html").find("*")
      .contents()
      .filter(function() {
        return this.nodeType === 3; //Node.TEXT_NODE
      }).each(function(){
          if (this.parentElement.tagName ==="SCRIPT") {
              if (this.parentElement.contentElOrigin) {
                  throw "two text nodes inside script tag?"
              }
              this.parentElement.__contentElOrigin = this.__elOrigin
          } else {
              var span = $("")
              span.attr("fromjs-text-node-converted-to-span", "true")
              span[0].textContent = this.textContent
              span[0].__elOrigin = this.__elOrigin

              $(this).replaceWith(span)
          }
      });

    var elsWithOrigin = jQuery("*").filter(function(){
        return this.__elOrigin
    })
    var id=1;

    elsWithOrigin.each(function(){
        var el = this;
        $(el).attr("fromjs-id", id)
        id++;
    })
    var elOrigins = {}
    function storeOrigin(origin, id){
        var serializedElOrigin = {};
        for (var key in origin) {
            if (key === "contents") {
                var contents = origin[key];
                serializedElOrigin[key] = contents.map(function(el){
                    return {elId: $(el).attr("fromjs-id")}
                })
            } else {
                serializedElOrigin[key] = origin[key]
            }
        }
        elOrigins[id] = serializedElOrigin
    }
    elsWithOrigin.each(function(){
        var el = this;
        storeOrigin(el.__elOrigin, $(el).attr("fromjs-id"))
    })
    jQuery("*").filter(function(){
        return this.__contentElOrigin
    }).each(function(){
        var contentOriginId = id++;
        storeOrigin(this.__contentElOrigin, contentOriginId)
        $(this).attr("fromjs-content-origin-id", contentOriginId)
    })

    var additionalFilesToCache = [];
    additionalFilesToCache.push("/demos/index.html?dontprocess=yes")
    $("script:not([type])").each(function(){
        if ($(this).attr("src") === "http://localhost:8080/dist/from.js") {
            return
        }

        var urlParts = location.href.replace(location.hash, "").split("/")
        urlParts.pop(); // remove html file path
        var urlPrefix = urlParts.join("/") + "/"

        additionalFilesToCache.push(urlPrefix + $(this).attr("src"))
        additionalFilesToCache.push(urlPrefix + $(this).attr("src") + ".map")
        additionalFilesToCache.push(urlPrefix + $(this).attr("src") + "?dontprocess=yes")

    })
    async.each(additionalFilesToCache, function(path, callback){
        $.get(path).then(function(res){
            sourceCache[path] = res;
            callback(null, {});
        })
    }, finish)

    function finish(){
        var serializedState = {
            html: document.body.parentElement.innerHTML,
            elOrigins: elOrigins,
            sourceCache: sourceCache,
            fromJSDynamicFileOrigins: window.fromJSDynamicFileOrigins
        }
        console.log("state size", JSON.stringify(serializedState).length)
        window.serializedState = serializedState

        var str = JSON.stringify(serializedState)
        var url = URL.createObjectURL(new Blob([str], {type: 'text/plain'}))

        document.body.innerHTML = "Done"
    }
}
<|endoftext|>


<commit_before>tpzBase32 = {
    // Port safety test of encodingAlphabet
    encodingAlphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
    quintetMask: 31
};

tpzBase32.encodeQuintet = function (quintet) {
    // Add guard clauses and their tests!!! including a negative range check

    if (quintet > 31) {
        throw {
            name: "argument out of range",
            message: "An integer between 0 and 31 inclusive is required."
        };
    }

    return tpzBase32.encodingAlphabet.charAt(quintet);
};

tpzBase32.normalizeToTpzBase32Alphabet = function (encodedCharacter) {
    // Add guard clauses and their tests!!!

    if (encodedCharacter === "0")
    {
        return "o";
    }
    if (encodedCharacter === "l" || encodedCharacter === "L")
    {
        return "1";
    }
    if (encodedCharacter === "2")
    {
        return "z";
    }
    if (encodedCharacter === "v" || encodedCharacter === "V")
    {
        return "u";
    }

    return encodedCharacter.toLowerCase();
};

tpzBase32.decodeToQuintet = function (encodedCharacter) {
    // Add guard clauses and their tests!!!

    var normalizedEncodedCharacter = tpzBase32.normalizeToTpzBase32Alphabet(encodedCharacter);
    var index = tpzBase32.encodingAlphabet.indexOf(normalizedEncodedCharacter);

    // if (index === -1)
    // {
        // throw new ArgumentOutOfRangeException("input");
    // }

    return index;
};

tpzBase32.Integer32Converter = function () {};

tpzBase32.Integer32Converter.prototype.encode = function (input) {
    return this.encode(input, false);
};

tpzBase32.Integer32Converter.prototype.encodeWithPadding = function (input) {
    return this.encode(input, true);
};

tpzBase32.Integer32Converter.prototype.encode = function (input, includePadding) {
    if (typeof input !== "number" || isNaN(input) ||
        input < -2147483648 || input > 2147483647 ||
        input % 1 !== 0) {
        throw {
            name: "argument out of range",
            message: "The input argument must be a non-NaN 32 bit integer value."
            };
        }

    if (input === 0) {
        zero = tpzBase32.encodingAlphabet.charAt(0);
        includePadding
            ? [zero, zero, zero, zero, zero, zero, zero].join("")
            zero;
    }

    var i;
    var result = ["!", "!", "!", "!", "!", "!", "!"];
    for (i = 0; i < 7; i++) {
        var quintet = (input >>> (5 * i)) & tpzBase32.quintetMask;
        result[i] = tpzBase32.encodeQuintet(quintet);
        if (!includePadding && (input > 0 && input < (1 << (5 * (i + 1))))) {
            return result.slice(0, i + 1).join("");
        }
    }

    return result.join("");
};

tpzBase32.Integer32Converter.prototype.decode = function (input) {
    // Add guard clauses and their tests!!!

    // if (input == null)
    // {
        // throw new ArgumentNullException("input");
    // }

    // if (input.Length == 0 || input.Length > 7)
    // {
        // throw new ArgumentOutOfRangeException("input", input,
                                              // "Must be string of between 1 and 7 characters inclusive.");
    // }

    var i;
    var result = 0;
    for (i = 0; i < input.length; i++) {
        var quintet = tpzBase32.decodeToQuintet(input.charAt(i));
        result |= quintet << (5 * i);
    }
    return result;
};
<commit_msg>WTF! Notepad++ indentation adjustment ate a return keyword and the colon of a ternary operator!?!? Should have caught it with a test run, but in any case: Fixed.<commit_after>tpzBase32 = {
    // Port safety test of encodingAlphabet
    encodingAlphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
    quintetMask: 31
};

tpzBase32.encodeQuintet = function (quintet) {
    // Add guard clauses and their tests!!! including a negative range check

    if (quintet > 31) {
        throw {
            name: "argument out of range",
            message: "An integer between 0 and 31 inclusive is required."
        };
    }

    return tpzBase32.encodingAlphabet.charAt(quintet);
};

tpzBase32.normalizeToTpzBase32Alphabet = function (encodedCharacter) {
    // Add guard clauses and their tests!!!

    if (encodedCharacter === "0")
    {
        return "o";
    }
    if (encodedCharacter === "l" || encodedCharacter === "L")
    {
        return "1";
    }
    if (encodedCharacter === "2")
    {
        return "z";
    }
    if (encodedCharacter === "v" || encodedCharacter === "V")
    {
        return "u";
    }

    return encodedCharacter.toLowerCase();
};

tpzBase32.decodeToQuintet = function (encodedCharacter) {
    // Add guard clauses and their tests!!!

    var normalizedEncodedCharacter = tpzBase32.normalizeToTpzBase32Alphabet(encodedCharacter);
    var index = tpzBase32.encodingAlphabet.indexOf(normalizedEncodedCharacter);

    // if (index === -1)
    // {
        // throw new ArgumentOutOfRangeException("input");
    // }

    return index;
};

tpzBase32.Integer32Converter = function () {};

tpzBase32.Integer32Converter.prototype.encode = function (input) {
    return this.encode(input, false);
};

tpzBase32.Integer32Converter.prototype.encodeWithPadding = function (input) {
    return this.encode(input, true);
};

tpzBase32.Integer32Converter.prototype.encode = function (input, includePadding) {
    if (typeof input !== "number" || isNaN(input) ||
        input < -2147483648 || input > 2147483647 ||
        input % 1 !== 0) {
        throw {
            name: "argument out of range",
            message: "The input argument must be a non-NaN 32 bit integer value."
            };
        }

    if (input === 0) {
        zero = tpzBase32.encodingAlphabet.charAt(0);
        return includePadding
            ? [zero, zero, zero, zero, zero, zero, zero].join("")
            : zero;
    }

    var i;
    var result = ["!", "!", "!", "!", "!", "!", "!"];
    for (i = 0; i < 7; i++) {
        var quintet = (input >>> (5 * i)) & tpzBase32.quintetMask;
        result[i] = tpzBase32.encodeQuintet(quintet);
        if (!includePadding && (input > 0 && input < (1 << (5 * (i + 1))))) {
            return result.slice(0, i + 1).join("");
        }
    }

    return result.join("");
};

tpzBase32.Integer32Converter.prototype.decode = function (input) {
    // Add guard clauses and their tests!!!

    // if (input == null)
    // {
        // throw new ArgumentNullException("input");
    // }

    // if (input.Length == 0 || input.Length > 7)
    // {
        // throw new ArgumentOutOfRangeException("input", input,
                                              // "Must be string of between 1 and 7 characters inclusive.");
    // }

    var i;
    var result = 0;
    for (i = 0; i < input.length; i++) {
        var quintet = tpzBase32.decodeToQuintet(input.charAt(i));
        result |= quintet << (5 * i);
    }
    return result;
};
<|endoftext|>


<commit_before>import Orb from '../orb';
import MegaOrb from '../megaorb';
import audio from '../audio';
import audioSrcOgg from '../public/sound/tonite.ogg';
import audioSrcMp3 from '../public/sound/tonite.mp3';
import Playlist from '../playlist';
import viewer from '../viewer';
import settings from '../settings';
import createTitles from '../titles';
import transition from '../transition';
import hud from '../hud';
import feature from '../utils/feature';
import { sleep } from '../utils/async';
import Room from '../room';
import progressBar from '../progress-bar';
import layout from '../room/layout';
import closestHead from '../utils/closestHead';

// Chromium does not support mp3:
// TODO: Switch to always use MP3 in production.
const audioSrc = feature.isChrome ? audioSrcOgg : audioSrcMp3;
const { roomDepth, holeHeight } = settings;
let pointerX;
let pointerY;
let titles;

export default (req) => {
  const toggleVR = async () => {
    if (!feature.hasVR) return;
    if (viewer.vrEffect.isPresenting) {
      viewer.vrEffect.exitPresent();
      viewer.switchCamera('orthographic');
    } else {
      viewer.vrEffect.requestPresent();
      const removeMessage = hud.enterVR();
      await audio.fadeOut();
      viewer.switchCamera('default');
      await sleep(1000);
      audio.pause();
      audio.rewind();
      await sleep(4000);
      removeMessage();
      audio.play();
    }
  };

  const hudSettings = {
    menuAdd: true,
    menuEnter: toggleVR,
    colophon: true,
  };

  let orb;
  let megaOrb;
  let playlist;
  let tick;
  const loopIndex = parseInt(req.params.loopIndex, 10);

  let onMouseMove;
  let onMouseDown;
  let onMouseUp;
  let hoverHead;

  const component = {
    hud: hudSettings,
    mount: async () => {
      progressBar.create();
      Room.reset();
      if (!viewer.vrEffect.isPresenting) {
        viewer.switchCamera('orthographic');
      }

      orb = new Orb();
      megaOrb = new MegaOrb();
      titles = createTitles(orb);
      titles.mount();

      const moveHead = (progress) => {
        moveCamera(progress);
        const [roomIndex, headIndex] = hoverHead;
        playlist.rooms[roomIndex].transformToHead(viewer.camera, headIndex);
      };

      const moveCamera = (progress) => {
        const position = layout.getPosition(progress + 0.5);
        position.y += holeHeight;
        position.z *= -1;
        viewer.camera.position.copy(position);
        orb.position.copy(position);
      };

      moveCamera(0);
      Room.rotate180();
      playlist = new Playlist();

      tick = () => {
        if (transition.isInside()) return;
        if (!viewer.vrEffect.isPresenting && !hoverHead) {
          Room.setHighlight(
            closestHead(
              pointerX,
              pointerY,
              playlist.rooms
            )
          );
        }
        audio.tick();
        Room.clear();
        playlist.tick();
        titles.tick();
        if (!feature.isMobile || !viewer.vrEffect.isPresenting) {
          progressBar.tick();
        }
        if (hoverHead) {
          moveHead(audio.progress || 0);
        } else {
          moveCamera(audio.progress || 0);
        }
      };
      viewer.events.on('tick', tick);

      hud.showLoader('Loading sound');

      await audio.load({
        src: audioSrc,
        loops: settings.totalLoopCount,
        loop: true,
        progressive: true,
      });

      if (component.destroyed) return;

      hud.showLoader('Gathering user performances');

      playlist.load({
        url: 'curated.json',
        pathRecording: req.params.id,
        loopIndex,
      }).then(() => {
        if (component.destroyed) return;
        onMouseMove = ({ clientX, clientY }) => {
          pointerX = clientX;
          pointerY = clientY;
        };

        onMouseDown = ({ clientX, clientY }) => {
          hoverHead = closestHead(clientX, clientY, playlist.rooms);
          if (!hoverHead[0]) hoverHead = null;
          if (hoverHead) {
            viewer.switchCamera('default');
            Room.group.add(viewer.camera);
          }
        };

        onMouseUp = () => {
          hoverHead = null;
          viewer.switchCamera('orthographic');
          Room.group.remove(viewer.camera);
        };

        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mousedown', onMouseDown);
        window.addEventListener('mouseup', onMouseUp);
      });
      if (component.destroyed) return;

      hud.hideLoader();
      if (transition.isInside()) {
        transition.exit();
      }

      if (loopIndex) {
        // Start at 3 rooms before the recording, or 60 seconds before
        // the end of the track – whichever comes first.
        const watchTime = 30;
        const startTime = Math.min(
          (loopIndex - 2) * audio.loopDuration,
          audio.duration - watchTime
        );
        audio.gotoTime(startTime);
        setTimeout(() => {
          if (component.destroyed) return;
          audio.fadeOut();
          transition.enter({
            text: 'Please take off your headset',
          });
          // TODO add share screen
        }, watchTime * 1000);
      }

      audio.fadeIn();
      audio.play();

      positionMegaOrb(megaOrb);
    },

    unmount: () => {
      component.destroyed = true;
      if (viewer.vrEffect.isPresenting) {
        viewer.vrEffect.exitPresent();
      }
      viewer.events.off('tick', tick);
      orb.destroy();
      titles.destroy();
      playlist.destroy();
      progressBar.destroy();
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mousedown', onMouseDown);
      window.removeEventListener('mouseup', onMouseUp);
    },
  };
  return component;
};

//  duration / loopDuration causes the mega orb to be too far off-screen
//  move it back a ways so we can see it more immediately
const endPosMoveAhead = 0.86;

const positionMegaOrb = (orb) => {
  orb.position.z = -(audio.duration * endPosMoveAhead / audio.loopDuration * roomDepth);
};

window.audio = audio;
<commit_msg>fix derp<commit_after>import Orb from '../orb';
import MegaOrb from '../megaorb';
import audio from '../audio';
import audioSrcOgg from '../public/sound/tonite.ogg';
import audioSrcMp3 from '../public/sound/tonite.mp3';
import Playlist from '../playlist';
import viewer from '../viewer';
import settings from '../settings';
import createTitles from '../titles';
import transition from '../transition';
import hud from '../hud';
import feature from '../utils/feature';
import { sleep } from '../utils/async';
import Room from '../room';
import progressBar from '../progress-bar';
import layout from '../room/layout';
import closestHead from '../utils/closestHead';

// Chromium does not support mp3:
// TODO: Switch to always use MP3 in production.
const audioSrc = feature.isChrome ? audioSrcOgg : audioSrcMp3;
const { roomDepth, holeHeight } = settings;
let pointerX;
let pointerY;
let titles;

export default (req) => {
  const toggleVR = async () => {
    if (!feature.hasVR) return;
    if (viewer.vrEffect.isPresenting) {
      viewer.vrEffect.exitPresent();
      viewer.switchCamera('orthographic');
    } else {
      viewer.vrEffect.requestPresent();
      const removeMessage = hud.enterVR();
      await audio.fadeOut();
      viewer.switchCamera('default');
      await sleep(1000);
      audio.pause();
      audio.rewind();
      await sleep(4000);
      removeMessage();
      audio.play();
    }
  };

  const hudSettings = {
    menuAdd: true,
    menuEnter: toggleVR,
    colophon: true,
  };

  let orb;
  let megaOrb;
  let playlist;
  let tick;
  const loopIndex = parseInt(req.params.loopIndex, 10);

  let onMouseMove;
  let onMouseDown;
  let onMouseUp;
  let hoverHead;

  const component = {
    hud: hudSettings,
    mount: async () => {
      progressBar.create();
      Room.reset();
      if (!viewer.vrEffect.isPresenting) {
        viewer.switchCamera('orthographic');
      }

      orb = new Orb();
      megaOrb = new MegaOrb();
      titles = createTitles(orb);
      titles.mount();

      const moveHead = (progress) => {
        moveCamera(progress);
        const [roomIndex, headIndex] = hoverHead;
        playlist.rooms[roomIndex].transformToHead(viewer.camera, headIndex);
      };

      const moveCamera = (progress) => {
        const position = layout.getPosition(progress + 0.5);
        position.y += holeHeight;
        position.z *= -1;
        viewer.camera.position.copy(position);
        orb.position.copy(position);
      };

      moveCamera(0);
      Room.rotate180();
      playlist = new Playlist();

      tick = () => {
        if (transition.isInside()) return;
        if (!viewer.vrEffect.isPresenting && !hoverHead) {
          Room.setHighlight(
            closestHead(
              pointerX,
              pointerY,
              playlist.rooms
            )
          );
        }
        audio.tick();
        Room.clear();
        playlist.tick();
        titles.tick();
        if (!feature.isMobile || !viewer.vrEffect.isPresenting) {
          progressBar.tick();
        }
        if (hoverHead) {
          moveHead(audio.progress || 0);
        } else {
          moveCamera(audio.progress || 0);
        }
      };
      viewer.events.on('tick', tick);

      hud.showLoader('Loading sound');

      await audio.load({
        src: audioSrc,
        loops: settings.totalLoopCount,
        loop: true,
        progressive: true,
      });

      if (component.destroyed) return;

      hud.showLoader('Gathering user performances');

      playlist.load({
        url: 'curated.json',
        pathRecording: req.params.id,
        loopIndex,
      }).then(() => {
        if (component.destroyed) return;
        onMouseMove = ({ clientX, clientY }) => {
          pointerX = clientX;
          pointerY = clientY;
        };

        onMouseDown = ({ clientX, clientY }) => {
          hoverHead = closestHead(clientX, clientY, playlist.rooms);
          if (hoverHead[0] === undefined) hoverHead = null;
          if (hoverHead) {
            viewer.switchCamera('default');
            Room.group.add(viewer.camera);
          }
        };

        onMouseUp = () => {
          hoverHead = null;
          viewer.switchCamera('orthographic');
          Room.group.remove(viewer.camera);
        };

        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mousedown', onMouseDown);
        window.addEventListener('mouseup', onMouseUp);
      });
      if (component.destroyed) return;

      hud.hideLoader();
      if (transition.isInside()) {
        transition.exit();
      }

      if (loopIndex) {
        // Start at 3 rooms before the recording, or 60 seconds before
        // the end of the track – whichever comes first.
        const watchTime = 30;
        const startTime = Math.min(
          (loopIndex - 2) * audio.loopDuration,
          audio.duration - watchTime
        );
        audio.gotoTime(startTime);
        setTimeout(() => {
          if (component.destroyed) return;
          audio.fadeOut();
          transition.enter({
            text: 'Please take off your headset',
          });
          // TODO add share screen
        }, watchTime * 1000);
      }

      audio.fadeIn();
      audio.play();

      positionMegaOrb(megaOrb);
    },

    unmount: () => {
      component.destroyed = true;
      if (viewer.vrEffect.isPresenting) {
        viewer.vrEffect.exitPresent();
      }
      viewer.events.off('tick', tick);
      orb.destroy();
      titles.destroy();
      playlist.destroy();
      progressBar.destroy();
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mousedown', onMouseDown);
      window.removeEventListener('mouseup', onMouseUp);
    },
  };
  return component;
};

//  duration / loopDuration causes the mega orb to be too far off-screen
//  move it back a ways so we can see it more immediately
const endPosMoveAhead = 0.86;

const positionMegaOrb = (orb) => {
  orb.position.z = -(audio.duration * endPosMoveAhead / audio.loopDuration * roomDepth);
};

window.audio = audio;
<|endoftext|>


<commit_before><commit_msg>bugfix...<commit_after><|endoftext|>


<commit_before>tpzBase32 = {
    // Port safety test of encodingAlphabet
    encodingAlphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
    quintetMask: 31
};

tpzBase32.encodeQuintet = function (quintet) {
    // Add guard clauses and their tests!!! including a negative range check

    if (quintet > 31) {
        throw {
            name: "argument out of range",
            message: "An integer between 0 and 31 inclusive is required."
        };
    }

    return tpzBase32.encodingAlphabet.charAt(quintet);
};

tpzBase32.normalizeToTpzBase32Alphabet = function (encodedCharacter) {
    // Add guard clauses and their tests!!!

    if (encodedCharacter === '0')
    {
        return 'o';
    }
    if (encodedCharacter === 'l' || encodedCharacter === 'L')
    {
        return '1';
    }
    if (encodedCharacter === '2')
    {
        return 'z';
    }
    if (encodedCharacter === 'v' || encodedCharacter === 'V')
    {
        return 'u';
    }

    return encodedCharacter.toLowerCase();
};

tpzBase32.decodeToQuintet = function (encodedCharacter) {
    // Add guard clauses and their tests!!!

    var normalizedEncodedCharacter = tpzBase32.normalizeToTpzBase32Alphabet(encodedCharacter);
    var index = tpzBase32.encodingAlphabet.indexOf(normalizedEncodedCharacter);

    // if (index === -1)
    // {
        // throw new ArgumentOutOfRangeException("input");
    // }

    return index;
};

tpzBase32.Integer32Converter = function () {};

tpzBase32.Integer32Converter.prototype.encode = function (input) {
    return this.encode(input, false);
};

tpzBase32.Integer32Converter.prototype.encodeWithPadding = function (input) {
    return this.encode(input, true);
};

tpzBase32.Integer32Converter.prototype.encode = function (input, includePadding) {
    if (typeof input !== "number" || isNaN(input) ||
        input < -2147483648 || input > 2147483647 ||
        input % 1 !== 0) {
        throw {
            name: "argument out of range",
            message: "The input argument must be a non-NaN 32 bit integer value."
            };
        }

    if (input === 0) {
        zero = tpzBase32.encodingAlphabet.charAt(0);
        includePadding
            ? [zero, zero, zero, zero, zero, zero, zero].join("")
            zero;
    }

    var i;
    var result = ["!", "!", "!", "!", "!", "!", "!"];
    for (i = 0; i < 7; i++) {
        var quintet = (input >>> (5 * i)) & tpzBase32.quintetMask;
        result[i] = tpzBase32.encodeQuintet(quintet);
        if (!includePadding && (input > 0 && input < (1 << (5 * (i + 1))))) {
            return result.slice(0, i + 1).join("");
        }
    }

    return result.join("");
};

tpzBase32.Integer32Converter.prototype.decode = function (input) {
    // Add guard clauses and their tests!!!

    // if (input == null)
    // {
        // throw new ArgumentNullException("input");
    // }

    // if (input.Length == 0 || input.Length > 7)
    // {
        // throw new ArgumentOutOfRangeException("input", input,
                                              // "Must be string of between 1 and 7 characters inclusive.");
    // }

    var i;
    var result = 0;
    for (i = 0; i < input.length; i++) {
        var quintet = tpzBase32.decodeToQuintet(input.charAt(i));
        result |= quintet << (5 * i);
    }
    return result;
};
<commit_msg>Aligned quote marks on double quotes (one function contained a smattering of single quotes.)<commit_after>tpzBase32 = {
    // Port safety test of encodingAlphabet
    encodingAlphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
    quintetMask: 31
};

tpzBase32.encodeQuintet = function (quintet) {
    // Add guard clauses and their tests!!! including a negative range check

    if (quintet > 31) {
        throw {
            name: "argument out of range",
            message: "An integer between 0 and 31 inclusive is required."
        };
    }

    return tpzBase32.encodingAlphabet.charAt(quintet);
};

tpzBase32.normalizeToTpzBase32Alphabet = function (encodedCharacter) {
    // Add guard clauses and their tests!!!

    if (encodedCharacter === "0")
    {
        return "o";
    }
    if (encodedCharacter === "l" || encodedCharacter === "L")
    {
        return "1";
    }
    if (encodedCharacter === "2")
    {
        return "z";
    }
    if (encodedCharacter === "v" || encodedCharacter === "V")
    {
        return "u";
    }

    return encodedCharacter.toLowerCase();
};

tpzBase32.decodeToQuintet = function (encodedCharacter) {
    // Add guard clauses and their tests!!!

    var normalizedEncodedCharacter = tpzBase32.normalizeToTpzBase32Alphabet(encodedCharacter);
    var index = tpzBase32.encodingAlphabet.indexOf(normalizedEncodedCharacter);

    // if (index === -1)
    // {
        // throw new ArgumentOutOfRangeException("input");
    // }

    return index;
};

tpzBase32.Integer32Converter = function () {};

tpzBase32.Integer32Converter.prototype.encode = function (input) {
    return this.encode(input, false);
};

tpzBase32.Integer32Converter.prototype.encodeWithPadding = function (input) {
    return this.encode(input, true);
};

tpzBase32.Integer32Converter.prototype.encode = function (input, includePadding) {
    if (typeof input !== "number" || isNaN(input) ||
        input < -2147483648 || input > 2147483647 ||
        input % 1 !== 0) {
        throw {
            name: "argument out of range",
            message: "The input argument must be a non-NaN 32 bit integer value."
            };
        }

    if (input === 0) {
        zero = tpzBase32.encodingAlphabet.charAt(0);
        includePadding
            ? [zero, zero, zero, zero, zero, zero, zero].join("")
            zero;
    }

    var i;
    var result = ["!", "!", "!", "!", "!", "!", "!"];
    for (i = 0; i < 7; i++) {
        var quintet = (input >>> (5 * i)) & tpzBase32.quintetMask;
        result[i] = tpzBase32.encodeQuintet(quintet);
        if (!includePadding && (input > 0 && input < (1 << (5 * (i + 1))))) {
            return result.slice(0, i + 1).join("");
        }
    }

    return result.join("");
};

tpzBase32.Integer32Converter.prototype.decode = function (input) {
    // Add guard clauses and their tests!!!

    // if (input == null)
    // {
        // throw new ArgumentNullException("input");
    // }

    // if (input.Length == 0 || input.Length > 7)
    // {
        // throw new ArgumentOutOfRangeException("input", input,
                                              // "Must be string of between 1 and 7 characters inclusive.");
    // }

    var i;
    var result = 0;
    for (i = 0; i < input.length; i++) {
        var quintet = tpzBase32.decodeToQuintet(input.charAt(i));
        result |= quintet << (5 * i);
    }
    return result;
};
<|endoftext|>


<commit_before>var e = module.exports = {};

var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');
var Table = require('cli-table');

e.init = () => {
    e.category = bu.CommandType.GENERAL;
};

e.requireCtx = require;

e.isCommand = true;

e.hidden = true;
e.usage = 'lines';
e.info = 'Gets the number of lines the bot is made of.';
e.longinfo = `<p>Gets the number of lines the bot is made of.</p>`;

e.execute = (msg) => {

    logger.debug(__dirname);
    exec(`cloc ${path.join(__dirname, '..')} --exclude-dir=codemirror`, (err, stdout, stderr) => {
        if (err) {
            logger.error(err);
            bu.send(msg, 'An error has occurred!');
            return;
        }
        let message = '```prolog\n' + stdout;
        let sections = stdout.split(/-+/);
        logger.debug(sections);
        for (let i = 0; i < sections.length; i++) {
            if (sections[i] == '')
                sections.splice(i, 1);
        }
        logger.debug(sections);
        let head = sections[1].split(/\s\s+/);
        var table = new Table({
            head: head
        });
        let middle = sections[2].slice(/\n/);
        for (let i = 0; i < middle.length; i++) {
            table.push(middle[i].split(/\s\s+/));
        }
        let footer = sections[3].slice(/\s\s+/);
        table.push(footer);
        logger.debug(table.toString());
    });

};<commit_msg>why do I keep mixing up split and slice<commit_after>var e = module.exports = {};

var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');
var Table = require('cli-table');

e.init = () => {
    e.category = bu.CommandType.GENERAL;
};

e.requireCtx = require;

e.isCommand = true;

e.hidden = true;
e.usage = 'lines';
e.info = 'Gets the number of lines the bot is made of.';
e.longinfo = `<p>Gets the number of lines the bot is made of.</p>`;

e.execute = (msg) => {

    logger.debug(__dirname);
    exec(`cloc ${path.join(__dirname, '..')} --exclude-dir=codemirror`, (err, stdout, stderr) => {
        if (err) {
            logger.error(err);
            bu.send(msg, 'An error has occurred!');
            return;
        }
        let message = '```prolog\n' + stdout;
        let sections = stdout.split(/-+/);
        logger.debug(sections);
        for (let i = 0; i < sections.length; i++) {
            if (sections[i] == '')
                sections.splice(i, 1);
        }
        logger.debug(sections);
        let head = sections[1].split(/\s\s+/);
        var table = new Table({
            head: head
        });
        let middle = sections[2].split(/\n/);
        for (let i = 0; i < middle.length; i++) {
            table.push(middle[i].split(/\s\s+/));
        }
        let footer = sections[3].slice(/\s\s+/);
        table.push(footer);
        logger.debug(table.toString());
    });

};<|endoftext|>


<commit_before>/**
 * This file contains mainModule with injecting dependencies, routing and configuration.
 *
 * @version 1.0
 * @author Dmitry
 * @since 04.09.2015
 */
angular.module("mainModule", ['gettext', 'ui.utils', 'ui.router', 'angularMoment', 'ngMaterial', 'md.data.table',
    'angular-loading-bar', 'templates', 'angular-cache', 'duScroll'])
    .value('duScrollDuration', 3000)
    .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
        $stateProvider
            .state('cheque', {
                abstract: true,
                url: "/cheques",
                views: {
                    "header": {
                        controller:
                            ['$rootScope', '$scope', '$state', function($rootScope, $scope, $state) {
                                $scope.selectedTab = $state.current.data.selectedTab;

                                $rootScope.$on('$stateChangeSuccess',
                                    function(event, toState, toParams, fromState, fromParams) {
                                        $scope.selectedTab = toState.data.selectedTab;
                                    });
                        }],
                        template: ''
                    },
                    "content": {
                        template: "<ui-view></ui-view>"
                    }
                }
            })
            .state('cheque.filter', {
                url: "^/filter",
                template: "<filters-page></filters-page>",
                data: {'selectedTab': 0}
            })
            .state('cheque.edit', {
                url: "^/cheque/{chequeId:[0-9]{1,10}}",
                controller:
                    ['$scope', '$stateParams', function($scope, $stateParams) {
                        $scope.chequeID = $stateParams.chequeId;
                    }],
                template: '<cheque-page cheque-id="chequeID"></cheque-page>',
                data: {'selectedTab': 1}
            })
            .state('cheque.create', {
                url: "^/cheque",
                template: '<cheque-page></cheque-page>',
                data: {'selectedTab': 1}
            })
            .state('cheque.profile', {
                url: "^/profile",
                template: '<profile-page></profile-page>',
                data: {'selectedTab': 3}
            });

            $urlRouterProvider.when('', '/filter');
            $urlRouterProvider.otherwise('/filter');
    }])
    .config(['$mdThemingProvider', function($mdThemingProvider){
            $mdThemingProvider
                .theme('payment')
                .primaryPalette('grey', {'default':'50'})
                .accentPalette('pink')
                .warnPalette('red');

            $mdThemingProvider
                .theme('header')
                .primaryPalette('grey', {'default': '900'})
                .accentPalette('indigo');

            $mdThemingProvider
                .theme('tabs')
                .primaryPalette('grey', {'default': '900'})
                .accentPalette('indigo');
    }])
    .config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
        cfpLoadingBarProvider.includeSpinner = false;
        cfpLoadingBarProvider.latencyThreshold = 100;
    }])
    .config(['$mdDateLocaleProvider',
        function($mdDateLocaleProvider) {
            // Example of a French localization.
            $mdDateLocaleProvider.months = 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_');
            $mdDateLocaleProvider.shortMonths = 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_');
            $mdDateLocaleProvider.days = 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_');
            $mdDateLocaleProvider.shortDays = 'вс_пн_вт_ср_чт_пт_сб'.split('_');
            // Can change week display to start on Monday.
            $mdDateLocaleProvider.firstDayOfWeek = 1;
    }])
    .run(['gettextCatalog', 'amMoment',
        function(gettextCatalog, amMoment){
            gettextCatalog.setCurrentLanguage('ru');
            amMoment.changeLocale('ru');
    }]);<commit_msg>Del comment<commit_after>/**
 * This file contains mainModule with injecting dependencies, routing and configuration.
 *
 * @version 1.0
 * @author Dmitry
 * @since 04.09.2015
 */
angular.module("mainModule", ['gettext', 'ui.utils', 'ui.router', 'angularMoment', 'ngMaterial', 'md.data.table',
    'angular-loading-bar', 'templates', 'angular-cache', 'duScroll'])
    .value('duScrollDuration', 3000)
    .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
        $stateProvider
            .state('cheque', {
                abstract: true,
                url: "/cheques",
                views: {
                    "header": {
                        controller:
                            ['$rootScope', '$scope', '$state', function($rootScope, $scope, $state) {
                                $scope.selectedTab = $state.current.data.selectedTab;

                                $rootScope.$on('$stateChangeSuccess',
                                    function(event, toState, toParams, fromState, fromParams) {
                                        $scope.selectedTab = toState.data.selectedTab;
                                    });
                        }],
                        template: ''
                    },
                    "content": {
                        template: "<ui-view></ui-view>"
                    }
                }
            })
            .state('cheque.filter', {
                url: "^/filter",
                template: "<filters-page></filters-page>",
                data: {'selectedTab': 0}
            })
            .state('cheque.edit', {
                url: "^/cheque/{chequeId:[0-9]{1,10}}",
                controller:
                    ['$scope', '$stateParams', function($scope, $stateParams) {
                        $scope.chequeID = $stateParams.chequeId;
                    }],
                template: '<cheque-page cheque-id="chequeID"></cheque-page>',
                data: {'selectedTab': 1}
            })
            .state('cheque.create', {
                url: "^/cheque",
                template: '<cheque-page></cheque-page>',
                data: {'selectedTab': 1}
            })
            .state('cheque.profile', {
                url: "^/profile",
                template: '<profile-page></profile-page>',
                data: {'selectedTab': 3}
            });

            $urlRouterProvider.when('', '/filter');
            $urlRouterProvider.otherwise('/filter');
    }])
    .config(['$mdThemingProvider', function($mdThemingProvider){
            $mdThemingProvider
                .theme('payment')
                .primaryPalette('grey', {'default':'50'})
                .accentPalette('pink')
                .warnPalette('red');

            $mdThemingProvider
                .theme('header')
                .primaryPalette('grey', {'default': '900'})
                .accentPalette('indigo');

            $mdThemingProvider
                .theme('tabs')
                .primaryPalette('grey', {'default': '900'})
                .accentPalette('indigo');
    }])
    .config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
        cfpLoadingBarProvider.includeSpinner = false;
        cfpLoadingBarProvider.latencyThreshold = 100;
    }])
    .config(['$mdDateLocaleProvider',
        function($mdDateLocaleProvider) {
            $mdDateLocaleProvider.months = 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_');
            $mdDateLocaleProvider.shortMonths = 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_');
            $mdDateLocaleProvider.days = 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_');
            $mdDateLocaleProvider.shortDays = 'вс_пн_вт_ср_чт_пт_сб'.split('_');
            // Can change week display to start on Monday.
            $mdDateLocaleProvider.firstDayOfWeek = 1;
    }])
    .run(['gettextCatalog', 'amMoment',
        function(gettextCatalog, amMoment){
            gettextCatalog.setCurrentLanguage('ru');
            amMoment.changeLocale('ru');
    }]);<|endoftext|>