<commit_before>'use strict';

// Basic template description.
exports.description = 'Create a complete Chaplin.js application.';

// Template-specific notes to be displayed before question prompts.
exports.notes = '';

// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';

// The initialize template.
exports.template = function(grunt, init, done) {
  var _ = grunt.util._;

  init.process({}, [
    // Prompt for the following values.
    // Built-In
    init.prompt('name'),
    init.prompt('description'),
    init.prompt('version'),
    init.prompt('repository'),
    init.prompt('homepage'),
    init.prompt('bugs'),
    init.prompt('licenses'),
    init.prompt('author_name'),
    init.prompt('author_email'),
    init.prompt('author_url'),
    // Custom
    {
      name: 'language',
      message: 'Language',
      default: 'coffee',
      validator: /coffee|js/,
      warning: 'Must be either "coffee" for coffee-script or "js" ' +
        'for javascript'
    }, {
      name: 'templateLanguage',
      message: 'Micro-templating language',
      default: 'handlebars',
      validator: /handlebars|haml|underscore/,
      warning: 'Must be one of the following template languages: ' +
        'handlebars, haml, or underscore.'
    }, {
      name: 'preprocessor',
      message: 'Stylesheet preprocessor',
      default: 'stylus',
      validator: /sass|scss|less|stylus|none/,
      warning: 'Must be one of the following preprocessors: ' +
        'sass, scss, less, stylus, or none (to indicate no preprocessor).'
    }, {
      name: 'bootstrap',
      message: 'Include Twitter Bootstrap?',
      default: 'Y/n',
      warning: 'Yes: Twitter bootstrap is included; no: it\'s not.',
    }
  ], function(err, props) {
    // Files to copy (and process).
    var files = init.filesToCopy(props);

    // Normalize options.
    props.bootstrap = /y/i.test(props.bootstrap);
    props.preprocessor = props.preprocessor ? props.preprocessor : 'none';

    // Remove files that aren't of the language requested.
    var lang = props.language === 'coffee' ? 'js' : 'coffee';
    files = _.omit(files, function(value, key) {
      if (/^src\/scripts\/vendor/.test(key)) return false;
      return _.endsWith(key, lang);
    });

    // Remove files that aren't of the template language requested.
    var templateLanguages = {
      haml: '.haml',
      handlebars: '.hbs'
    };

    delete templateLanguages[props.templateLanguage];
    files = _.omit(files, function(value, key) {
      return _.any(templateLanguages, function(lang) {
        return _.endsWith(key, lang);
      });
    });

    if (props.templateLanguage === 'haml') {
      // Haml can provide the index file.
      // TODO: Should we generalize this check so other template languages
      //  that can be rendered as well as pre-compiled could be used?
      delete files['src/index.html'];
    }

    // Remove stylesheets that aren't part of the preprocessor requested.
    var preprocessors = {
      none: '.css',
      scss: '.scss',
      sass: '.sass',
      less: '.less',
      stylus: '.styl'
    };

    delete preprocessors[props.preprocessor];
    files = _.omit(files, function(value, key) {
      return _.any(preprocessors, function(lang) {
        return _.endsWith(key, lang);
      });
    });

    // Gather standard and additional dependencies.
    var devDependencies = {
      'grunt': '0.4.x',
      'grunt-contrib-clean': '0.4.0rc6',
      'grunt-contrib-copy': '0.4.0rc7',
      'grunt-contrib-connect': '0.1.1rc6',
      'grunt-contrib-watch': '0.2.0rc7',
      'grunt-requirejs': '0.3.x',
      'grunt-contrib-mincss': '0.4.0rc7',
      'grunt-contrib-htmlmin': '0.1.1rc7',
      'grunt-bower-task': '0.1.x',
      'grunt-urequire': 'git://github.com/aearly/grunt-urequire.git',
      // grunt-urequire requires lodash incorrectly,
      // see: https://github.com/aearly/grunt-urequire/pull/3
      'lodash': '0.10.x',
      'connect-url-rewrite': '0.1.x'
    };

    // Language libraries
    switch (props.language) {
    case 'js':
      devDependencies['grunt-contrib-jshint'] = '0.1.1rc6';
      break;

    case 'coffee':
      devDependencies['grunt-contrib-coffee'] = '0.4.0rc7';
      devDependencies['grunt-coffeelint'] =
        // NPM seems to be out-dated; master works with grunt 0.4.x
        'git://github.com/vojtajina/grunt-coffeelint.git';
      break;
    }

    // Micro-templating library
    switch (props.templateLanguage) {
    case 'haml':
      devDependencies['grunt-haml'] = '0.3.x';

    case 'handlebars':
      // Waiting on a pull request to add modular AMD
      // See: https://github.com/gruntjs/grunt-contrib-handlebars/pull/24
      devDependencies['grunt-contrib-handlebars'] =
        'git://github.com/concordusapps/grunt-contrib-handlebars.git';
      break;
    }

    if (props.templateLanguage !== 'haml') {
      // Remove the HAML runtime.
      delete files['src/scripts/lib/haml.coffee'];
      delete files['src/scripts/lib/haml.js'];
    }

    // Stylesheet preprocessor
    switch (props.preprocessor) {
    case 'sass':
    case 'scss':
      devDependencies['grunt-contrib-compass'] = '0.1.x';
      break;

    case 'stylus':
      devDependencies['grunt-contrib-stylus'] = '0.4.0rc7';
      break;

    case 'less':
      devDependencies['grunt-contrib-less'] = '0.5.x';
      break;
    }

    // Add properly-named license files.
    init.addLicenseFiles(files, props.licenses);

    // Actually copy (and process) files.
    init.copyAndProcess(files, props);

    // Generate package.json file.
    init.writePackageJSON('package.json', _.extend(props, {
      keywords: [],
      node_version: '0.8.x',
      devDependencies: devDependencies
    }));

    // Gather client-side, browser dependencies
    // Collect the standard ones.
    var dependencies = {
      'jquery': '1.8.x',
      'underscore': '1.4.x',
      'backbone': '0.9.x',
      'requirejs': '2.1.x',
      'almond': '0.2.x',
      'chaplin': '0.7.x'
    };

    if (props.templateLanguage === 'handlebars') {
      // Handlebars requires a run-time library.
      dependencies['handlebars'] = '1.0.x'
    }

    // Gatrher the export overrides (these are consumed by grunt-bower-task
    // to replace the main declaration in the component.json).
    // Collect the standard ones
    var exportsOverride = {
      'jquery': {'scripts': 'jquery.js' },
      'almond': {'scripts': 'almond.js' },
      'backbone': {'scripts': 'backbone.js'},
      'requirejs': {'scripts': 'require.js'},
      'underscore': {'scripts': 'underscore.js'},
      'chaplin': {'scripts': 'amd/chaplin.js'},
    };

    if (props.templateLanguage === 'handlebars') {
      // Handlebars requires a run-time library.
      exportsOverride['handlebars'] = {'scripts': 'handlebars.runtime.js'};
    }

    if (props.bootstrap) {
      // Include the bootstrap libraries.
      switch (props.preprocessor) {
      case 'sass':
      case 'scss':
        dependencies['bootstrap-sass'] = '2.2.x';
        exportsOverride['bootstrap-sass'] = {
          'scripts': 'js/**/*.js',
          'styles': 'lib/**/*.scss',
          'images': 'img/glyphicons-*.png',
        };
        break;

      case 'less':
        dependencies['bootstrap'] = '2.2.x';
        exportsOverride['bootstrap'] = {
          'styles': 'less/*.less',
          'scripts': 'js/*.js',
          'images': 'img/glyphicons-*.png'
        };
        break;

      case 'stylus':
      default:
        dependencies['bootstrap'] = '2.2.x';
        exportsOverride['bootstrap'] = {
          'styles': 'docs/assets/css/bootstrap*.css',
          'scripts': 'js/*.js',
          'images': 'img/glyphicons-*.png'
        };
      }
    }

    // Generate a component.json file.
    init.writePackageJSON('component.json', {
      name: props.name,
      version: props.version,
      dependencies: dependencies
    }, function(pkg, props) {
      pkg.exportsOverride = exportsOverride;
      return pkg;
    });

    // All done!
    done();
  });

};
<commit_msg>Update chaplin version.<commit_after>'use strict';

// Basic template description.
exports.description = 'Create a complete Chaplin.js application.';

// Template-specific notes to be displayed before question prompts.
exports.notes = '';

// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';

