<commit_before>var async = require('async');
var chai = require('chai');

var testUtils = require('../test_utils');

var expect = chai.expect;

describe('Model (integration)', function() {

  before(function() {
    testUtils.setupOrm.call(this);
    testUtils.setupTestModels.call(this);
  });

  beforeEach(function(cb) {
    this.orm._resetDatastores(cb);
  });

  describe('#find()', function() {

    before(function() {
      this.IndexedModel = this.createModel({
        properties: {
          indexed: {type: 'string', index: true, cache: true},
          indexed_no_replace: {
            type: 'string', index: true, cache: true, replace: false
          }
        },
        callbacks: {
          beforeInput: function(values, cb) {
            cb(null, testUtils.appendValue(values, 'beforeInput'));
          },
          afterInput: function(values, cb) {
            cb(null, testUtils.appendValue(values, 'afterInput'));
          }
        }
      });
    });

    it('should mutate the index value by default', function(done) {
      var self = this;
      async.waterfall([
        function(cb) {
          var instance = self.IndexedModel.create({indexed: 'foo'});
          instance.save(function(err) {
            if (err) {return cb(err);}
            cb(null, instance.getId());
          });
        },
        function(id, cb) {
          self.IndexedModel.find('indexed', 'foo', function(err, instance) {
            if (err) {return cb(err);}
            instance.should.exist;
            instance.isNew.should.be.false;
            instance.isChanged().should.be.false;
            instance.getId().should.eq(id);
            cb();
          });
        }
      ], done);
    });

    it('should not mutate the index value if requested', function(done) {
      var self = this;
      async.waterfall([
        function(cb) {
          var instance = self.IndexedModel.create({indexed: 'foo'}, true);
          instance.save(function(err) {
            if (err) {return cb(err);}
            cb(null, instance.getId());
          });
        },
        function(id, cb) {
          self.IndexedModel.find('indexed', 'foo', true,
            function(err, instance) {
            if (err) {return cb(err);}
            instance.getId().should.eq(id);
            cb();
          });
        }
      ], done);
    });

    it('should only work with indexed properties', function() {
      var self = this;
      (function() {
        self.BasicModel.find('nonindex', 'foo', function() {});
      }).should.throw('attribute "nonindex" is not an index');
    });

    it('should callback with null if nothing is found', function(done) {
      this.IndexedModel.find('indexed', 'bar', function(err, instance) {
        if (err) {return done(err);}
        expect(instance).to.be.null;
        done();
      });
    });

    it('should use old indexes that have not been replaced', function(done) {
      var self = this;
      async.waterfall([
        function(cb) {
          var instance = self.IndexedModel.create({indexed_no_replace: 'foo'}, true);
          instance.save(function(err) {
            if (err) {return cb(err);}
            instance.set({indexed_no_replace: 'bar'}, true).save(function(err) {
              if (err) {return cb(err);}
              cb(null, instance.getId());
            });
          });
        },
        function(id, cb) {
          self.IndexedModel.find('indexed_no_replace', 'foo', true,
            function(err, instance) {
            if (err) {return cb(err);}
            instance.getId().should.eq(id);
            cb();
          });
        }
      ], done);
    });

    it('should not use indexes that have been replaced', function(done) {
      var self = this;
      async.waterfall([
        function(cb) {
          var instance = self.IndexedModel.create({indexed: 'foo'}, true);
          instance.save(function(err) {
            if (err) {return cb(err);}
            instance.set({indexed: 'bar'}, true).save(function(err) {
              if (err) {return cb(err);}
              cb(null, instance.getId());
            });
          });
        },
        function(id, cb) {
          self.IndexedModel.find('indexed', 'foo', true,
            function(err, instance) {
            if (err) {return cb(err);}
            expect(instance).to.be.null;
            cb();
          });
        }
      ], done);
    });
  });
});
<commit_msg>Cleanup<commit_after>var async = require('async');
var chai = require('chai');

var testUtils = require('../test_utils');

var expect = chai.expect;

describe('Model (integration)', function() {

  before(function() {
    testUtils.setupOrm.call(this);
    testUtils.setupTestModels.call(this);
  });

  beforeEach(function(cb) {
    this.orm._resetDatastores(cb);
  });

  describe('#find()', function() {

    before(function() {
      this.IndexedModel = this.createModel({
        properties: {
          indexed: {type: 'string', index: true, cache: true},
          indexed_no_replace: {
            type: 'string', index: true, cache: true, replace: false
          }
        },
        callbacks: {
          beforeInput: function(values, cb) {
            cb(null, testUtils.appendValue(values, 'beforeInput'));
          },
          afterInput: function(values, cb) {
            cb(null, testUtils.appendValue(values, 'afterInput'));
          }
        }
      });
    });

    it('should mutate the index value by default', function(done) {
      var self = this;
      async.waterfall([
        function(cb) {
          var instance = self.IndexedModel.create({indexed: 'foo'});
          instance.save(function(err) {
            if (err) {return cb(err);}
            cb(null, instance.getId());
          });
        },
        function(id, cb) {
          self.IndexedModel.find('indexed', 'foo', function(err, instance) {
            if (err) {return cb(err);}
            instance.should.exist;
            instance.isNew.should.be.false;
            instance.isChanged().should.be.false;
            instance.getId().should.eq(id);
            cb();
          });
        }
      ], done);
    });

    it('should not mutate the index value if requested', function(done) {
      var self = this;
      async.waterfall([
        function(cb) {
          var instance = self.IndexedModel.create({indexed: 'foo'}, true);
          instance.save(function(err) {
            if (err) {return cb(err);}
            cb(null, instance.getId());
          });
        },
        function(id, cb) {
          self.IndexedModel.find('indexed', 'foo', true,
            function(err, instance) {
            if (err) {return cb(err);}
            instance.getId().should.eq(id);
            cb();
          });
        }
      ], done);
    });

    it('should only work with indexed properties', function() {
      var self = this;
      (function() {
        self.BasicModel.find('nonindex', 'foo', function() {});
      }).should.throw('attribute "nonindex" is not an index');
    });

    it('should callback with null if nothing is found', function(done) {
      this.IndexedModel.find('indexed', 'bar', function(err, instance) {
        if (err) {return done(err);}
        expect(instance).to.be.null;
        done();
      });
    });

    it('should use old indexes that have not been replaced', function(done) {
      var self = this;
      async.waterfall([
        function(cb) {
          var instance = self.IndexedModel.create({
            indexed_no_replace: 'foo'
          }, true);
          instance.save(function(err) {
            if (err) {return cb(err);}
            instance.set({
              indexed_no_replace: 'bar'
            }, true).save(function(err) {
              if (err) {return cb(err);}
              cb(null, instance.getId());
            });
          });
        },
        function(id, cb) {
          self.IndexedModel.find('indexed_no_replace', 'foo', true,
            function(err, instance) {
            if (err) {return cb(err);}
            instance.getId().should.eq(id);
            cb();
          });
        }
      ], done);
    });

    it('should not use indexes that have been replaced', function(done) {
      var self = this;
      async.waterfall([
        function(cb) {
          var instance = self.IndexedModel.create({indexed: 'foo'}, true);
          instance.save(function(err) {
            if (err) {return cb(err);}
            instance.set({indexed: 'bar'}, true).save(function(err) {
              if (err) {return cb(err);}
              cb(null, instance.getId());
            });
          });
        },
        function(id, cb) {
          self.IndexedModel.find('indexed', 'foo', true,
            function(err, instance) {
            if (err) {return cb(err);}
            expect(instance).to.be.null;
            cb();
          });
        }
      ], done);
    });
  });
});
<|endoftext|>


