<commit_before>var S	= {
	cssAnimation												: 'webkitAnimationEnd animationend oAnimationEnd',
	cssTransition												: 'webkitTransitionEnd transitionend oTransitionEnd',
	menuY														: 0,
	minCanvasWidth												: 640,
	minMinimalistWidth											: 1080,
	months														: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' ],
	narrow														: false,
	slowLoad													: 5000,

	ready														: function()
	{
		var h	= window.location.hash;

		S.detectBrowser();

		S.findTooltips();
		S.loadPosts();
		S.loadTweets();
		S.drawGradients();
		S.addLettering();
		S.sortScrolling();
		S.addMinimalist();

		S.menuY	= $( '#menubar' ).offset().top;

		$( window ).scroll( S.handleScrolling ).scroll().resize( S.handleResize ).resize();

		$( 'html, body' ).scrollTop( 0 );

		if ( h.length > 0 )
		{
			S.scrollTo( h );
		}
	},

	detectBrowser												: function()
	{
		if ( $.browser.msie )
		{
			$( 'html' ).addClass( 'ie' );

			if ( $.browser.version )
			{
				$( 'html' ).addClass( 'ie' + Number( $.browser.version ) );
			}
			else
			{
				$( 'html' ).addClass( 'ie6' );
			}
		}

		if ( $.browser.webkit )
		{
			$( 'html' ).addClass( 'webkit' );

			if ( navigator.userAgent.indexOf( 'Chrome' ) === -1 )
			{
				$( 'html' ).addClass( 'safari' );
			}
			else
			{
				$( 'html' ).addClass( 'chrome' );
			}
		}

		if ( $.browser.mozilla )
		{
			$( 'html' ).addClass( 'ff' );
		}

		if ( $.browser.opera )
		{
			$( 'html' ).addClass( 'opera' );
		}

		if ( navigator.userAgent.indexOf( 'Windows' ) != -1 )
		{
			$( 'html' ).addClass( 'windows' );
		}
		else if ( navigator.userAgent.indexOf( 'Mac' ) != -1 )
		{
			$( 'html' ).addClass( 'mac' );
		}

		if ( navigator.userAgent.indexOf( 'iPad' ) != -1 )
		{
			$( 'html' ).addClass( 'ipad' );
		}

		$( 'html' ).removeClass( 'no-js' );
	},

	findTooltips												: function()
	{
		$( '[title]' ).each( function()
		{
			var a	= $( this );
			var t	= $( '' + $( this ).attr( 'title' ) + '' ).prepend( '' );

			t.appendTo( a ).css({
				'margin-left'	: ( a.width() - t.outerWidth() ) * .5 + 'px'
			});

			a.removeAttr( 'title' );
		});
	},

	loadPosts													: function()
	{
		var ul	= $( '#posts' );

		if ( !ul.length )
		{
			return;
		}

		var t	= setTimeout( function()
		{
			$( 'li', ul ).append( ' Well, this is magical...' );
		}, S.slowLoad );

		var r	= $.getJSON( '/blog/json/', function(d)
		{
			clearTimeout( t );

			ul.bind( S.cssTransition, function(e)
			{
				var l	= d.length;
				var i;

				ul.unbind( S.cssTransition ).empty();

				for ( i = 0; i < l; i++ )
				{
					ul.append( S.formatPost( d[ i ] ) );
				}

				S.findTooltips();

				ul.removeClass( 'fadeOut' );
			}).addClass( 'fadeOut' );
		});
	},

	formatPost													: function(s)
	{
		var d	= new Date( s[ 'post_date_gmt' ] );

		return '
→ ' + s[ 'post_title' ] + '
';
	},

	truncate													: function(s, l, a)
	{
		return s.length > l ? s.substr( 0, l ) + a : s;
	},

	loadTweets													: function()
	{
		var ul	= $( '#tweets' );

		if ( !ul.length )
		{
			return;
		}

		var t	= setTimeout( function()
		{
			$( 'li', ul ).append( ' Well, this is magical...' );
		}, S.slowLoad );

		var r	= $.getJSON( 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=ahmednuaman&count=5&callback=?', function(d)
		{
			clearTimeout( t );

			ul.bind( S.cssTransition, function()
			{
				var l	= d.length;
				var i;

				ul.unbind( S.cssTransition ).empty();

				for ( i = 0; i < l; i++ )
				{
					ul.append( S.formatTweet( d[ i ] ) );
				}

				S.findTooltips();

				ul.removeClass( 'fadeOut' );
			}).addClass( 'fadeOut' );
		});
	},

	formatTweet													: function(s)
	{
		var d	= new Date( s.created_at );

		return '
→ ' + S.prepareLinks( s.text ) + '
';
	},

	prepareLinks												: function(t, i)
	{
		//t	= t.replace( /&/gim, '&' ).replace( /</gim, '<' ).replace( />/gim, '>' );

		t	= t.replace( /((https?:\/\/|www\.)[^\s]+)/gim, function(m)
		{
			var l	= ( m.indexOf( 'http' ) === -1 ? 'http://' : '' ) + m;

			return '' + m + '';
		});

		t	= t.replace( /\s?(\@[^\s]+)\s?/gim, function(m)
		{
			m		= m.replace( /\s/gim, '' );

			var l	= 'http://twitter.com/' + m;

			return ' ' + m + ' ';
		});

		t	= t.replace( /\s?(\#[^\s]+)\s?/gim, function(m)
		{
			m		= m.replace( /\s/gim, '' );

			var l	= 'http://twitter.com/search?q=' + m;

			return ' ' + m + ' ';
		});

		return t;
	},

	drawGradients												: function()
	{
		if ( !'HTMLCanvasElement' in window )
		{
			return;
		}

		$( '.thumbnail canvas' ).each( function()
		{
			var c	= $( this ).get( 0 ).getContext( '2d' );
			var p	= $( this ).parent();
			var h	= p.outerHeight();
			var w	= p.outerWidth()
			var g;

			$( this ).attr({
				height	: h,
				width	: w
			});

			c.clearRect( 0, 0, w, h );
			c.save();
			c.beginPath();
			c.moveTo(0.0, 383.0);
			c.bezierCurveTo(0.0, 337.5, 0.0, 0.0, 0.0, 0.0);
			c.bezierCurveTo(0.0, 0.0, 501.5, 0.0, 620.0, 0.0);
			c.bezierCurveTo(323.5, 54.0, 113.5, 191.5, 0.0, 383.0);
			c.closePath();
			g = c.createLinearGradient(87.6, -73.5, 343.8, 231.8);
			g.addColorStop(0.00, 'rgba(255, 255, 255, .05)');
			g.addColorStop(1.00, 'rgba(255, 255, 255, .15)');
			c.fillStyle = g;
			c.fill();
			c.restore();
		});
	},

	addLettering												: function()
	{
		$( 'h1' ).lettering();
	},

	handleScrolling												: function()
	{
		var c	= 'fixed';
		var m	= $( '#menubar' );
		var t	= m.hasClass( c );
		var y	= $( window ).scrollTop();

		if ( !t && y > S.menuY )
		{
			m.addClass( c );
		}

		if ( y <= S.menuY )
		{
			m.removeClass( c );
		}
	},

	sortScrolling												: function()
	{
		$( 'a[href^="#"]' ).click( function(e)
		{
			S.scrollTo( e.currentTarget.hash );

			return false;
		});
	},

	addMinimalist												: function()
	{
		$( 'h1' ).click( function()
		{
			if ( S.narrow )
			{
				return;
			}

			$( 'html' ).addClass( 'minimalist' );

			S.reset();
		});
	},

	repositionTooltips											: function()
	{
		$( '.tooltip' ).each( function()
		{
			var t	= $( this );
			var p	= t.parent();

			t.css({
				'margin-left'	: ( p.width() - t.outerWidth() ) * .5 + 'px'
			});
		});
	},

	handleResize												: function()
	{
		var w	= $( window ).width();

		S.narrow	= w < S.minMinimalistWidth;

		if ( S.narrow )
		{
			$( 'html' ).removeClass( 'minimalist' );

			S.reset();
		}
	},

	reset														: function()
	{
		S.menuY	= $( '#menubar' ).offset().top;

		S.repositionTooltips();
	},

	scrollTo													: function(h)
	{
		var y	= $( h ).offset().top - $( '#menubar' ).outerHeight();

		$( 'html, body' ).animate({
			'scrollTop'	: y
		}, 2000, 'easeInOutExpo' );
	}
};

$.extend($.easing,
{
	def: 'easeOutQuad',
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	}
});

var _gaq=[['_setAccount','UA-352545-12'],['_trackPageview'],['_trackPageLoadTime']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));