// The initialize template.
exports.template = function(grunt, init, done) {
  var _ = grunt.util._;

  init.process({}, [
    // Prompt for the following values.
    // Built-In
    init.prompt('name'),
    init.prompt('description'),
    init.prompt('version'),
    init.prompt('repository'),
    init.prompt('homepage'),
    init.prompt('bugs'),
    init.prompt('licenses'),
    init.prompt('author_name'),
    init.prompt('author_email'),
    init.prompt('author_url'),
    // Custom
    {
      name: 'language',
      message: 'Language',
      default: 'coffee',
      validator: /coffee|js/,
      warning: 'Must be either "coffee" for coffee-script or "js" ' +
        'for javascript'
    }, {
      name: 'templateLanguage',
      message: 'Micro-templating language',
      default: 'handlebars',
      validator: /handlebars|haml|underscore/,
      warning: 'Must be one of the following template languages: ' +
        'handlebars, haml, or underscore.'
    }, {
      name: 'preprocessor',
      message: 'Stylesheet preprocessor',
      default: 'stylus',
      validator: /sass|scss|less|stylus|none/,
      warning: 'Must be one of the following preprocessors: ' +
        'sass, scss, less, stylus, or none (to indicate no preprocessor).'
    }, {
      name: 'bootstrap',
      message: 'Include Twitter Bootstrap?',
      default: 'Y/n',
      warning: 'Yes: Twitter bootstrap is included; no: it\'s not.',
    }
  ], function(err, props) {
    // Files to copy (and process).
    var files = init.filesToCopy(props);

    // Normalize options.
    props.bootstrap = /y/i.test(props.bootstrap);
    props.preprocessor = props.preprocessor ? props.preprocessor : 'none';

    // Remove files that aren't of the language requested.
    var lang = props.language === 'coffee' ? 'js' : 'coffee';
    files = _.omit(files, function(value, key) {
      if (/^src\/scripts\/vendor/.test(key)) return false;
      return _.endsWith(key, lang);
    });

    // Remove files that aren't of the template language requested.
    var templateLanguages = {
      haml: '.haml',
      handlebars: '.hbs'
    };

    delete templateLanguages[props.templateLanguage];
    files = _.omit(files, function(value, key) {
      return _.any(templateLanguages, function(lang) {
        return _.endsWith(key, lang);
      });
    });

    if (props.templateLanguage === 'haml') {
      // Haml can provide the index file.
      // TODO: Should we generalize this check so other template languages
      //  that can be rendered as well as pre-compiled could be used?
      delete files['src/index.html'];
    }

    // Remove stylesheets that aren't part of the preprocessor requested.
    var preprocessors = {
      none: '.css',
      scss: '.scss',
      sass: '.sass',
      less: '.less',
      stylus: '.styl'
    };

    delete preprocessors[props.preprocessor];
    files = _.omit(files, function(value, key) {
      return _.any(preprocessors, function(lang) {
        return _.endsWith(key, lang);
      });
    });

    // Gather standard and additional dependencies.
    var devDependencies = {
      'grunt': '0.4.x',
      'grunt-contrib-clean': '0.4.0rc6',
      'grunt-contrib-copy': '0.4.0rc7',
      'grunt-contrib-connect': '0.1.1rc6',
      'grunt-contrib-watch': '0.2.0rc7',
      'grunt-requirejs': '0.3.x',
      'grunt-contrib-mincss': '0.4.0rc7',
      'grunt-contrib-htmlmin': '0.1.1rc7',
      'grunt-bower-task': '0.1.x',
      'grunt-urequire': 'git://github.com/aearly/grunt-urequire.git',
      // grunt-urequire requires lodash incorrectly,
      // see: https://github.com/aearly/grunt-urequire/pull/3
      'lodash': '0.10.x',
      'connect-url-rewrite': '0.1.x'
    };

    // Language libraries
    switch (props.language) {
    case 'js':
      devDependencies['grunt-contrib-jshint'] = '0.1.1rc6';
      break;

    case 'coffee':
      devDependencies['grunt-contrib-coffee'] = '0.4.0rc7';
      devDependencies['grunt-coffeelint'] =
        // NPM seems to be out-dated; master works with grunt 0.4.x
        'git://github.com/vojtajina/grunt-coffeelint.git';
      break;
    }

    // Micro-templating library
    switch (props.templateLanguage) {
    case 'haml':
      devDependencies['grunt-haml'] = '0.3.x';

    case 'handlebars':
      // Waiting on a pull request to add modular AMD
      // See: https://github.com/gruntjs/grunt-contrib-handlebars/pull/24
      devDependencies['grunt-contrib-handlebars'] =
        'git://github.com/concordusapps/grunt-contrib-handlebars.git';
      break;
    }

    if (props.templateLanguage !== 'haml') {
      // Remove the HAML runtime.
      delete files['src/scripts/lib/haml.coffee'];
      delete files['src/scripts/lib/haml.js'];
    }

    // Stylesheet preprocessor
    switch (props.preprocessor) {
    case 'sass':
    case 'scss':
      devDependencies['grunt-contrib-compass'] = '0.1.x';
      break;

    case 'stylus':
      devDependencies['grunt-contrib-stylus'] = '0.4.0rc7';
      break;

    case 'less':
      devDependencies['grunt-contrib-less'] = '0.5.x';
      break;
    }

    // Add properly-named license files.
    init.addLicenseFiles(files, props.licenses);

    // Actually copy (and process) files.
    init.copyAndProcess(files, props);

    // Generate package.json file.
    init.writePackageJSON('package.json', _.extend(props, {
      keywords: [],
      node_version: '0.8.x',
      devDependencies: devDependencies
    }));

    // Gather client-side, browser dependencies
    // Collect the standard ones.
    var dependencies = {
      'jquery': '1.8.x',
      'underscore': '1.4.x',
      'backbone': '0.9.x',
      'requirejs': '2.1.x',
      'almond': '0.2.x',
      'chaplin': '0.8.x'
    };

    if (props.templateLanguage === 'handlebars') {
      // Handlebars requires a run-time library.
      dependencies['handlebars'] = '1.0.x'
    }

    // Gatrher the export overrides (these are consumed by grunt-bower-task
    // to replace the main declaration in the component.json).
    // Collect the standard ones
    var exportsOverride = {
      'jquery': {'scripts': 'jquery.js' },
      'almond': {'scripts': 'almond.js' },
      'backbone': {'scripts': 'backbone.js'},
      'requirejs': {'scripts': 'require.js'},
      'underscore': {'scripts': 'underscore.js'},
      'chaplin': {'scripts': 'amd/chaplin.js'},
    };

    if (props.templateLanguage === 'handlebars') {
      // Handlebars requires a run-time library.
      exportsOverride['handlebars'] = {'scripts': 'handlebars.runtime.js'};
    }

    if (props.bootstrap) {
      // Include the bootstrap libraries.
      switch (props.preprocessor) {
      case 'sass':
      case 'scss':
        dependencies['bootstrap-sass'] = '2.2.x';
        exportsOverride['bootstrap-sass'] = {
          'scripts': 'js/**/*.js',
          'styles': 'lib/**/*.scss',
          'images': 'img/glyphicons-*.png',
        };
        break;

      case 'less':
        dependencies['bootstrap'] = '2.2.x';
        exportsOverride['bootstrap'] = {
          'styles': 'less/*.less',
          'scripts': 'js/*.js',
          'images': 'img/glyphicons-*.png'
        };
        break;

      case 'stylus':
      default:
        dependencies['bootstrap'] = '2.2.x';
        exportsOverride['bootstrap'] = {
          'styles': 'docs/assets/css/bootstrap*.css',
          'scripts': 'js/*.js',
          'images': 'img/glyphicons-*.png'
        };
      }
    }

    // Generate a component.json file.
    init.writePackageJSON('component.json', {
      name: props.name,
      version: props.version,
      dependencies: dependencies
    }, function(pkg, props) {
      pkg.exportsOverride = exportsOverride;
      return pkg;
    });

    // All done!
    done();
  });

};
<|endoftext|>


<commit_before>
//   createTooltipForProteinNames.js

//  /js/createTooltipForProteinNames.js

//  Javascript for adding tooltip with PDR info to the protein names

//   Search for this JS filename for companion Java class that must be called for every Action for pages that
//   this JS file is included on.

//

//////////////////////////////////
// JavaScript directive:   all variables have to be declared with "var", maybe other things
"use strict";
////////////////////////////
var _protein_listing_webservice_base_url_set = null;
var _searchIds_protein_listing = null;

$(document).ready(function() {
	setTimeout( function() { // put in setTimeout so it doesn't run on the main page init thread
		try {
			createTooltipForProteinNames();
		} catch( e ) {
			reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
			throw e;
		}
	},10);
});

var createTooltipForProteinNames = function() {

	_protein_listing_webservice_base_url_set = $("#protein_listing_webservice_base_url_set").val();
	if ( _protein_listing_webservice_base_url_set === undefined
			|| _protein_listing_webservice_base_url_set === null
			|| _protein_listing_webservice_base_url_set === "" ) {
		return;  //  EARLY exit since no URL configured for protein listings
	}
	_searchIds_protein_listing = [];
	$(".search_id_input_field_protein_listing_tooltip_jq").each( function() {
		var $this = $( this );
		var searchId = $this.val();
		_searchIds_protein_listing.push( searchId );
	});
	setTimeout( function() { // put in setTimeout so if it fails it doesn't kill anything else
		try {
			$('.proteinName').each(function() {
				var $elementToAddToolTipTo =  $(this);
				var htmlIdString = $elementToAddToolTipTo.attr( "id" );
				var proteinIdString = htmlIdString.replace( "protein-id-", "" );
				addSingleTooltipForProteinNameOnTopRight( {$elementToAddToolTipTo: $elementToAddToolTipTo, proteinIdString: proteinIdString } );
			});
		} catch( e ) {
			reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
			throw e;
		}
	},50);
};

var __proteinDataForToolTipFormattedHTMLCache = {};

//   Add the tool tip to display on the top right of the element
window.addSingleTooltipForProteinNameOnTopRight = function( params ) {
	params.tipPosition = {
            my: 'bottom left',
            at: 'top right',
            viewport: $(window)
         };
	addSingleTooltipForProteinName( params );
};

/////////////   This does not work.  When the text is updated after the AJAX call, the position switches to bottom right.

//Add the tool tip to display on the bottom middle of the element

//var addSingleTooltipForProteinNameOnBottomMiddle = function( params ) {
//
//params.tipPosition = {
//       my: 'top center',
//       at: 'bottom center',
//       viewport: $(window)
//    };
//	addSingleTooltipForProteinName( params );
//};

window.addSingleTooltipForProteinName = function( params ) {

	_protein_listing_webservice_base_url_set = $("#protein_listing_webservice_base_url_set").val();
	if ( _protein_listing_webservice_base_url_set === undefined
			|| _protein_listing_webservice_base_url_set === null
			|| _protein_listing_webservice_base_url_set === "" ) {
		return;  //  EARLY exit since no URL configured for protein listings
	}
	if ( _searchIds_protein_listing === null ) {
		_searchIds_protein_listing = [];
		$(".search_id_input_field_protein_listing_tooltip_jq").each( function() {
			var $this = $( this );
			var searchId = $this.val();
			_searchIds_protein_listing.push( searchId );
		});
	}
	var  $elementToAddToolTipTo = params.$elementToAddToolTipTo;
	var proteinDisplayName = params.proteinDisplayName;
	var tooltipDelay = params.tooltipDelay;    //  milliseconds
	var tipPosition = params.tipPosition;
	if ( tipPosition === undefined || tipPosition === null ) {
		//  Default to position tool tip on top right corner of element
		tipPosition = {
	            my: 'bottom left',
	            at: 'top right',
	            viewport: $(window)
	         };
	}
	var proteinIdString = params.proteinIdString;
	$elementToAddToolTipTo.qtip({
              content: {
                  text: function(event, api) {
                	  var mainProteinDataFormattedHTML = __proteinDataForToolTipFormattedHTMLCache[ proteinIdString ];
                	  if ( mainProteinDataFormattedHTML !== undefined ) {
        				  if ( proteinDisplayName ) {
        					  //  Prepend Protein Display name
        					  var HTML_Addition_DisplayedProteinName =
        						  _addSingleTooltipForProteinName_HTML_Addition_DisplayedProteinName( { displayedProteinName : proteinDisplayName } );
        					  mainProteinDataFormattedHTML =
        						  HTML_Addition_DisplayedProteinName + mainProteinDataFormattedHTML;
        				  }
                		  return mainProteinDataFormattedHTML;  //   EARLY Function RETURN
                	  } else {
                		  if ( _protein_listing_webservice_base_url_set !== undefined
                				  && _protein_listing_webservice_base_url_set !== null
                				  && _protein_listing_webservice_base_url_set !== "" ) {
                				var requestData = {
                						searchId : _searchIds_protein_listing,
                						proteinSequenceVersionId : proteinIdString
                				};
                			  var _URL = "services/proteinNameForTooltip/getData";
                			  $.ajax({
                					type : "GET",
                					url : _URL,
                					data : requestData,
                					dataType : "json",
                					traditional: true  //  Force traditional serialization of the data sent
                					//   One thing this means is that arrays are sent as the object property instead of object property followed by "[]".
                					//   So proteinIdsToGetSequence array is passed as "proteinIdsToGetSequence=<value>" which is what Jersey expects
                			  })
                			  .done( function( data ) {
                				  try {
                					  //  first, show any "local" descriptions for this protein
                					  var descriptionCount = 0;
                					  if( data.annotations && data.annotations.length > 0 ) {
                						  for( var i = 0; i < data.annotations.length; i++ ) {
                							  var annotation = data.annotations[ i ];
                							  if( annotation.description != null && annotation.description.length > 0 ) {
                								  descriptionCount++;
                							  }
                						  }
                					  }
                					  var mainProteinDataFormattedHTML =  "";
                					  if( descriptionCount === 0 ) {
                						  mainProteinDataFormattedHTML += "
No description uploaded to Proxl.
";
                					  } else {
                						  mainProteinDataFormattedHTML += "
";
                    					  if( data.annotations && data.annotations.length > 0 ) {
                    						  mainProteinDataFormattedHTML += "
";
                    						  mainProteinDataFormattedHTML += "Description(s) uploaded to ProXL: ";
                    						  mainProteinDataFormattedHTML += "
";
                    						  for( var i = 0; i < data.annotations.length; i++ ) {
                    							  var annotation = data.annotations[ i ];
                        						  mainProteinDataFormattedHTML += "
";
                        						  mainProteinDataFormattedHTML += "" + annotation.description + " ";
                        						  mainProteinDataFormattedHTML += "
";
                    						  }
                    					  }
                						  mainProteinDataFormattedHTML += "
";
                					  }
                					  if ( data.dataFound ) {
                						  mainProteinDataFormattedHTML +=
                							  "
"
                							  + "From YRC PDR: "
                							  + "
"
                							  + "
Source: " + data.source + "
"
                							  + "
Name: " + data.name + "
";
                						  if ( data.description !== undefined && data.description !== null ) {
                							  mainProteinDataFormattedHTML += "
Description: " + data.description + "
";
                						  } else {
                							  mainProteinDataFormattedHTML += "
Description: Not found.
"
                						  }
                					  } else {
                						  mainProteinDataFormattedHTML += "
No data found in YRC PDR.
";
                					  }
                					  __proteinDataForToolTipFormattedHTMLCache[ proteinIdString ] = mainProteinDataFormattedHTML;
                					  var output = mainProteinDataFormattedHTML;
                					  if ( proteinDisplayName ) {
                						  var HTML_Addition_DisplayedProteinName =
                							  _addSingleTooltipForProteinName_HTML_Addition_DisplayedProteinName( { displayedProteinName : proteinDisplayName } );
                						  output =
                							  HTML_Addition_DisplayedProteinName + mainProteinDataFormattedHTML;
                					  }
                					  api.set('content.text', output);
                					} catch( e ) {
                						reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
                						throw e;
                					}
                			  } );
                			  return 'Loading listing information...'; // Set some initial text
                		  } else {
                			  return 'No listing information available';  //  Shouldn't get here
                		  }
                	  }
                  }
              },
              position: tipPosition,
              show: {
            	  delay: tooltipDelay  //  milliseconds
              }
          });
};