<commit_before>export default
    function InventoryUpdate(PromptForPasswords, LaunchJob, Rest, ProcessErrors, Alert, Wait) {
        return function (params) {

            var scope = params.scope,
            url = params.url,
            inventory_source;

            if (scope.removeUpdateSubmitted) {
                scope.removeUpdateSubmitted();
            }
            scope.removeUpdateSubmitted = scope.$on('UpdateSubmitted', function () {
                Wait('stop');
                if (scope.socketStatus === 'error') {
                    Alert('Sync Started', '
The request to start the inventory sync process was submitted. ' +
                    'To monitor the status refresh the page by clicking the  button.
', 'alert-info', null, null, null, null, true);
                    if (scope.refreshGroups) {
                        // inventory detail page
                        scope.refreshGroups();
                    }
                    else if (scope.refresh) {
                        scope.refresh();
                    }
                }
            });

            if (scope.removePromptForPasswords) {
                scope.removePromptForPasswords();
            }
            scope.removePromptForPasswords = scope.$on('PromptForPasswords', function() {
                PromptForPasswords({ scope: scope, passwords: inventory_source.passwords_needed_to_update, callback: 'StartTheUpdate' });
            });

            if (scope.removeStartTheUpdate) {
                scope.removeStartTheUpdate();
            }
            scope.removeStartTheUpdate = scope.$on('StartTheUpdate', function(e, passwords) {
                LaunchJob({ scope: scope, url: url, passwords: passwords, callback: 'UpdateSubmitted' });
            });

            // Check to see if we have permission to perform the update and if any passwords are needed
            Wait('start');
            Rest.setUrl(url);
            Rest.get()
            .success(function (data) {
                if(params.updateAllSources) {
                    let userCanUpdateAllSources = true;
                    _.forEach(data, function(inventory_source){
                        if (!inventory_source.can_update) {
                            userCanUpdateAllSources = false;
                        }
                    });

                    if(userCanUpdateAllSources) {
                        scope.$emit('StartTheUpdate', {});
                    }
                }
                else {
                    inventory_source = data;
                    if (data.can_update) {
                        if (data.passwords_needed_to_update) {
                            Wait('stop');
                            scope.$emit('PromptForPasswords');
                        }
                        else {
                            scope.$emit('StartTheUpdate', {});
                        }
                    } else {
                        Wait('stop');
                        Alert('Permission Denied', 'You do not have access to run the inventory sync. Please contact your system administrator.',
                        'alert-danger');
                    }
                }
            })
            .error(function (data, status) {
                ProcessErrors(scope, data, status, null, { hdr: 'Error!',
                msg: 'Failed to get inventory source ' + url + ' GET returned: ' + status });
                });
            };
    }

InventoryUpdate.$inject =
    [   'PromptForPasswords',
        'LaunchJob',
        'Rest',
        'ProcessErrors',
        'Alert',
        'Wait'
    ];
<commit_msg>Updated error message when can_update comes back false on an inventory source update GET<commit_after>export default
    function InventoryUpdate(PromptForPasswords, LaunchJob, Rest, ProcessErrors, Alert, Wait) {
        return function (params) {

            var scope = params.scope,
            url = params.url,
            inventory_source;

            if (scope.removeUpdateSubmitted) {
                scope.removeUpdateSubmitted();
            }
            scope.removeUpdateSubmitted = scope.$on('UpdateSubmitted', function () {
                Wait('stop');
                if (scope.socketStatus === 'error') {
                    Alert('Sync Started', '
The request to start the inventory sync process was submitted. ' +
                    'To monitor the status refresh the page by clicking the  button.
', 'alert-info', null, null, null, null, true);
                    if (scope.refreshGroups) {
                        // inventory detail page
                        scope.refreshGroups();
                    }
                    else if (scope.refresh) {
                        scope.refresh();
                    }
                }
            });

            if (scope.removePromptForPasswords) {
                scope.removePromptForPasswords();
            }
            scope.removePromptForPasswords = scope.$on('PromptForPasswords', function() {
                PromptForPasswords({ scope: scope, passwords: inventory_source.passwords_needed_to_update, callback: 'StartTheUpdate' });
            });

            if (scope.removeStartTheUpdate) {
                scope.removeStartTheUpdate();
            }
            scope.removeStartTheUpdate = scope.$on('StartTheUpdate', function(e, passwords) {
                LaunchJob({ scope: scope, url: url, passwords: passwords, callback: 'UpdateSubmitted' });
            });

            // Check to see if we have permission to perform the update and if any passwords are needed
            Wait('start');
            Rest.setUrl(url);
            Rest.get()
            .success(function (data) {
                if(params.updateAllSources) {
                    let userCanUpdateAllSources = true;
                    _.forEach(data, function(inventory_source){
                        if (!inventory_source.can_update) {
                            userCanUpdateAllSources = false;
                        }
                    });

                    if(userCanUpdateAllSources) {
                        scope.$emit('StartTheUpdate', {});
                    }
                }
                else {
                    inventory_source = data;
                    if (data.can_update) {
                        if (data.passwords_needed_to_update) {
                            Wait('stop');
                            scope.$emit('PromptForPasswords');
                        }
                        else {
                            scope.$emit('StartTheUpdate', {});
                        }
                    } else {
                        Wait('stop');
                        Alert('Error Launching Sync', 'Unable to execute the inventory sync. Please contact your system administrator.',
                        'alert-danger');
                    }
                }
            })
            .error(function (data, status) {
                ProcessErrors(scope, data, status, null, { hdr: 'Error!',
                msg: 'Failed to get inventory source ' + url + ' GET returned: ' + status });
                });
            };
    }

InventoryUpdate.$inject =
    [   'PromptForPasswords',
        'LaunchJob',
        'Rest',
        'ProcessErrors',
        'Alert',
        'Wait'
    ];
<|endoftext|>


<commit_before><commit_msg>dont use lastAttempt if we're editting blocks<commit_after><|endoftext|>


<commit_before><commit_msg>Authorization redirect fixes<commit_after><|endoftext|>


<commit_before><commit_msg>try catch sql<commit_after><|endoftext|>


<commit_before>/***************************************************************************************************************************************************************
 *
 * PA11Y TEST
 *
 **************************************************************************************************************************************************************/

'use strict';

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// Dependencies
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
const Helper    = require( './helper.js' );
const Express   = require( 'express' );
const Pa11y     = require( 'pa11y' );
const Puppeteer = require( 'puppeteer' );
const Fs        = require( 'fs' );
const Path      = require( 'path' );

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// GLOBALS
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
const OPTIONS = {
	timeout: 60000,
	hideElements: '.sr-only, .is-visuallyhidden, .visuallyhidden, .no-a11y-test, .uikit-page-alerts__sronly, .uikit-skip-link',
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// CLI OUTPUT FORMATTING
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
const DisplayResults = results => {
	if( results.issues.length ) {
		results.issues.map( issue => {
			Helper.log.error( `Error found at ${ issue.selector }`)
			console.log( `${ issue.context }\n ${ issue.message }\n` );
		})

		process.exit( 1 );
	}
	else {
		Helper.log.success( 'No errors' );
	}
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// RUN TESTS
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
const RunPa11y = async ( urls ) => {
	// Start the browser
	const browser = await Puppeteer.launch();

	// For each url create a new page and run the Pa11y Test
	const tests = urls.map( async ( url ) => {
		const page = await browser.newPage();

		// Run the Pa11y test
		await Pa11y( url, {
			browser,
			page,
			...OPTIONS,
		})
		.then( result => {
			console.log( `Pa11y automated ${ result.documentTitle }` );
			DisplayResults( result );
		})
		.catch( error => Helper.log.error( error ) );

		// Close the page
		await page.close();
	});

	// Wait for all the tests to finish
	await Promise.all( tests );

	// Close the browser
	await browser.close();
}

// Global variables
const UikitJson = Path.normalize( `${ process.cwd() }/uikit.json` );
const TestURL   = 'http://localhost:8080';

// Start the test - immediatley executed async function
( async() => {

	// Run all of the tests
	try {
			// Start express at port 8080
		const App    = Express();
		const Server = App.listen( '8080' );

		// Set up the server localhost:8080 and the current directory
		App.use( Express.static( './' ) );

		// Default one url to test
		let urls = [ `${ TestURL }/tests/site` ];

		// If there is a uikit.json file we should test all the components
		if( Fs.existsSync( UikitJson ) ){

			// Create a url based off the keys in the uikit.json
			urls = Object.keys( require( UikitJson ) ).map( key => {
				return `${ TestURL }/packages/${ key.substring( 8 ) }/tests/site`
			});
		}
		await RunPa11y( urls );

		// Close the express server
		await Server.close();
	}
	catch( error ){
		console.error( error );
	}
})();
<commit_msg>Wrapping async in try catch<commit_after>/***************************************************************************************************************************************************************
 *
 * PA11Y TEST
 *
 **************************************************************************************************************************************************************/

'use strict';

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// Dependencies
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
const Helper    = require( './helper.js' );
const Express   = require( 'express' );
const Pa11y     = require( 'pa11y' );
const Puppeteer = require( 'puppeteer' );
const Fs        = require( 'fs' );
const Path      = require( 'path' );

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// GLOBALS
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
const OPTIONS = {
	timeout: 60000,
	hideElements: '.sr-only, .is-visuallyhidden, .visuallyhidden, .no-a11y-test, .uikit-page-alerts__sronly, .uikit-skip-link',
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// CLI OUTPUT FORMATTING
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
const DisplayResults = results => {
	if( results.issues.length ) {
		results.issues.map( issue => {
			Helper.log.error( `Error found at ${ issue.selector }`)
			console.log( `${ issue.context }\n ${ issue.message }\n` );
		})

		process.exit( 1 );
	}
	else {
		Helper.log.success( 'No errors' );
	}
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// RUN TESTS
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
const RunPa11y = async ( urls ) => {
	try {
		// Start the browser
		const browser = await Puppeteer.launch();

		// For each url create a new page and run the Pa11y Test
		const tests = urls.map( async ( url ) => {
			const page = await browser.newPage();

			// Run the Pa11y test
			await Pa11y( url, {
				browser,
				page,
				...OPTIONS,
			})
			.then( result => {
				console.log( `Pa11y automated ${ result.documentTitle }` );
				DisplayResults( result );
			})
			.catch( error => Helper.log.error( error ) );

			// Close the page
			await page.close();
		});

		// Wait for all the tests to finish
		await Promise.all( tests );

		// Close the browser
		await browser.close();
	}
	catch( error ){
		throw new Error( error );
	}
}

// Global variables
const UikitJson = Path.normalize( `${ process.cwd() }/uikit.json` );
const TestURL   = 'http://localhost:8080';

// Start the test - immediatley executed async function
( async() => {
	try {
		// Run all of the tests
		// Start express at port 8080
		const App    = Express();
		const Server = App.listen( '8080' );

		// Set up the server localhost:8080 and the current directory
		App.use( Express.static( './' ) );

		// Default one url to test
		let urls = [ `${ TestURL }/tests/site` ];

		// If there is a uikit.json file we should test all the components
		if( Fs.existsSync( UikitJson ) ){

			// Create a url based off the keys in the uikit.json
			urls = Object.keys( require( UikitJson ) ).map( key => {
				return `${ TestURL }/packages/${ key.substring( 8 ) }/tests/site`
			});
		}

		await RunPa11y( urls );

		// Close the express server
		await Server.close();
	}
	catch( error ) {
		throw new Error( error );
	}
})();
<|endoftext|>


<commit_before>'use babel';
/**
  Breakpoint Gutter Component
  @description Creates a breakpoint gutter, allows the breakpoint
    functionality for creating/destroying breakpoints as well as drawing
    them, should have one of these *per* editor instance
**/

import { BreakpointActions } from '../actions';

export default class BreakpointGutter {
  /**
    @constructor
    @desc initializes props, sets breakpoint toggle click listener, renders
      the initial breakpoints & creates breakpoint gutter
    @param {TextEditor} editor to put the breakpoint gutter in
    @param {object[]} editorBreakpoints => bps for a single editor
    @param {HTMLElement} $lineNumGutter
  **/
  constructor(editor, editorBreakpoints, $lineNumGutter) {
    this.editor = editor;
    this.editorBreakpoints = editorBreakpoints;
    this.breakpointDecorations = [];
    this.$lineNumGutter = $lineNumGutter;

    this.element = editor.addGutter({name: 'delve-breakpoint', priority: -100});
    this._registerToggleListener($lineNumGutter);
    this.render();
  }

  _registerToggleListener($targetGutter) {
    const _breakpointToggleListener = evt => {
      let $lineNumber = evt.target;
      let row = parseInt($lineNumber.getAttribute('data-buffer-row'), 10);
      if (isNaN(row)) return;

      evt.preventDefault();
      evt.stopPropagation();
      evt.stopImmediatePropagation();

      let existing = this.editorBreakpoints.find(b => b.location.line == row);

      if (existing)
        BreakpointActions.clearBreakpoint(existing.id);
      else
        BreakpointActions.create(this.editor.getPath(), row);
    };

    this._breakpointToggleListener = _breakpointToggleListener;
    $targetGutter.addEventListener('click', _breakpointToggleListener);
  }

  destroy() {
    this.$lineNumGutter
    .removeEventListener('click', this._breakpointToggleListener);

    this.element.destroy();
  }

  render() {
    this.breakpointDecorations.forEach(d => d.destroy());

    this.breakpointDecorations = this.editorBreakpoints.map(bp => {
      const row = bp.location.line - 1; // Atom is 0 indexed; Delve is 1 indexed
      const buffer = this.getBuffer();

      const breakpoint = document.createElement('div');
      breakpoint.classList.add('delve-breakpoint');
      if (bp.pendingChange) breakpoint.classList.add('is-pending');

      let range;
      if (buffer.isRowBlank(row))
        range = buffer.rangeForRow(buffer.nextNonBlankRow(row), false);
      else
        range = buffer.rangeForRow(row, false);

      const marker = this.editor.markBufferRange(range, {invalidate: 'never'});

      return this.element.decorateMarker(marker, {
        type: 'gutter', item: breakpoint
      });
    });
  }

  updateBreakpoints(breakpoints) {
    this.editorBreakpoints = breakpoints;
    this.render();
  }

  getFile() { return this.editor.getPath(); }
  getElement() { return this.element; }
}
<commit_msg>Bind to breakpoint gutter click handler<commit_after>'use babel';
/**
  Breakpoint Gutter Component
  @description Creates a breakpoint gutter, allows the breakpoint
    functionality for creating/destroying breakpoints as well as drawing
    them, should have one of these *per* editor instance
**/

import { BreakpointActions } from '../actions';

export default class BreakpointGutter {
  /**
    @constructor
    @desc initializes props, sets breakpoint toggle click listener, renders
      the initial breakpoints & creates breakpoint gutter
    @param {TextEditor} editor to put the breakpoint gutter in
    @param {object[]} editorBreakpoints => bps for a single editor
    @param {HTMLElement} $lineNumGutter
  **/
  constructor(editor, editorBreakpoints, $lineNumGutter) {
    this.editor = editor;
    this.editorBreakpoints = editorBreakpoints;
    this.breakpointDecorations = [];
    this.$lineNumGutter = $lineNumGutter;

    this.element = editor.addGutter({name: 'delve-breakpoint', priority: -100});
    this._registerToggleListener($lineNumGutter);
    this.render();
  }

  _registerToggleListener($targetGutter) {
    const _breakpointToggleListener = evt => {
      let $lineNumber = evt.target;
      let row = parseInt($lineNumber.getAttribute('data-buffer-row'), 10);
      if (isNaN(row)) return;

      evt.preventDefault();
      evt.stopPropagation();
      evt.stopImmediatePropagation();

      let existing = this.editorBreakpoints.find(b => b.location.line == row);

      if (existing)
        BreakpointActions.clearBreakpoint(existing.id);
      else
        BreakpointActions.create(this.editor.getPath(), row);
    };

    this._breakpointToggleListener = _breakpointToggleListener.bind(this);
    $targetGutter.addEventListener('click', this._breakpointToggleListener);
  }

  destroy() {
    this.$lineNumGutter
    .removeEventListener('click', this._breakpointToggleListener);

    this.element.destroy();
  }

  render() {
    this.breakpointDecorations.forEach(d => d.destroy());

    this.breakpointDecorations = this.editorBreakpoints.map(bp => {
      const row = bp.location.line - 1; // Atom is 0 indexed; Delve is 1 indexed
      const buffer = this.getBuffer();

      const breakpoint = document.createElement('div');
      breakpoint.classList.add('delve-breakpoint');
      if (bp.pendingChange) breakpoint.classList.add('is-pending');

      let range;
      if (buffer.isRowBlank(row))
        range = buffer.rangeForRow(buffer.nextNonBlankRow(row), false);
      else
        range = buffer.rangeForRow(row, false);

      const marker = this.editor.markBufferRange(range, {invalidate: 'never'});

      return this.element.decorateMarker(marker, {
        type: 'gutter', item: breakpoint
      });
    });
  }

  updateBreakpoints(breakpoints) {
    this.editorBreakpoints = breakpoints;
    this.render();
  }

  getFile() { return this.editor.getPath(); }
  getElement() { return this.element; }
}
<|endoftext|>


<commit_before>/**
 * list.js provides the functions to create a hashed key-value list.
 */

var MAX_ELEMENTS = 100;
var HASH_MULTIPLIER = 37;

var List = function () {
    this.h_list = [];
    this.h_list.length = MAX_ELEMENTS;
};

List.prototype = {

    /**
     * get: returns the value attached to the given key.
     */
    get: function(key) {
        var h;
        h = this.hash(key);
        return this.h_list[h];
    },

    /**
     * add: inserts an object into the list, assigning it to the given key.
     */
    add: function (key, value) {
        var h;
        h = this.hash(key);
        this.h_list[h] = value;
    },

    /**
     * hash: hashes the given key and returns it.
     */
    hash: function (key) {
        var i, h;
        h = 0;

        for (i = 0; i < key.length; i = i + 1)
            h = (HASH_MULTIPLIER * h) + key.charCodeAt();
        return h % MAX_ELEMENTS;
    }

};

var li = new List();
li.add("ben", "scholz");
window.document.writeln(li.get("ben"));

<commit_msg>removed old test code<commit_after>/**
 * list.js provides the functions to create a hashed key-value list.
 */

var MAX_ELEMENTS = 100;     /* maximum elements for all lists */
var HASH_MULTIPLIER = 37;   /* prime multiplier for hash function */

/**
 * List allows to access elements through a key (string of characters)
 */
var List = function () {
    this.h_list = [];
    this.h_list.length = MAX_ELEMENTS;
};

List.prototype = {

    /**
     * get: returns the value attached to the given key.
     */
    get: function(key) {
        var h;
        h = this.hash(key);
        return this.h_list[h];
    },

    /**
     * add: inserts an object into the list, assigning it to the given key.
     */
    add: function (key, value) {
        var h;
        h = this.hash(key);
        this.h_list[h] = value;
    },

    /**
     * hash: hashes the given key and returns it.
     */
    hash: function (key) {
        var i, h;
        h = 0;

        for (i = 0; i < key.length; i = i + 1)
            h = (HASH_MULTIPLIER * h) + key.charCodeAt();
        return h % MAX_ELEMENTS;
    }

};

<|endoftext|>


<commit_before>//This page handles all resources page content

//jquery for phone fields
$(".required").keyup(function () {
    if (this.value.length == this.maxLength) {
      var $next = $(this).next('.required');
      if ($next.length)
          $(this).next('.required').focus();
      else
          $(this).blur();
    }
});

const auth = firebase.auth();
const btnLogout = document.getElementById('btnLogout');

//Add logout event
btnLogout.addEventListener('click', function(e) {
	auth.signOut();
  console.log(e.message);
});

//Add a realtime listener
auth.onAuthStateChanged(function(firebaseUser) {
	if(firebaseUser) {
		console.log(firebaseUser);
		btnLogout.classList.remove('hide');
    console.log(firebaseUser.email);
    closeModal();
	} else {
		console.log('not logged in');
    showModal();
		btnLogout.classList.add('hide');
	}
});

function closeModal() {
  $('#myModal').modal('close');
};

function showModal(){
  $('#myModal').modal('show');
};

//Loads all statistics on page load
window.onload = allStatistics();
var statRef = firebase.database();

function updateStatistic(statisticID) {
	var id = statisticID;
	var statValue = id + "Value";

	var valueUpdate = document.getElementById(statValue);
	statRef.ref("data_dashboard").child(id).update({
		value: ""+ valueUpdate.value +""
	});
};

//Filters all statistics
function allStatistics() {

	//Clears table of statistics
	var tableRef = document.getElementById('table_body');
	while ( tableRef.rows.length > 0 )
	{
	 tableRef.deleteRow(0);
	}

	//Pull statistics from Firebase database
	rootref.child("data_dashboard").on("child_added", function(snap) {

		//store data from firebase to be used in table
		var id = snap.key;
		var stringID = id.toString();
		var statValue = snap.child("value");

		//Creates table with statistics pulled from firebase
		$("#table_body").append("
<input id='"+id+"Statistic' type='text' value=\""+stringID+"\" ></input>	<input id='"+id+"Value' type='text'  value=\""+statValue+"\" ></input>		<input type='submit' class='btn btn-success btn-send' value='Update' onclick='updateStatistic(\""+ stringID + "\")''></input>
"
		);
		});
};
<commit_msg>Update firebase-edit-data-dashboard.js<commit_after>//This page handles all resources page content

//jquery for phone fields
$(".required").keyup(function () {
    if (this.value.length == this.maxLength) {
      var $next = $(this).next('.required');
      if ($next.length)
          $(this).next('.required').focus();
      else
          $(this).blur();
    }
});

const auth = firebase.auth();
const btnLogout = document.getElementById('btnLogout');

//Add logout event
btnLogout.addEventListener('click', function(e) {
	auth.signOut();
  console.log(e.message);
});

//Add a realtime listener
auth.onAuthStateChanged(function(firebaseUser) {
	if(firebaseUser) {
		console.log(firebaseUser);
		btnLogout.classList.remove('hide');
    console.log(firebaseUser.email);
    closeModal();
	} else {
		console.log('not logged in');
    showModal();
		btnLogout.classList.add('hide');
	}
});

function closeModal() {
  $('#myModal').modal('close');
};

function showModal(){
  $('#myModal').modal('show');
};

//Loads all statistics on page load
window.onload = allStatistics();
var statRef = firebase.database();

function updateStatistic(statisticID) {
	var id = statisticID;
	var statValue = id + "Value";

	var valueUpdate = document.getElementById(statValue);
	statRef.ref("data_dashboard").child(id).update({
		value: ""+ valueUpdate.value +""
	});
};

//Filters all statistics
function allStatistics() {

	//Clears table of statistics
	var tableRef = document.getElementById('table_body');
	while ( tableRef.rows.length > 0 )
	{
	 tableRef.deleteRow(0);
	}

	//Pull statistics from Firebase database
	rootref.child("data_dashboard").on("child_added", function(snap) {

		//store data from firebase to be used in table
		var id = snap.key;
		var stringID = id.toString();
		var statValue = snap.child("value").val();

		//Creates table with statistics pulled from firebase
		$("#table_body").append("
<input id='"+id+"Statistic' type='text' value=\""+stringID+"\" ></input>	<input id='"+id+"Value' type='text'  value=\""+statValue+"\" ></input>		<input type='submit' class='btn btn-success btn-send' value='Update' onclick='updateStatistic(\""+ stringID + "\")''></input>
"
		);
		});
};
<|endoftext|>


<commit_before>/* Copyright 2016 Streampunk Media Ltd.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

var Grain = require('../model/Grain.js');
var Timecode = require('../model/Timecode.js');
var test = require('tape');

test('A newly created grain from mainly strings', function (t) {
  var g = new Grain([new Buffer(10), new Buffer(5)],
    '12345:67890', '98765:43210', '10:11:12:13',
    'CCA06626-AEB1-4014-8287-BBEF45E7DD51',
    '0313B546-1325-4983-B80B-1C3C312FC181',
    '25/1');
  console.log(JSON.stringify(g, null, 2));
  t.end();
});
<commit_msg>Patched grain test so that it will pass.<commit_after>/* Copyright 2016 Streampunk Media Ltd.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

var Grain = require('../model/Grain.js');
var Timecode = require('../model/Timecode.js');
var test = require('tape');

test('A newly created grain from mainly strings', function (t) {
  var g = new Grain([new Buffer(10), new Buffer(5)],
    '12345:67890', '98765:43210', '10:11:12:13',
    'CCA06626-AEB1-4014-8287-BBEF45E7DD51',
    '0313B546-1325-4983-B80B-1C3C312FC181',
    '25/1');
  // console.log(JSON.stringify(g, null, 2));
  t.end();
});
<|endoftext|>


<commit_before>//'use strict';

//WOAH https://gist.github.com/ryanflorence/1198466
(function (name, definition){
  if (typeof define === 'function'){ // AMD
    define(definition);
  } else if (typeof module !== 'undefined' && module.exports) { // Node.js
    module.exports = definition();
  } else { // Browser
    var theModule = definition(), global = this, old = global[name];
    theModule.noConflict = function () {
      global[name] = old;
      return theModule;
    };
    global[name] = theModule;
  }
})('sud', function () {
    var pk = {};

    function scope_gen(n) {
        // for normal sudoku latin square, n is 3
        // a latin square has n^4 cells
        var i, j, r, c, gr, gc, l, p;
        var out = [];
        l = n * n * n * n;
        /* malloc from stdlib.h */
        for (i = 0; i < l; i++) {
            var scope = new Array(l);
            r = Math.floor(i / (n * n));
            c = i % (n * n);
            gr = Math.floor(r / n) * n;
            gc = Math.floor(c / n) * n;
            for (j = 0; j < n * n; j++) {
                scope[r * n * n + j] = true;
                scope[j * n * n + c] = true;
                scope[(gr + Math.floor(j / n)) * n * n + gc + j %
                    n] = true;
            }
            scope[i] = false;
            var eye = [];
            for (j = 0; j < l; j++)
                if (scope[j]) {
                    eye.push(j);
                }
            out.push(eye);
        }
        return out;
    }
    //the cell class
    var cell = function (i) {
        //cell object constructor
        if (i) {
            if (typeof i === "object") {
                this.v = i.v;
            } else {
                var idea = i - 1;
                if ((idea < 9) && (idea >= 0)) {
                    this.putIdea(idea);
                } else {
                    this.v = 0x7fe7;
                }
            }
        } else {
            this.v = 0x7fe7;
        }
    };
    cell.prototype.putIdea = function (idea) {
        this.v = (idea | open | pk.may_b[idea]);
    };
    cell.prototype.copyIn = function (i) {
        this.v = i.v;
    };
    cell.prototype.txt = function () {
        return this.v.toString();
    };
    cell.prototype.yo = function (mask) {
        return ((this.v & mask) !== 0);
    };
    cell.prototype.reset = function (mask) {
        //reset the mask
        this.v &= ~mask;
    };
    cell.prototype.value = function () {
        //value of an open or filled cell
        return (this.v & pk.data);
    };
    cell.prototype.rm = function (i) {
        // returns success or failure (false or true respectively)
        if (this.yo(pk.may_b[i])) {
            //has it in probable
            if (!this.yo(pk.wait)) {
                return true;
                // it is the only probable!!
            }
            this.reset(pk.may_b[i]);
            this.v -= 1;
            if (this.yo(open)) {
                // only one probable left now
                for (i = 0; i < 9; i += 1) {
                    if (this.yo(pk.may_b[i])) {
                        break;
                    }
                }
                this.putIdea(i);
            }
        }
        return false;
        //removed ok
    };
    cell.prototype.trial = function (i) {
        // returns trial value or >=9 if no trial available
        for (; i < 9; i += 1) {
            if (this.yo(pk.may_b[i])) {
                break;
            }
        }
        return i;
    };
    pk.cell = cell;
    //the package globals
    pk.wait = 0x20;
    var open = 0x10;
    pk.data = 0xf;
    pk.may_b = [
        0x4000, 0x2000, 0x1000,
        0x0800, 0x0400, 0x0200,
        0x0100, 0x0080, 0x0040
    ];
    pk.clr = scope_gen(3);
    //the sud class. models a sudoku
    var sud = function (inp) {
        if (inp) {
            if (typeof inp === "object") {
                this.left = inp.left;
                this.i_v = [];
                for (var i = 0; i < 81; i += 1) {
                    this.i_v[i] = new pk.cell(inp.i_v[i]);
                }
                return;
            } else inp = inp.toString()
        } else inp = '123456789'
        var len = inp.length
        this.left = 81
        this.i_v = []
        var i = 0
        for (; i < len && i < 81; i += 1) {
            this.i_v[i] = new pk.cell(inp.charAt(i))
        }
        for (; i < 81; i += 1) this.i_v[i] = new pk.cell()
        arguments.callee.__out__ = []
    }
    sud.prototype.copyIn = function (t) {
        this.left = t.left;
        for (var i = 0; i < 81; i += 1) this.i_v[i].copyIn(t.i_v[
            i]);
    }
    sud.prototype.first = function () {
        // first waiting cell or >=81; for ordered listing of solutions
        var i = 0
        for (; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.wait)) {
                break;
            }
        }
        return i
    }
    sud.prototype.idea = function () {
        //first open cell or >=81
        var i = 0
        for (; i < 81; i += 1) {
            if (this.i_v[i].yo(open)) {
                break
            }
        }
        return i
    }
    sud.prototype.toString = function () {
        var buf = ''
        for (var i = 0; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.cell.open)) {
                buf += '?';
            } else {
                buf += (1 + this.i_v[i].value());
            }
        }
        return buf;
    }
    sud.prototype.hook = function () {
        // returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
        var x, pos, val
        while ((pos = this.idea()) < 81) {
            val = this.i_v[pos].value()
            for (x = 0; x < 20; x += 1) {
                if (this.i_v[pk.clr[pos][x]].rm(val)) {
                    return -1;
                }
            }
            this.i_v[pos].reset(open)
            if ((this.left -= 1) === 0) {
                this.constructor.__out__.push(this.toString())
                return this.constructor.__out__.length === this.constructor
                    .__n__ ? 2 : 1;
            }
        }
        return 0
    }
    sud.prototype.crook = function () {
        var mc, cc, pos, val = 0
        var copy = new pk.sud(this)
        if ((pos = this.first()) < 81) {
            mc = this.i_v[pos]
            cc = copy.i_v[pos]
        } else return 1
        while ((val = mc.trial(val)) < 9) {
            copy.copyIn(this)
            cc.putIdea(val)
            switch (copy.squash()) {
            case 1:
                val += 1
                break
            case 2:
                return 2
            case -1:
                mc.rm(val) // should i check?
                if (
                        ((pos = this.idea()) < 81)
                        &&
                        (this.i_v[pos].value() > val)
                ) {
                    copy = null
                    return 0
                }
            }
        }
        copy = null
        return 1
    }
    sud.prototype.squash = function () {
        var ret
        do
            if ((ret = this.hook()) !== 0) return ret;
        while (0 === (ret = this.crook())) return ret
    }
    pk.sud = sud;
    //the list class. subclass of sud.
    //solution lister engine
    //an iterator
    var list = function (inp) {
        // calling superclass constructor
        pk.sud.call(this, inp)
        this.status = function (ls, pos, val) {
            this.l = new pk.list(ls)
            this.p = pos
            this.v = val
        }
        if (typeof inp === 'object') return
        pk.nxt = []
        switch (this.squash()) {
        case -1:
            break
        case 2:
        }
    }
    // subclass extends superclass
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
    list.prototype = Object.create(pk.sud.prototype)
    list.prototype.constructor = list
    list.prototype.hook = function () {
        // returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
        var x, pos, val
        if (pk.stata) {
            if (pk.stata.length === 0) {
                delete pk.stata
                return 1
            } else return 0
        }
        while ((pos = this.idea()) < 81) {
            val = this.i_v[pos].value()
            for (x = 0; x < 20; x += 1) {
                if (this.i_v[pk.clr[pos][x]].rm(val)) return -1
            } // try removing braces
            this.i_v[pos].reset(open)
            if ((this.left -= 1) === 0) {
                pk.nxt.push(this.toString())
                if (pk.nxt.length === pk.n) {
                    pk.stata = []
                    // i hope empty array is true in js
                    return 2
                } else return 1
            }
        }
        return 0
    }
    list.prototype.crook = function () {
        var mc, cc, pos, val = 0,
            copy
        if (pk.stata) {
            copy = pk.stata.pop();
            mc = this.i_v[copy.p];
            cc = copy.l.i_v[copy.p];
        } else {
            if ((pos = this.first()) >= 81) return 1
            else {
                copy = new this.status(this, pos, 0)
                mc = this.i_v[copy.p]
                cc = copy.l.i_v[copy.p]
            }
        }
        while (pk.stata || ((copy.v = mc.trial(copy.v)) < 9)) {
            if (!pk.stata) {
                copy.l.copyIn(this);
                cc.putIdea(copy.v);
            }
            switch (copy.l.squash()) {
            case 1:
                copy.v += 1;
                break;
            case 2:
                pk.stata.push(copy);
                return 2;
            case -1:
                mc.rm(copy.v); /* should i check? */
                if (
                    ((pos = this.idea()) < 81) && (this.i_v[pos].value() >
                        copy.v)) return 0
            }
        }
        return 1
    }
    list.prototype.next = function () {
        if (pk.nxt.length === 0) return undefined
        pk.out = pk.nxt
        pk.nxt = []
        this.squash()
        return pk.out
    }
    list.prototype.hasNext = function () {
        return pk.nxt.length !== 0;
    }
    pk.list = list;
    //exports

    var o = {};
    o.iter = function (constraints, n) {
        pk.n = n || 2
        return new pk.list(constraints)
    }
    o.list = function (constraints, n) {
        var master = new pk.sud(constraints)
        master.constructor.__n__ = n || 2;
        switch (master.squash()) {
        case -1:
            console.log("no solution")
            break
        case 2:
        }
        return master.constructor.__out__
    }
    return o;
});
/*
TODO:
change pk.nxt pk.out pk.n pk.stata. /pk\.[^.]* /
change /stat/
for class list
use ed
add semicolons to statements
add braces to loop or if/else bodies
use semver.org and publish to npm
*/
<commit_msg>got rid of pk.may_b<commit_after>//'use strict';