$( document ).ready( S.ready );<commit_msg>updated json link<commit_after>var S	= {
	cssAnimation												: 'webkitAnimationEnd animationend oAnimationEnd',
	cssTransition												: 'webkitTransitionEnd transitionend oTransitionEnd',
	menuY														: 0,
	minCanvasWidth												: 640,
	minMinimalistWidth											: 1080,
	months														: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' ],
	narrow														: false,
	slowLoad													: 5000,

	ready														: function()
	{
		var h	= window.location.hash;

		S.detectBrowser();

		S.findTooltips();
		S.loadPosts();
		S.loadTweets();
		S.drawGradients();
		S.addLettering();
		S.sortScrolling();
		S.addMinimalist();

		S.menuY	= $( '#menubar' ).offset().top;

		$( window ).scroll( S.handleScrolling ).scroll().resize( S.handleResize ).resize();

		$( 'html, body' ).scrollTop( 0 );

		if ( h.length > 0 )
		{
			S.scrollTo( h );
		}
	},

	detectBrowser												: function()
	{
		if ( $.browser.msie )
		{
			$( 'html' ).addClass( 'ie' );

			if ( $.browser.version )
			{
				$( 'html' ).addClass( 'ie' + Number( $.browser.version ) );
			}
			else
			{
				$( 'html' ).addClass( 'ie6' );
			}
		}

		if ( $.browser.webkit )
		{
			$( 'html' ).addClass( 'webkit' );

			if ( navigator.userAgent.indexOf( 'Chrome' ) === -1 )
			{
				$( 'html' ).addClass( 'safari' );
			}
			else
			{
				$( 'html' ).addClass( 'chrome' );
			}
		}

		if ( $.browser.mozilla )
		{
			$( 'html' ).addClass( 'ff' );
		}

		if ( $.browser.opera )
		{
			$( 'html' ).addClass( 'opera' );
		}

		if ( navigator.userAgent.indexOf( 'Windows' ) != -1 )
		{
			$( 'html' ).addClass( 'windows' );
		}
		else if ( navigator.userAgent.indexOf( 'Mac' ) != -1 )
		{
			$( 'html' ).addClass( 'mac' );
		}

		if ( navigator.userAgent.indexOf( 'iPad' ) != -1 )
		{
			$( 'html' ).addClass( 'ipad' );
		}

		$( 'html' ).removeClass( 'no-js' );
	},

	findTooltips												: function()
	{
		$( '[title]' ).each( function()
		{
			var a	= $( this );
			var t	= $( '' + $( this ).attr( 'title' ) + '' ).prepend( '' );

			t.appendTo( a ).css({
				'margin-left'	: ( a.width() - t.outerWidth() ) * .5 + 'px'
			});

			a.removeAttr( 'title' );
		});
	},

	loadPosts													: function()
	{
		var ul	= $( '#posts' );

		if ( !ul.length )
		{
			return;
		}

		var t	= setTimeout( function()
		{
			$( 'li', ul ).append( ' Well, this is magical...' );
		}, S.slowLoad );

		var r	= $.getJSON( '/blog/json/', function(d)
		{
			clearTimeout( t );

			ul.bind( S.cssTransition, function(e)
			{
				var l	= d.length;
				var i;

				ul.unbind( S.cssTransition ).empty();

				for ( i = 0; i < l; i++ )
				{
					ul.append( S.formatPost( d[ i ] ) );
				}

				S.findTooltips();

				ul.removeClass( 'fadeOut' );
			}).addClass( 'fadeOut' );
		});
	},

	formatPost													: function(s)
	{
		var d	= new Date( s.post_date_gmt );

		return '
→ ' + s.post_title + '
';
	},

	truncate													: function(s, l, a)
	{
		return s.length > l ? s.substr( 0, l ) + a : s;
	},

	loadTweets													: function()
	{
		var ul	= $( '#tweets' );

		if ( !ul.length )
		{
			return;
		}

		var t	= setTimeout( function()
		{
			$( 'li', ul ).append( ' Well, this is magical...' );
		}, S.slowLoad );

		var r	= $.getJSON( 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=ahmednuaman&count=5&callback=?', function(d)
		{
			clearTimeout( t );

			ul.bind( S.cssTransition, function()
			{
				var l	= d.length;
				var i;

				ul.unbind( S.cssTransition ).empty();

				for ( i = 0; i < l; i++ )
				{
					ul.append( S.formatTweet( d[ i ] ) );
				}

				S.findTooltips();

				ul.removeClass( 'fadeOut' );
			}).addClass( 'fadeOut' );
		});
	},

	formatTweet													: function(s)
	{
		var d	= new Date( s.created_at );

		return '
→ ' + S.prepareLinks( s.text ) + '
';
	},

	prepareLinks												: function(t, i)
	{
		//t	= t.replace( /&/gim, '&' ).replace( /</gim, '<' ).replace( />/gim, '>' );

		t	= t.replace( /((https?:\/\/|www\.)[^\s]+)/gim, function(m)
		{
			var l	= ( m.indexOf( 'http' ) === -1 ? 'http://' : '' ) + m;

			return '' + m + '';
		});

		t	= t.replace( /\s?(\@[^\s]+)\s?/gim, function(m)
		{
			m		= m.replace( /\s/gim, '' );

			var l	= 'http://twitter.com/' + m;

			return ' ' + m + ' ';
		});

		t	= t.replace( /\s?(\#[^\s]+)\s?/gim, function(m)
		{
			m		= m.replace( /\s/gim, '' );

			var l	= 'http://twitter.com/search?q=' + m;

			return ' ' + m + ' ';
		});

		return t;
	},

	drawGradients												: function()
	{
		if ( !'HTMLCanvasElement' in window )
		{
			return;
		}

		$( '.thumbnail canvas' ).each( function()
		{
			var c	= $( this ).get( 0 ).getContext( '2d' );
			var p	= $( this ).parent();
			var h	= p.outerHeight();
			var w	= p.outerWidth()
			var g;

			$( this ).attr({
				height	: h,
				width	: w
			});

			c.clearRect( 0, 0, w, h );
			c.save();
			c.beginPath();
			c.moveTo(0.0, 383.0);
			c.bezierCurveTo(0.0, 337.5, 0.0, 0.0, 0.0, 0.0);
			c.bezierCurveTo(0.0, 0.0, 501.5, 0.0, 620.0, 0.0);
			c.bezierCurveTo(323.5, 54.0, 113.5, 191.5, 0.0, 383.0);
			c.closePath();
			g = c.createLinearGradient(87.6, -73.5, 343.8, 231.8);
			g.addColorStop(0.00, 'rgba(255, 255, 255, .05)');
			g.addColorStop(1.00, 'rgba(255, 255, 255, .15)');
			c.fillStyle = g;
			c.fill();
			c.restore();
		});
	},

	addLettering												: function()
	{
		$( 'h1' ).lettering();
	},

	handleScrolling												: function()
	{
		var c	= 'fixed';
		var m	= $( '#menubar' );
		var t	= m.hasClass( c );
		var y	= $( window ).scrollTop();

		if ( !t && y > S.menuY )
		{
			m.addClass( c );
		}

		if ( y <= S.menuY )
		{
			m.removeClass( c );
		}
	},

	sortScrolling												: function()
	{
		$( 'a[href^="#"]' ).click( function(e)
		{
			S.scrollTo( e.currentTarget.hash );

			return false;
		});
	},

	addMinimalist												: function()
	{
		$( 'h1' ).click( function()
		{
			if ( S.narrow )
			{
				return;
			}

			$( 'html' ).addClass( 'minimalist' );

			S.reset();
		});
	},

	repositionTooltips											: function()
	{
		$( '.tooltip' ).each( function()
		{
			var t	= $( this );
			var p	= t.parent();

			t.css({
				'margin-left'	: ( p.width() - t.outerWidth() ) * .5 + 'px'
			});
		});
	},

	handleResize												: function()
	{
		var w	= $( window ).width();

		S.narrow	= w < S.minMinimalistWidth;

		if ( S.narrow )
		{
			$( 'html' ).removeClass( 'minimalist' );

			S.reset();
		}
	},

	reset														: function()
	{
		S.menuY	= $( '#menubar' ).offset().top;

		S.repositionTooltips();
	},

	scrollTo													: function(h)
	{
		var y	= $( h ).offset().top - $( '#menubar' ).outerHeight();

		$( 'html, body' ).animate({
			'scrollTop'	: y
		}, 2000, 'easeInOutExpo' );
	}
};

$.extend($.easing,
{
	def: 'easeOutQuad',
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	}
});

var _gaq=[['_setAccount','UA-352545-12'],['_trackPageview'],['_trackPageLoadTime']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));

$( document ).ready( S.ready );<|endoftext|>


<commit_before>var gulp = require("gulp");
var changed = require('gulp-changed');
var sourcemaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");
var del = require("del");
var runSequence = require("run-sequence");

var app = {
  source: "./src/**/*.js",
  html: "./src/**/*.html",
  css: "./src/**/*.css",
  files: "./src/**/*.*",
  dist: "./dist"
};

gulp.task("build-app", function () {
  return gulp.src(app.source)
    .pipe(sourcemaps.init())
    .pipe(babel({modules: 'system'}))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest(app.dist));
});

gulp.task("copy-html", function() {
  return gulp.src(app.html)
    .pipe(gulp.dest(app.dist));
});

gulp.task("copy-css", function() {
  return gulp.src(app.css)
    .pipe(gulp.dest(app.dist));
});

gulp.task("copy-everything", function() {
  return gulp.src(app.files)
    .pipe(gulp.dest(app.dist))
});

gulp.task("clean", function(callback) {
  del([app.dist], callback);
});

gulp.task("build", function(callback) {
  return runSequence(
    'copy-everything',
    "clean",
    [ "build-app", "copy-html", "copy-css"],
    callback
  );
});

gulp.task("watch", function(callback) {
  gulp.watch(app.source, ['build-app']);
  gulp.watch(app.html, ['build-html']);
  gulp.watch(app.css, ['build-css']);
});

gulp.task("default", function(callback) {
  return runSequence("build");
});<commit_msg>fix watch task<commit_after>var gulp = require("gulp");
var changed = require('gulp-changed');
var sourcemaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");
var del = require("del");
var runSequence = require("run-sequence");

var app = {
  source: "./src/**/*.js",
  html: "./src/**/*.html",
  css: "./src/**/*.css",
  files: "./src/**/*.*",
  dist: "./dist"
};

gulp.task("build-app", function () {
  return gulp.src(app.source)
    .pipe(sourcemaps.init())
    .pipe(babel({modules: 'system'}))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest(app.dist));
});

gulp.task("copy-html", function() {
  return gulp.src(app.html)
    .pipe(gulp.dest(app.dist));
});

gulp.task("copy-css", function() {
  return gulp.src(app.css)
    .pipe(gulp.dest(app.dist));
});

gulp.task("copy-everything", function() {
  return gulp.src(app.files)
    .pipe(gulp.dest(app.dist))
});

gulp.task("clean", function(callback) {
  del([app.dist], callback);
});

gulp.task("build", function(callback) {
  return runSequence(
    'copy-everything',
    "clean",
    [ "build-app", "copy-html", "copy-css"],
    callback
  );
});

gulp.task("watch", function(callback) {
  gulp.watch(app.source, ['build-app']);
  gulp.watch(app.html, ['copy-html']);
  gulp.watch(app.css, ['copy-css']);
});

gulp.task("default", function(callback) {
  return runSequence("build");
});<|endoftext|>


<commit_before>var gulp = require('gulp');
var install = require('gulp-install');
var conflict = require('gulp-conflict');
var inquirer = require('inquirer');
var mustache = require("gulp-mustache");
var rename = require('gulp-rename');
var clean = require('gulp-clean');