// tool tip HTML Addition to add the displayed protein name
var _addSingleTooltipForProteinName_HTML_Addition_DisplayedProteinName = function ( params ) {

	var displayedProteinName = params.displayedProteinName;
	var html = "
"
	  + "Full name: "
	  + displayedProteinName
	  + "
";
	return html;
};

window.createTooltipForProteinNames = createTooltipForProteinNames;

export { createTooltipForProteinNames }

<commit_msg>JS Fix: export function that is imported<commit_after>
//   createTooltipForProteinNames.js

//  /js/createTooltipForProteinNames.js

//  Javascript for adding tooltip with PDR info to the protein names

//   Search for this JS filename for companion Java class that must be called for every Action for pages that
//   this JS file is included on.

//

//////////////////////////////////
// JavaScript directive:   all variables have to be declared with "var", maybe other things
"use strict";
////////////////////////////
var _protein_listing_webservice_base_url_set = null;
var _searchIds_protein_listing = null;

$(document).ready(function() {
	setTimeout( function() { // put in setTimeout so it doesn't run on the main page init thread
		try {
			createTooltipForProteinNames();
		} catch( e ) {
			reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
			throw e;
		}
	},10);
});

var createTooltipForProteinNames = function() {

	_protein_listing_webservice_base_url_set = $("#protein_listing_webservice_base_url_set").val();
	if ( _protein_listing_webservice_base_url_set === undefined
			|| _protein_listing_webservice_base_url_set === null
			|| _protein_listing_webservice_base_url_set === "" ) {
		return;  //  EARLY exit since no URL configured for protein listings
	}
	_searchIds_protein_listing = [];
	$(".search_id_input_field_protein_listing_tooltip_jq").each( function() {
		var $this = $( this );
		var searchId = $this.val();
		_searchIds_protein_listing.push( searchId );
	});
	setTimeout( function() { // put in setTimeout so if it fails it doesn't kill anything else
		try {
			$('.proteinName').each(function() {
				var $elementToAddToolTipTo =  $(this);
				var htmlIdString = $elementToAddToolTipTo.attr( "id" );
				var proteinIdString = htmlIdString.replace( "protein-id-", "" );
				addSingleTooltipForProteinNameOnTopRight( {$elementToAddToolTipTo: $elementToAddToolTipTo, proteinIdString: proteinIdString } );
			});
		} catch( e ) {
			reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
			throw e;
		}
	},50);
};

var __proteinDataForToolTipFormattedHTMLCache = {};

//   Add the tool tip to display on the top right of the element
var addSingleTooltipForProteinNameOnTopRight = function( params ) {
	params.tipPosition = {
            my: 'bottom left',
            at: 'top right',
            viewport: $(window)
         };
	addSingleTooltipForProteinName( params );
};

/////////////   This does not work.  When the text is updated after the AJAX call, the position switches to bottom right.

//Add the tool tip to display on the bottom middle of the element

//var addSingleTooltipForProteinNameOnBottomMiddle = function( params ) {
//
//params.tipPosition = {
//       my: 'top center',
//       at: 'bottom center',
//       viewport: $(window)
//    };
//	addSingleTooltipForProteinName( params );
//};

var addSingleTooltipForProteinName = function( params ) {

	_protein_listing_webservice_base_url_set = $("#protein_listing_webservice_base_url_set").val();
	if ( _protein_listing_webservice_base_url_set === undefined
			|| _protein_listing_webservice_base_url_set === null
			|| _protein_listing_webservice_base_url_set === "" ) {
		return;  //  EARLY exit since no URL configured for protein listings
	}
	if ( _searchIds_protein_listing === null ) {
		_searchIds_protein_listing = [];
		$(".search_id_input_field_protein_listing_tooltip_jq").each( function() {
			var $this = $( this );
			var searchId = $this.val();
			_searchIds_protein_listing.push( searchId );
		});
	}
	var  $elementToAddToolTipTo = params.$elementToAddToolTipTo;
	var proteinDisplayName = params.proteinDisplayName;
	var tooltipDelay = params.tooltipDelay;    //  milliseconds
	var tipPosition = params.tipPosition;
	if ( tipPosition === undefined || tipPosition === null ) {
		//  Default to position tool tip on top right corner of element
		tipPosition = {
	            my: 'bottom left',
	            at: 'top right',
	            viewport: $(window)
	         };
	}
	var proteinIdString = params.proteinIdString;
	$elementToAddToolTipTo.qtip({
              content: {
                  text: function(event, api) {
                	  var mainProteinDataFormattedHTML = __proteinDataForToolTipFormattedHTMLCache[ proteinIdString ];
                	  if ( mainProteinDataFormattedHTML !== undefined ) {
        				  if ( proteinDisplayName ) {
        					  //  Prepend Protein Display name
        					  var HTML_Addition_DisplayedProteinName =
        						  _addSingleTooltipForProteinName_HTML_Addition_DisplayedProteinName( { displayedProteinName : proteinDisplayName } );
        					  mainProteinDataFormattedHTML =
        						  HTML_Addition_DisplayedProteinName + mainProteinDataFormattedHTML;
        				  }
                		  return mainProteinDataFormattedHTML;  //   EARLY Function RETURN
                	  } else {
                		  if ( _protein_listing_webservice_base_url_set !== undefined
                				  && _protein_listing_webservice_base_url_set !== null
                				  && _protein_listing_webservice_base_url_set !== "" ) {
                				var requestData = {
                						searchId : _searchIds_protein_listing,
                						proteinSequenceVersionId : proteinIdString
                				};
                			  var _URL = "services/proteinNameForTooltip/getData";
                			  $.ajax({
                					type : "GET",
                					url : _URL,
                					data : requestData,
                					dataType : "json",
                					traditional: true  //  Force traditional serialization of the data sent
                					//   One thing this means is that arrays are sent as the object property instead of object property followed by "[]".
                					//   So proteinIdsToGetSequence array is passed as "proteinIdsToGetSequence=<value>" which is what Jersey expects
                			  })
                			  .done( function( data ) {
                				  try {
                					  //  first, show any "local" descriptions for this protein
                					  var descriptionCount = 0;
                					  if( data.annotations && data.annotations.length > 0 ) {
                						  for( var i = 0; i < data.annotations.length; i++ ) {
                							  var annotation = data.annotations[ i ];
                							  if( annotation.description != null && annotation.description.length > 0 ) {
                								  descriptionCount++;
                							  }
                						  }
                					  }
                					  var mainProteinDataFormattedHTML =  "";
                					  if( descriptionCount === 0 ) {
                						  mainProteinDataFormattedHTML += "
No description uploaded to Proxl.
";
                					  } else {
                						  mainProteinDataFormattedHTML += "
";
                    					  if( data.annotations && data.annotations.length > 0 ) {
                    						  mainProteinDataFormattedHTML += "
";
                    						  mainProteinDataFormattedHTML += "Description(s) uploaded to ProXL: ";
                    						  mainProteinDataFormattedHTML += "
";
                    						  for( var i = 0; i < data.annotations.length; i++ ) {
                    							  var annotation = data.annotations[ i ];
                        						  mainProteinDataFormattedHTML += "
";
                        						  mainProteinDataFormattedHTML += "" + annotation.description + " ";
                        						  mainProteinDataFormattedHTML += "
";
                    						  }
                    					  }
                						  mainProteinDataFormattedHTML += "
";
                					  }
                					  if ( data.dataFound ) {
                						  mainProteinDataFormattedHTML +=
                							  "
"
                							  + "From YRC PDR: "
                							  + "
"
                							  + "
Source: " + data.source + "
"
                							  + "
Name: " + data.name + "
";
                						  if ( data.description !== undefined && data.description !== null ) {
                							  mainProteinDataFormattedHTML += "
Description: " + data.description + "
";
                						  } else {
                							  mainProteinDataFormattedHTML += "
Description: Not found.
"
                						  }
                					  } else {
                						  mainProteinDataFormattedHTML += "
No data found in YRC PDR.
";
                					  }
                					  __proteinDataForToolTipFormattedHTMLCache[ proteinIdString ] = mainProteinDataFormattedHTML;
                					  var output = mainProteinDataFormattedHTML;
                					  if ( proteinDisplayName ) {
                						  var HTML_Addition_DisplayedProteinName =
                							  _addSingleTooltipForProteinName_HTML_Addition_DisplayedProteinName( { displayedProteinName : proteinDisplayName } );
                						  output =
                							  HTML_Addition_DisplayedProteinName + mainProteinDataFormattedHTML;
                					  }
                					  api.set('content.text', output);
                					} catch( e ) {
                						reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
                						throw e;
                					}
                			  } );
                			  return 'Loading listing information...'; // Set some initial text
                		  } else {
                			  return 'No listing information available';  //  Shouldn't get here
                		  }
                	  }
                  }
              },
              position: tipPosition,
              show: {
            	  delay: tooltipDelay  //  milliseconds
              }
          });
};

// tool tip HTML Addition to add the displayed protein name
var _addSingleTooltipForProteinName_HTML_Addition_DisplayedProteinName = function ( params ) {

	var displayedProteinName = params.displayedProteinName;
	var html = "
"
	  + "Full name: "
	  + displayedProteinName
	  + "
";
	return html;
};

window.createTooltipForProteinNames = createTooltipForProteinNames;

window.addSingleTooltipForProteinNameOnTopRight = addSingleTooltipForProteinNameOnTopRight;
window.addSingleTooltipForProteinName = addSingleTooltipForProteinName;

export { createTooltipForProteinNames, addSingleTooltipForProteinNameOnTopRight, addSingleTooltipForProteinName }