//WOAH https://gist.github.com/ryanflorence/1198466
(function (name, definition){
  if (typeof define === 'function'){ // AMD
    define(definition);
  } else if (typeof module !== 'undefined' && module.exports) { // Node.js
    module.exports = definition();
  } else { // Browser
    var theModule = definition(), global = this, old = global[name];
    theModule.noConflict = function () {
      global[name] = old;
      return theModule;
    };
    global[name] = theModule;
  }
})('sud', function () {
    var pk = {};

    function scope_gen(n) {
        // for normal sudoku latin square, n is 3
        // a latin square has n^4 cells
        var i, j, r, c, gr, gc, l, p;
        var out = [];
        l = n * n * n * n;
        /* malloc from stdlib.h */
        for (i = 0; i < l; i++) {
            var scope = new Array(l);
            r = Math.floor(i / (n * n));
            c = i % (n * n);
            gr = Math.floor(r / n) * n;
            gc = Math.floor(c / n) * n;
            for (j = 0; j < n * n; j++) {
                scope[r * n * n + j] = true;
                scope[j * n * n + c] = true;
                scope[(gr + Math.floor(j / n)) * n * n + gc + j %
                    n] = true;
            }
            scope[i] = false;
            var eye = [];
            for (j = 0; j < l; j++)
                if (scope[j]) {
                    eye.push(j);
                }
            out.push(eye);
        }
        return out;
    }
    //the cell class
    var cell = function (i) {
        //cell object constructor
        if (i) {
            if (typeof i === "object") {
                this.v = i.v;
            } else {
                var idea = i - 1;
                if ((idea < 9) && (idea >= 0)) {
                    this.putIdea(idea);
                } else {
                    this.v = 0x7fe7;
                }
            }
        } else {
            this.v = 0x7fe7;
        }
    };
    cell.prototype.putIdea = function (idea) {
        this.v = (idea | open | may_b[idea]);
    };
    cell.prototype.copyIn = function (i) {
        this.v = i.v;
    };
    cell.prototype.txt = function () {
        return this.v.toString();
    };
    cell.prototype.yo = function (mask) {
        return ((this.v & mask) !== 0);
    };
    cell.prototype.reset = function (mask) {
        //reset the mask
        this.v &= ~mask;
    };
    cell.prototype.value = function () {
        //value of an open or filled cell
        return (this.v & pk.data);
    };
    cell.prototype.rm = function (i) {
        // returns success or failure (false or true respectively)
        if (this.yo(may_b[i])) {
            //has it in probable
            if (!this.yo(pk.wait)) {
                return true;
                // it is the only probable!!
            }
            this.reset(may_b[i]);
            this.v -= 1;
            if (this.yo(open)) {
                // only one probable left now
                for (i = 0; i < 9; i += 1) {
                    if (this.yo(may_b[i])) {
                        break;
                    }
                }
                this.putIdea(i);
            }
        }
        return false;
        //removed ok
    };
    cell.prototype.trial = function (i) {
        // returns trial value or >=9 if no trial available
        for (; i < 9; i += 1) {
            if (this.yo(may_b[i])) {
                break;
            }
        }
        return i;
    };
    pk.cell = cell;
    //the package globals
    pk.wait = 0x20;
    var open = 0x10;
    pk.data = 0xf;
    var may_b = [
        0x4000, 0x2000, 0x1000,
        0x0800, 0x0400, 0x0200,
        0x0100, 0x0080, 0x0040
    ];
    pk.clr = scope_gen(3);
    //the sud class. models a sudoku
    var sud = function (inp) {
        if (inp) {
            if (typeof inp === "object") {
                this.left = inp.left;
                this.i_v = [];
                for (var i = 0; i < 81; i += 1) {
                    this.i_v[i] = new pk.cell(inp.i_v[i]);
                }
                return;
            } else inp = inp.toString()
        } else inp = '123456789'
        var len = inp.length
        this.left = 81
        this.i_v = []
        var i = 0
        for (; i < len && i < 81; i += 1) {
            this.i_v[i] = new pk.cell(inp.charAt(i))
        }
        for (; i < 81; i += 1) this.i_v[i] = new pk.cell()
        arguments.callee.__out__ = []
    }
    sud.prototype.copyIn = function (t) {
        this.left = t.left;
        for (var i = 0; i < 81; i += 1) this.i_v[i].copyIn(t.i_v[
            i]);
    }
    sud.prototype.first = function () {
        // first waiting cell or >=81; for ordered listing of solutions
        var i = 0
        for (; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.wait)) {
                break;
            }
        }
        return i
    }
    sud.prototype.idea = function () {
        //first open cell or >=81
        var i = 0
        for (; i < 81; i += 1) {
            if (this.i_v[i].yo(open)) {
                break
            }
        }
        return i
    }
    sud.prototype.toString = function () {
        var buf = ''
        for (var i = 0; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.cell.open)) {
                buf += '?';
            } else {
                buf += (1 + this.i_v[i].value());
            }
        }
        return buf;
    }
    sud.prototype.hook = function () {
        // returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
        var x, pos, val
        while ((pos = this.idea()) < 81) {
            val = this.i_v[pos].value()
            for (x = 0; x < 20; x += 1) {
                if (this.i_v[pk.clr[pos][x]].rm(val)) {
                    return -1;
                }
            }
            this.i_v[pos].reset(open)
            if ((this.left -= 1) === 0) {
                this.constructor.__out__.push(this.toString())
                return this.constructor.__out__.length === this.constructor
                    .__n__ ? 2 : 1;
            }
        }
        return 0
    }
    sud.prototype.crook = function () {
        var mc, cc, pos, val = 0
        var copy = new pk.sud(this)
        if ((pos = this.first()) < 81) {
            mc = this.i_v[pos]
            cc = copy.i_v[pos]
        } else return 1
        while ((val = mc.trial(val)) < 9) {
            copy.copyIn(this)
            cc.putIdea(val)
            switch (copy.squash()) {
            case 1:
                val += 1
                break
            case 2:
                return 2
            case -1:
                mc.rm(val) // should i check?
                if (
                        ((pos = this.idea()) < 81)
                        &&
                        (this.i_v[pos].value() > val)
                ) {
                    copy = null
                    return 0
                }
            }
        }
        copy = null
        return 1
    }
    sud.prototype.squash = function () {
        var ret
        do
            if ((ret = this.hook()) !== 0) return ret;
        while (0 === (ret = this.crook())) return ret
    }
    pk.sud = sud;
    //the list class. subclass of sud.
    //solution lister engine
    //an iterator
    var list = function (inp) {
        // calling superclass constructor
        pk.sud.call(this, inp)
        this.status = function (ls, pos, val) {
            this.l = new pk.list(ls)
            this.p = pos
            this.v = val
        }
        if (typeof inp === 'object') return
        pk.nxt = []
        switch (this.squash()) {
        case -1:
            break
        case 2:
        }
    }
    // subclass extends superclass
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
    list.prototype = Object.create(pk.sud.prototype)
    list.prototype.constructor = list
    list.prototype.hook = function () {
        // returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
        var x, pos, val
        if (pk.stata) {
            if (pk.stata.length === 0) {
                delete pk.stata
                return 1
            } else return 0
        }
        while ((pos = this.idea()) < 81) {
            val = this.i_v[pos].value()
            for (x = 0; x < 20; x += 1) {
                if (this.i_v[pk.clr[pos][x]].rm(val)) return -1
            } // try removing braces
            this.i_v[pos].reset(open)
            if ((this.left -= 1) === 0) {
                pk.nxt.push(this.toString())
                if (pk.nxt.length === pk.n) {
                    pk.stata = []
                    // i hope empty array is true in js
                    return 2
                } else return 1
            }
        }
        return 0
    }
    list.prototype.crook = function () {
        var mc, cc, pos, val = 0,
            copy
        if (pk.stata) {
            copy = pk.stata.pop();
            mc = this.i_v[copy.p];
            cc = copy.l.i_v[copy.p];
        } else {
            if ((pos = this.first()) >= 81) return 1
            else {
                copy = new this.status(this, pos, 0)
                mc = this.i_v[copy.p]
                cc = copy.l.i_v[copy.p]
            }
        }
        while (pk.stata || ((copy.v = mc.trial(copy.v)) < 9)) {
            if (!pk.stata) {
                copy.l.copyIn(this);
                cc.putIdea(copy.v);
            }
            switch (copy.l.squash()) {
            case 1:
                copy.v += 1;
                break;
            case 2:
                pk.stata.push(copy);
                return 2;
            case -1:
                mc.rm(copy.v); /* should i check? */
                if (
                    ((pos = this.idea()) < 81) && (this.i_v[pos].value() >
                        copy.v)) return 0
            }
        }
        return 1
    }
    list.prototype.next = function () {
        if (pk.nxt.length === 0) return undefined
        pk.out = pk.nxt
        pk.nxt = []
        this.squash()
        return pk.out
    }
    list.prototype.hasNext = function () {
        return pk.nxt.length !== 0;
    }
    pk.list = list;
    //exports

    var o = {};
    o.iter = function (constraints, n) {
        pk.n = n || 2
        return new pk.list(constraints)
    }
    o.list = function (constraints, n) {
        var master = new pk.sud(constraints)
        master.constructor.__n__ = n || 2;
        switch (master.squash()) {
        case -1:
            console.log("no solution")
            break
        case 2:
        }
        return master.constructor.__out__
    }
    return o;
});
/*
TODO:
change pk.nxt pk.out pk.n pk.stata. /pk\.[^.]* /
change /stat/
for class list
use ed
add semicolons to statements
add braces to loop or if/else bodies
use semver.org and publish to npm
*/
<|endoftext|>