gulp.task('default', function( next ){
  inquirer.prompt([
    {
      type    : 'input',
      name    : 'name',
      message : 'Your extension name (e.g. for cytoscape-my-extension write "my-extension")\n>'
    },

    {
      type    : 'input',
      name    : 'githubProj',
      message : 'Github project name (e.g. org/cytoscape-my-extension)\n>'
    },

    {
      type    : 'list',
      name    : 'type',
      message : 'Extension type',
      choices : [
        { 'value': 'core', name: 'core : Adds a function to the core (graph)' },
        { 'value': 'collection', name: 'collection : Adds a function to collections (nodes/edges)' },
        { 'value': 'layout', name: 'layout : Adds a layout' },
        { 'value': 'renderer', name: 'renderer : Adds a renderer' }
      ]
    },

    {
      type    : 'input',
      name    : 'description',
      message : 'A one-line description of your extension\n>'
    },

    {
      type    : 'input',
      name    : 'version',
      message : 'Version number',
      default : '1.0.0'
    },

    {
      type    : 'input',
      name    : 'license',
      message : 'License',
      default : 'MIT'
    },

    {
      type    : 'confirm',
      name    : 'moveon',
      message : 'Create extension with above options?'
    }
  ],
  function( answers ){
    if( !answers.moveon ){
      return next();
    }

    answers.fullName = 'cytoscape-' + answers.name;
    answers.camelName = answers.name.replace(/(-\w)/g, function( v ){
      return v[1].toUpperCase();
    });

    // e.g. answers.layout = true for templating
    answers[ answers.type ] = true;

    gulp.src([
      __dirname + '/templates/**',
      __dirname + '/templates/.gitignore',
      __dirname + '/templates/.npmignore',
      __dirname + '/templates/.spmignore'
    ])  // Note use of __dirname to be relative to generator
      .pipe( mustache(answers) )             // Mustache template support
      .pipe( conflict('./') )                // Confirms overwrites on file conflicts
      .pipe( gulp.dest('./') )               // Without __dirname here = relative to cwd
      .pipe( install() )                     // Run `bower install` and/or `npm install` if necessary
      .on('finish', function(){

        gulp.src('./cytoscape-ext.js')
          .pipe( clean() ) // delete orig file
          .pipe( rename('cytoscape-' + answers.name + '.js') )
          .pipe( gulp.dest('./') )
          .on('finish', function(){
            next();
          })
        ;

      });
  });
});
<commit_msg>remove renderer option until renderer scaffolding is supported<commit_after>var gulp = require('gulp');
var install = require('gulp-install');
var conflict = require('gulp-conflict');
var inquirer = require('inquirer');
var mustache = require("gulp-mustache");
var rename = require('gulp-rename');
var clean = require('gulp-clean');