<|endoftext|>


<commit_before>// Copyright 2019-2020 Google LLC
//
// 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
//
//     https://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.

/**
 * This sample demonstrates how to perform basic operations on topics with
 * the Google Cloud Pub/Sub API.
 *
 * For more information, see the README.md under /pubsub and the documentation
 * at https://cloud.google.com/pubsub/docs.
 */

'use strict';

// sample-metadata:
//   title: Publish Ordered Message
//   description: Demonstrates how to publish messages to a topic
//     with ordering. Please see "Create Subscription With Ordering" for
//     information on setting up a subscription that will receive the
//     messages with proper ordering.
//   usage: node publishOrderedMessage.js <topic-name> <data>

async function main(
  topicName = 'YOUR_TOPIC_NAME',
  data = JSON.stringify({foo: 'bar'}),
  orderingKey = 'key1'
) {
  // [START pubsub_publish_with_ordering_keys]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const topicName = 'YOUR_TOPIC_NAME';
  // const data = JSON.stringify({foo: 'bar'});
  // const orderingKey = 'key1';

  // Imports the Google Cloud client library
  const {PubSub} = require('@google-cloud/pubsub');

  // Creates a client; cache this for further use
  const pubSubClient = new PubSub();

  async function publishOrderedMessage() {
    // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
    const dataBuffer = Buffer.from(data);

    // Be sure to set an ordering key that matches other messages
    // you want to receive in order, relative to each other.
    const message = {
      data: dataBuffer,
      orderingKey: orderingKey,
    };

    // Publishes the message
    const messageId = await pubSubClient
      .topic(topicName, {enableMessageOrdering: true})
      .publishMessage(message);

    console.log(`Message ${messageId} published.`);

    return messageId;
  }

  return await publishOrderedMessage();
  // [END pubsub_publish_with_ordering_keys]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));
<commit_msg>docs(sample): regional endpoint in publish ordered message sample (#1140)<commit_after>// Copyright 2019-2020 Google LLC
//
// 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
//
//     https://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.

/**
 * This sample demonstrates how to perform basic operations on topics with
 * the Google Cloud Pub/Sub API.
 *
 * For more information, see the README.md under /pubsub and the documentation
 * at https://cloud.google.com/pubsub/docs.
 */

'use strict';

// sample-metadata:
//   title: Publish Ordered Message
//   description: Demonstrates how to publish messages to a topic
//     with ordering. Please see "Create Subscription With Ordering" for
//     information on setting up a subscription that will receive the
//     messages with proper ordering.
//   usage: node publishOrderedMessage.js <topic-name> <data>

async function main(
  topicName = 'YOUR_TOPIC_NAME',
  data = JSON.stringify({foo: 'bar'}),
  orderingKey = 'key1'
) {
  // [START pubsub_publish_with_ordering_keys]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const topicName = 'YOUR_TOPIC_NAME';
  // const data = JSON.stringify({foo: 'bar'});
  // const orderingKey = 'key1';

  // Imports the Google Cloud client library
  const {PubSub} = require('@google-cloud/pubsub');

  // Creates a client; cache this for further use
  const pubSubClient = new PubSub({
    // Sending messages to the same region ensures they are received in order
    // even when multiple publishers are used.
    apiEndpoint: 'us-east1-pubsub.googleapis.com:443',
  });

  async function publishOrderedMessage() {
    // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
    const dataBuffer = Buffer.from(data);

    // Be sure to set an ordering key that matches other messages
    // you want to receive in order, relative to each other.
    const message = {
      data: dataBuffer,
      orderingKey: orderingKey,
    };

    // Publishes the message
    const messageId = await pubSubClient
      .topic(topicName, {enableMessageOrdering: true})
      .publishMessage(message);

    console.log(`Message ${messageId} published.`);

    return messageId;
  }

  return await publishOrderedMessage();
  // [END pubsub_publish_with_ordering_keys]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var pegjs = require('pegjs');
var UglifyJS = require('uglifyjs');
var mkdirp = require('mkdirp');

var newLineChars = /(\n|\r\n|\r|\u2028|\u2029)/g;
global.indent = function ( data, tabs ) {
  return data.replace(newLineChars, function(m, nl){ return nl + (tabs || "  "); });
};

global.buildParser = function ( grammer ) {
  return "module.exports = " + pegjs.buildParser(grammer, {
    cache: false, output: "source", optimize: "speed", allowedStartRules: ["start"]
  }) + ";\n";
};

global.minify = function ( data ) {
  return UglifyJS.minify(data, { fromString: true }).code;
};

global.readFile = function ( filename ) {
  return fs.readFileSync(filename).toString();
};

global.writeFile = function ( filename, data ) {
  mkdirp.sync(filename);
  return fs.writeFileSync(filename, data);
};

global.exists = fs.existsSync;
global.lstat = fs.lstatSync;
global.basename = fs.basename;
global.dirname = fs.dirname;
global.extname = fs.extname;
global.join = path.join;
global.resolve = path.resolve;

global.lstat = function ( path ) {
  var stat = fs.lstatSync(path);
  stat.path = path;
  stat.basename = basename(path);
  stat.dirname = dirname(path);
  stat.extname = extname(path);
  return stat;
};

global.walk = function ( path, callback ) {
  var stat = lstat(path);
  if ( stat.isDirectory() )
    fs.readdirSync(path).forEach(function(item){
      walk(join(path, item), callback);
    });
  else
    callback(path, stat);
};

global.MODULE_DIR = join(__dirname, '..');
global.DIST_DIR = join(__dirname, '..', 'dist');
global.EXAMPLES_DIR = join(__dirname, '..', 'examples');
global.LIB_DIR = join(__dirname, '..', 'lib');
global.SRC_DIR = join(__dirname, '..', 'src');
<commit_msg>scripts: fixed incorrect module reference from 'fs' to 'path' for 3 methods<commit_after>var fs = require('fs');
var path = require('path');
var pegjs = require('pegjs');
var UglifyJS = require('uglifyjs');
var mkdirp = require('mkdirp');

var newLineChars = /(\n|\r\n|\r|\u2028|\u2029)/g;
global.indent = function ( data, tabs ) {
  return data.replace(newLineChars, function(m, nl){ return nl + (tabs || "  "); });
};

global.buildParser = function ( grammer ) {
  return "module.exports = " + pegjs.buildParser(grammer, {
    cache: false, output: "source", optimize: "speed", allowedStartRules: ["start"]
  }) + ";\n";
};

global.minify = function ( data ) {
  return UglifyJS.minify(data, { fromString: true }).code;
};

global.readFile = function ( filename ) {
  return fs.readFileSync(filename).toString();
};

global.writeFile = function ( filename, data ) {
  mkdirp.sync(filename);
  return fs.writeFileSync(filename, data);
};

global.exists = fs.existsSync;
global.lstat = fs.lstatSync;
global.basename = path.basename;
global.dirname = path.dirname;
global.extname = path.extname;
global.join = path.join;
global.resolve = path.resolve;

global.lstat = function ( path ) {
  var stat = fs.lstatSync(path);
  stat.path = path;
  stat.basename = basename(path);
  stat.dirname = dirname(path);
  stat.extname = extname(path);
  return stat;
};

global.walk = function ( path, callback ) {
  var stat = lstat(path);
  if ( stat.isDirectory() )
    fs.readdirSync(path).forEach(function(item){
      walk(join(path, item), callback);
    });
  else
    callback(path, stat);
};

global.MODULE_DIR = join(__dirname, '..');
global.DIST_DIR = join(__dirname, '..', 'dist');
global.EXAMPLES_DIR = join(__dirname, '..', 'examples');
global.LIB_DIR = join(__dirname, '..', 'lib');
global.SRC_DIR = join(__dirname, '..', 'src');
<|endoftext|>


<commit_before>// Once upon a time we shall have a versioned property graph from which history
// will be one extractable aspect, much like a git for graphs. Now we just have
// a plain list of events for a specific user.

// Enums and chrome don't play along well. Object.freeze I guess? actually rhizi code cuases
// exceptions but that shouldn't break the console, as evidenced by the '__commandLineAPI is not defined'
// error below.
//
// Uncaught TypeError: Can't add property addednodes, object is not extensible rhizicore.js:4
// Uncaught TypeError: Can't add property text, object is not extensible textanalysis.js:3
// Uncaught TypeError: Can't add property key, object is not extensible buttons.js:5
// Uncaught ReferenceError: sentence is not defined robot.js:11
// Resource interpreted as Font but transferred with MIME type application/font-sfnt: "http://localhost:8000/external/Lato300.ttf". jquery.js:2
// > document
// ReferenceError: __commandLineAPI is not defined
//var ActionEnum = Enum();

function History(user) {
    this.records = [];
    this.user = user;
}

var ACTION_KEYSTROKES = 'ACTION_KEYSTROKES';
var ACTION_MOUSE = 'ACTION_MOUSE';
var ACTION_GRAPH_ADD = 'ACTION_GRAPH_ADD';
var ACTION_GRAPH_DELETE = 'ACTION_GRAPH_DELETE';

var KEYSTROKE_WHERE_TEXTANALYSIS = 'KEYSTROKE_WHERE_TEXTANALYSIS';
var KEYSTROKE_WHERE_DOCUMENT = 'KEYSTROKE_WHERE_DOCUMENT';
var KEYSTROKE_WHERE_EDIT_NODE = 'KEYSTROKE_WHERE_EDIT_NODE';

History.prototype.record = function(d)
{
    if (d === undefined || d.action === undefined) {
        throw "Invalid arguments";
    }
    d['user'] = this.user;
    d['timestamp'] = new Date();
    this.records.push(d);
};

History.prototype.save_to_file = function()
{
    // TODO: filename and chrome support (grep json;base64 for other locations)
    // perhaps has to wait for FileWriter api?
    location.href = 'data:text/json;base64,' + window.btoa(JSON.stringify(this.records, function (k, v) { return v; }, 2));
};

History.prototype.clear_history = function()
{
    this.records = [];
}

History.prototype.record_nodes_removal = function(ids)
{
    this.record({
        'action': ACTION_GRAPH_DELETE,
        'node_ids': ids
    });
}

History.prototype.record_links = function(links)
{
    if (links === undefined || links.length === undefined || links.length <= 0) {
        throw "Invalid arguments"
    }
    this.record({
        'action': ACTION_GRAPH_ADD,
        'nodes': [],
        'links': links
    });
}

History.prototype.record_nodes = function(nodes)
{
    if (nodes === undefined || nodes.length === undefined || nodes.length <= 0) {
        throw "Invalid arguments"
    }
    this.record({'action': ACTION_GRAPH_ADD,
     'nodes': nodes,
     'linkes': []
    });
}

History.prototype.record_keystrokes = function(where, keys)
{
    if (keys === undefined || keys.length === undefined || keys.length <= 0) {
        throw "Invalid arguments";
    }
    keys = keys.filter(function(k) { return k !== undefined; });
    if (keys.length == 0) {
        return;
    }
    this.record({'action': ACTION_KEYSTROKES,
        'keys': keys,
        'where': where
    });
}
<commit_msg>history: correct spelling mistake in field s/linkes/links/<commit_after>// Once upon a time we shall have a versioned property graph from which history
// will be one extractable aspect, much like a git for graphs. Now we just have
// a plain list of events for a specific user.

// Enums and chrome don't play along well. Object.freeze I guess? actually rhizi code cuases
// exceptions but that shouldn't break the console, as evidenced by the '__commandLineAPI is not defined'
// error below.
//
// Uncaught TypeError: Can't add property addednodes, object is not extensible rhizicore.js:4
// Uncaught TypeError: Can't add property text, object is not extensible textanalysis.js:3
// Uncaught TypeError: Can't add property key, object is not extensible buttons.js:5
// Uncaught ReferenceError: sentence is not defined robot.js:11
// Resource interpreted as Font but transferred with MIME type application/font-sfnt: "http://localhost:8000/external/Lato300.ttf". jquery.js:2
// > document
// ReferenceError: __commandLineAPI is not defined
//var ActionEnum = Enum();

function History(user) {
    this.records = [];
    this.user = user;
}

var ACTION_KEYSTROKES = 'ACTION_KEYSTROKES';
var ACTION_MOUSE = 'ACTION_MOUSE';
var ACTION_GRAPH_ADD = 'ACTION_GRAPH_ADD';
var ACTION_GRAPH_DELETE = 'ACTION_GRAPH_DELETE';

var KEYSTROKE_WHERE_TEXTANALYSIS = 'KEYSTROKE_WHERE_TEXTANALYSIS';
var KEYSTROKE_WHERE_DOCUMENT = 'KEYSTROKE_WHERE_DOCUMENT';
var KEYSTROKE_WHERE_EDIT_NODE = 'KEYSTROKE_WHERE_EDIT_NODE';

History.prototype.record = function(d)
{
    if (d === undefined || d.action === undefined) {
        throw "Invalid arguments";
    }
    d['user'] = this.user;
    d['timestamp'] = new Date();
    this.records.push(d);
};

History.prototype.save_to_file = function()
{
    // TODO: filename and chrome support (grep json;base64 for other locations)
    // perhaps has to wait for FileWriter api?
    location.href = 'data:text/json;base64,' + window.btoa(JSON.stringify(this.records, function (k, v) { return v; }, 2));
};

History.prototype.clear_history = function()
{
    this.records = [];
}

History.prototype.record_nodes_removal = function(ids)
{
    this.record({
        'action': ACTION_GRAPH_DELETE,
        'node_ids': ids
    });
}

History.prototype.record_links = function(links)
{
    if (links === undefined || links.length === undefined || links.length <= 0) {
        throw "Invalid arguments"
    }
    this.record({
        'action': ACTION_GRAPH_ADD,
        'nodes': [],
        'links': links
    });
}

History.prototype.record_nodes = function(nodes)
{
    if (nodes === undefined || nodes.length === undefined || nodes.length <= 0) {
        throw "Invalid arguments"
    }
    this.record({'action': ACTION_GRAPH_ADD,
     'nodes': nodes,
     'links': []
    });
}

History.prototype.record_keystrokes = function(where, keys)
{
    if (keys === undefined || keys.length === undefined || keys.length <= 0) {
        throw "Invalid arguments";
    }
    keys = keys.filter(function(k) { return k !== undefined; });
    if (keys.length == 0) {
        return;
    }
    this.record({'action': ACTION_KEYSTROKES,
        'keys': keys,
        'where': where
    });
}
<|endoftext|>


<commit_before>/**
 * Bootstrap Table Portuguese Portugal Translation
 * Author: Burnspirit<burnspirit@gmail.com>
 */

$.fn.bootstrapTable.locales['pt-PT'] = $.fn.bootstrapTable.locales['pt'] = {
  formatCopyRows () {
    return 'Copy Rows'
  },
  formatPrint () {
    return 'Print'
  },
  formatLoadingMessage () {
    return 'A carregar, por favor aguarde'
  },
  formatRecordsPerPage (pageNumber) {
    return `${pageNumber} registos por página`
  },
  formatShowingRows (pageFrom, pageTo, totalRows, totalNotFiltered) {
    if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) {
      return `A mostrar ${pageFrom} até ${pageTo} de ${totalRows} linhas (filtered from ${totalNotFiltered} total rows)`
    }

    return `A mostrar ${pageFrom} até ${pageTo} de ${totalRows} linhas`
  },
  formatSRPaginationPreText () {
    return 'previous page'
  },
  formatSRPaginationPageText (page) {
    return `to page ${page}`
  },
  formatSRPaginationNextText () {
    return 'next page'
  },
  formatDetailPagination (totalRows) {
    return `Showing ${totalRows} rows`
  },
  formatClearSearch () {
    return 'Clear Search'
  },
  formatSearch () {
    return 'Pesquisa'
  },
  formatNoMatches () {
    return 'Nenhum registo encontrado'
  },
  formatPaginationSwitch () {
    return 'Esconder/Mostrar pagina&ccedilão'
  },
  formatPaginationSwitchDown () {
    return 'Show pagination'
  },
  formatPaginationSwitchUp () {
    return 'Hide pagination'
  },
  formatRefresh () {
    return 'Atualizar'
  },
  formatToggle () {
    return 'Alternar'
  },
  formatToggleOn () {
    return 'Show card view'
  },
  formatToggleOff () {
    return 'Hide card view'
  },
  formatColumns () {
    return 'Colunas'
  },
  formatColumnsToggleAll () {
    return 'Toggle all'
  },
  formatFullscreen () {
    return 'Fullscreen'
  },
  formatAllRows () {
    return 'Tudo'
  },
  formatAutoRefresh () {
    return 'Auto Refresh'
  },
  formatExport () {
    return 'Export data'
  },
  formatJumpTo () {
    return 'GO'
  },
  formatAdvancedSearch () {
    return 'Advanced search'
  },
  formatAdvancedCloseButton () {
    return 'Close'
  },
  formatFilterControlSwitch () {
    return 'Hide/Show controls'
  },
  formatFilterControlSwitchHide () {
    return 'Hide controls'
  },
  formatFilterControlSwitchShow () {
    return 'Show controls'
  }
}

$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['pt-PT'])
<commit_msg>translating locales for pt-PT<commit_after>/**
 * Bootstrap Table Portuguese Portugal Translation
 * Author: Burnspirit<burnspirit@gmail.com>
 */

$.fn.bootstrapTable.locales['pt-PT'] = $.fn.bootstrapTable.locales['pt'] = {
  formatCopyRows () {
    return 'Copiar Linhas'
  },
  formatPrint () {
    return 'Print'
  },
  formatLoadingMessage () {
    return 'A carregar, por favor aguarde'
  },
  formatRecordsPerPage (pageNumber) {
    return `${pageNumber} registos por página`
  },
  formatShowingRows (pageFrom, pageTo, totalRows, totalNotFiltered) {
    if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) {
      return `A mostrar ${pageFrom} até ${pageTo} de ${totalRows} linhas (filtered from ${totalNotFiltered} total rows)`
    }

    return `A mostrar ${pageFrom} até ${pageTo} de ${totalRows} linhas`
  },
  formatSRPaginationPreText () {
    return 'página anterior'
  },
  formatSRPaginationPageText (page) {
    return `ir para agina&ccedilão ${page}`
  },
  formatSRPaginationNextText () {
    return 'próxima página'
  },
  formatDetailPagination (totalRows) {
    return `Mostrando ${totalRows} linhas`
  },
  formatClearSearch () {
    return 'Limpar Pesquisa'
  },
  formatSearch () {
    return 'Pesquisa'
  },
  formatNoMatches () {
    return 'Nenhum registo encontrado'
  },
  formatPaginationSwitch () {
    return 'Esconder/Mostrar pagina&ccedilão'
  },
  formatPaginationSwitchDown () {
    return 'Mostra pagina&ccedilão'
  },
  formatPaginationSwitchUp () {
    return 'Esconder pagina&ccedilão'
  },
  formatRefresh () {
    return 'Actualizar'
  },
  formatToggle () {
    return 'Alternar'
  },
  formatToggleOn () {
    return 'Show card view'
  },
  formatToggleOff () {
    return 'Hide card view'
  },
  formatColumns () {
    return 'Colunas'
  },
  formatColumnsToggleAll () {
    return 'Activar tudo'
  },
  formatFullscreen () {
    return 'Ecrã completo'
  },
  formatAllRows () {
    return 'Tudo'
  },
  formatAutoRefresh () {
    return 'Actualização autmática'
  },
  formatExport () {
    return 'Exportar dados'
  },
  formatJumpTo () {
    return 'Avançar'
  },
  formatAdvancedSearch () {
    return 'Pesquisa avançada'
  },
  formatAdvancedCloseButton () {
    return 'Fechar'
  },
  formatFilterControlSwitch () {
    return 'Esconder/Exibir controlos'
  },
  formatFilterControlSwitchHide () {
    return 'Esconder controlos'
  },
  formatFilterControlSwitchShow () {
    return 'Exibir controlos'
  }
}