<commit_before>var EditorBaseView = require('./editor-base-view');
var ENTER_KEY_CODE = 13;

module.exports = EditorBaseView.extend({

  tagName: 'textarea',
  className: 'Table-editorTextarea CDB-Textarea CDB-Text',

  _onKeyPressed: function (ev) {
    if (!ev.shiftKey && ev.which === ENTER_KEY_CODE) {
      this._editorModel.confirm();
    }
  }

});
<commit_msg>Fixed for enter key press<commit_after>var EditorBaseView = require('./editor-base-view');
var ENTER_KEY_CODE = 13;

module.exports = EditorBaseView.extend({

  tagName: 'textarea',
  className: 'Table-editorTextarea CDB-Textarea CDB-Text',

  _onKeyPressed: function (ev) {
    if (!ev.shiftKey && ev.which === ENTER_KEY_CODE) {
      this._onValueChange();
      this._editorModel.confirm();
    }
  }

});
<|endoftext|>


<commit_before>import React from 'react';

import {getDashboards} from '../apis';

const DashboardsPage = React.createClass({
  getInitialState() {
    return {
      dashboards: [],
    };
  },

  componentDidMount() {
    getDashboards().then((dashboards) => {
      this.setState({
        dashboards,
      });
    });
  },

  render() {
    let tableHeader;
    if (this.state.dashboards.length === 0) {
      tableHeader = "Loading Dashboards...";
    } else {
      tableHeader = `${this.state.dashboards.length} Dashboards`;
    }

    return (

                Dashboards

{tableHeader}

                          Name

                          {
                            this.state.dashboards.map((dashboard) => {
                              return (

                                  {dashboard.name}

                              );
                            })
                          }

    );
  },
});