gulp.task('default', function( next ){
  inquirer.prompt([
    {
      type    : 'input',
      name    : 'name',
      message : 'Your extension name (e.g. for cytoscape-my-extension write "my-extension")\n>'
    },

    {
      type    : 'input',
      name    : 'githubProj',
      message : 'Github project name (e.g. org/cytoscape-my-extension)\n>'
    },

    {
      type    : 'list',
      name    : 'type',
      message : 'Extension type',
      choices : [
        { 'value': 'core', name: 'core : Adds a function to the core (graph)' },
        { 'value': 'collection', name: 'collection : Adds a function to collections (nodes/edges)' },
        { 'value': 'layout', name: 'layout : Adds a layout' }
        //{ 'value': 'renderer', name: 'renderer : Adds a renderer' }
      ]
    },

    {
      type    : 'input',
      name    : 'description',
      message : 'A one-line description of your extension\n>'
    },

    {
      type    : 'input',
      name    : 'version',
      message : 'Version number',
      default : '1.0.0'
    },

    {
      type    : 'input',
      name    : 'license',
      message : 'License',
      default : 'MIT'
    },

    {
      type    : 'confirm',
      name    : 'moveon',
      message : 'Create extension with above options?'
    }
  ],
  function( answers ){
    if( !answers.moveon ){
      return next();
    }

    answers.fullName = 'cytoscape-' + answers.name;
    answers.camelName = answers.name.replace(/(-\w)/g, function( v ){
      return v[1].toUpperCase();
    });

    // e.g. answers.layout = true for templating
    answers[ answers.type ] = true;

    gulp.src([
      __dirname + '/templates/**',
      __dirname + '/templates/.gitignore',
      __dirname + '/templates/.npmignore',
      __dirname + '/templates/.spmignore'
    ])  // Note use of __dirname to be relative to generator
      .pipe( mustache(answers) )             // Mustache template support
      .pipe( conflict('./') )                // Confirms overwrites on file conflicts
      .pipe( gulp.dest('./') )               // Without __dirname here = relative to cwd
      .pipe( install() )                     // Run `bower install` and/or `npm install` if necessary
      .on('finish', function(){

        gulp.src('./cytoscape-ext.js')
          .pipe( clean() ) // delete orig file
          .pipe( rename('cytoscape-' + answers.name + '.js') )
          .pipe( gulp.dest('./') )
          .on('finish', function(){
            next();
          })
        ;

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


<commit_before>// rust Template for the preamble
var preamble = (basis, classname) =>
`// 3D Projective Geometric Algebra
// Written by a generator written by enki.
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
#![feature(const_slice_len)]

use std::fmt;
use std::ops::{Index,IndexMut,Add,Sub,Mul,BitAnd,BitOr,BitXor,Not};

type float_t = f64;

// use std::f64::consts::PI;
const PI: float_t = 3.14159265358979323846;

const basis: &'static [&'static str] = &[ ${basis.map(x=>'"'+x+'"').join(',')} ];
const basis_count: usize = basis.len();

#[derive(Default,Debug,Clone,PartialEq)]
struct ${classname} {
    mvec: [float_t; basis_count]
}

impl ${classname} {
    pub const fn zero() -> Self {
        Self {
            mvec: [0.0; basis_count]
        }
    }

    pub const fn new(f: float_t, idx: usize) -> Self {
        let mut ret = Self::zero();
        ret.mvec[idx] = f;
        ret
    }
}

// basis vectors are available as global constants.
${basis.slice(1).map((x,i)=>`const ${x}: ${classname} = ${classname}::new(1.0, ${i+1});`).join('\n')}

impl Index<usize> for ${classname} {
    type Output = float_t;

    fn index<'a>(&'a self, index: usize) -> &'a Self::Output {
        &self.mvec[index]
    }
}

impl IndexMut<usize> for ${classname} {
    fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut Self::Output {
        &mut self.mvec[index]
    }
}

impl fmt::Display for ${classname} {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut n = 0;
        let ret = self.mvec.iter().enumerate().filter_map(|(i, &coeff)| {
            if coeff > 0.00001 || coeff < -0.00001 {
                n = 1;
                Some(format!("{}{}",
                        format!("{:.*}", 7, coeff).trim_end_matches('0').trim_end_matches('.'),
                        if i > 0 { basis[i] } else { "" }
                    )
                )
            } else {
                None
            }
        }).collect::<Vec<String>>().join(" + ");
        if n==0 { write!(f,"0") } else { write!(f, "{}", ret) }
    }
}

macro_rules! define_binary_op(
    (
        // Operator, operator method, and scalar bounds.
        $Op: ident, $op: ident;
        // Argument identifiers and types + output.
        $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty;
        // Operator actual implementation.
        $action: expr;
        // Lifetime.
        $($lives: tt),*
    ) => {
       impl<$($lives ,)*> $Op<$Rhs> for $Lhs {
           type Output = $Result;

           #[inline]
           fn $op($lhs, $rhs: $Rhs) -> Self::Output {
               $action
           }
       }
    }
);

macro_rules! define_binary_op_all(
    (
        // Operator, operator method, and scalar bounds.
        $Op: ident, $op: ident;
        // Argument identifiers and types + output.
        $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty;
        // Operators actual implementations.
        [val val] => $action_val_val: expr;
        [ref val] => $action_ref_val: expr;
        [val ref] => $action_val_ref: expr;
        [ref ref] => $action_ref_ref: expr;
    ) => {
        define_binary_op!(
            $Op, $op;
            $lhs: $Lhs, $rhs: $Rhs, Output = $Result;
            $action_val_val;
        );

        define_binary_op!(
            $Op, $op;
            $lhs: &'a $Lhs, $rhs: $Rhs, Output = $Result;
            $action_ref_val;
            'a
        );

        define_binary_op!(
            $Op, $op;
            $lhs: $Lhs, $rhs: &'b $Rhs, Output = $Result;
            $action_val_ref;
            'b
        );

        define_binary_op!(
            $Op, $op;
            $lhs: &'a $Lhs, $rhs: &'b $Rhs, Output = $Result;
            $action_ref_ref;
            'a, 'b
        );
    }
);

// TODO define_unary_op

`;

// rust Template for our binary operators

var binary = (classname, symbol, name, name_a, name_b, name_ret, code, classname_a = classname, classname_b = classname, desc) => {

  let body = ``;

  if (symbol) {

    if (name.match(/^s/)) {
body = `
define_binary_op_all!(
    ${{ "+": "Add", "*": "Mul" }[symbol] || name},
    ${{ "+": "add", "*": "mul" }[symbol] || name};
    self: float_t, b: ${classname}, Output = ${classname};
    [val val] => &self ${symbol} &b;
    [ref val] =>  self ${symbol} &b;
    [val ref] => &self ${symbol}  b;
    [ref ref] => {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n        ')}
        ${name_ret}
    };
);
`;
    } else if (name.match(/s$/)) {
    body = `
define_binary_op_all!(
    ${{ "+": "Add", "*": "Mul" }[symbol] || name},
    ${{ "+": "add", "*": "mul" }[symbol] || name};
    self: ${classname}, b: float_t, Output = ${classname};
    [val val] => &self ${symbol} &b;
    [ref val] =>  self ${symbol} &b;
    [val ref] => &self ${symbol}  b;
    [ref ref] => {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n        ')}
        ${name_ret}
    };
);
`;
    } else {
      body = `
define_binary_op_all!(
    ${{ "+": "Add", "*": "Mul", "^": "BitXor", "&": "BitAnd", "|": "BitOr" }[symbol] || name},
    ${{ "+": "add", "-": "sub", "*": "mul", "^": "bitxor", "&": "bitand", "|": "bitor" }[symbol] || name};
    self: ${classname}, b: ${classname}, Output = ${classname};
    [val val] => &self ${symbol} &b;
    [ref val] =>  self ${symbol} &b;
    [val ref] => &self ${symbol}  b;
    [ref ref] => {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n		')}
        ${name_ret}
    };
);
`;
    }
  } else {
    // no binary named function yet
    body = ``;
    }

  return `// ${name}
// ${desc}
${body}`;
};

// rust Template for our unary operators
var unary = (classname, symbol, name, name_a, name_ret, code, classname_a = classname, desc) => {
  let body = `impl ${classname} {
    pub fn ${name}(self: & Self) -> ${classname} {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n        ')}
        ${name_ret}
    }
}`;

  if (symbol == `!`) {
    body = `${body}

impl ${{ "!": "Not" }[symbol] || name} for & ${classname} {
    type Output = ${classname};

    fn ${{ "!": "not" }[symbol] || name}(self: Self) -> ${classname} {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n        ')}
        ${name_ret}
    }
}`;
  }

  return `// ${name}
// ${desc}
${body}`;
}

// rust template for CGA
var CGA = (basis,classname)=>({
preamble:`
  pub fn eo() -> Self { e4 + e5 }
  pub fn ei() -> Self { (e5 - e4)*0.5 }

  pub fn up(x: float_t, y: float_t, z: float_t) -> Self {
    x*e1 + y*e2 + z*e3 + 0.5*(x*x+y*y+z*z)*Self::ei() + Self::eo()
  }
`,
amble:`
    let px = &${classname}::up(1.0,2.0,3.0);
    let line = px ^ ${classname}::eo() ^ ${classname}::ei();
    let sphere = (${classname}::eo() - ${classname}::ei()).Dual();
    println!("a point       : {}", px);
    println!("a line        : {}", line);
    println!("a sphere      : {}", sphere);

`
})

// rust template for algebras without examples
var GENERIC = (basis,classname)=>({
preamble:``,
amble:`
  println!("${basis[1]}*${basis[1]}         : {}", ${basis[1]} * ${basis[1]});
  println!("pss           : {}", ${basis[basis.length-1]});
  println!("pss*pss       : {}", ${basis[basis.length-1]}*${basis[basis.length-1]});
`
})

// rust template for PGA
var PGA3D = (basis,classname)=>({
preamble:`
    // A rotor (Euclidean line) and translator (Ideal line)
    pub fn rotor(angle: float_t, line: & Self) -> Self {
        (angle / 2.0).cos() + (angle / 2.0).sin() * line.normalized()
    }

    pub fn translator(dist: float_t, line: & Self) -> Self {
        1.0 + dist / 2.0 * line
    }

    // A plane is defined using its homogenous equation ax + by + cz + d = 0
    pub fn plane(a: float_t, b: float_t, c:float_t, d:float_t) -> Self {
        a * e1 + b * e2 + c * e3 + d * e0
    }

    // PGA lines are bivectors.
    pub fn e01() -> Self { e0^e1 }
    pub fn e02() -> Self { e0^e2 }
    pub fn e03() -> Self { e0^e3 }
    pub fn e12() -> Self { e1^e2 }
    pub fn e31() -> Self { e3^e1 }
    pub fn e23() -> Self { e2^e3 }

    // PGA points are trivectors.
    pub fn e123() -> Self { e1^e2^e3 }
    pub fn e032() -> Self { e0^e3^e2 }
    pub fn e013() -> Self { e0^e1^e3 }
    pub fn e021() -> Self { e0^e2^e1 }

    // A point is just a homogeneous point, euclidean coordinates plus the origin
    pub fn point(x: float_t, y: float_t, z:float_t) -> Self {
         Self::e123() + x * Self::e032() + y * Self::e013() + z * Self::e021()
    }

    // for our toy problem (generate points on the surface of a torus)
    // we start with a function that generates motors.
    // circle(t) with t going from 0 to 1.
    pub fn circle(t: float_t, radius: float_t, line: & Self) -> Self {
        Self::rotor(t * 2.0 * PI, line) * Self::translator(radius, &(e1 * e0))
    }

    // a torus is now the product of two circles.
    pub fn torus(s: float_t, t: float_t, r1: float_t, l1: & Self, r2: float_t, l2: & Self) -> Self {
        Self::circle(s, r2, l2) * Self::circle(t, r1, l1)
    }

    // and to sample its points we simply sandwich the origin ..
    pub fn point_on_torus(s: float_t, t: float_t) -> Self {
        let to = &Self::torus(s, t, 0.25, &Self::e12(), 0.6, &Self::e31());

        to * Self::e123() * to.Reverse()
    }

`,
amble:`
    // Elements of the even subalgebra (scalar + bivector + pss) of unit length are motors
    let rot = &${classname}::rotor(PI / 2.0, &(e1 * e2));

    // The outer product ^ is the MEET. Here we intersect the yz (x=0) and xz (y=0) planes.
    let ax_z = &(e1 ^ e2);

    // line and plane meet in point. We intersect the line along the z-axis (x=0,y=0) with the xy (z=0) plane.
    let orig = &(ax_z ^ e3);

    // We can also easily create points and join them into a line using the regressive (vee, &) product.
    let px = &${classname}::point(1.0, 0.0, 0.0);
    let line = &(orig & px);

    // Lets also create the plane with equation 2x + z - 3 = 0
    let p = &${classname}::plane(2.0, 0.0, 1.0, -3.0);

    // rotations work on all elements
    let rotated_plane = rot * p * rot.Reverse();
    let rotated_line  = rot * line * rot.Reverse();
    let rotated_point = rot * px * rot.Reverse();

    // See the 3D PGA Cheat sheet for a huge collection of useful formulas
    let point_on_plane = &((p | px) * p);

    // Some output
    println!("a point       : {}", px);
    println!("a line        : {}", line);
    println!("a plane       : {}", p);
    println!("a rotor       : {}", rot);
    println!("rotated line  : {}", rotated_line);
    println!("rotated point : {}", rotated_point);
    println!("rotated plane : {}", rotated_plane);
    println!("point on plane: {}", point_on_plane.normalized());
    println!("point on torus: {}", ${classname}::point_on_torus(0.0, 0.0));
`});

// rust Template for the postamble
var postamble = (basis,classname,example) =>
  `impl ${classname} {
    pub fn norm(self: & Self) -> float_t {
        let scalar_part = (self * self.Conjugate())[0];

        scalar_part.abs().sqrt()
    }

    pub fn inorm(self: & Self) -> float_t {
        self.Dual().norm()
    }

    pub fn normalized(self: & Self) -> Self {
        self * (1.0 / self.norm())
    }

    ${example.preamble}

}

fn main() {
${example.amble}
}`;

Object.assign(exports,{preamble,postamble,unary,binary,desc:"rust",PGA3D,CGA,GENERIC});
<commit_msg>Support R600<commit_after>// rust Template for the preamble
var preamble = (basis, classname) =>
`// 3D Projective Geometric Algebra
// Written by a generator written by enki.
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
#![feature(const_slice_len)]

use std::fmt;
use std::ops::{Index,IndexMut,Add,Sub,Mul,BitAnd,BitOr,BitXor,Not};

type float_t = f64;

// use std::f64::consts::PI;
const PI: float_t = 3.14159265358979323846;

const basis: &'static [&'static str] = &[ ${basis.map(x=>'"'+x+'"').join(',')} ];
const basis_count: usize = basis.len();

#[derive(Default,Debug,Clone,PartialEq)]
struct ${classname} {
    mvec: Vec<float_t>
}

impl ${classname} {
    pub fn zero() -> Self {
        Self {
            mvec: vec![0.0; basis_count]
        }
    }

    pub fn new(f: float_t, idx: usize) -> Self {
        let mut ret = Self::zero();
        ret.mvec[idx] = f;
        ret
    }

    // basis vectors are available as methods
    ${basis.slice(1).map((x,i)=>`pub fn ${x}() -> Self { ${classname}::new(1.0, ${i+1}) }`).join('\n')}
}

impl Index<usize> for ${classname} {
    type Output = float_t;

    fn index<'a>(&'a self, index: usize) -> &'a Self::Output {
        &self.mvec[index]
    }
}

impl IndexMut<usize> for ${classname} {
    fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut Self::Output {
        &mut self.mvec[index]
    }
}

impl fmt::Display for ${classname} {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut n = 0;
        let ret = self.mvec.iter().enumerate().filter_map(|(i, &coeff)| {
            if coeff > 0.00001 || coeff < -0.00001 {
                n = 1;
                Some(format!("{}{}",
                        format!("{:.*}", 7, coeff).trim_end_matches('0').trim_end_matches('.'),
                        if i > 0 { basis[i] } else { "" }
                    )
                )
            } else {
                None
            }
        }).collect::<Vec<String>>().join(" + ");
        if n==0 { write!(f,"0") } else { write!(f, "{}", ret) }
    }
}

macro_rules! define_binary_op(
    (
        // Operator, operator method, and scalar bounds.
        $Op: ident, $op: ident;
        // Argument identifiers and types + output.
        $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty;
        // Operator actual implementation.
        $action: expr;
        // Lifetime.
        $($lives: tt),*
    ) => {
       impl<$($lives ,)*> $Op<$Rhs> for $Lhs {
           type Output = $Result;

           #[inline]
           fn $op($lhs, $rhs: $Rhs) -> Self::Output {
               $action
           }
       }
    }
);

macro_rules! define_binary_op_all(
    (
        // Operator, operator method, and scalar bounds.
        $Op: ident, $op: ident;
        // Argument identifiers and types + output.
        $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty;
        // Operators actual implementations.
        [val val] => $action_val_val: expr;
        [ref val] => $action_ref_val: expr;
        [val ref] => $action_val_ref: expr;
        [ref ref] => $action_ref_ref: expr;
    ) => {
        define_binary_op!(
            $Op, $op;
            $lhs: $Lhs, $rhs: $Rhs, Output = $Result;
            $action_val_val;
        );

        define_binary_op!(
            $Op, $op;
            $lhs: &'a $Lhs, $rhs: $Rhs, Output = $Result;
            $action_ref_val;
            'a
        );

        define_binary_op!(
            $Op, $op;
            $lhs: $Lhs, $rhs: &'b $Rhs, Output = $Result;
            $action_val_ref;
            'b
        );

        define_binary_op!(
            $Op, $op;
            $lhs: &'a $Lhs, $rhs: &'b $Rhs, Output = $Result;
            $action_ref_ref;
            'a, 'b
        );
    }
);

// TODO define_unary_op

`;

// rust Template for our binary operators

var binary = (classname, symbol, name, name_a, name_b, name_ret, code, classname_a = classname, classname_b = classname, desc) => {

  let body = ``;

  if (symbol) {

    if (name.match(/^s/)) {
body = `
define_binary_op_all!(
    ${{ "+": "Add", "*": "Mul" }[symbol] || name},
    ${{ "+": "add", "*": "mul" }[symbol] || name};
    self: float_t, b: ${classname}, Output = ${classname};
    [val val] => &self ${symbol} &b;
    [ref val] =>  self ${symbol} &b;
    [val ref] => &self ${symbol}  b;
    [ref ref] => {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n        ')}
        ${name_ret}
    };
);
`;
    } else if (name.match(/s$/)) {
    body = `
define_binary_op_all!(
    ${{ "+": "Add", "*": "Mul" }[symbol] || name},
    ${{ "+": "add", "*": "mul" }[symbol] || name};
    self: ${classname}, b: float_t, Output = ${classname};
    [val val] => &self ${symbol} &b;
    [ref val] =>  self ${symbol} &b;
    [val ref] => &self ${symbol}  b;
    [ref ref] => {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n        ')}
        ${name_ret}
    };
);
`;
    } else {
      body = `
define_binary_op_all!(
    ${{ "+": "Add", "*": "Mul", "^": "BitXor", "&": "BitAnd", "|": "BitOr" }[symbol] || name},
    ${{ "+": "add", "-": "sub", "*": "mul", "^": "bitxor", "&": "bitand", "|": "bitor" }[symbol] || name};
    self: ${classname}, b: ${classname}, Output = ${classname};
    [val val] => &self ${symbol} &b;
    [ref val] =>  self ${symbol} &b;
    [val ref] => &self ${symbol}  b;
    [ref ref] => {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n		')}
        ${name_ret}
    };
);
`;
    }
  } else {
    // no binary named function yet
    body = ``;
    }

  return `// ${name}
// ${desc}
${body}`;
};

// rust Template for our unary operators
var unary = (classname, symbol, name, name_a, name_ret, code, classname_a = classname, desc) => {
  let body = `impl ${classname} {
    pub fn ${name}(self: & Self) -> ${classname} {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n        ')}
        ${name_ret}
    }
}`;

  if (symbol == `!`) {
    body = `${body}

impl ${{ "!": "Not" }[symbol] || name} for & ${classname} {
    type Output = ${classname};

    fn ${{ "!": "not" }[symbol] || name}(self: Self) -> ${classname} {
        let mut ${name_ret} = ${classname}::zero();
        let ${name_a} = self;
        ${code.replace(/^ */g, '').replace(/\n */g, '\n        ')}
        ${name_ret}
    }
}`;
  }

  return `// ${name}
// ${desc}
${body}`;
}

// rust template for CGA
var CGA = (basis,classname)=>({
preamble:`
  pub fn eo() -> Self { Self::e4() + Self::e5() }
  pub fn ei() -> Self { (Self::e5() - Self::e4())*0.5 }

  pub fn up(x: float_t, y: float_t, z: float_t) -> Self {
    x * Self::e1() + y * Self::e2() + z * Self::e3() + 0.5 * (x * x + y * y + z * z) * Self::ei() + Self::eo()
  }
`,
amble:`
    let px = &${classname}::up(1.0,2.0,3.0);
    let line = px ^ ${classname}::eo() ^ ${classname}::ei();
    let sphere = (${classname}::eo() - ${classname}::ei()).Dual();
    println!("a point       : {}", px);
    println!("a line        : {}", line);
    println!("a sphere      : {}", sphere);

`
})

// rust template for algebras without examples
var GENERIC = (basis,classname)=>({
preamble:``,
amble:`
  println!("${basis[1]}*${basis[1]}         : {}", ${classname}::${basis[1]}() * ${classname}::${basis[1]}());
  println!("pss           : {}", ${classname}::${basis[basis.length-1]}());
  println!("pss*pss       : {}", ${classname}::${basis[basis.length-1]}() * ${classname}::${basis[basis.length-1]}());
`
})

// rust template for PGA
var PGA3D = (basis,classname)=>({
preamble:`
    // A rotor (Euclidean line) and translator (Ideal line)
    pub fn rotor(angle: float_t, line: & Self) -> Self {
        (angle / 2.0).cos() + (angle / 2.0).sin() * line.normalized()
    }

    pub fn translator(dist: float_t, line: & Self) -> Self {
        1.0 + dist / 2.0 * line
    }

    // A plane is defined using its homogenous equation ax + by + cz + d = 0
    pub fn plane(a: float_t, b: float_t, c: float_t, d: float_t) -> Self {
        a * Self::e1() + b * Self::e2() + c * Self::e3() + d * Self::e0()
    }

    // A point is just a homogeneous point, euclidean coordinates plus the origin
    pub fn point(x: float_t, y: float_t, z:float_t) -> Self {
         Self::e123() + x * Self::e032() + y * Self::e013() + z * Self::e021()
    }

    // for our toy problem (generate points on the surface of a torus)
    // we start with a function that generates motors.
    // circle(t) with t going from 0 to 1.
    pub fn circle(t: float_t, radius: float_t, line: & Self) -> Self {
        Self::rotor(t * 2.0 * PI, line) * Self::translator(radius, &(Self::e1() * Self::e0()))
    }

    // a torus is now the product of two circles.
    pub fn torus(s: float_t, t: float_t, r1: float_t, l1: & Self, r2: float_t, l2: & Self) -> Self {
        Self::circle(s, r2, l2) * Self::circle(t, r1, l1)
    }

    // and to sample its points we simply sandwich the origin ..
    pub fn point_on_torus(s: float_t, t: float_t) -> Self {
        let to = &Self::torus(s, t, 0.25, &Self::e12(), 0.6, &Self::e31());

        to * Self::e123() * to.Reverse()
    }

`,
amble:`
    // Elements of the even subalgebra (scalar + bivector + pss) of unit length are motors
    let rot = &${classname}::rotor(PI / 2.0, &(${classname}::e1() * ${classname}::e2()));

    // The outer product ^ is the MEET. Here we intersect the yz (x=0) and xz (y=0) planes.
    let ax_z = &(${classname}::e1() ^ ${classname}::e2());

    // line and plane meet in point. We intersect the line along the z-axis (x=0,y=0) with the xy (z=0) plane.
    let orig = &(ax_z ^ ${classname}::e3());

    // We can also easily create points and join them into a line using the regressive (vee, &) product.
    let px = &${classname}::point(1.0, 0.0, 0.0);
    let line = &(orig & px);

    // Lets also create the plane with equation 2x + z - 3 = 0
    let p = &${classname}::plane(2.0, 0.0, 1.0, -3.0);

    // rotations work on all elements
    let rotated_plane = rot * p * rot.Reverse();
    let rotated_line  = rot * line * rot.Reverse();
    let rotated_point = rot * px * rot.Reverse();

    // See the 3D PGA Cheat sheet for a huge collection of useful formulas
    let point_on_plane = &((p | px) * p);

    // Some output
    println!("a point       : {}", px);
    println!("a line        : {}", line);
    println!("a plane       : {}", p);
    println!("a rotor       : {}", rot);
    println!("rotated line  : {}", rotated_line);
    println!("rotated point : {}", rotated_point);
    println!("rotated plane : {}", rotated_plane);
    println!("point on plane: {}", point_on_plane.normalized());
    println!("point on torus: {}", ${classname}::point_on_torus(0.0, 0.0));
`});

// rust Template for the postamble
var postamble = (basis,classname,example) =>
  `impl ${classname} {
    pub fn norm(self: & Self) -> float_t {
        let scalar_part = (self * self.Conjugate())[0];

        scalar_part.abs().sqrt()
    }

    pub fn inorm(self: & Self) -> float_t {
        self.Dual().norm()
    }

    pub fn normalized(self: & Self) -> Self {
        self * (1.0 / self.norm())
    }

    ${example.preamble}

}

fn main() {
${example.amble}
}`;

Object.assign(exports,{preamble,postamble,unary,binary,desc:"rust",PGA3D,CGA,GENERIC});
<|endoftext|>


<commit_before>'use strict';

var $ = require('jquery');
var _ = require('lodash');

var events = require('../controllers/events');
var ships = require('../models/ships');

module.exports = {
    init: function () {
        module.exports.renderStartingShipsList();
        module.exports.bindStartButton();
    },
    bindStartButton: function () {
        $('#start-build').on('click', function () {
            var chosenShipId = $('#starting-ships select').val();
            events.trigger('view.new.start', {
                shipId: chosenShipId,
                callsign: $('#callsign').val(),
                playerName: $('#player-name').val()
            });
        });
    },
    renderStartingShipsList: function () {
        var $select = $('<select>');

        // get list of starting ships
        var filterFunction = function (item) {
            return item.starting === true;
        };

        var startingShips = _.filter(ships, filterFunction);

        // bind starting ships to DOM
        _.forEach(startingShips, function (item) {
            var $newOption = $('<option value="' + item.id + '">' + item.shipData.name + ' (' + item.startingXp +' XP to spend)</option>');
            $select.append($newOption);
        });

        $('#starting-ships').append($select);

        module.exports.resetStartingShipsList();
    },
    reset: function () {
        module.exports.resetStartingShipsList();
    },
    resetStartingShipsList: function () {
        $('#starting-ships option').first().prop('selected', 'selected');
    },
    hide: function () {
        $('.new').removeClass('active');
    },
    show: function () {
        $('.new').addClass('active');
    }
};
<commit_msg>Fix lint error<commit_after>'use strict';

var $ = require('jquery');
var _ = require('lodash');

var events = require('../controllers/events');
var ships = require('../models/ships');

module.exports = {
    init: function () {
        module.exports.renderStartingShipsList();
        module.exports.bindStartButton();
    },
    bindStartButton: function () {
        $('#start-build').on('click', function () {
            var chosenShipId = $('#starting-ships select').val();
            events.trigger('view.new.start', {
                shipId: chosenShipId,
                callsign: $('#callsign').val(),
                playerName: $('#player-name').val()
            });
        });
    },
    renderStartingShipsList: function () {
        var $select = $('<select>');

        // get list of starting ships
        var filterFunction = function (item) {
            return item.starting === true;
        };

        var startingShips = _.filter(ships, filterFunction);

        // bind starting ships to DOM
        _.forEach(startingShips, function (item) {
            var $newOption = $('<option value="' + item.id + '">' + item.shipData.name + ' (' + item.startingXp + ' XP to spend)</option>');
            $select.append($newOption);
        });

        $('#starting-ships').append($select);

        module.exports.resetStartingShipsList();
    },
    reset: function () {
        module.exports.resetStartingShipsList();
    },
    resetStartingShipsList: function () {
        $('#starting-ships option').first().prop('selected', 'selected');
    },
    hide: function () {
        $('.new').removeClass('active');
    },
    show: function () {
        $('.new').addClass('active');
    }
};
<|endoftext|>


<commit_before>/**
 * WordPress dependencies
 */
import { createNewPost, clickButton, saveDraft } from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import { activateExperience, deactivateExperience, insertBlock, selectBlockByClassName } from '../../utils';

describe( 'Story Animations', () => {
	beforeAll( async () => {
		await activateExperience( 'stories' );
	} );

	afterAll( async () => {
		await deactivateExperience( 'stories' );
	} );

	beforeEach( async () => {
		await createNewPost( { postType: 'amp_story' } );
	} );

	it( 'should save correct animation values', async () => {
		// Add Author block with animation.
		await insertBlock( 'Author' );
		page.waitForSelector( '.components-select-control__input' );
		await page.select( '.components-select-control__input', 'fly-in-bottom' );
		page.waitForSelector( 'input[aria-label="Delay (ms)"]' );
		await page.type( 'input[aria-label="Delay (ms)"]', '15' );

		await saveDraft();
		await page.reload();

		page.waitForSelector( '.wp-block-amp-amp-story-post-author' );

		await selectBlockByClassName( 'wp-block-amp-amp-story-post-author' );
		page.waitForSelector( 'input[aria-label="Delay (ms)"]' );

		expect( await page.evaluate( () => {
			return document.querySelector( 'input[aria-label="Delay (ms)"]' ).value;
		} ) ).toBe( '15' );

		expect( await page.evaluate( () => {
			return document.querySelector( '.components-select-control__input [value="fly-in-bottom"]' ).selected;
		} ) ).toBe( true );
	} );

	it( 'should save correct animation after values', async () => {
		// Add Author block with animation.
		await insertBlock( 'Author' );
		page.waitForSelector( '.components-select-control__input' );
		await page.select( '.components-select-control__input', 'fly-in-bottom' );

		// Add Date block with animation.
		await insertBlock( 'Date' );
		page.waitForSelector( '.components-select-control__input' );
		await page.select( '.components-select-control__input', 'pulse' );
		page.waitForSelector( 'label[for="amp-stories-animation-order-picker"]' );
		await clickButton( 'Immediately' );

		page.waitForSelector( '.components-animate__appear' );
		await page.click( '.components-animate__appear button[aria-checked="false"]' );
		await saveDraft();
		await page.reload();

		page.waitForSelector( '.wp-block-amp-amp-story-post-author' );

		await selectBlockByClassName( 'wp-block-amp-amp-story-post-author' );
		page.waitForSelector( 'input[aria-label="Delay (ms)"]' );

		await selectBlockByClassName( 'wp-block-amp-amp-story-post-date' );
		page.waitForSelector( '.components-animate__appear' );

		expect( await page.evaluate( () => {
			return document.querySelector( 'button[aria-label="Begin after: Story Author"]' ).innerHTML;
		} ) ).toContain( 'admin' );
	} );

	it( 'should not allow creating a cycle in animation after', async () => {
		// Add Author block with animation.
		await insertBlock( 'Author' );
		await page.select( '.components-select-control__input', 'fly-in-bottom' );

		// Add Date block with animation.
		await insertBlock( 'Date' );
		await page.select( '.components-select-control__input', 'pulse' );
		page.waitForSelector( 'label[for="amp-stories-animation-order-picker"]' );
		await clickButton( 'Immediately' );

		page.waitForSelector( '.components-animate__appear' );
		await page.click( '.components-animate__appear button[aria-checked="false"]' );

		await selectBlockByClassName( 'wp-block-amp-amp-story-post-author' );

		page.waitForSelector( 'label[for="amp-stories-animation-order-picker"]' );
		await clickButton( 'Immediately' );
		page.waitForSelector( '.components-animate__appear' );

		expect( await page.evaluate( () => {
			return document.querySelector( '.components-animate__appear button[aria-checked="false"]' );
		} ) ).toBeNull();
	} );
} );
<commit_msg>Try fixing tests.<commit_after>/**
 * WordPress dependencies
 */
import { createNewPost, clickButton, saveDraft } from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import { activateExperience, deactivateExperience, insertBlock, selectBlockByClassName } from '../../utils';

describe( 'Story Animations', () => {
	beforeAll( async () => {
		await activateExperience( 'stories' );
	} );

	afterAll( async () => {
		await deactivateExperience( 'stories' );
	} );

	beforeEach( async () => {
		await createNewPost( { postType: 'amp_story' } );
	} );

	it( 'should save correct animation values', async () => {
		// Add Author block with animation.
		await insertBlock( 'Author' );
		await page.waitForSelector( '.components-select-control__input' );
		await page.select( '.components-select-control__input', 'fly-in-bottom' );
		await page.waitForSelector( 'input[aria-label="Delay (ms)"]' );
		await page.type( 'input[aria-label="Delay (ms)"]', '15' );

		await saveDraft();
		await page.reload();

		await page.waitForSelector( '.wp-block-amp-amp-story-post-author' );

		await selectBlockByClassName( 'wp-block-amp-amp-story-post-author' );
		await page.waitForSelector( 'input[aria-label="Delay (ms)"]' );

		expect( await page.evaluate( () => {
			return document.querySelector( 'input[aria-label="Delay (ms)"]' ).value;
		} ) ).toBe( '15' );

		expect( await page.evaluate( () => {
			return document.querySelector( '.components-select-control__input [value="fly-in-bottom"]' ).selected;
		} ) ).toBe( true );
	} );

	it( 'should save correct animation after values', async () => {
		// Add Author block with animation.
		await insertBlock( 'Author' );
		await page.waitForSelector( '.components-select-control__input' );
		await page.select( '.components-select-control__input', 'fly-in-bottom' );

		// Add Date block with animation.
		await insertBlock( 'Date' );
		await page.waitForSelector( '.components-select-control__input' );
		await page.select( '.components-select-control__input', 'pulse' );

		// Add Author block as Begin After.
		await page.waitForSelector( 'button[aria-label="Begin immediately"]' );
		await clickButton( 'Immediately' );

		page.waitForSelector( '.components-animate__appear button[aria-checked="false"]' );
		await page.click( '.components-animate__appear button[aria-checked="false"]' );
		await saveDraft();
		await page.reload();

		await page.waitForSelector( '.wp-block-amp-amp-story-post-date' );
		await selectBlockByClassName( 'wp-block-amp-amp-story-post-date' );

		page.waitForSelector( '.components-animate__appear button[aria-label="Begin after: Story Author"]' );

		expect( await page.evaluate( () => {
			//return document.querySelector( '.components-animate__appear button[aria-label="Begin after: Story Author"]' ).innerHTML;
		} ) ).toContain( 'admin' );
	} );

	it( 'should not allow creating a cycle in animation after', async () => {
		// Add Author block with animation.
		await insertBlock( 'Author' );
		await page.select( '.components-select-control__input', 'fly-in-bottom' );

		// Add Date block with animation.
		await insertBlock( 'Date' );
		await page.select( '.components-select-control__input', 'pulse' );
		await page.waitForSelector( 'label[for="amp-stories-animation-order-picker"]' );
		await clickButton( 'Immediately' );

		await page.waitForSelector( '.components-animate__appear button[aria-checked="false"]' );
		await page.click( '.components-animate__appear button[aria-checked="false"]' );

		await selectBlockByClassName( 'wp-block-amp-amp-story-post-author' );

		await page.waitForSelector( 'label[for="amp-stories-animation-order-picker"]' );
		await clickButton( 'Immediately' );
		await page.waitForSelector( '.components-animate__appear' );

		expect( await page.evaluate( () => {
			return document.querySelector( '.components-animate__appear button[aria-checked="false"]' );
		} ) ).toBeNull();
	} );
} );
<|endoftext|>


<commit_before>import { connect } from "react-redux";
import { updateSession } from "../../../shared/util";
import { setConfig } from "../../../shared/ducks/config";
import TaxonPageTabs from "../components/taxon_page_tabs";
import {
  fetchDescription,
  fetchLinks,
  fetchNames,
  fetchInteractions,
  fetchTrending,
  fetchRare,
  fetchSimilar,
  showPhotoChooser
} from "../../shared/ducks/taxon";

function mapStateToProps( state ) {
  const speciesTabs = ["map", "articles", "taxonomy", "status", "similar"];
  const aboveSpeciesTabs = ["map", "articles", "highlights", "taxonomy"];
  let chosenTab = "map";
  if (
    ( state.taxon.taxon.rank_level <= 10 && speciesTabs.indexOf( state.config.chosenTab ) >= 0 ) ||
    ( state.taxon.taxon.rank_level > 10 && aboveSpeciesTabs.indexOf( state.config.chosenTab ) >= 0 )
  ) {
    chosenTab = state.config.chosenTab;
  }
  return {
    taxon: state.taxon.taxon,
    currentUser: state.config.currentUser,
    chosenTab
  };
}

function mapDispatchToProps( dispatch ) {
  const loadDataForTab = tab => {
    switch ( tab ) {
      case "articles":
        dispatch( fetchDescription( ) );
        dispatch( fetchLinks( ) );
        break;
      case "taxonomy":
        dispatch( fetchNames( ) );
        break;
      case "interactions":
        dispatch( fetchInteractions( ) );
        break;
      case "highlights":
        dispatch( fetchTrending( ) );
        dispatch( fetchRare( ) );
        break;
      case "similar":
        dispatch( fetchSimilar( ) );
        break;
      default:
        // it's cool, you probably have what you need
    }
  };
  return {
    showPhotoChooserModal: ( ) => dispatch( showPhotoChooser( ) ),
    choseTab: tab => {
      dispatch( setConfig( { chosenTab: tab } ) );
      loadDataForTab( tab );
      updateSession( { preferred_taxon_page_tab: tab } );
    },
    loadDataForTab
  };
}

const TaxonPageTabsContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)( TaxonPageTabs );

export default TaxonPageTabsContainer;
<commit_msg>Removed default tab choice (should be set in the component)<commit_after>import { connect } from "react-redux";
import { updateSession } from "../../../shared/util";
import { setConfig } from "../../../shared/ducks/config";
import TaxonPageTabs from "../components/taxon_page_tabs";
import {
  fetchDescription,
  fetchLinks,
  fetchNames,
  fetchInteractions,
  fetchTrending,
  fetchRare,
  fetchSimilar,
  showPhotoChooser
} from "../../shared/ducks/taxon";

function mapStateToProps( state ) {
  const speciesTabs = ["map", "articles", "taxonomy", "status", "similar"];
  const aboveSpeciesTabs = ["map", "articles", "highlights", "taxonomy"];
  let chosenTab;
  if (
    ( state.taxon.taxon.rank_level <= 10 && speciesTabs.indexOf( state.config.chosenTab ) >= 0 ) ||
    ( state.taxon.taxon.rank_level > 10 && aboveSpeciesTabs.indexOf( state.config.chosenTab ) >= 0 )
  ) {
    chosenTab = state.config.chosenTab;
  }
  return {
    taxon: state.taxon.taxon,
    currentUser: state.config.currentUser,
    chosenTab
  };
}

function mapDispatchToProps( dispatch ) {
  const loadDataForTab = tab => {
    switch ( tab ) {
      case "articles":
        dispatch( fetchDescription( ) );
        dispatch( fetchLinks( ) );
        break;
      case "taxonomy":
        dispatch( fetchNames( ) );
        break;
      case "interactions":
        dispatch( fetchInteractions( ) );
        break;
      case "highlights":
        dispatch( fetchTrending( ) );
        dispatch( fetchRare( ) );
        break;
      case "similar":
        dispatch( fetchSimilar( ) );
        break;
      default:
        // it's cool, you probably have what you need
    }
  };
  return {
    showPhotoChooserModal: ( ) => dispatch( showPhotoChooser( ) ),
    choseTab: tab => {
      dispatch( setConfig( { chosenTab: tab } ) );
      loadDataForTab( tab );
      updateSession( { preferred_taxon_page_tab: tab } );
    },
    loadDataForTab
  };
}

const TaxonPageTabsContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)( TaxonPageTabs );

export default TaxonPageTabsContainer;
<|endoftext|>


<commit_before>'use strict';

var IJ = require('../../..');
var invertRGBA = require('../../../lib/filter/invert').invertRGBA;

describe('invert 3 components', function () {
    it('should invert colors, not alpha', function () {

        var image = new IJ(1,2,[230, 83, 120, 255, 100, 140, 13, 240]);

        var inverted = [25, 172, 135, 255, 155, 115, 242, 240];

        image.invert();
        image.data.should.eql(inverted);

    });
});
<commit_msg>remove unused import<commit_after>'use strict';

var IJ = require('../../..');

describe('invert 3 components', function () {
    it('should invert colors, not alpha', function () {

        var image = new IJ(1,2,[230, 83, 120, 255, 100, 140, 13, 240]);

        var inverted = [25, 172, 135, 255, 155, 115, 242, 240];

        image.invert();
        image.data.should.eql(inverted);

    });
});
<|endoftext|>


<commit_before>var CoreView = require('backbone/core-view');
var _ = require('underscore');
var template = require('./editor-header.tpl');
var moment = require('moment');
var ContextMenuView = require('../components/context-menu/context-menu-view');
var CustomListCollection = require('../components/custom-list/custom-list-collection');
var ConfirmationView = require('../components/modals/confirmation/modal-confirmation-view');
var templateConfirmation = require('./delete-map-confirmation.tpl');
var removeMap = require('./map-operations/remove-map');
var renameMap = require('./map-operations/rename-map');
var InlineEditorView = require('../components/inline-editor/inline-editor-view');
var templateInlineEditor = require('./inline-editor.tpl');

module.exports = CoreView.extend({
  events: {
    'click .js-privacy': '_onClickPrivacy',
    'click .js-toggle-menu': '_onToggleContextMenuClicked'
  },

  initialize: function (opts) {
    if (!opts.editorModel) throw new Error('editorModel is required');
    if (!opts.modals) throw new Error('modals is required');
    if (!opts.visDefinitionModel) throw new Error('visDefinitionModel is required');
    if (!opts.privacyCollection) throw new Error('privacyCollection is required');
    if (!opts.onClickPrivacy) throw new Error('onClickPrivacy is required');

    this._editorModel = opts.editorModel;
    this._modals = opts.modals;
    this._visDefinitionModel = opts.visDefinitionModel;
    this._title = this._visDefinitionModel.get('name');
    this._privacyCollection = opts.privacyCollection;
    this._mapcapsCollection = opts.mapcapsCollection;

    _.bind(this._changeStyle, this);
    this._bindEvents();

    this._mapcapsCollection.fetch({reset: true});
  },

  render: function () {
    var model = this._privacyCollection.searchByPrivacy(this._visDefinitionModel.get('privacy'));
    var published = this._mapcapsCollection.length > 0
                    ? _t('editor.published', { when: moment(this._mapcapsCollection.first().get('created_at')).fromNow() })
                    : '';
    this.$el.html(
      template({
        title: this._title,
        privacy: model.get('privacy'),
        cssClass: model.get('cssClass'),
        published: published
      })
    );

    this._initViews();
    return this;
  },

  _initViews: function () {
    var self = this;
    this._inlineEditor = new InlineEditorView({
      template: templateInlineEditor,
      renderOptions: {
        name: self._visDefinitionModel.get('name')
      },
      onEdit: self._renameMap.bind(self)
    });

    this.$('.js-header').append(this._inlineEditor.render().el);
  },

  _bindEvents: function () {
    this.listenTo(this._visDefinitionModel, 'change:privacy', this.render);
    this.add_related_model(this._visDefinitionModel);

    this.listenTo(this._editorModel, 'change:edition', this._changeStyle);
    this.add_related_model(this._editorModel);

    this._mapcapsCollection.on('add reset', this.render, this);
    this.add_related_model(this._mapcapsCollection);
  },

  _renameMap: function () {
    var newName = this._inlineEditor.getValue();

    if (newName !== '' && newName !== this._visDefinitionModel.get('name')) {
      // Speed!
      this._onRenameSuccess(newName);

      renameMap({
        newName: newName,
        visDefinitionModel: this._visDefinitionModel,
        onError: this._onRenameError.bind(this)
      });
    }
  },

  _onToggleContextMenuClicked: function (event) {
    if (this._hasContextMenu()) {
      this._hideContextMenu();
    } else {
      this._showContextMenu({
        x: event.pageX,
        y: event.pageY
      });
    }
  },

  _hasContextMenu: function () {
    return this._menuView != null;
  },

  _showContextMenu: function (position) {
    var menuItems = new CustomListCollection([{
      label: _t('editor.maps.options.rename'),
      val: 'rename-map'
    }, {
      label: _t('editor.maps.options.remove'),
      val: 'delete-map',
      destructive: true
    }]);

    var triggerElementID = 'context-menu-trigger-' + this.cid;
    this.$('.js-toggle-menu').attr('id', triggerElementID);
    this._menuView = new ContextMenuView({
      collection: menuItems,
      triggerElementID: triggerElementID,
      position: position
    });

    menuItems.bind('change:selected', function (menuItem) {
      if (menuItem.get('val') === 'delete-map') {
        this._confirmDeleteLayer();
      }
      if (menuItem.get('val') === 'rename-map') {
        this._inlineEditor.edit();
      }
    }, this);

    this._menuView.model.bind('change:visible', function (model, isContextMenuVisible) {
      if (this._hasContextMenu() && !isContextMenuVisible) {
        this._hideContextMenu();
      }
    }, this);

    this._menuView.show();
    this.addView(this._menuView);
  },

  _confirmDeleteLayer: function () {
    var self = this;
    var mapName = this._visDefinitionModel.get('name');

    this._modals.create(function (modalModel) {
      return new ConfirmationView({
        modalModel: modalModel,
        template: templateConfirmation,
        loadingTitle: _t('editor.maps.delete.loading', {name: mapName}),
        renderOpts: {
          name: mapName
        },
        runAction: function () {
          removeMap({
            onSuccess: self._onSuccessDestroyMap.bind(self, modalModel),
            visDefinitionModel: self._visDefinitionModel
          });
        }
      });
    });
  },

  _hideContextMenu: function () {
    this._menuView.remove();
    this.removeView(this._menuView);
    delete this._menuView;
  },

  _onSuccessDestroyMap: function (modal) {
    this.options.onRemoveMap && this.options.onRemoveMap();
  },

  _onErrorDestroyMap: function (modal) {
    modal.destroy();
  },

  _onRenameSuccess: function (newName) {
    this.$('.js-title').text(newName).show();
    this._inlineEditor.hide();
  },

  _onRenameError: function (oldName) {
    this.$('.js-title').text(oldName).show();
    this._inlineEditor.hide();
  },

  _changeStyle: function (m) {
    this._getTitle().toggleClass('is-dark', m.isEditing());
  },

  _getTitle: function () {
    return this.$('.Editor-HeaderInfo');
  },

  _onClickPrivacy: function () {
    this.options.onClickPrivacy && this.options.onClickPrivacy();
  }
});
<commit_msg>add dummy skeleton to options menu<commit_after>var CoreView = require('backbone/core-view');
var _ = require('underscore');
var template = require('./editor-header.tpl');
var moment = require('moment');
var ContextMenuView = require('../components/context-menu/context-menu-view');
var CustomListCollection = require('../components/custom-list/custom-list-collection');
var ConfirmationView = require('../components/modals/confirmation/modal-confirmation-view');
var templateConfirmation = require('./delete-map-confirmation.tpl');
var removeMap = require('./map-operations/remove-map');
var renameMap = require('./map-operations/rename-map');
var InlineEditorView = require('../components/inline-editor/inline-editor-view');
var templateInlineEditor = require('./inline-editor.tpl');

module.exports = CoreView.extend({
  events: {
    'click .js-privacy': '_onClickPrivacy',
    'click .js-toggle-menu': '_onToggleContextMenuClicked'
  },

  initialize: function (opts) {
    if (!opts.editorModel) throw new Error('editorModel is required');
    if (!opts.modals) throw new Error('modals is required');
    if (!opts.visDefinitionModel) throw new Error('visDefinitionModel is required');
    if (!opts.privacyCollection) throw new Error('privacyCollection is required');
    if (!opts.onClickPrivacy) throw new Error('onClickPrivacy is required');

    this._editorModel = opts.editorModel;
    this._modals = opts.modals;
    this._visDefinitionModel = opts.visDefinitionModel;
    this._title = this._visDefinitionModel.get('name');
    this._privacyCollection = opts.privacyCollection;
    this._mapcapsCollection = opts.mapcapsCollection;

    _.bind(this._changeStyle, this);
    this._bindEvents();

    this._mapcapsCollection.fetch({reset: true});
  },

  render: function () {
    var model = this._privacyCollection.searchByPrivacy(this._visDefinitionModel.get('privacy'));
    var published = this._mapcapsCollection.length > 0
                    ? _t('editor.published', { when: moment(this._mapcapsCollection.first().get('created_at')).fromNow() })
                    : '';
    this.$el.html(
      template({
        title: this._title,
        privacy: model.get('privacy'),
        cssClass: model.get('cssClass'),
        published: published
      })
    );

    this._initViews();
    return this;
  },

  _initViews: function () {
    var self = this;
    this._inlineEditor = new InlineEditorView({
      template: templateInlineEditor,
      renderOptions: {
        name: self._visDefinitionModel.get('name')
      },
      onEdit: self._renameMap.bind(self)
    });

    this.$('.js-header').append(this._inlineEditor.render().el);
  },

  _bindEvents: function () {
    this.listenTo(this._visDefinitionModel, 'change:privacy', this.render);
    this.add_related_model(this._visDefinitionModel);

    this.listenTo(this._editorModel, 'change:edition', this._changeStyle);
    this.add_related_model(this._editorModel);

    this._mapcapsCollection.on('add reset', this.render, this);
    this.add_related_model(this._mapcapsCollection);
  },

  _renameMap: function () {
    var newName = this._inlineEditor.getValue();

    if (newName !== '' && newName !== this._visDefinitionModel.get('name')) {
      // Speed!
      this._onRenameSuccess(newName);

      renameMap({
        newName: newName,
        visDefinitionModel: this._visDefinitionModel,
        onError: this._onRenameError.bind(this)
      });
    }
  },

  _onToggleContextMenuClicked: function (event) {
    if (this._hasContextMenu()) {
      this._hideContextMenu();
    } else {
      this._showContextMenu({
        x: event.pageX,
        y: event.pageY
      });
    }
  },

  _hasContextMenu: function () {
    return this._menuView != null;
  },

  _showContextMenu: function (position) {
    var menuItems = new CustomListCollection([{
      label: _t('editor.maps.options.rename'),
      val: 'rename-map'
    },
    {
      label: _t('editor.maps.options.export-map'),
      val: 'export-map'
    }, {
      label: _t('editor.maps.options.remove'),
      val: 'delete-map',
      destructive: true
    }]);

    var triggerElementID = 'context-menu-trigger-' + this.cid;
    this.$('.js-toggle-menu').attr('id', triggerElementID);
    this._menuView = new ContextMenuView({
      collection: menuItems,
      triggerElementID: triggerElementID,
      position: position
    });

    menuItems.bind('change:selected', function (menuItem) {
      if (menuItem.get('val') === 'delete-map') {
        this._confirmDeleteLayer();
      }
      if (menuItem.get('val') === 'export-map') {
        this._exportMap();
      }
      if (menuItem.get('val') === 'rename-map') {
        this._inlineEditor.edit();
      }
    }, this);

    this._menuView.model.bind('change:visible', function (model, isContextMenuVisible) {
      if (this._hasContextMenu() && !isContextMenuVisible) {
        this._hideContextMenu();
      }
    }, this);

    this._menuView.show();
    this.addView(this._menuView);
  },

  _confirmDeleteLayer: function () {
    var self = this;
    var mapName = this._visDefinitionModel.get('name');

    this._modals.create(function (modalModel) {
      return new ConfirmationView({
        modalModel: modalModel,
        template: templateConfirmation,
        loadingTitle: _t('editor.maps.delete.loading', {name: mapName}),
        renderOpts: {
          name: mapName
        },
        runAction: function () {
          removeMap({
            onSuccess: self._onSuccessDestroyMap.bind(self, modalModel),
            visDefinitionModel: self._visDefinitionModel
          });
        }
      });
    });
  },

  _exportMap: function () {
    console.log('Hola');
  }

  _hideContextMenu: function () {
    this._menuView.remove();
    this.removeView(this._menuView);
    delete this._menuView;
  },

  _onSuccessDestroyMap: function (modal) {
    this.options.onRemoveMap && this.options.onRemoveMap();
  },

  _onErrorDestroyMap: function (modal) {
    modal.destroy();
  },

  _onRenameSuccess: function (newName) {
    this.$('.js-title').text(newName).show();
    this._inlineEditor.hide();
  },

  _onRenameError: function (oldName) {
    this.$('.js-title').text(oldName).show();
    this._inlineEditor.hide();
  },

  _changeStyle: function (m) {
    this._getTitle().toggleClass('is-dark', m.isEditing());
  },

  _getTitle: function () {
    return this.$('.Editor-HeaderInfo');
  },

  _onClickPrivacy: function () {
    this.options.onClickPrivacy && this.options.onClickPrivacy();
  }
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var acorn = require("acorn"), fs = require("fs"), idast = require("../idast"), walk = require("acorn/util/walk");

if (process.argv.length != 3) {
  console.log("Usage:", process.argv[0], "<input-file>");
  process.exit(1);
}

var file = process.argv[2];
console.error("# AST node IDs in '" + file + "':");
var i = 0;
// walk.simple(acorn.parse(fs.readFileSync(file)), {
//   Statement: function(node, st) {
//     console.log(st);
//     i++;
//   },
//   Expression: function(node, st) {
//     console.log(st);
//     i++;
//   },
// }, idast.base, "");
walk.recursive(acorn.parse(fs.readFileSync(file)), "", {
  Node: function(node, st, c) {
    console.log(st, "@", node.start + ":" + node.end);
  },
}, idast.base);
console.error("# Printed " + i + " AST node IDs in '" + file + "'");
<commit_msg>Rm commented out code<commit_after>#!/usr/bin/env node

var acorn = require("acorn"), fs = require("fs"), idast = require("../idast"), walk = require("acorn/util/walk");

if (process.argv.length != 3) {
  console.log("Usage:", process.argv[0], "<input-file>");
  process.exit(1);
}

var file = process.argv[2];
console.error("# AST node IDs in '" + file + "':");
var i = 0;
walk.recursive(acorn.parse(fs.readFileSync(file)), "", {
  Node: function(node, st, c) {
    console.log(st, "@", node.start + ":" + node.end);
  },
}, idast.base);
console.error("# Printed " + i + " AST node IDs in '" + file + "'");
<|endoftext|>


<commit_before>/**
 * This class manages the activity information of all text-lines of the pad
 *
 * @class activity
 */

var panel = require('./panel');

var activity = function() {

    var debug = true;

    /**
     * This array contains all text-lines of the pad with their current activity
     * structure:
     *    key => [ divid, activity ]
     *    ... with key = linenumber-1
     *
     * }
     *
     * @property ep_activity
     * @type {[[Number]]}
     */
    var ep_activity = new Array();

    /**
     * containing all callbacks,
     * called when heat on one line is big enough
     */
    var hooks = new Array();

    /**
     * default settings
     *
     * @property settings
     * @type {Object}
     */
    var default_increase_amount = 1;    // default amount for increasing activity

    /**
     * Decay of activity - gets called once per second from aceEditEvent
     * decrements all activity-values > 0 of max(0.01, 5%)
     *
     * @method _decay
     */
    var _decay = function() {
        //TODO: add trigger for changeEvent
        for(var i=0; i<ep_activity.length; i++) {
            if (ep_activity[i][1]>0) {
                var temp_debug = ep_activity[i][1];
                ep_activity[i][1] = Math.max( 0, ep_activity[i][1]-Math.max(0.01, 0.20*ep_activity[i][1]) );
            }
        }
        checkForHighestTemperature();
    };

    function checkForHighestTemperature() {
        var line = -1;
        var highestTemperature = 0.0;
        //console.log("-----------------------------------------");
        ep_activity.forEach(function(element, index) {
            //console.log(index + " - " + element[1]);
            if(element[1] > highestTemperature) {
                line = index;
            }
        });
        hooks.forEach(function(element) {
            element(line);
        });
    }
<<<<<<< HEAD

    /**
     * evaluate div-array from editor for changes.
     *
     * @method _evalArray
     * @param {Array} divArray containig all divs from editor
     * @param {Function} callback callback, when evaluation is done
     */
    var _evalArray = function(divArray, callback) {
        if(divArray.length == 0) {
            callback(); // nothing to do here
            return;
        }
        var sanitizedArray = sanitizeArray(divArray);
        if(ep_activity.length == sanitizedArray.length) {
            for(var i = 0; i < ep_activity.length; i++) {
                if(ep_activity[i][0] != sanitizedArray[i][0]) {
                    ep_activity[i][0] = sanitizedArray[i][0];
                    ep_activity[i][1] = ep_activity[i][1] + default_increase_amount;
                }
            }
        } else {
            for(var index = 0; index < sanitizedArray.length; index++) {
                sanitizedArray[index][1] = getOldActivity(sanitizedArray[index][0]);
            }
            ep_activity = sanitizedArray;
        }
        callback();
    };

    function getOldActivity(id) {
        var old_activity = 1.0;
        ep_activity.forEach(function(element) {
            if(element[0] === id) {
                old_activity = element[1];
            }
        });
        return old_activity;
    }

    function sanitizeArray(divArray) {
        var tmp = new Array();
        for(var i = 0; i < divArray.length; i++) {
            var element = divArray[i];
            tmp.push([element.id.replace("magicdomid", ""), 1.0]);
        }
        return tmp;
    }

    /**
     * returns copy of ep_activity array
     * so it's not possible to directly change the epactivity
     * outside the module
     *
     * @method _getall
     */
    var _getall = function() {
        return ep_activity.slice();
    };

    var _register = function(callback) {
        console.log("REGISTER NEW HOOK");
        hooks.push(callback) ;
    };

    return {
        decay : _decay,
        getall : _getall,
        evalArray: _evalArray,
        register: _register
    };

}();

module.exports = activity;
<commit_msg>forgot something..<commit_after>/**
 * This class manages the activity information of all text-lines of the pad
 *
 * @class activity
 */

var panel = require('./panel');

var activity = function() {

    var debug = true;

    /**
     * This array contains all text-lines of the pad with their current activity
     * structure:
     *    key => [ divid, activity ]
     *    ... with key = linenumber-1
     *
     * }
     *
     * @property ep_activity
     * @type {[[Number]]}
     */
    var ep_activity = new Array();

    /**
     * containing all callbacks,
     * called when heat on one line is big enough
     */
    var hooks = new Array();

    /**
     * default settings
     *
     * @property settings
     * @type {Object}
     */
    var default_increase_amount = 1;    // default amount for increasing activity

    /**
     * Decay of activity - gets called once per second from aceEditEvent
     * decrements all activity-values > 0 of max(0.01, 5%)
     *
     * @method _decay
     */
    var _decay = function() {
        //TODO: add trigger for changeEvent
        for(var i=0; i<ep_activity.length; i++) {
            if (ep_activity[i][1]>0) {
                var temp_debug = ep_activity[i][1];
                ep_activity[i][1] = Math.max( 0, ep_activity[i][1]-Math.max(0.01, 0.20*ep_activity[i][1]) );
            }
        }
        checkForHighestTemperature();
    };

    function checkForHighestTemperature() {
        var line = -1;
        var highestTemperature = 0.0;
        //console.log("-----------------------------------------");
        ep_activity.forEach(function(element, index) {
            //console.log(index + " - " + element[1]);
            if(element[1] > highestTemperature) {
                line = index;
            }
        });
        hooks.forEach(function(element) {
            element(line);
        });
    }

    /**
     * evaluate div-array from editor for changes.
     *
     * @method _evalArray
     * @param {Array} divArray containig all divs from editor
     * @param {Function} callback callback, when evaluation is done
     */
    var _evalArray = function(divArray, callback) {
        if(divArray.length == 0) {
            callback(); // nothing to do here
            return;
        }
        var sanitizedArray = sanitizeArray(divArray);
        if(ep_activity.length == sanitizedArray.length) {
            for(var i = 0; i < ep_activity.length; i++) {
                if(ep_activity[i][0] != sanitizedArray[i][0]) {
                    ep_activity[i][0] = sanitizedArray[i][0];
                    ep_activity[i][1] = ep_activity[i][1] + default_increase_amount;
                }
            }
        } else {
            for(var index = 0; index < sanitizedArray.length; index++) {
                sanitizedArray[index][1] = getOldActivity(sanitizedArray[index][0]);
            }
            ep_activity = sanitizedArray;
        }
        callback();
    };

    function getOldActivity(id) {
        var old_activity = 1.0;
        ep_activity.forEach(function(element) {
            if(element[0] === id) {
                old_activity = element[1];
            }
        });
        return old_activity;
    }

    function sanitizeArray(divArray) {
        var tmp = new Array();
        for(var i = 0; i < divArray.length; i++) {
            var element = divArray[i];
            tmp.push([element.id.replace("magicdomid", ""), 1.0]);
        }
        return tmp;
    }

    /**
     * returns copy of ep_activity array
     * so it's not possible to directly change the epactivity
     * outside the module
     *
     * @method _getall
     */
    var _getall = function() {
        return ep_activity.slice();
    };

    var _register = function(callback) {
        console.log("REGISTER NEW HOOK");
        hooks.push(callback) ;
    };

    return {
        decay : _decay,
        getall : _getall,
        evalArray: _evalArray,
        register: _register
    };

}();

module.exports = activity;
<|endoftext|>