$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['pt-PT'])
<|endoftext|>


<commit_before>var fs = require('fs');
var metadata = require('../package.json');
var path = require('path');
var program = require('commander');

function getPackage(source) {
	var version = parseInt(/^v(\d+)\./.exec(process.version)[1]) >= 6 ? 'es6' : 'es5'

	if(source === 'github') {
		return 'compiler-bin-js-' + version;
	}
	else {
		return 'compiler-bin-' + version;
	}
}

program
	.command('dependency')
	.action(function() {
		if(metadata._requested && (metadata._requested.type === 'git' || metadata._requested.type === 'hosted')) {
			console.log('github:kaoscript/' + getPackage('github'));
		}
		else if(metadata._resolved) {
			console.log('@kaoscript/' + getPackage() + '@^' + metadata.version.split('.').slice(0, 2).join('.'));
		}
		else {
			console.log('github:kaoscript/' + getPackage('github'));
		}
	});

program
	.command('binary')
	.action(function() {
		var data = fs.readFileSync(path.join(__dirname, '..', 'node_modules', '@kaoscript', getPackage(), 'compiler.js'));

		fs.writeFileSync(path.join(__dirname, '..', 'lib', 'compiler.js'), data);
	});

program.parse(process.argv);<commit_msg>fix install on node v4-v5<commit_after>var fs = require('fs');
var metadata = require('../package.json');
var path = require('path');
var program = require('commander');

function getPackage(source) {
	var version = parseInt(/^v(\d+)\./.exec(process.version)[1]) >= 6 ? 'es6' : 'es5'

	if(source === 'github') {
		return 'compiler-bin-js-' + version;
	}
	else {
		return 'compiler-bin-' + version;
	}
}

program
	.command('dependency')
	.action(function() {
		if(metadata._requested && (metadata._requested.type === 'git' || metadata._requested.type === 'hosted')) {
			console.log('github:kaoscript/' + getPackage('github'));
		}
		else if(metadata._resolved && metadata._resolved.substr(0, 4) !== 'git:') {
			console.log('@kaoscript/' + getPackage() + '@^' + metadata.version.split('.').slice(0, 2).join('.'));
		}
		else {
			console.log('github:kaoscript/' + getPackage('github'));
		}
	});

program
	.command('binary')
	.action(function() {
		var data = fs.readFileSync(path.join(__dirname, '..', 'node_modules', '@kaoscript', getPackage(), 'compiler.js'));

		fs.writeFileSync(path.join(__dirname, '..', 'lib', 'compiler.js'), data);
	});