export default DashboardsPage;
<commit_msg>Use the dashboard ID for the iterator key<commit_after>import React from 'react';

import {getDashboards} from '../apis';

const DashboardsPage = React.createClass({
  getInitialState() {
    return {
      dashboards: [],
    };
  },

  componentDidMount() {
    getDashboards().then((dashboards) => {
      this.setState({
        dashboards,
      });
    });
  },

  render() {
    let tableHeader;
    if (this.state.dashboards.length === 0) {
      tableHeader = "Loading Dashboards...";
    } else {
      tableHeader = `${this.state.dashboards.length} Dashboards`;
    }

    return (

                Dashboards

{tableHeader}

                          Name

                          {
                            this.state.dashboards.map((dashboard) => {
                              return (

                                  {dashboard.name}

                              );
                            })
                          }

    );
  },
});

export default DashboardsPage;
<|endoftext|>


<commit_before>'use strict';

var geoHashingApp = angular.module('GeoHashingApp', ['ngRoute', 'yaMap', 'textAngular', 'ui.router']);

geoHashingApp.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise("/");
    //
    // Now set up the states
    $stateProvider
        .state('main_state', {
            url: "/",
            templateUrl: 'views/main.html',
            controller: 'MarkersListCtrl',
            data:{
                needAuth:  false
            }
        })
        .state('edit_marker', {
            url: '/edit/marker/:id',
            templateUrl: 'views/edit_marker.html',
            controller: 'EditMarkerCtrl',
            data:{
                needAuth:  true
            }
        })
        .state('add_marker', {
            url: '/add/marker',
            templateUrl: 'views/edit_marker.html',
            controller: 'EditMarkerCtrl',
            data:{
                needAuth:  true
            }
        })
        .state('show_marker',{
            url: '/show/:id',
            templateUrl: 'views/single_marker_view.html',
            controller: 'SingleMarkerViewCtrl',
            data:{
                needAuth:  false
            }
        });
});

geoHashingApp.run(function($rootScope, $location, AuthenticationService) {

    // enumerate routes that don't need authentication
    var routesThatDontRequireAuth = ['/login'];

    // check if current location matches route
    var routeClean = function (route) {
        return _.find(routesThatDontRequireAuth,
            function (noAuthRoute) {
                return _.str.startsWith(route, noAuthRoute);
            });
    };

    $rootScope.$on('$stateChangeStart', function (ev, to, toParams, from, fromParams) {
        // if route requires auth and user is not logged in
        if (!routeClean($location.url()) && !AuthenticationService.isLoggedIn()) {
            // redirect back to login
            $location.path('/login');
        }
    });
});<commit_msg>master Intercept change state event and check a state of an application<commit_after>'use strict';

var geoHashingApp = angular.module('GeoHashingApp', ['ngRoute', 'yaMap', 'textAngular', 'ui.router']);

geoHashingApp.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise("/");
    //
    // Now set up the states
    $stateProvider
        .state('main_state', {
            url: "/",
            templateUrl: 'views/main.html',
            controller: 'MarkersListCtrl',
            data:{
                needAuth:  false
            }
        })
        .state('edit_marker', {
            url: '/edit/marker/:id',
            templateUrl: 'views/edit_marker.html',
            controller: 'EditMarkerCtrl',
            data:{
                needAuth:  true
            }
        })
        .state('add_marker', {
            url: '/add/marker',
            templateUrl: 'views/edit_marker.html',
            controller: 'EditMarkerCtrl',
            data:{
                needAuth:  true
            }
        })
        .state('show_marker',{
            url: '/show/:id',
            templateUrl: 'views/single_marker_view.html',
            controller: 'SingleMarkerViewCtrl',
            data:{
                needAuth:  false
            }
        });
});

geoHashingApp.run(function($rootScope, $location, AuthenticationService) {

   $rootScope.$on('$stateChangeStart', function (ev, to, toParams, from, fromParams) {
        // if route requires auth and user is not logged in
        if (to.data.needAuth && !AuthenticationService.isLoggedIn()) {
            // redirect back to login
            $location.path('/login');
        }
    });
});<|endoftext|>