program.parse(process.argv);<|endoftext|>


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

    function setMapByCoords(lng, lat) {
        var myLatLng = new google.maps.LatLng(lat, lng);
        var map = new google.maps.Map(document.getElementById('map'),
            {
                zoom: 17,
                center: myLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
        var marker = new google.maps.Marker(
            {
                position: myLatLng,
                map: map
            });
    }

    function initMap() {
        var map_element = $('#map');
        var e_slug = map_element.data('event');
        var lng = map_element.data('lng');
        var lat = map_element.data('lat');
        if (!lng || !lat) {
            $.ajax({
                type: 'post',
                url: Routing.generate('get_event_map_position', {slug: e_slug})
            }).done(
                function (data) {
                    if (data.result) {
                        setMapByCoords(data.lng, data.lat)
                    } else {
                        console.log('Error:' + data.error);
                    }
                }
            );
        } else {
            setMapByCoords(lng, lat)
        }
    }

    if ($('#map').length > 0) {
        initMap();
    }
});<commit_msg>Fix google undefined error (sentry js error)<commit_after>
$(document).ready(function () {

    function setMapByCoords(lng, lat) {
        var myLatLng = new google.maps.LatLng(lat, lng);
        if (typeof google === 'undefined') {
            return;
        }
        var map = new google.maps.Map(document.getElementById('map'),
            {
                zoom: 17,
                center: myLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
        var marker = new google.maps.Marker(
            {
                position: myLatLng,
                map: map
            });
    }

    function initMap() {
        var map_element = $('#map');
        var e_slug = map_element.data('event');
        var lng = map_element.data('lng');
        var lat = map_element.data('lat');
        if (!lng || !lat) {
            $.ajax({
                type: 'post',
                url: Routing.generate('get_event_map_position', {slug: e_slug})
            }).done(
                function (data) {
                    if (data.result) {
                        setMapByCoords(data.lng, data.lat)
                    } else {
                        console.log('Error:' + data.error);
                    }
                }
            );
        } else {
            setMapByCoords(lng, lat)
        }
    }

    if ($('#map').length > 0) {
        initMap();
    }
});<|endoftext|>


<commit_before>$(document).ready(function() {
  var index = 0;
  var commInd = 0;
  var commands = [];

  var themes = {"normal": {"text": "#FFFFFF", "bg": "#000000"}, "ubuntu": {"text": "#DADADA", "bg": "#300A24"}, "white": {"text": "#000000", "bg": "#FFFFFF"}, "matrix": {"text": "#0FFF00", "bg": "#000000"}};
  function parseCmd(cmd) {
    if (cmd.split(" ")[0] === "sudo") {

      if (cmd.split(" ")[1] !== undefined) {
        if (cmd.split(" ")[1] === "make") {
          if (cmd.split(" ")[2] === "me" && cmd.split(" ")[3] === "a" && cmd.split(" ")[4] === "sandwich") {
            $(".input").after("
Okay.");
          } else if (cmd.split(" ")[2] === "me" && cmd.split(" ")[3] === "a" && cmd.split(" ")[4] === "cake") {
            $(".input").after("
The cake is still a lie.");
          } else {
            $(".input").after("
sudo: make it yourself");
          }
        }

        else if (cmd.split(" ")[1] === "ls" || cmd.split(" ")[1] === "cd") {
          $(".input").after("
Listen, sudo is not going to help you here. There is still no files.")
        }

        else if (cmd.split(" ")[1] === "help") {
          $(".input").after("
List of useful commands:
make    Makes something, I guess.")
        }

        else {
          $(".input").after("
sudo: "+cmd.split(" ")[1]+": command not found");
        }
      }

      else {
        $(".input").after("
sudo: no command specified");
      }
    } else {

      if (cmd.split(" ")[0] === "make") {
        if (cmd.split(" ")[1] === "me" && cmd.split(" ")[2] === "a" && cmd.split(" ")[3] === "sandwich") {
          $(".input").after("
What? Make it yourself.");
        } else if (cmd.split(" ")[1] === "me" && cmd.split(" ")[2] === "a" && cmd.split(" ")[3] === "cake") {
          $(".input").after("
The cake is a lie.");
        } else {
          $(".input").after("
make: make it yourself");
        }
      }

      else if (cmd.split(" ")[0] === "help") {
        $(".input").after("
List of useful commands:
load    Loads something. Type \"load --help\" for help on loading.
make    Makes something, I guess.
sudo    Administrator privileges (for everyone). Type \"sudo help\" for help with sudo commands.
setbg   Followed by a hex code. Sets the terminal background colour.
settext Followed by a hex code. Sets the terminal text colour.
theme   Followed by a theme name. Sets the terminal colours according to chosen theme. Type \"theme --help\" for a list of themes.");
      }

      else if (cmd.split(" ")[0] === "load") {
        var loadThis = cmd.split(" ")[1];
        if (loadThis === "--help") {
          $(".input").after("
cats    Loads kittens. :3
about   Loads some stuff about me.");
        } else if (loadThis === "cats") {
          $(".input").after("
Loading cats...");
          setTimeout(function() {
            window.location.href = "https://snowstormer.github.io/cats.html";
          }, 500)
        } else if (loadThis === "about") {
          $(".input").after("
Hi. My name is Snowstormer. I live in Estonia. Meow.");
        } else {
          $(".input").after("
Cannot load this. Please execute \"load --help\" for help on loading.")
        }
      }

      else if (cmd.split(" ")[0] === "ls" || cmd.split(" ")[0] === "cd") {
        $(".input").after("
I know, I know. This all is really interesting, but it's not a real terminal. There is no files here.")
      }

      else if (cmd.split(" ")[0] === "setbg") {
        if (/(^#[0-9A-Fa-f]{6}$)|(^#[0-9A-Fa-f]{3}$)/i.test(cmd.split(" ")[1])) {
          $("body").css("background", cmd.split(" ")[1]);
        } else {
          $(".input").after("
Invalid hex code.");
        }
      }

      else if (cmd.split(" ")[0] === "settext") {
        if (/(^#[0-9A-Fa-f]{6}$)|(^#[0-9A-Fa-f]{3}$)/i.test(cmd.split(" ")[1])) {
          $("body").css("color", cmd.split(" ")[1]);
        } else {
          $(".input").after("
Invalid hex code.");
        }
      }

      else if (cmd.split(" ")[0] === "theme") {
        if (cmd.split(" ")[1] !== "--help") {
          if (cmd.split(" ")[1] in themes) {
            $("body").css("color", themes[cmd.split(" ")[1]]["text"]);
            $("body").css("background", themes[cmd.split(" ")[1]]["bg"]);
          } else {
            $(".input").after("
No such theme exists, please type \"theme --help\" to get a list of themes.");
          }
        } else {
          $(".input").after("
List of available themes:
normal  The normal terminal look (white on black).
white   Inverted terminal (black on white).
ubuntu  Ubuntu terminal style (light grey on purple).
matrix   Matrix terminal (light green on black).");
        }
      }

      else {
        $(".input").after("
"+cmd.split(" ")[0]+": command not found");
      }
    }
  }

  function enterPressed() {
    if ($(".input").val() !== "") {
      parseCmd($(".input").val());
      commands.push($(".input").val());
      $(".input").replaceWith($(".input").val());
      $(".inptext"+index).after("
> <input type=\"text\" class=\"input\" spellcheck=\"false\" />")
      index += 1;
      commInd = 0;
      $(".input").focus();
    }
  }

  $(".input").focus();

  $("html").click(function() {
    $(".input").focus();
  });

  $(document).keyup(function(e){
    if(e.keyCode == 13) {
      enterPressed();
    } else if (e.keyCode == 38) {
      var newCommands = commands.slice().reverse();
      if (newCommands[commInd] != undefined && commInd != -1) {
        $(".input").val(newCommands[commInd]);
        commInd += 1;
      } else {
        $(".input").val(newCommands[newCommands.length-1]);
      }
    } else if (e.keyCode == 40) {
      var newCommands = commands.slice().reverse();
      commInd -= 1;
      if (newCommands[commInd] != undefined && commInd != -1) {
        $(".input").val(newCommands[commInd]);
      } else {
        commInd = 0;
        $(".input").val("");
      }
    } else {
      commInd = 0;
    }
  });
});
<commit_msg>remove unneeded space<commit_after>$(document).ready(function() {
  var index = 0;
  var commInd = 0;
  var commands = [];

  var themes = {"normal": {"text": "#FFFFFF", "bg": "#000000"}, "ubuntu": {"text": "#DADADA", "bg": "#300A24"}, "white": {"text": "#000000", "bg": "#FFFFFF"}, "matrix": {"text": "#0FFF00", "bg": "#000000"}};
  function parseCmd(cmd) {
    if (cmd.split(" ")[0] === "sudo") {

      if (cmd.split(" ")[1] !== undefined) {
        if (cmd.split(" ")[1] === "make") {
          if (cmd.split(" ")[2] === "me" && cmd.split(" ")[3] === "a" && cmd.split(" ")[4] === "sandwich") {
            $(".input").after("
Okay.");
          } else if (cmd.split(" ")[2] === "me" && cmd.split(" ")[3] === "a" && cmd.split(" ")[4] === "cake") {
            $(".input").after("
The cake is still a lie.");
          } else {
            $(".input").after("
sudo: make it yourself");
          }
        }

        else if (cmd.split(" ")[1] === "ls" || cmd.split(" ")[1] === "cd") {
          $(".input").after("
Listen, sudo is not going to help you here. There is still no files.")
        }

        else if (cmd.split(" ")[1] === "help") {
          $(".input").after("
List of useful commands:
make    Makes something, I guess.")
        }

        else {
          $(".input").after("
sudo: "+cmd.split(" ")[1]+": command not found");
        }
      }

      else {
        $(".input").after("
sudo: no command specified");
      }
    } else {

      if (cmd.split(" ")[0] === "make") {
        if (cmd.split(" ")[1] === "me" && cmd.split(" ")[2] === "a" && cmd.split(" ")[3] === "sandwich") {
          $(".input").after("
What? Make it yourself.");
        } else if (cmd.split(" ")[1] === "me" && cmd.split(" ")[2] === "a" && cmd.split(" ")[3] === "cake") {
          $(".input").after("
The cake is a lie.");
        } else {
          $(".input").after("
make: make it yourself");
        }
      }

      else if (cmd.split(" ")[0] === "help") {
        $(".input").after("
List of useful commands:
load    Loads something. Type \"load --help\" for help on loading.
make    Makes something, I guess.
sudo    Administrator privileges (for everyone). Type \"sudo help\" for help with sudo commands.
setbg   Followed by a hex code. Sets the terminal background colour.
settext Followed by a hex code. Sets the terminal text colour.
theme   Followed by a theme name. Sets the terminal colours according to chosen theme. Type \"theme --help\" for a list of themes.");
      }

      else if (cmd.split(" ")[0] === "load") {
        var loadThis = cmd.split(" ")[1];
        if (loadThis === "--help") {
          $(".input").after("
cats    Loads kittens. :3
about   Loads some stuff about me.");
        } else if (loadThis === "cats") {
          $(".input").after("
Loading cats...");
          setTimeout(function() {
            window.location.href = "https://snowstormer.github.io/cats.html";
          }, 500)
        } else if (loadThis === "about") {
          $(".input").after("
Hi. My name is Snowstormer. I live in Estonia. Meow.");
        } else {
          $(".input").after("
Cannot load this. Please execute \"load --help\" for help on loading.")
        }
      }

      else if (cmd.split(" ")[0] === "ls" || cmd.split(" ")[0] === "cd") {
        $(".input").after("
I know, I know. This all is really interesting, but it's not a real terminal. There is no files here.")
      }

      else if (cmd.split(" ")[0] === "setbg") {
        if (/(^#[0-9A-Fa-f]{6}$)|(^#[0-9A-Fa-f]{3}$)/i.test(cmd.split(" ")[1])) {
          $("body").css("background", cmd.split(" ")[1]);
        } else {
          $(".input").after("
Invalid hex code.");
        }
      }

      else if (cmd.split(" ")[0] === "settext") {
        if (/(^#[0-9A-Fa-f]{6}$)|(^#[0-9A-Fa-f]{3}$)/i.test(cmd.split(" ")[1])) {
          $("body").css("color", cmd.split(" ")[1]);
        } else {
          $(".input").after("
Invalid hex code.");
        }
      }

      else if (cmd.split(" ")[0] === "theme") {
        if (cmd.split(" ")[1] !== "--help") {
          if (cmd.split(" ")[1] in themes) {
            $("body").css("color", themes[cmd.split(" ")[1]]["text"]);
            $("body").css("background", themes[cmd.split(" ")[1]]["bg"]);
          } else {
            $(".input").after("
No such theme exists, please type \"theme --help\" to get a list of themes.");
          }
        } else {
          $(".input").after("
List of available themes:
normal  The normal terminal look (white on black).
white   Inverted terminal (black on white).
ubuntu  Ubuntu terminal style (light grey on purple).
matrix  Matrix terminal (light green on black).");
        }
      }

      else {
        $(".input").after("
"+cmd.split(" ")[0]+": command not found");
      }
    }
  }

  function enterPressed() {
    if ($(".input").val() !== "") {
      parseCmd($(".input").val());
      commands.push($(".input").val());
      $(".input").replaceWith($(".input").val());
      $(".inptext"+index).after("
> <input type=\"text\" class=\"input\" spellcheck=\"false\" />")
      index += 1;
      commInd = 0;
      $(".input").focus();
    }
  }

  $(".input").focus();

  $("html").click(function() {
    $(".input").focus();
  });

  $(document).keyup(function(e){
    if(e.keyCode == 13) {
      enterPressed();
    } else if (e.keyCode == 38) {
      var newCommands = commands.slice().reverse();
      if (newCommands[commInd] != undefined && commInd != -1) {
        $(".input").val(newCommands[commInd]);
        commInd += 1;
      } else {
        $(".input").val(newCommands[newCommands.length-1]);
      }
    } else if (e.keyCode == 40) {
      var newCommands = commands.slice().reverse();
      commInd -= 1;
      if (newCommands[commInd] != undefined && commInd != -1) {
        $(".input").val(newCommands[commInd]);
      } else {
        commInd = 0;
        $(".input").val("");
      }
    } else {
      commInd = 0;
    }
  });
});
<|endoftext|>


<commit_before>var detect = require('rtc/detect');
var isTestling = typeof __testlingConsole != 'undefined';

require('./profile');
require('./datachannel');
// require('./heartbeat-disconnect');
require('./custom-id');

if (! detect.moz) {
  require('./reactive');
}

// if we are running in testling then run the media tests
if (isTestling) {
  require('./media');

  // if (! detect.moz) {
  //   require('./media-reactive');
  // }
}
<commit_msg>Run the media capture tests first<commit_after>var detect = require('rtc/detect');
var isTestling = typeof __testlingConsole != 'undefined';

// if we are running in testling then run the media tests
if (isTestling) {
  require('./media');

  // if (! detect.moz) {
  //   require('./media-reactive');
  // }
}

require('./profile');
require('./datachannel');
// require('./heartbeat-disconnect');
require('./custom-id');

if (! detect.moz) {
  require('./reactive');
}<|endoftext|>


<commit_before>var signaller = require('rtc-pluggable-signaller');
var extend = require('cog/extend');

function createSignaller(opts) {
  return signaller(extend({ signaller: location.origin }, opts));
}

require('rtc-quickconnect-test')(
  require('..'),
  createSignaller
);
<commit_msg>Ensure we prime the test signaller using both / and /primus endpoints<commit_after>var signaller = require('rtc-pluggable-signaller');
var extend = require('cog/extend');

function createSignaller(opts) {
  return signaller(extend({
    signaller: location.origin,
    endpoints: ['/', '/primus']
  }, opts));
}

require('rtc-quickconnect-test')(
  require('..'),
  createSignaller
);
<|endoftext|>


<commit_before>let getParameterNames = require('@captemulation/get-parameter-names');
let Context = require('./context');

let Flow = module.exports = function(context) {
  context = context || new Context();
  let nextResultIdx = -1;

  function wrapPromise(promise, resultName) {
    let then = promise.then.bind(promise);
    promise.then = function(fn, reject) {
      let params = fn ? getParameterNames(fn) : [];
      let fnWrapper = function(result) {
        if (nextResultIdx >= 0) {
          context.results[nextResultIdx++] = result;
          if (params[0]) context.results[params[0]] = result;
        } else {
          ++nextResultIdx;
        }
        if (fn) return fn(result);
      }
      let newPromise = then(fnWrapper, reject);
      return wrapPromise(newPromise);
    }
    return promise;
  }

  return wrapPromise(Promise.resolve());
}
<commit_msg>update flow.js for node v4 consistency<commit_after>let getParameterNames = require('@captemulation/get-parameter-names');
let Context = require('./context');

let Flow = module.exports = function(context) {
  context = context || new Context();
  let nextResultIdx = -1;

  function wrapPromise(promise, resultName) {
    let then = promise.then.bind(promise);
    promise.then = function(fn, reject) {
      let params = fn ? getParameterNames(fn) : [];
      let fnWrapper = function(result) {
        if (nextResultIdx >= 0) {
          context.results[nextResultIdx++] = result;
          if (params[0]) context.results[params[0]] = result;
        } else {
          ++nextResultIdx;
        }
        if (fn) {
          let nextResult = fn(result);
          if (!(nextResult instanceof Promise)) {
            context.results[nextResultIdx] = nextResult;
          }
          return nextResult;
        }
      }
      let newPromise = then(fnWrapper, reject);
      return wrapPromise(newPromise);
    }
    return promise;
  }

  return wrapPromise(Promise.resolve());
}
<|endoftext|>


<commit_before>// ==UserScript==
//
// @name Ilta-Saatana Ilta-Sanomille
// @description Saatana!
// @version 1.0
//
// @match http://*.iltasanomat.fi/*
//
// @require http://code.jquery.com/jquery-2.0.2.min.js
// @require http://iltasaatana.veetipaananen.fi/scripts/satan.js
//
// ==/UserScript==

$(document).ready(function() {

	$.fn.satanify = function() {
		this.each(function() {
			$(this).text(satanify($(this).text()));
		});
	};

	$.fn.satanifySidebar = function() {
		this.each(function() {
			if ($(this).children().is("img:only-child, .still-image:only-child"))
				return;

			var numberbullet = $(".numberbullet", this).clone();
			$(".numberbullet", this).remove();

			var timestamp = $(".time-stamp", this).clone();
			$(".time-stamp", this).remove();

			$(this).text(satanify($(this).text()) + "\n");

			$(this).prepend(numberbullet);
			$(this).append(timestamp);
		});
	};

	// headings
	$("h2 a, h3 a, a h2, a h3").satanify();

	// sidebar: most read & most commented
	$("[id^=mostRead_] li[id^=item_] a").satanifySidebar();
	$("div.most-commented-text").satanifySidebar();

	// ordinary sidebar & inline lists
	var ll_classes = [
		"ll-news",
		"ll-istv",
		"ll-entertainment",
		"ll-sports",
		"ll-digi",
		"ll-cars",
		"ll-health",
		"ll-travel",
		"ll-living",
		"ll-family",
		"ll-fashion",
		"ll-food",
		"ll-liv",
	];

	for (var i = 0; i < ll_classes.length; i++) {
		$(".link-list." + ll_classes[i] + " li:not(.big-item) > a").satanifySidebar();
	}

	// big items
	$("li.big-item h4").satanify();

});
<commit_msg>IS: preserve images in sidebars<commit_after>// ==UserScript==
//
// @name Ilta-Saatana Ilta-Sanomille
// @description Saatana!
// @version 1.0
//
// @match http://*.iltasanomat.fi/*
//
// @require http://code.jquery.com/jquery-2.0.2.min.js
// @require http://iltasaatana.veetipaananen.fi/scripts/satan.js
//
// ==/UserScript==

$(document).ready(function() {

	$.fn.satanify = function() {
		this.each(function() {
			$(this).text(satanify($(this).text()));
		});
	};

	$.fn.satanifySidebar = function() {
		this.each(function() {
			if ($(this).children().is("img:only-child, .still-image:only-child"))
				return;

			var still = $(".still-image", this).clone();
			$(".still-image", this).remove();

			var numberbullet = $(".numberbullet", this).clone();
			$(".numberbullet", this).remove();

			var timestamp = $(".time-stamp", this).clone();
			$(".time-stamp", this).remove();

			$(this).text(satanify($(this).text()) + "\n");

			$(this).prepend(still);
			$(this).prepend(numberbullet);
			$(this).append(timestamp);
		});
	};

	// headings
	$("h2 a, h3 a, a h2, a h3").satanify();

	// sidebar: most read & most commented
	$("[id^=mostRead_] li[id^=item_] a").satanifySidebar();
	$("div.most-commented-text").satanifySidebar();

	// ordinary sidebar & inline lists
	var ll_classes = [
		"ll-news",
		"ll-istv",
		"ll-entertainment",
		"ll-sports",
		"ll-digi",
		"ll-cars",
		"ll-health",
		"ll-travel",
		"ll-living",
		"ll-family",
		"ll-fashion",
		"ll-food",
		"ll-liv",
	];

	for (var i = 0; i < ll_classes.length; i++) {
		$(".link-list." + ll_classes[i] + " li:not(.big-item) > a").satanifySidebar();
	}

	// big items
	$("li.big-item h4").satanify();

});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var path = require('path');
var fs = require('fs');
var spawn = require('cross-spawn');
var cli = require('../lib/cli');

before(function() {
  if (fs.existsSync('tmp')) { return; }
  fs.mkdirSync('tmp');
});

it('cli parses options', function(done) {
  assert.strictEqual(cli.argsToOptions({'css': 'file.css'}).cssFile, 'file.css');
  assert.strictEqual(cli.argsToOptions({'optionsFile': 'options.json'}).optionsFile, 'options.json');
  assert.strictEqual(cli.argsToOptions({'extraCss': 'body{color:red;}'}).extraCss, 'body{color:red;}');
  assert.strictEqual(cli.argsToOptions({'insertPreservedExtraCss': 'true'}).insertPreservedExtraCss, true);
  assert.strictEqual(cli.argsToOptions({'applyStyleTags': 'true'}).applyStyleTags, true);
  assert.strictEqual(cli.argsToOptions({'removeStyleTags': 'true'}).removeStyleTags, true);
  assert.strictEqual(cli.argsToOptions({'preserveImportant': 'true'}).preserveImportant, true);
  assert.strictEqual(cli.argsToOptions({'preserveMediaQueries': 'true'}).preserveMediaQueries, true);
  assert.strictEqual(cli.argsToOptions({'preserveFontFaces': 'true'}).preserveFontFaces, true);
  assert.strictEqual(cli.argsToOptions({'preserveKeyFrames': 'true'}).preserveKeyFrames, true);
  assert.strictEqual(cli.argsToOptions({'applyWidthAttributes': 'true'}).applyWidthAttributes, true);
  assert.strictEqual(cli.argsToOptions({'applyHeightAttributes': 'true'}).applyHeightAttributes, true);
  assert.strictEqual(cli.argsToOptions({'applyAttributesTableElements': 'true'}).applyAttributesTableElements, true);
  assert.strictEqual(cli.argsToOptions({'xmlMode': 'true'}).xmlMode, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesInlineAttribute': 'true'}).webResources.inlineAttribute, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesImages': '12'}).webResources.images, 12);
  assert.strictEqual(cli.argsToOptions({'webResourcesLinks': 'true'}).webResources.links, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesScripts': '24'}).webResources.scripts, 24);
  assert.strictEqual(cli.argsToOptions({'webResourcesRelativeTo': 'web'}).webResources.relativeTo, 'web');
  assert.strictEqual(cli.argsToOptions({'webResourcesRebaseRelativeTo': 'root'}).webResources.rebaseRelativeTo, 'root');
  assert.strictEqual(cli.argsToOptions({'webResourcesCssmin': 'true'}).webResources.cssmin, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesUglify': 'true'}).webResources.uglify, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesStrict': 'true'}).webResources.strict, true);
  done();
});

it('cli no css', function(done) {
  var inputPath = 'test/cases/juice-content/no-css.html';
  var expectedPath = 'test/cases/juice-content/no-css.out';
  var outputPath = 'tmp/no-css.out';

  var juiceProcess = spawn('bin/juice', [inputPath, outputPath]);

  juiceProcess.on('error', done);

  juiceProcess.on('exit', function(code) {
    assert(code === 0, 'Expected exit code to be 0');
    var output = fs.readFileSync(outputPath, 'utf8');
    var expectedOutput = fs.readFileSync(expectedPath, 'utf8');
    assert.equal(output, expectedOutput);
    done();
  });
});

it('cli css included', function(done) {
  var htmlPath = 'test/cases/integration.html';
  var cssPath = 'test/cases/integration.css';
  var expectedPath = 'test/cases/integration.out';
  var outputPath = 'tmp/integration.out';

  var juiceProcess = spawn('bin/juice', [htmlPath, '--css', cssPath, '--apply-width-attributes', 'false', outputPath]);

  juiceProcess.on('error', done);

  juiceProcess.on('exit', function(code) {
    assert(code === 0, 'Expected exit code to be 0');
    var output = fs.readFileSync(outputPath, 'utf8');
    var expectedOutput = fs.readFileSync(expectedPath, 'utf8');
    assert.equal(output, expectedOutput);
    done();
  });
});

it('cli options included', function(done) {
  var htmlPath = 'test/cases/juice-content/font-face-preserve.html';
  var optionsFilePath = 'test/cases/juice-content/font-face-preserve.json';
  var expectedPath = 'test/cases/juice-content/font-face-preserve.out';
  var outputPath = 'tmp/font-face-preserve.out';

  var juiceProcess = spawn('bin/juice', [htmlPath, '--options-file', optionsFilePath, outputPath]);

  juiceProcess.on('error', done);

  juiceProcess.on('exit', function(code) {
    assert(code === 0, 'Expected exit code to be 0');
    var output = fs.readFileSync(outputPath, 'utf8').replace(/\r/g, '');
    var expectedOutput = fs.readFileSync(expectedPath, 'utf8');
    assert.equal(output, expectedOutput);
    done();
  });
});

it('cli supports codeBlock', function(done) {
  var htmlPath = 'test/cases/cli/code-block-cli.html';
  var optionsFilePath = 'test/cases/cli/code-block-cli.json';
  var expectedPath = 'test/cases/cli/code-block-cli.out';
  var outputPath = 'tmp/font-face-preserve.out';

  var juiceProcess = spawn('bin/juice', [htmlPath, '--options-file', optionsFilePath, outputPath]);

  juiceProcess.on('error', done);

  juiceProcess.on('exit', function(code) {
    assert(code === 0, 'Expected exit code to be 0');
    var output = fs.readFileSync(outputPath, 'utf8').replace(/\r/g, '');
    var expectedOutput = fs.readFileSync(expectedPath, 'utf8');
    assert.equal(output, expectedOutput);
    done();
  });
});<commit_msg>Updated test tmp file name.<commit_after>'use strict';

var assert = require('assert');
var path = require('path');
var fs = require('fs');
var spawn = require('cross-spawn');
var cli = require('../lib/cli');

before(function() {
  if (fs.existsSync('tmp')) { return; }
  fs.mkdirSync('tmp');
});

it('cli parses options', function(done) {
  assert.strictEqual(cli.argsToOptions({'css': 'file.css'}).cssFile, 'file.css');
  assert.strictEqual(cli.argsToOptions({'optionsFile': 'options.json'}).optionsFile, 'options.json');
  assert.strictEqual(cli.argsToOptions({'extraCss': 'body{color:red;}'}).extraCss, 'body{color:red;}');
  assert.strictEqual(cli.argsToOptions({'insertPreservedExtraCss': 'true'}).insertPreservedExtraCss, true);
  assert.strictEqual(cli.argsToOptions({'applyStyleTags': 'true'}).applyStyleTags, true);
  assert.strictEqual(cli.argsToOptions({'removeStyleTags': 'true'}).removeStyleTags, true);
  assert.strictEqual(cli.argsToOptions({'preserveImportant': 'true'}).preserveImportant, true);
  assert.strictEqual(cli.argsToOptions({'preserveMediaQueries': 'true'}).preserveMediaQueries, true);
  assert.strictEqual(cli.argsToOptions({'preserveFontFaces': 'true'}).preserveFontFaces, true);
  assert.strictEqual(cli.argsToOptions({'preserveKeyFrames': 'true'}).preserveKeyFrames, true);
  assert.strictEqual(cli.argsToOptions({'applyWidthAttributes': 'true'}).applyWidthAttributes, true);
  assert.strictEqual(cli.argsToOptions({'applyHeightAttributes': 'true'}).applyHeightAttributes, true);
  assert.strictEqual(cli.argsToOptions({'applyAttributesTableElements': 'true'}).applyAttributesTableElements, true);
  assert.strictEqual(cli.argsToOptions({'xmlMode': 'true'}).xmlMode, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesInlineAttribute': 'true'}).webResources.inlineAttribute, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesImages': '12'}).webResources.images, 12);
  assert.strictEqual(cli.argsToOptions({'webResourcesLinks': 'true'}).webResources.links, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesScripts': '24'}).webResources.scripts, 24);
  assert.strictEqual(cli.argsToOptions({'webResourcesRelativeTo': 'web'}).webResources.relativeTo, 'web');
  assert.strictEqual(cli.argsToOptions({'webResourcesRebaseRelativeTo': 'root'}).webResources.rebaseRelativeTo, 'root');
  assert.strictEqual(cli.argsToOptions({'webResourcesCssmin': 'true'}).webResources.cssmin, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesUglify': 'true'}).webResources.uglify, true);
  assert.strictEqual(cli.argsToOptions({'webResourcesStrict': 'true'}).webResources.strict, true);
  done();
});

it('cli no css', function(done) {
  var inputPath = 'test/cases/juice-content/no-css.html';
  var expectedPath = 'test/cases/juice-content/no-css.out';
  var outputPath = 'tmp/no-css.out';

  var juiceProcess = spawn('bin/juice', [inputPath, outputPath]);

  juiceProcess.on('error', done);

  juiceProcess.on('exit', function(code) {
    assert(code === 0, 'Expected exit code to be 0');
    var output = fs.readFileSync(outputPath, 'utf8');
    var expectedOutput = fs.readFileSync(expectedPath, 'utf8');
    assert.equal(output, expectedOutput);
    done();
  });
});

it('cli css included', function(done) {
  var htmlPath = 'test/cases/integration.html';
  var cssPath = 'test/cases/integration.css';
  var expectedPath = 'test/cases/integration.out';
  var outputPath = 'tmp/integration.out';

  var juiceProcess = spawn('bin/juice', [htmlPath, '--css', cssPath, '--apply-width-attributes', 'false', outputPath]);

  juiceProcess.on('error', done);

  juiceProcess.on('exit', function(code) {
    assert(code === 0, 'Expected exit code to be 0');
    var output = fs.readFileSync(outputPath, 'utf8');
    var expectedOutput = fs.readFileSync(expectedPath, 'utf8');
    assert.equal(output, expectedOutput);
    done();
  });
});

it('cli options included', function(done) {
  var htmlPath = 'test/cases/juice-content/font-face-preserve.html';
  var optionsFilePath = 'test/cases/juice-content/font-face-preserve.json';
  var expectedPath = 'test/cases/juice-content/font-face-preserve.out';
  var outputPath = 'tmp/font-face-preserve.out';

  var juiceProcess = spawn('bin/juice', [htmlPath, '--options-file', optionsFilePath, outputPath]);

  juiceProcess.on('error', done);

  juiceProcess.on('exit', function(code) {
    assert(code === 0, 'Expected exit code to be 0');
    var output = fs.readFileSync(outputPath, 'utf8').replace(/\r/g, '');
    var expectedOutput = fs.readFileSync(expectedPath, 'utf8');
    assert.equal(output, expectedOutput);
    done();
  });
});

it('cli supports codeBlock', function(done) {
  var htmlPath = 'test/cases/cli/code-block-cli.html';
  var optionsFilePath = 'test/cases/cli/code-block-cli.json';
  var expectedPath = 'test/cases/cli/code-block-cli.out';
  var outputPath = 'tmp/code-block-cli.out';

  var juiceProcess = spawn('bin/juice', [htmlPath, '--options-file', optionsFilePath, outputPath]);

  juiceProcess.on('error', done);

  juiceProcess.on('exit', function(code) {
    assert(code === 0, 'Expected exit code to be 0');
    var output = fs.readFileSync(outputPath, 'utf8').replace(/\r/g, '');
    var expectedOutput = fs.readFileSync(expectedPath, 'utf8');
    assert.equal(output, expectedOutput);
    done();
  });
});<|endoftext|>


<commit_before>var test = require('tape')
var fs = require('fs')
var spawn = require('child_process').spawn

var inputPath = 'test/fixture/ignore.js'

try {
  fs.mkdirSync('tmp')
} catch(err) {
  // dir exists
}

test('cli: json option', function (t) {
  t.plan(1)

  var outputFile = fs.openSync('tmp/ignore.json', 'w')

  var handle = spawn(
    'node',
    [ 'bin/cli.js', '--json', inputPath ],
    { stdio: [ 'ignore', outputFile, 'ignore']}
  )
  handle.on('close', function () {
    var json = fs.readFileSync('tmp/ignore.json', 'utf8')
    if (json) t.ok(/"id": "visible"/.test(json.toString()))
  })
})
<commit_msg>test fix<commit_after>var test = require('tape')
var fs = require('fs')
var spawn = require('child_process').spawn

var inputPath = 'test/fixture/ignore.js'

try {
  fs.mkdirSync('tmp')
} catch(err) {
  // dir exists
}

test('cli: json option', function (t) {
  t.plan(1)

  var outputFile = fs.openSync('tmp/ignore.json', 'w')

  var handle = spawn(
    'node',
    [ 'bin/cli.js', '--data', inputPath ],
    { stdio: [ 'ignore', outputFile, 'ignore']}
  )
  handle.on('close', function () {
    var json = fs.readFileSync('tmp/ignore.json', 'utf8')
    if (json) t.ok(/"id": "visible"/.test(json.toString()))
  })
})
<|endoftext|>