<commit_before>(function(window, document, exportName, undefined) {
    "use strict";

    var isMultiTouch = false;
    var multiTouchStartPos;
    var eventTarget;
    var touchElements = {};

    // polyfills
    if(!document.createTouch) {
        document.createTouch = function(view, target, identifier, pageX, pageY, screenX, screenY, clientX, clientY) {
            // auto set
            if(clientX == undefined || clientY == undefined) {
                clientX = pageX - window.pageXOffset;
                clientY = pageY - window.pageYOffset;
            }

            return new Touch(target, identifier, {
                pageX: pageX,
                pageY: pageY,
                screenX: screenX,
                screenY: screenY,
                clientX: clientX,
                clientY: clientY
            });
        };
    }

    if(!document.createTouchList) {
        document.createTouchList = function() {
            var touchList = new TouchList();
            for (var i = 0; i < arguments.length; i++) {
                touchList[i] = arguments[i];
            }
            touchList.length = arguments.length;
            return touchList;
        };
    }

    /**
     * Simple trick to fake touch event support
     * this is enough for most libraries like Modernizr and Hammer
     */
    function fakeTouchSupport() {
        if (!("ontouchstart" in window)) {
            window.ontouchstart = null;
            window.ontouchmove = null;
            window.ontouchcancel = null;
            window.ontouchend = null;

            document.documentElement.ontouchstart = null;
            document.documentElement.ontouchmove = null;
            document.documentElement.ontouchcancel = null;
            document.documentElement.ontouchend = null;
        }
    }

    /**
     * we don't have to emulate on a touch device
     * @returns {boolean}
     */
    function hasTouchSupport() {
        return ("ontouchstart" in window) || // touch events
               (window.Modernizr && window.Modernizr.touch) || // modernizr
               (navigator.msMaxTouchPoints || navigator.maxTouchPoints) > 2; // pointer events
    }

    /**
     * setup mouse events on the window
     */
    function setMouseEvents() {
        window.addEventListener("mousedown", onMouse('touchstart'), false);
        window.addEventListener("mousemove", onMouse('touchmove'), false);
        window.addEventListener("mouseup", onMouse('touchend'), false);
    }

    /**
     * only trigger touches when the left mousebutton has been pressed
     * @param touchType
     * @returns {Function}
     */
    function onMouse(touchType) {
        return function(ev) {
            if (ev.which !== 1) {
                return;
            }

            // The EventTarget on which the touch point started when it was first placed on the surface,
            // even if the touch point has since moved outside the interactive area of that element.
            // also, when the target doesnt exist anymore, we update it
            if (ev.type == 'mousedown' || !eventTarget || (eventTarget && !eventTarget.dispatchEvent)) {
                eventTarget = ev.target;
            }

            // shiftKey has been lost, so trigger a touchend
            if (isMultiTouch && !ev.shiftKey) {
                triggerTouch('touchend', ev);
                isMultiTouch = false;
            }

            triggerTouch(touchType, ev);

            // we're entering the multi-touch mode!
            if (!isMultiTouch && ev.shiftKey) {
                isMultiTouch = true;
                multiTouchStartPos = {
                    pageX: ev.pageX,
                    pageY: ev.pageY,
                    clientX: ev.clientX,
                    clientY: ev.clientY,
                    screenX: ev.screenX,
                    screenY: ev.screenY
                };
                triggerTouch('touchstart', ev);
            }

            // reset
            if (ev.type == 'mouseup') {
                multiTouchStartPos = null;
                isMultiTouch = false;
                eventTarget = null;
            }
        }
    }

    /**
     * trigger a touch event
     * @param eventName
     * @param mouseEv
     */
    function triggerTouch(eventName, mouseEv) {
        var touchEvent = document.createEvent('Event');
        touchEvent.initEvent(eventName, true, true);

        touchEvent.altKey = mouseEv.altKey;
        touchEvent.ctrlKey = mouseEv.ctrlKey;
        touchEvent.metaKey = mouseEv.metaKey;
        touchEvent.shiftKey = mouseEv.shiftKey;

        touchEvent.touches = getActiveTouches(mouseEv, eventName);
        touchEvent.targetTouches = getActiveTouches(mouseEv, eventName);
        touchEvent.changedTouches = getChangedTouches(mouseEv, eventName);

        eventTarget.dispatchEvent(touchEvent);
    }

    /**
     * create empty touchlist with the methods
     * @constructor
     * @returns touchlist
     */
    function TouchList() {
        this.item = function(index) {
            return this[index] || null;
        };

        // specified by Mozilla
        this.identifiedTouch = function(id) {
            return this[id + 1] || null;
        };

        this.length = 0;
    }

    /**
     * create a touchList based on the mouse event
     * @param mouseEv
     * @returns {TouchList}
     */
    function createTouchList(mouseEv) {
        var touchList = document.createTouchList();

        if (isMultiTouch) {
            var f = TouchEmulator.multiTouchOffset;
            var deltaX = multiTouchStartPos.pageX - mouseEv.pageX;
            var deltaY = multiTouchStartPos.pageY - mouseEv.pageY;

            touchList[0] = (new Touch(eventTarget, 1, multiTouchStartPos, (deltaX*-1) - f, (deltaY*-1) + f));
            touchList[1] = (new Touch(eventTarget, 2, multiTouchStartPos, deltaX+f, deltaY-f));
            touchList.length = 2;
        } else {
            touchList[0] = (new Touch(eventTarget, 1, mouseEv, 0, 0));
            touchList.length = 1;
        }

        return touchList;
    }

    /**
     * create an touch point
     * @constructor
     * @param target
     * @param identifier
     * @param position
     * @param deltaX
     * @param deltaY
     * @returns {Object} touchPoint
     */
    function Touch(target, identifier, position, deltaX, deltaY) {
        deltaX = deltaX || 0;
        deltaY = deltaY || 0;

        this.identifier = identifier;
        this.target = target;
        this.clientX = position.clientX + deltaX;
        this.clientY = position.clientY + deltaY;
        this.screenX = position.screenX + deltaX;
        this.screenY = position.screenY + deltaY;
        this.pageX = position.pageX + deltaX;
        this.pageY = position.pageY + deltaY;
    }

    /**
     * receive all active touches
     * @param mouseEv
     * @returns {TouchList}
     */
    function getActiveTouches(mouseEv, eventName) {
        if (mouseEv.type == 'mouseup') {
            return document.createTouchList();
        }

        var touchList = createTouchList(mouseEv);
        if(isMultiTouch && mouseEv.type != 'mouseup' && eventName == 'touchend') {
            delete touchList[1];
            touchList.length = 1;
        }
        return touchList;
    }

    /**
     * receive a filtered set of touches with only the changed pointers
     * @param mouseEv
     * @param eventName
     * @returns {TouchList}
     */
    function getChangedTouches(mouseEv, eventName) {
        var touchList = createTouchList(mouseEv);

        // we only want to return the added/removed item on multitouch
        // which is the second pointer, so remove the first pointer from the touchList
        //
        // but when the mouseEv.type is mouseup, we want to send all touches because then
        // no new input will be possible
        if(isMultiTouch && mouseEv.type != 'mouseup' &&
            (eventName == 'touchstart' || eventName == 'touchend')) {
            touchList[0] = touchList[1];
            touchList.length = 1;
        }

        return touchList;
    }

    /**
     * setup touch events on the window
     * this means that the script is using itself!
     */
    function setTouchEvents() {
        window.addEventListener("touchstart", showTouches, false);
        window.addEventListener("touchmove", showTouches, false);
        window.addEventListener("touchend", showTouches, false);
        window.addEventListener("touchcancel", showTouches, false);
    }

    /**
     * show the touchpoints on the screen
     */
    function showTouches(ev) {
        var touch, i, el, styles;

        // first all visible touches
        for(i = 0; i < ev.touches.length; i++) {
            touch = ev.touches[i];
            el = touchElements[touch.identifier];
            if(!el) {
                el = touchElements[touch.identifier] = document.createElement("div");
                document.body.appendChild(el);
            }

            styles = TouchEmulator.template(touch);
            for(var prop in styles) {
                el.style[prop] = styles[prop];
            }
        }

        // remove all ended touches
        if(ev.type == 'touchend' || ev.type == 'touchcancel') {
            for(i = 0; i < ev.changedTouches.length; i++) {
                touch = ev.changedTouches[i];
                el = touchElements[touch.identifier];
                if(el) {
                    el.parentNode.removeChild(el);
                    delete touchElements[touch.identifier];
                }
            }
        }
    }

    /**
     * TouchEmulator initializer
     */
    function TouchEmulator() {
        if (hasTouchSupport()) {
            return;
        }

        fakeTouchSupport();
        setMouseEvents();
        setTouchEvents();
    }

    // start distance when entering the multitouch mode
    TouchEmulator.multiTouchOffset = 75;

    /**
     * css template for the touch rendering
     * @param touch
     * @returns object
     */
    TouchEmulator.template = function(touch) {
        var size = 30;
        var transform = 'translate('+ (touch.clientX-(size/2)) +'px, '+ (touch.clientY-(size/2)) +'px)';
        return {
            position: 'fixed',
            left: 0,
            top: 0,
            background: '#fff',
            border: 'solid 1px #999',
            opacity: .6,
            borderRadius: '100%',
            height: size + 'px',
            width: size + 'px',
            padding: 0,
            margin: 0,
            display: 'block',
            overflow: 'hidden',
            pointerEvents: 'none',
            webkitUserSelect: 'none',
            mozUserSelect: 'none',
            userSelect: 'none',
            webkitTransform: transform,
            mozTransform: transform,
            transform: transform
        }
    };

    // export
    if (typeof define == "function" && define.amd) {
        define(function() {
            return TouchEmulator;
        });
    } else if (typeof module != "undefined" && module.exports) {
        module.exports = TouchEmulator;
    } else {
        window[exportName] = TouchEmulator;
    }
})(window, document, "TouchEmulator");
<commit_msg>refactor<commit_after>(function(window, document, exportName, undefined) {
    "use strict";

    var isMultiTouch = false;
    var multiTouchStartPos;
    var eventTarget;
    var touchElements = {};

    // polyfills
    if(!document.createTouch) {
        document.createTouch = function(view, target, identifier, pageX, pageY, screenX, screenY, clientX, clientY) {
            // auto set
            if(clientX == undefined || clientY == undefined) {
                clientX = pageX - window.pageXOffset;
                clientY = pageY - window.pageYOffset;
            }

            return new Touch(target, identifier, {
                pageX: pageX,
                pageY: pageY,
                screenX: screenX,
                screenY: screenY,
                clientX: clientX,
                clientY: clientY
            });
        };
    }

    if(!document.createTouchList) {
        document.createTouchList = function() {
            var touchList = new TouchList();
            for (var i = 0; i < arguments.length; i++) {
                touchList[i] = arguments[i];
            }
            touchList.length = arguments.length;
            return touchList;
        };
    }

    /**
     * create an touch point
     * @constructor
     * @param target
     * @param identifier
     * @param pos
     * @param deltaX
     * @param deltaY
     * @returns {Object} touchPoint
     */
    function Touch(target, identifier, pos, deltaX, deltaY) {
        deltaX = deltaX || 0;
        deltaY = deltaY || 0;

        this.identifier = identifier;
        this.target = target;
        this.clientX = pos.clientX + deltaX;
        this.clientY = pos.clientY + deltaY;
        this.screenX = pos.screenX + deltaX;
        this.screenY = pos.screenY + deltaY;
        this.pageX = pos.pageX + deltaX;
        this.pageY = pos.pageY + deltaY;
    }

    /**
     * create empty touchlist with the methods
     * @constructor
     * @returns touchList
     */
    function TouchList() {
        var touchList = [];

        touchList.item = function(index) {
            return this[index] || null;
        };

        // specified by Mozilla
        touchList.identifiedTouch = function(id) {
            return this[id + 1] || null;
        };

        return touchList;
    }

    /**
     * Simple trick to fake touch event support
     * this is enough for most libraries like Modernizr and Hammer
     */
    function fakeTouchSupport() {
        var objs = [window, document.documentElement];
        var props = ['ontouchstart', 'ontouchmove', 'ontouchcancel', 'ontouchend'];

        for(var o=0; o<objs.length; o++) {
            for(var p=0; p<props.length; p++) {
                if(objs[o] && objs[o][props[p]] == undefined) {
                    objs[o][props[p]] = null;
                }
            }
        }
    }

    /**
     * we don't have to emulate on a touch device
     * @returns {boolean}
     */
    function hasTouchSupport() {
        return ("ontouchstart" in window) || // touch events
               (window.Modernizr && window.Modernizr.touch) || // modernizr
               (navigator.msMaxTouchPoints || navigator.maxTouchPoints) > 2; // pointer events
    }

    /**
     * only trigger touches when the left mousebutton has been pressed
     * @param touchType
     * @returns {Function}
     */
    function onMouse(touchType) {
        return function(ev) {
            if (ev.which !== 1) {
                return;
            }

            // The EventTarget on which the touch point started when it was first placed on the surface,
            // even if the touch point has since moved outside the interactive area of that element.
            // also, when the target doesnt exist anymore, we update it
            if (ev.type == 'mousedown' || !eventTarget || (eventTarget && !eventTarget.dispatchEvent)) {
                eventTarget = ev.target;
            }

            // shiftKey has been lost, so trigger a touchend
            if (isMultiTouch && !ev.shiftKey) {
                triggerTouch('touchend', ev);
                isMultiTouch = false;
            }

            triggerTouch(touchType, ev);

            // we're entering the multi-touch mode!
            if (!isMultiTouch && ev.shiftKey) {
                isMultiTouch = true;
                multiTouchStartPos = {
                    pageX: ev.pageX,
                    pageY: ev.pageY,
                    clientX: ev.clientX,
                    clientY: ev.clientY,
                    screenX: ev.screenX,
                    screenY: ev.screenY
                };
                triggerTouch('touchstart', ev);
            }

            // reset
            if (ev.type == 'mouseup') {
                multiTouchStartPos = null;
                isMultiTouch = false;
                eventTarget = null;
            }
        }
    }

    /**
     * trigger a touch event
     * @param eventName
     * @param mouseEv
     */
    function triggerTouch(eventName, mouseEv) {
        var touchEvent = document.createEvent('Event');
        touchEvent.initEvent(eventName, true, true);

        touchEvent.altKey = mouseEv.altKey;
        touchEvent.ctrlKey = mouseEv.ctrlKey;
        touchEvent.metaKey = mouseEv.metaKey;
        touchEvent.shiftKey = mouseEv.shiftKey;

        touchEvent.touches = getActiveTouches(mouseEv, eventName);
        touchEvent.targetTouches = getActiveTouches(mouseEv, eventName);
        touchEvent.changedTouches = getChangedTouches(mouseEv, eventName);

        eventTarget.dispatchEvent(touchEvent);
    }

    /**
     * create a touchList based on the mouse event
     * @param mouseEv
     * @returns {TouchList}
     */
    function createTouchList(mouseEv) {
        var touchList = new TouchList();

        if (isMultiTouch) {
            var f = TouchEmulator.multiTouchOffset;
            var deltaX = multiTouchStartPos.pageX - mouseEv.pageX;
            var deltaY = multiTouchStartPos.pageY - mouseEv.pageY;

            touchList.push(new Touch(eventTarget, 1, multiTouchStartPos, (deltaX*-1) - f, (deltaY*-1) + f));
            touchList.push(new Touch(eventTarget, 2, multiTouchStartPos, deltaX+f, deltaY-f));
        } else {
            touchList.push(new Touch(eventTarget, 1, mouseEv, 0, 0));
        }

        return touchList;
    }

    /**
     * receive all active touches
     * @param mouseEv
     * @returns {TouchList}
     */
    function getActiveTouches(mouseEv, eventName) {
        // empty list
        if (mouseEv.type == 'mouseup') {
            return new TouchList();
        }

        var touchList = createTouchList(mouseEv);
        if(isMultiTouch && mouseEv.type != 'mouseup' && eventName == 'touchend') {
            touchList.splice(1, 1);
        }
        return touchList;
    }

    /**
     * receive a filtered set of touches with only the changed pointers
     * @param mouseEv
     * @param eventName
     * @returns {TouchList}
     */
    function getChangedTouches(mouseEv, eventName) {
        var touchList = createTouchList(mouseEv);

        // we only want to return the added/removed item on multitouch
        // which is the second pointer, so remove the first pointer from the touchList
        //
        // but when the mouseEv.type is mouseup, we want to send all touches because then
        // no new input will be possible
        if(isMultiTouch && mouseEv.type != 'mouseup' &&
            (eventName == 'touchstart' || eventName == 'touchend')) {
            touchList.splice(0, 1);
        }

        return touchList;
    }

    /**
     * show the touchpoints on the screen
     */
    function showTouches(ev) {
        var touch, i, el, styles;

        // first all visible touches
        for(i = 0; i < ev.touches.length; i++) {
            touch = ev.touches[i];
            el = touchElements[touch.identifier];
            if(!el) {
                el = touchElements[touch.identifier] = document.createElement("div");
                document.body.appendChild(el);
            }

            styles = TouchEmulator.template(touch);
            for(var prop in styles) {
                el.style[prop] = styles[prop];
            }
        }

        // remove all ended touches
        if(ev.type == 'touchend' || ev.type == 'touchcancel') {
            for(i = 0; i < ev.changedTouches.length; i++) {
                touch = ev.changedTouches[i];
                el = touchElements[touch.identifier];
                if(el) {
                    el.parentNode.removeChild(el);
                    delete touchElements[touch.identifier];
                }
            }
        }
    }

    /**
     * TouchEmulator initializer
     */
    function TouchEmulator() {
        if (hasTouchSupport()) {
            return;
        }

        fakeTouchSupport();

        window.addEventListener("mousedown", onMouse('touchstart'), false);
        window.addEventListener("mousemove", onMouse('touchmove'), false);
        window.addEventListener("mouseup", onMouse('touchend'), false);

        // it uses itself!
        window.addEventListener("touchstart", showTouches, false);
        window.addEventListener("touchmove", showTouches, false);
        window.addEventListener("touchend", showTouches, false);
        window.addEventListener("touchcancel", showTouches, false);
    }

    // start distance when entering the multitouch mode
    TouchEmulator.multiTouchOffset = 75;

    /**
     * css template for the touch rendering
     * @param touch
     * @returns object
     */
    TouchEmulator.template = function(touch) {
        var size = 30;
        var transform = 'translate('+ (touch.clientX-(size/2)) +'px, '+ (touch.clientY-(size/2)) +'px)';
        return {
            position: 'fixed',
            left: 0,
            top: 0,
            background: '#fff',
            border: 'solid 1px #999',
            opacity: .6,
            borderRadius: '100%',
            height: size + 'px',
            width: size + 'px',
            padding: 0,
            margin: 0,
            display: 'block',
            overflow: 'hidden',
            pointerEvents: 'none',
            webkitUserSelect: 'none',
            mozUserSelect: 'none',
            userSelect: 'none',
            webkitTransform: transform,
            mozTransform: transform,
            transform: transform
        }
    };

    // export
    if (typeof define == "function" && define.amd) {
        define(function() {
            return TouchEmulator;
        });
    } else if (typeof module != "undefined" && module.exports) {
        module.exports = TouchEmulator;
    } else {
        window[exportName] = TouchEmulator;
    }
})(window, document, "TouchEmulator");
<|endoftext|>


<commit_before>import React, {PropTypes, Component} from 'react'

import { getModeIcon } from '../../util/itinerary'

export default class ModeButton extends Component {
  static propTypes = {
    active: PropTypes.bool,
    label: PropTypes.string,
    mode: PropTypes.string,
    icons: PropTypes.object,
    onClick: PropTypes.func
  }

  render () {
    const {active, icons, label, mode, onClick} = this.props
    const buttonColor = active ? '#000' : '#bbb'
    console.log(icons);
    console.log('>> getting mode icon for ', mode);
    return (

        <button
          className='mode-button'
          onClick={onClick}
          title={mode}
          style={{ borderColor: buttonColor }}
        >

            {getModeIcon(mode, icons)}

        </button>

{label}

        {active &&

}

    )
  }
}
<commit_msg>style(debug): Remove debugging console.logs<commit_after>import React, {PropTypes, Component} from 'react'

import { getModeIcon } from '../../util/itinerary'

export default class ModeButton extends Component {
  static propTypes = {
    active: PropTypes.bool,
    label: PropTypes.string,
    mode: PropTypes.string,
    icons: PropTypes.object,
    onClick: PropTypes.func
  }

  render () {
    const {active, icons, label, mode, onClick} = this.props
    const buttonColor = active ? '#000' : '#bbb'
    return (

        <button
          className='mode-button'
          onClick={onClick}
          title={mode}
          style={{ borderColor: buttonColor }}
        >

            {getModeIcon(mode, icons)}

        </button>

{label}

        {active &&

}

    )
  }
}
<|endoftext|>


<commit_before>"use strict";
var etg = require("./etg");
var Cards = require("./Cards");
var etgutil = require("./etgutil");
var elecols = [
	"#a98", "#a59", "#768", "#963", "#654", "#5a0", "#c52", "#258", "#887", "#38d", "#ca2", "#333", "#5ac",
	"#dcb", "#dbc", "#bac", "#cb9", "#ba9", "#ac7", "#da8", "#8ac", "#ccb", "#9be", "#ed8", "#999", "#ade"];
var cssPrefix = ""+ret+"</svg>";
}
exports.deck = function(deck){
	function classString(){
		var ret = "";
		for(var cls in classes){
			ret += "."+cls+"{"+classes[cls]+"}";
		}
		return ret;
	}
	var prefix = "<svg xmlns='http://www.w3.org/2000/svg'",
		texts="", x=16, y=0, classes = {}, mark, paths = {}, suffix, pathsvg="";
	etgutil.iterdeck(deck, function(code){
		if (!(code in Cards.Codes)){
			var ismark = etg.fromTrueMark(code);
			if (~ismark) mark = ismark;
			return;
		}
		var card = Cards.Codes[code];
		var elech = eleChar(card), elecls = (card.shiny?"A":"B") + " " + elech;
		if (card.shiny) classes.A = "stroke:#daa520;stroke-width:.5";
		else classes.B = "stroke:black;stroke-width:.5";
		classes[elech] = "fill:"+elecols[card.element+(card.upped?13:0)];
		var textColor = card.upped ? "" : " fill='#fff'";
		if (!paths[elecls]) paths[elecls]="";
		paths[elecls]+="M"+x+" "+y+"h100v16h-100";
		texts += "<text x='" + (x+2) + "' y='" + (y+13) + "'" + textColor + ">" + card.name + "</text>";
		y += 16;
		if (y == 160){
			y=0;
			x+=100;
		}
	});
	for (var elecls in paths){
		pathsvg += "<path class='"+elecls+"' d='"+paths[elecls]+"'/>";
	}
	if (mark !== undefined){
		var cls = String.fromCharCode(97+mark);
		classes[cls] = "fill:"+elecols[mark];
		suffix = "<path class='"+cls+"' d='M0 0h16v160H0'/><text x='5' y='-4' transform='rotate(90)'"+(~[0,8,10,12].indexOf(mark)?"":" fill='#fff'")+">"+etg.eleNames[mark]+"</text></svg>";
	}else suffix = "</svg>"
	return prefix+" height='160' width='"+(y?x+100:x)+"'>"+cssPrefix+classString()+"]]></style>"+pathsvg+texts+suffix;
}
<commit_msg>Tighter SVG card code<commit_after>"use strict";
var etg = require("./etg");
var Cards = require("./Cards");
var etgutil = require("./etgutil");
var elecols = [
	"#a98", "#a59", "#768", "#963", "#654", "#5a0", "#c52", "#258", "#887", "#38d", "#ca2", "#333", "#5ac",
	"#dcb", "#dbc", "#bac", "#cb9", "#ba9", "#ac7", "#da8", "#8ac", "#ccb", "#9be", "#ed8", "#999", "#ade"];
var cssPrefix = "<image xlink:href='../assets/cardBacks.png' x='"+(card.element+card.upped*13)*-128+"' width='3328' height='256'/><text x='2' y='15'"+textColor+">"+card.name+"</text>" + (card.cost ? "<text x='108' y='15'"+textColor+">"+card.cost+"</text>" : "") +
		"<image xlink:href='../Cards/"+etgutil.asShiny(etgutil.asUpped(code, false), false).toString(32)+".png' y='20' width='128' height='128'/>" +
		"<foreignObject x='2' y='140' width='124' height='116' requiredExtensions='http://www.w3.org/1999/xhtml'>
" +
		card.info().replace(/\|/g, " | ").replace(/(\d\d?):(\d+)/g, "$1") +
		(card.rarity ? "" : "") +
		"
</foreignObject></svg>";
}
exports.deck = function(deck){
	function classString(){
		var ret = "";
		for(var cls in classes){
			ret += "."+cls+"{"+classes[cls]+"}";
		}
		return ret;
	}
	var prefix = "<svg xmlns='http://www.w3.org/2000/svg'",
		texts="", x=16, y=0, classes = {}, mark, paths = {}, suffix, pathsvg="";
	etgutil.iterdeck(deck, function(code){
		if (!(code in Cards.Codes)){
			var ismark = etg.fromTrueMark(code);
			if (~ismark) mark = ismark;
			return;
		}
		var card = Cards.Codes[code];
		var elech = eleChar(card), elecls = (card.shiny?"A":"B") + " " + elech;
		if (card.shiny) classes.A = "stroke:#daa520;stroke-width:.5";
		else classes.B = "stroke:black;stroke-width:.5";
		classes[elech] = "fill:"+elecols[card.element+(card.upped?13:0)];
		var textColor = card.upped ? "" : " fill='#fff'";
		if (!paths[elecls]) paths[elecls]="";
		paths[elecls]+="M"+x+" "+y+"h100v16h-100";
		texts += "<text x='" + (x+2) + "' y='" + (y+13) + "'" + textColor + ">" + card.name + "</text>";
		y += 16;
		if (y == 160){
			y=0;
			x+=100;
		}
	});
	for (var elecls in paths){
		pathsvg += "<path class='"+elecls+"' d='"+paths[elecls]+"'/>";
	}
	if (mark !== undefined){
		var cls = String.fromCharCode(97+mark);
		classes[cls] = "fill:"+elecols[mark];
		suffix = "<path class='"+cls+"' d='M0 0h16v160H0'/><text x='5' y='-4' transform='rotate(90)'"+(~[0,8,10,12].indexOf(mark)?"":" fill='#fff'")+">"+etg.eleNames[mark]+"</text></svg>";
	}else suffix = "</svg>"
	return prefix+" height='160' width='"+(y?x+100:x)+"'>"+cssPrefix+classString()+"]]></style>"+pathsvg+texts+suffix;
}
<|endoftext|>


<commit_before>(function() {

  'use strict';

function gameLoop () {
    window.requestAnimationFrame(gameLoop);
    window.goomba.render();
    window.goomba.moveX();
    window.goomba.moveY();
    window.goomba.collisionDetection();
}

// goomba_tilemap.addEventListener('load', gameLoop);
for (let i = 0; i < 1000; i++ ) {
  gameLoop();
}

}());
<commit_msg>Animation loops, but doesn't animate<commit_after>(function() {

  'use strict';

function gameLoop () {
    window.goomba.render();
    window.goomba.moveX();
    window.goomba.moveY();
    window.goomba.collisionDetection();
    window.requestAnimationFrame(gameLoop);

}

// window.goomba.addEventListener('load', gameLoop);
// for (let i = 0; i < 1000; i++ ) {
  window.requestAnimationFrame(gameLoop);
  // gameLoop();
// }

}());
<|endoftext|>