<commit_before>//-------------------------------------------------------------------------------
// Copyright IBM Corp. 2015
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//-------------------------------------------------------------------------------

'use strict';

var request = require("request");
var _ = require("lodash");
var async = require("async");
var pipesSDK = require.main.require('pipes-sdk');
var connectorExt = pipesSDK.connectorExt;
var bluemixHelperConfig = require.main.require('bluemix-helper-config');
var configManager = bluemixHelperConfig.configManager;
var vcapServices = bluemixHelperConfig.vcapServices;

var concurrency = 20;	//Async queue concurrency
/**
 * Pipes Connector for Reddit
 */
function redditConnector( parentDirPath ){
	//Call constructor from super class
	connectorExt.call(this, "reddit", "Reddit AMA", {
		copyToDashDb: false,
		extraRequiredFields: "amaURL",
		useOAuth: false,
		useCustomTables: true
	});

	this.getTablePrefix = function(){
		return "reddit";
	}

	this.getCloudantDbName = function(pipe, table){
		return pipe.name + "_" + table.name;
	}

	var watsonToneAnalyzerService = vcapServices.getService( configManager.get("WATSON_TONE_ANALYZER") || "tone analyzer" );

	this.fetchRecords = function( table, pushRecordFn, done, pipeRunStep, pipeRunStats, logger, pipe, pipeRunner ){
		if ( !watsonToneAnalyzerService ){
			var msg = "Unable to find Watson Tone Analyzer Service";
			console.log( msg );
			return done( msg );
		}
		if ( !pipe.amaURL ){
			return done("Missing field amaURL");
		}
		console.log("Connecting to AMA with url " + pipe.amaURL );
		request.get(pipe.amaURL, {"json": true},
			function( err, response, body ){
				if ( err ){
					console.log("Unable to fetch AMA: " + err );
					return done( err );
				}
				//console.log("response: " + body);
				//Create an async queue to process the record with Watson Tone Analyzer
				var q = async.queue( function( post, callback ){
					//Call Tone analyzer to get sentiments from the post
					request.post( watsonToneAnalyzerService.credentials.url + "/v1/tone",{
						'auth': {
						  'user': watsonToneAnalyzerService.credentials.username,
						  'pass': watsonToneAnalyzerService.credentials.password,
						  'sendImmediately': true
						},
						'json': {
							'text': post.selftext || post.body
						}
					}, function( err, response, body ){
						if ( err ){
							console.log("Error accessing Watson Tone Analyzer");
							return callback( err );
						}

	        			pushRecordFn({
							author: post.author,
							created: post.created_utc,
							edited: post.edited,
							id: post.id,
							num_comments: post.num_comments,
							title: post.title || "",
							text: post.selftext || post.body,
							sentiment: body
						});
						return callback();
		        	});

				}, concurrency );

				_.forEach( body, function( listing ){
					if ( listing.kind == "Listing" && listing.hasOwnProperty("data" ) ){
						if ( listing.data.hasOwnProperty("children") ){
							//Get the children from the data fields, only process the top posts for now
							_.forEach( listing.data.children, function( post ){
								if ( post.hasOwnProperty("data") ){
									q.push( post.data )
								}
							});
						}
					}
				})

				//Add a drain function
				q.drain = function(){
					return done();
				}
			}
		);
	};
}

//Extend event Emitter
require('util').inherits(redditConnector, connectorExt);

module.exports = new redditConnector();<commit_msg>Flatten JSON and filter rows without sentiment<commit_after>//-------------------------------------------------------------------------------
// Copyright IBM Corp. 2015
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//-------------------------------------------------------------------------------

'use strict';

var request = require("request");
var _ = require("lodash");
var async = require("async");
var pipesSDK = require.main.require('pipes-sdk');
var connectorExt = pipesSDK.connectorExt;
var bluemixHelperConfig = require.main.require('bluemix-helper-config');
var configManager = bluemixHelperConfig.configManager;
var vcapServices = bluemixHelperConfig.vcapServices;

var concurrency = 20;	//Async queue concurrency
/**
 * Pipes Connector for Reddit
 */
function redditConnector( parentDirPath ){
	//Call constructor from super class
	connectorExt.call(this, "reddit", "Reddit AMA", {
		copyToDashDb: false,
		extraRequiredFields: "amaURL",
		useOAuth: false,
		useCustomTables: true
	});

	this.getTablePrefix = function(){
		return "reddit";
	}

	this.getCloudantDbName = function(pipe, table){
		return pipe.name + "_" + table.name;
	}

	var watsonToneAnalyzerService = vcapServices.getService( configManager.get("WATSON_TONE_ANALYZER") || "tone analyzer" );

	this.fetchRecords = function( table, pushRecordFn, done, pipeRunStep, pipeRunStats, logger, pipe, pipeRunner ){
		if ( !watsonToneAnalyzerService ){
			var msg = "Unable to find Watson Tone Analyzer Service";
			console.log( msg );
			return done( msg );
		}
		if ( !pipe.amaURL ){
			return done("Missing field amaURL");
		}
		console.log("Connecting to AMA with url " + pipe.amaURL );
		request.get(pipe.amaURL, {"json": true},
			function( err, response, body ){
				if ( err ){
					console.log("Unable to fetch AMA: " + err );
					return done( err );
				}
				//console.log("response: " + body);
				//Create an async queue to process the record with Watson Tone Analyzer
				var q = async.queue( function( post, callback ){
					//Call Tone analyzer to get sentiments from the post
					request.post( watsonToneAnalyzerService.credentials.url + "/v1/tone",{
						'auth': {
						  'user': watsonToneAnalyzerService.credentials.username,
						  'pass': watsonToneAnalyzerService.credentials.password,
						  'sendImmediately': true
						},
						'json': {
							'text': post.selftext || post.body
						}
					}, function( err, response, body ){
						if ( err ){
							console.log("Error accessing Watson Tone Analyzer");
							return callback( err );
						}
						var sentiments = {
						author: post.author,
						created: post.created_utc,
						edited: post.edited,
						id: post.id,
						num_comments: post.num_comments,
						title: post.title || "",
						text: post.selftext || post.body
                                                };

						if(body.children){
						_.forEach(body.children, function(child) {
							if(body.children){
							_.forEach(child.children, function(grandchild) {
								sentiments[grandchild.name] = parseFloat(grandchild.normalized_score * 100);
							});
						}

						});
                            pushRecordFn(sentiments); // push records only if tone analyzer returns data
                      }else{
                      	console.log("No record found"); //skip this record
                      }

   				return callback();

                                });

				}, concurrency );

				_.forEach( body, function( listing ){
					if ( listing.kind == "Listing" && listing.hasOwnProperty("data" ) ){
						if ( listing.data.hasOwnProperty("children") ){
							//Get the children from the data fields, only process the top posts for now
							_.forEach( listing.data.children, function( post ){
								if ( post.hasOwnProperty("data") ){
									q.push( post.data )
								}
							});
						}
					}
				})

				//Add a drain function
				q.drain = function(){
					return done();
				}
			}
		);
	};
}

//Extend event Emitter
require('util').inherits(redditConnector, connectorExt);

module.exports = new redditConnector();
<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    // Save current buffer state.
    canvas_buffer.save();

    // Setup translate/rotation for wall drawing.
    canvas_buffer.translate(
      canvas_x,
      canvas_y
    );
    canvas_buffer.rotate(rotation * math_degree);

    // Draw walls.
    var loop_counter = 3;
    do{
        canvas_draw_path({
          'properties': {
            'fillStyle': colors[0][loop_counter],
          },
          'vertices': [
            {
              'type': 'moveTo',
              'x': 0,
              'y': 0,
            },
            {
              'x': wall_splits[[0,0,2,4,][loop_counter]],
              'y': wall_splits[[1,1,3,5,][loop_counter]],
            },
            {
              'x': wall_splits[[2,4,6,6,][loop_counter]],
              'y': wall_splits[[3,5,7,7,][loop_counter]],
            },
          ],
        });
    }while(loop_counter--);

    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][0],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_x,
          'y': -canvas_x,
        },
        {
          'x': wall_splits[0],
          'y': wall_splits[1],
        },
        {
          'x': wall_splits[2],
          'y': wall_splits[3],
        },
        {
          'x': canvas_x,
          'y': -canvas_x,
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][1],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_x,
          'y': -canvas_x,
        },
        {
          'x': wall_splits[0],
          'y': wall_splits[1],
        },
        {
          'x': wall_splits[4],
          'y': wall_splits[5],
        },
        {
          'x': -canvas_x,
          'y': canvas_x,
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][2],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': canvas_x,
          'y': -canvas_x,
        },
        {
          'x': wall_splits[2],
          'y': wall_splits[3],
        },
        {
          'x': wall_splits[6],
          'y': wall_splits[7],
        },
        {
          'x': canvas_x,
          'y': canvas_x,
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][3],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_x,
          'y': canvas_x,
        },
        {
          'x': wall_splits[4],
          'y': wall_splits[5],
        },
        {
          'x': wall_splits[6],
          'y': wall_splits[7],
        },
        {
          'x': canvas_x,
          'y': canvas_x,
        },
      ],
    });

    // Restore buffer state.
    canvas_buffer.restore();

    // Draw current speed.
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.fillText(
      speed + ' m/s',
      5,
      25
    );
}

function logic(){
    if(key_left){
        rotation -= speed / 10 + 1;
    }
    if(key_right){
        rotation += speed / 10 + 1;
    }

    if(key_speedminus
      && speed > 0){
        speed -= 1;
    }
    if(key_speedplus){
        speed += 1;
    }

    var do_split = false;

    // Move wall split location.
    var loop_counter = 3;
    do{
        var double = loop_counter * 2;

        wall_splits[double] += wall_splits[double] >= 0
          ? speed
          : -speed;
        wall_splits[double + 1] += wall_splits[double + 1] >= 0
          ? speed
          : -speed;

        // Check if wall split reached edge of screen.
        if(wall_splits[double] < -canvas_x
          || wall_splits[double] > canvas_x){
            // Reset wall splits.
            wall_splits[double] = [
              -2,
              -2,
              2,
              -2,
              -2,
              2,
              2,
              2,
            ][double];
            wall_splits[double + 1] = [
              -2,
              -2,
              2,
              -2,
              -2,
              2,
              2,
              2,
            ][double + 1];

            do_split = true;
        }
    }while(loop_counter--);

    if(do_split){
        colors[1] = colors[0];
        colors[0] = [
          '#' + core_random_hex(),
          '#' + core_random_hex(),
          '#' + core_random_hex(),
          '#' + core_random_hex(),
        ];
    }
}

function repo_init(){
    core_storage_init({
      'data': {
        'audio-volume': 1,
        'key-slowdown': 'S',
        'key-speedup': 'W',
        'movement-keys': 'AD',
        'ms-per-frame': 30,
      },
      'prefix': 'Tubes-2D3D.htm-',
    });
    canvas_init();

    window.onkeydown = function(e){
        if(canvas_mode <= 0){
            return;
        }

        var key = e.keyCode || e.which;

        // ESC: menu.
        if(key === 27){
            core_menu_toggle();
            return;
        }

        key = String.fromCharCode(key);

        if(key === core_storage_data['movement-keys'][0]){
            key_left = true;

        }else if(key === core_storage_data['movement-keys'][1]){
            key_right = true;

        }else if(key === core_storage_data['key-slowdown']){
            key_speedminus = true;

        }else if(key === core_storage_data['key-speedup']){
            key_speedplus = true;

        }else if(key === 'Q'){
            canvas_menu_quit();
        }
    };

    window.onkeyup = function(e){
        var key = String.fromCharCode(e.keyCode || e.which);

        if(key === core_storage_data['movement-keys'][0]){
            key_left = false;

        }else if(key === core_storage_data['movement-keys'][1]){
            key_right = false;

        }else if(key === core_storage_data['key-slowdown']){
            key_speedminus = false;

        }else if(key === core_storage_data['key-speedup']){
            key_speedplus = false;
        }
    };
}

function setmode_logic(newgame){
    // Main menu mode.
    if(canvas_mode === 0){
        document.body.innerHTML = '

Enter the Tubes

'
          + '

<input disabled value=ESC>Menu
'
          + '<input id=movement-keys maxlength=2>Move ←→
'
          + '<input id=key-slowdown maxlength=1>Speed--
'
          + '<input id=key-speedup maxlength=1>Speed++

'
          + '
<input id=audio-volume max=1 min=0 step=0.01 type=range>Audio
'
          + '<input id=ms-per-frame>ms/Frame
'
          + 'Reset Settings

';
        core_storage_update();

    // New game mode.
    }else{
        if(newgame){
            core_storage_save();
        }

        key_left = false;
        key_right = false;
        key_speedminus = false;
        key_speedplus = false;
        speed = 10;
        rotation = 0;

        wall_splits = [
          -2,
          -2,
          2,
          -2,
          -2,
          2,
          2,
          2,
        ];

        // Set initial tube colors.
        colors = [
          ['#f0f', '#06f', '#ff0', '#f60'],// Initial
          ['#0f0', '#f00', '#00f', '#0ff'],// First swap
        ];
    }
}

var colors = [];
var key_left = false;
var key_right = false;
var key_speedminus = false;
var key_speedplus = false;
var rotation = 0;
var speed = 0;
var wall_splits = [];
<commit_msg>fixed incorrect function name<commit_after>'use strict';

function draw_logic(){
    // Save current buffer state.
    canvas_buffer.save();

    // Setup translate/rotation for wall drawing.
    canvas_buffer.translate(
      canvas_x,
      canvas_y
    );
    canvas_buffer.rotate(rotation * math_degree);

    // Draw walls.
    var loop_counter = 3;
    do{
        canvas_draw_path({
          'properties': {
            'fillStyle': colors[0][loop_counter],
          },
          'vertices': [
            {
              'type': 'moveTo',
              'x': 0,
              'y': 0,
            },
            {
              'x': wall_splits[[0,0,2,4,][loop_counter]],
              'y': wall_splits[[1,1,3,5,][loop_counter]],
            },
            {
              'x': wall_splits[[2,4,6,6,][loop_counter]],
              'y': wall_splits[[3,5,7,7,][loop_counter]],
            },
          ],
        });
    }while(loop_counter--);

    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][0],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_x,
          'y': -canvas_x,
        },
        {
          'x': wall_splits[0],
          'y': wall_splits[1],
        },
        {
          'x': wall_splits[2],
          'y': wall_splits[3],
        },
        {
          'x': canvas_x,
          'y': -canvas_x,
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][1],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_x,
          'y': -canvas_x,
        },
        {
          'x': wall_splits[0],
          'y': wall_splits[1],
        },
        {
          'x': wall_splits[4],
          'y': wall_splits[5],
        },
        {
          'x': -canvas_x,
          'y': canvas_x,
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][2],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': canvas_x,
          'y': -canvas_x,
        },
        {
          'x': wall_splits[2],
          'y': wall_splits[3],
        },
        {
          'x': wall_splits[6],
          'y': wall_splits[7],
        },
        {
          'x': canvas_x,
          'y': canvas_x,
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][3],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_x,
          'y': canvas_x,
        },
        {
          'x': wall_splits[4],
          'y': wall_splits[5],
        },
        {
          'x': wall_splits[6],
          'y': wall_splits[7],
        },
        {
          'x': canvas_x,
          'y': canvas_x,
        },
      ],
    });

    // Restore buffer state.
    canvas_buffer.restore();

    // Draw current speed.
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.fillText(
      speed + ' m/s',
      5,
      25
    );
}

function logic(){
    if(key_left){
        rotation -= speed / 10 + 1;
    }
    if(key_right){
        rotation += speed / 10 + 1;
    }

    if(key_speedminus
      && speed > 0){
        speed -= 1;
    }
    if(key_speedplus){
        speed += 1;
    }

    var do_split = false;

    // Move wall split location.
    var loop_counter = 3;
    do{
        var double = loop_counter * 2;

        wall_splits[double] += wall_splits[double] >= 0
          ? speed
          : -speed;
        wall_splits[double + 1] += wall_splits[double + 1] >= 0
          ? speed
          : -speed;

        // Check if wall split reached edge of screen.
        if(wall_splits[double] < -canvas_x
          || wall_splits[double] > canvas_x){
            // Reset wall splits.
            wall_splits[double] = [
              -2,
              -2,
              2,
              -2,
              -2,
              2,
              2,
              2,
            ][double];
            wall_splits[double + 1] = [
              -2,
              -2,
              2,
              -2,
              -2,
              2,
              2,
              2,
            ][double + 1];

            do_split = true;
        }
    }while(loop_counter--);

    if(do_split){
        colors[1] = colors[0];
        colors[0] = [
          '#' + core_random_hex(),
          '#' + core_random_hex(),
          '#' + core_random_hex(),
          '#' + core_random_hex(),
        ];
    }
}

function repo_init(){
    core_storage_init({
      'data': {
        'audio-volume': 1,
        'key-slowdown': 'S',
        'key-speedup': 'W',
        'movement-keys': 'AD',
        'ms-per-frame': 30,
      },
      'prefix': 'Tubes-2D3D.htm-',
    });
    canvas_init();

    window.onkeydown = function(e){
        if(canvas_mode <= 0){
            return;
        }

        var key = e.keyCode || e.which;

        // ESC: menu.
        if(key === 27){
            core_escape();
            return;
        }

        key = String.fromCharCode(key);

        if(key === core_storage_data['movement-keys'][0]){
            key_left = true;

        }else if(key === core_storage_data['movement-keys'][1]){
            key_right = true;

        }else if(key === core_storage_data['key-slowdown']){
            key_speedminus = true;

        }else if(key === core_storage_data['key-speedup']){
            key_speedplus = true;

        }else if(key === 'Q'){
            canvas_menu_quit();
        }
    };

    window.onkeyup = function(e){
        var key = String.fromCharCode(e.keyCode || e.which);

        if(key === core_storage_data['movement-keys'][0]){
            key_left = false;

        }else if(key === core_storage_data['movement-keys'][1]){
            key_right = false;

        }else if(key === core_storage_data['key-slowdown']){
            key_speedminus = false;

        }else if(key === core_storage_data['key-speedup']){
            key_speedplus = false;
        }
    };
}

function setmode_logic(newgame){
    // Main menu mode.
    if(canvas_mode === 0){
        document.body.innerHTML = '

Enter the Tubes

'
          + '

<input disabled value=ESC>Menu
'
          + '<input id=movement-keys maxlength=2>Move ←→
'
          + '<input id=key-slowdown maxlength=1>Speed--
'
          + '<input id=key-speedup maxlength=1>Speed++

'
          + '
<input id=audio-volume max=1 min=0 step=0.01 type=range>Audio
'
          + '<input id=ms-per-frame>ms/Frame
'
          + 'Reset Settings

';
        core_storage_update();

    // New game mode.
    }else{
        if(newgame){
            core_storage_save();
        }

        key_left = false;
        key_right = false;
        key_speedminus = false;
        key_speedplus = false;
        speed = 10;
        rotation = 0;

        wall_splits = [
          -2,
          -2,
          2,
          -2,
          -2,
          2,
          2,
          2,
        ];

        // Set initial tube colors.
        colors = [
          ['#f0f', '#06f', '#ff0', '#f60'],// Initial
          ['#0f0', '#f00', '#00f', '#0ff'],// First swap
        ];
    }
}

var colors = [];
var key_left = false;
var key_right = false;
var key_speedminus = false;
var key_speedplus = false;
var rotation = 0;
var speed = 0;
var wall_splits = [];
<|endoftext|>


<commit_before>var cheerio = require('cheerio');
var extname = require('path').extname;
var _ = require('lodash');
var Identity = require('fake-identity');
var moment = require('moment');
var faker = require('faker');

var createIdentity = function() {

  var mock = Identity.generate();

  // person
  mock.fullName = mock.firstName + ' ' + mock.lastName;
  mock.fullNameReverse = mock.lastName + ', ' + mock.firstName;
  mock.sexShort = mock.sex.charAt(0).toUpperCase();
  mock.dob = moment(mock.dateOfBirth).format('DD/MM/YYYY');
  mock.memberId = faker.finance.account(9);
  mock.customerId = faker.finance.account(10);
  mock.groupNumber = faker.finance.account(12);

  // address
  mock.addressLine1 = mock.street;
  mock.addressLine2 = mock.city + ' ' + mock.state + ', ' + mock.state + ' ' + mock.zipCode;

  // text
  mock.sentence = faker.lorem.sentence();
  mock.sentences = faker.lorem.sentences();
  mock.paragraph = faker.lorem.paragraph();

  // medical
  mock.diagnosisType = faker.finance.account(7);
  mock.procedureCode = faker.finance.account(5);

  return mock;
};

var isHTMLFile = function(filePath) {
  return /\.html|\.htm/.test(extname(filePath));
};

module.exports = function() {

  return function(files, metalsmith, done) {

    var data = metalsmith.metadata();
    data.mocks = {};

    setImmediate(done);

    _.each(files, function(file, name) {

      // gulpsmith || vanilla Metalsmith support
      if(!isHTMLFile(file.path || name)) {
        return;
      }

      var contents = file.contents.toString();
      var $ = cheerio.load(contents);

      var mocked = false;

      // get mock targets
      $('[data-mock]').each(function() {

        var $this = $(this);
        var mock = $this.data('mock') || '';

        var targets = mock.split(':');

        if(targets.length === 2) {

          mocked = true;

          var mockType = targets[0];
          var mockIndex = targets[1];

          mock = data.mocks['_'+mockIndex] ? data.mocks['_'+mockIndex] : createIdentity();
          data.mocks['_'+mockIndex] = mock;

          $this.text(mock[mockType]);

        }

      });

      if(mocked) {
        file.contents = new Buffer($.html());
      }

    });
  };

};
<commit_msg>add mock paragraphs<commit_after>var cheerio = require('cheerio');
var extname = require('path').extname;
var _ = require('lodash');
var Identity = require('fake-identity');
var moment = require('moment');
var faker = require('faker');

var createIdentity = function() {

  var mock = Identity.generate();

  // person
  mock.fullName = mock.firstName + ' ' + mock.lastName;
  mock.fullNameReverse = mock.lastName + ', ' + mock.firstName;
  mock.sexShort = mock.sex.charAt(0).toUpperCase();
  mock.dob = moment(mock.dateOfBirth).format('DD/MM/YYYY');
  mock.memberId = faker.finance.account(9);
  mock.customerId = faker.finance.account(10);
  mock.groupNumber = faker.finance.account(12);

  // address
  mock.addressLine1 = mock.street;
  mock.addressLine2 = mock.city + ' ' + mock.state + ', ' + mock.state + ' ' + mock.zipCode;

  // text
  mock.sentence = faker.lorem.sentence();
  mock.sentences = faker.lorem.sentences();
  mock.paragraph = faker.lorem.paragraph();
  mock.paragraphs = faker.lorem.paragraphs();

  // medical
  mock.diagnosisType = faker.finance.account(7);
  mock.procedureCode = faker.finance.account(5);

  return mock;
};

var isHTMLFile = function(filePath) {
  return /\.html|\.htm/.test(extname(filePath));
};

module.exports = function() {

  return function(files, metalsmith, done) {

    var data = metalsmith.metadata();
    data.mocks = {};

    setImmediate(done);

    _.each(files, function(file, name) {

      // gulpsmith || vanilla Metalsmith support
      if(!isHTMLFile(file.path || name)) {
        return;
      }

      var contents = file.contents.toString();
      var $ = cheerio.load(contents);

      var mocked = false;

      // get mock targets
      $('[data-mock]').each(function() {

        var $this = $(this);
        var mock = $this.data('mock') || '';

        var targets = mock.split(':');

        if(targets.length === 2) {

          mocked = true;

          var mockType = targets[0];
          var mockIndex = targets[1];

          mock = data.mocks['_'+mockIndex] ? data.mocks['_'+mockIndex] : createIdentity();
          data.mocks['_'+mockIndex] = mock;

          $this.text(mock[mockType]);

        }

      });

      if(mocked) {
        file.contents = new Buffer($.html());
      }

    });
  };

};
<|endoftext|>


<commit_before>// Copyright (c) 2016-2018 Walter Bender
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
//

const NUMBERBLOCKDEFAULT = 4;

const DEFAULTPALETTE = 'rhythm';

const TITLESTRING = _('Music Blocks is a collection of tools for exploring musical concepts.');

// We don't include 'extras' since we want to be able to delete
// plugins from the extras palette.
BUILTINPALETTES = ['rhythm',  'meter', 'pitch', 'intervals', 'tone', 'volume', 'drum', 'flow', 'action', 'boxes', 'widgets', 'mouse', 'pen', 'number', 'boolean', 'media', 'sensors', 'heap', 'mice', 'extras'];

const BUILTINPALETTESFORL23N = [_('rhythm'), _('meter'), _('pitch'), _('intervals'), _('tone'), _('volume'), _('drum'), _('flow'), _('action'), _('boxes'), _('widgets'), _('mouse'), _('pen'), _('number'), _('boolean'), _('media'), _('sensors'), _('heap'), _('mice'), _('extras')];

function getMainToolbarButtonNames(name) {
    return (['popdown-palette', 'run', 'step', 'step-music', 'stop-turtle', 'hard-stop-turtle', 'clear', 'palette', 'hide-blocks', 'collapse-blocks', 'go-home', 'help', 'sugarizer-stop'].indexOf(name) > -1);
};

function getAuxToolbarButtonNames(name) {
    return (['planet', 'planet-disabled', 'open', 'save', 'paste-disabled', 'Cartesian', 'compile', 'utility', 'new-project', 'restore-trash'].indexOf(name) > -1);
}

function createDefaultStack() {
    DATAOBJS =
        [[0, 'start', screen.width / 3, 75, [null, 1, null]],

         [1, 'newnote', 0, 0, [0, 2, 5, 9]],
         [2, 'divide', 0, 0, [1, 3, 4]],
         [3, ['number', {'value': 1}], 0, 0, [2]],
         [4, ['number', {'value': 4}], 0, 0, [2]],
         [5, 'vspace', 0, 0, [1, 6]],
         [6, 'pitch', 0, 0, [5, 7, 8, null]],
         [7, ['solfege', {'value': 'sol'}], 0, 0, [6]],
         [8, ['number', {'value': 4}], 0, 0, [6]],
         [9, 'hidden', 0, 0, [1, 10]],

         [10, 'newnote', 0, 0, [9, 11, 14, 18]],
         [11, 'divide', 0, 0, [10, 12, 13]],
         [12, ['number', {'value': 1}], 0, 0, [11]],
         [13, ['number', {'value': 4}], 0, 0, [11]],
         [14, 'vspace', 0, 0, [10, 15]],
         [15, 'pitch', 0, 0, [14, 16, 17, null]],
         [16, ['solfege', {'value': 'mi'}], 0, 0, [15]],
         [17, ['number', {'value': 4}], 0, 0, [15]],
         [18, 'hidden', 0, 0, [10, 19]],

         [19, 'newnote', 0, 0, [18, 20, 23, 27]],
         [20, 'divide', 0, 0, [19, 21, 22]],
         [21, ['number', {'value': 1}], 0, 0, [20]],
         [22, ['number', {'value': 2}], 0, 0, [20]],
         [23, 'vspace', 0, 0, [19, 24]],
         [24, 'pitch', 0, 0, [23, 25, 26, null]],
         [25, ['solfege', {'value': 'sol'}], 0, 0, [24]],
         [26, ['number', {'value': 4}], 0, 0, [24]],
         [27, 'hidden', 0, 0, [19, null]],
        ];
};

function createHelpContent() {
    HELPCONTENT = [
        [_('Welcome to Music Blocks'), _('Music Blocks is a collection of manipulative tools for exploring fundamental musical concepts in an integrative and fun way.'), 'activity/activity-icon-mouse-color.svg'],
        [_('Meet Mr. Mouse!'), _('Mr Mouse is our Music Blocks conductor.') + ' ' + _('Mr Mouse encourages you to explore Music Blocks.') + ' ' + _('Let us start our tour!'), 'activity/activity-icon-mouse-color.svg'],
	//.TRANS: the buttons used to open various palettes of blocks
        [_('Palette buttons'),
        //.TRANS: Please add commas to list: Rhythm, Pitch, Tone, Action, and more.
	 _('This toolbar contains the palette buttons, including Rhythm Pitch Tone Action and more.') + ' ' + _('Click to show the palettes of blocks and drag blocks from the palettes onto the canvas to use them.'), 'images/icons.svg'],
        [_('Play music'), _('Click to run the music note by note.') + ' ' + _('Alternatively, you can hit the ENTER or RETURN key.'), 'header-icons/play-button.svg'],
        [_('Run fast'), _('Click the run button to run the project in fast mode.'), 'header-icons/run-button.svg'],
        [_('Run slow'), _('Long press the run button to run the project in slow mode.'), 'header-icons/slow-button.svg'],
        [_('Run music slow'), _('Extra-long press the run button to run the music in slow mode.'), 'header-icons/slow-music-button.svg'],
        [_('Run step by step'), _('Click to run the project step by step.'), 'header-icons/step-button.svg'],
        [_('Run note by note'), _('Click to run the music note by note.'), 'header-icons/step-music-button.svg'],
        [_('Stop'), _('Stop the music (and the turtles).') + ' ' + _('You can also type Alt-S to stop.'), 'header-icons/stop-turtle-button.svg'],
        [_('Clean'), _('Clear the screen and return the turtles to their initial positions.'), 'header-icons/clear-button.svg'],
        [_('Show/hide blocks'), _('Hide or show the blocks and the palettes.'), 'header-icons/hide-blocks-button.svg'],
        [_('Expand/collapse collapsable blocks'), _('Expand or collapse start and action stacks.'), 'header-icons/collapse-blocks-button.svg'],
        [_('Home'), _('Return all blocks to the center of the screen.'), 'header-icons/go-home-button.svg'],
        [_('Help'), _('Show these messages.'), 'header-icons/help-button.svg'],
        [_('Expand/collapse option toolbar'), _('Click this button to expand or collapse the auxillary toolbar.'), 'header-icons/menu-button.svg'],
        [_('Load samples from server'), _('This button opens a viewer for loading example projects.'), 'header-icons/planet-button.svg'],
        [_('Load project from files'), _('You can also load projects from the file system.'), 'header-icons/open-button.svg'],
        [_('Save project'), _('Save your project to a file.'), 'header-icons/save-button.svg'],
        [_('Save sheet music'), _('Save your project to as a Lilypond file.'), 'header-icons/lilypond-button.svg'],
        [_('Copy'), _('To copy a stack to the clipboard, do a long press on the stack.') + ' ' + _('You can also use Alt+C to copy a stack of blocks.') + ' ' + _('The Paste Button will highlight.'), 'header-icons/paste-button.svg'],
        [_('Paste'), _('The paste button is enabled when there are blocks copied onto the clipboard.') + ' ' + _('You can also use Alt+V to paste a stack of blocks. '), 'header-icons/paste-disabled-button.svg'],
        [_('Cartesian') + '/' + _('Polar'), _('Show or hide a coordinate grid.'), 'header-icons/Cartesian-polar-button.svg'],
        // [_('Polar'), _('Show or hide a polar-coordinate grid.'), 'header-icons/polar-button.svg'],
        [_('Settings'), _('Open a panel for configuring Music Blocks.'), 'header-icons/utility-button.svg'],
        [_('Search'), _('You can search for blocks by name.'), 'header-icons/search-button.svg'],
        [_('Enable scrolling'), _('You can scroll the blocks on the canvas.'), 'header-icons/scroll-unlock-button.svg'],
        [_('Decrease block size'), _('Decrease the size of the blocks.'), 'header-icons/smaller-button.svg'],
        [_('Increase block size'), _('Increase the size of the blocks.'), 'header-icons/bigger-button.svg'],
        [_('Display statistics'), _('Display statistics about your Music project.'), 'header-icons/stats-button.svg'],
        [_('Load plugin from file'), _('You can load new blocks from the file system.'), 'header-icons/plugins-button.svg'],
        [_('Delete plugin'), _('Delete a selected plugin.'), 'header-icons/plugins-delete-button.svg'],
        [_('Select language'), _('Select your language preference.'), 'header-icons/language-button.svg'],
        [_('New Project'), _('Initialise a new project.'), 'header-icons/new-project-button.svg'],
        [_('Restore'), _('Restore blocks from the trash.'), 'header-icons/restore-trash-button.svg'],
        [_('Keyboard shortcuts'), _('You can type "d" to create a "do" block, "r" to create a "re" block, etc.'), 'header-icons/type-icon.svg'],
        [_('Guide'), _('A detailed guide to Music Blocks is available.'), 'activity/activity-icon-mouse-color.svg', 'https://sugarlabs.github.io/musicblocks/guide', _('Music Blocks Guide')],
        [_('Congratulations.'), _('You have finished the tour. Please enjoy Music Blocks!'), 'activity/activity-icon-mouse-color.svg']
    ];
};
<commit_msg>use guitar in default blocks<commit_after>// Copyright (c) 2016-2018 Walter Bender
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
//

const NUMBERBLOCKDEFAULT = 4;

const DEFAULTPALETTE = 'rhythm';

const TITLESTRING = _('Music Blocks is a collection of tools for exploring musical concepts.');

// We don't include 'extras' since we want to be able to delete
// plugins from the extras palette.
BUILTINPALETTES = ['rhythm',  'meter', 'pitch', 'intervals', 'tone', 'volume', 'drum', 'flow', 'action', 'boxes', 'widgets', 'mouse', 'pen', 'number', 'boolean', 'media', 'sensors', 'heap', 'mice', 'extras'];

const BUILTINPALETTESFORL23N = [_('rhythm'), _('meter'), _('pitch'), _('intervals'), _('tone'), _('volume'), _('drum'), _('flow'), _('action'), _('boxes'), _('widgets'), _('mouse'), _('pen'), _('number'), _('boolean'), _('media'), _('sensors'), _('heap'), _('mice'), _('extras')];

function getMainToolbarButtonNames(name) {
    return (['popdown-palette', 'run', 'step', 'step-music', 'stop-turtle', 'hard-stop-turtle', 'clear', 'palette', 'hide-blocks', 'collapse-blocks', 'go-home', 'help', 'sugarizer-stop'].indexOf(name) > -1);
};

function getAuxToolbarButtonNames(name) {
    return (['planet', 'planet-disabled', 'open', 'save', 'paste-disabled', 'Cartesian', 'compile', 'utility', 'new-project', 'restore-trash'].indexOf(name) > -1);
}

function createDefaultStack() {
    DATAOBJS =
	[[0, 'start', screen.width / 3, 75, [null, 1, null]],

	 [1, 'settimbre', 0, 0, [0, 2, 4, 3]],
	 [2, ['voicename', {'value': 'guitar'}], 0, 0, [1]],
	 [3, 'hidden', 0, 0, [1, null]],

	 [4, 'newnote', 0, 0, [1, 5, 8, 12]],
	 [5, 'divide', 0, 0, [4, 6, 7]],
	 [6, ['number', {'value': 1}], 0, 0, [5]],
	 [7, ['number', {'value': 4}], 0, 0, [5]],
	 [8, 'vspace', 0, 0, [4, 9]],
	 [9, 'pitch', 0, 0, [8, 10, 11, null]],
	 [10, ['solfege', {'value': 'sol'}], 0, 0, [9]],
	 [11, ['number', {'value': 4}], 0, 0, [9]],
	 [12, 'hidden', 0, 0, [4, 13]],

	 [13, 'newnote', 0, 0, [12, 14, 17, 21]],
	 [14, 'divide', 0, 0, [13, 15, 16]],
	 [15, ['number', {'value': 1}], 0, 0, [14]],
	 [16, ['number', {'value': 4}], 0, 0, [14]],
	 [17, 'vspace', 0, 0, [13, 18]],
	 [18, 'pitch', 0, 0, [17, 19, 20, null]],
	 [19, ['solfege', {'value': 'mi'}], 0, 0, [18]],
	 [20, ['number', {'value': 4}], 0, 0, [18]],
	 [21, 'hidden', 0, 0, [13, 22]],

	 [22, 'newnote', 0, 0, [21, 23, 26, 30]],
	 [23, 'divide', 0, 0, [22, 24, 25]],
	 [24, ['number', {'value': 1}], 0, 0, [23]],
	 [25, ['number', {'value': 2}], 0, 0, [23]],
	 [26, 'vspace', 0, 0, [22, 27]],
	 [27, 'pitch', 0, 0, [26, 28, 29, null]],
	 [28, ['solfege', {'value': 'sol'}], 0, 0, [27]],
	 [29, ['number', {'value': 4}], 0, 0, [27]],
	 [30, 'hidden', 0, 0, [22, null]]
	];
};

function createHelpContent() {
    HELPCONTENT = [
        [_('Welcome to Music Blocks'), _('Music Blocks is a collection of manipulative tools for exploring fundamental musical concepts in an integrative and fun way.'), 'activity/activity-icon-mouse-color.svg'],
        [_('Meet Mr. Mouse!'), _('Mr Mouse is our Music Blocks conductor.') + ' ' + _('Mr Mouse encourages you to explore Music Blocks.') + ' ' + _('Let us start our tour!'), 'activity/activity-icon-mouse-color.svg'],
	//.TRANS: the buttons used to open various palettes of blocks
        [_('Palette buttons'),
        //.TRANS: Please add commas to list: Rhythm, Pitch, Tone, Action, and more.
	 _('This toolbar contains the palette buttons, including Rhythm Pitch Tone Action and more.') + ' ' + _('Click to show the palettes of blocks and drag blocks from the palettes onto the canvas to use them.'), 'images/icons.svg'],
        [_('Play music'), _('Click to run the music note by note.') + ' ' + _('Alternatively, you can hit the ENTER or RETURN key.'), 'header-icons/play-button.svg'],
        [_('Run fast'), _('Click the run button to run the project in fast mode.'), 'header-icons/run-button.svg'],
        [_('Run slow'), _('Long press the run button to run the project in slow mode.'), 'header-icons/slow-button.svg'],
        [_('Run music slow'), _('Extra-long press the run button to run the music in slow mode.'), 'header-icons/slow-music-button.svg'],
        [_('Run step by step'), _('Click to run the project step by step.'), 'header-icons/step-button.svg'],
        [_('Run note by note'), _('Click to run the music note by note.'), 'header-icons/step-music-button.svg'],
        [_('Stop'), _('Stop the music (and the turtles).') + ' ' + _('You can also type Alt-S to stop.'), 'header-icons/stop-turtle-button.svg'],
        [_('Clean'), _('Clear the screen and return the turtles to their initial positions.'), 'header-icons/clear-button.svg'],
        [_('Show/hide blocks'), _('Hide or show the blocks and the palettes.'), 'header-icons/hide-blocks-button.svg'],
        [_('Expand/collapse collapsable blocks'), _('Expand or collapse start and action stacks.'), 'header-icons/collapse-blocks-button.svg'],
        [_('Home'), _('Return all blocks to the center of the screen.'), 'header-icons/go-home-button.svg'],
        [_('Help'), _('Show these messages.'), 'header-icons/help-button.svg'],
        [_('Expand/collapse option toolbar'), _('Click this button to expand or collapse the auxillary toolbar.'), 'header-icons/menu-button.svg'],
        [_('Load samples from server'), _('This button opens a viewer for loading example projects.'), 'header-icons/planet-button.svg'],
        [_('Load project from files'), _('You can also load projects from the file system.'), 'header-icons/open-button.svg'],
        [_('Save project'), _('Save your project to a file.'), 'header-icons/save-button.svg'],
        [_('Save sheet music'), _('Save your project to as a Lilypond file.'), 'header-icons/lilypond-button.svg'],
        [_('Copy'), _('To copy a stack to the clipboard, do a long press on the stack.') + ' ' + _('You can also use Alt+C to copy a stack of blocks.') + ' ' + _('The Paste Button will highlight.'), 'header-icons/paste-button.svg'],
        [_('Paste'), _('The paste button is enabled when there are blocks copied onto the clipboard.') + ' ' + _('You can also use Alt+V to paste a stack of blocks. '), 'header-icons/paste-disabled-button.svg'],
        [_('Cartesian') + '/' + _('Polar'), _('Show or hide a coordinate grid.'), 'header-icons/Cartesian-polar-button.svg'],
        // [_('Polar'), _('Show or hide a polar-coordinate grid.'), 'header-icons/polar-button.svg'],
        [_('Settings'), _('Open a panel for configuring Music Blocks.'), 'header-icons/utility-button.svg'],
        [_('Search'), _('You can search for blocks by name.'), 'header-icons/search-button.svg'],
        [_('Enable scrolling'), _('You can scroll the blocks on the canvas.'), 'header-icons/scroll-unlock-button.svg'],
        [_('Decrease block size'), _('Decrease the size of the blocks.'), 'header-icons/smaller-button.svg'],
        [_('Increase block size'), _('Increase the size of the blocks.'), 'header-icons/bigger-button.svg'],
        [_('Display statistics'), _('Display statistics about your Music project.'), 'header-icons/stats-button.svg'],
        [_('Load plugin from file'), _('You can load new blocks from the file system.'), 'header-icons/plugins-button.svg'],
        [_('Delete plugin'), _('Delete a selected plugin.'), 'header-icons/plugins-delete-button.svg'],
        [_('Select language'), _('Select your language preference.'), 'header-icons/language-button.svg'],
        [_('New Project'), _('Initialise a new project.'), 'header-icons/new-project-button.svg'],
        [_('Restore'), _('Restore blocks from the trash.'), 'header-icons/restore-trash-button.svg'],
        [_('Keyboard shortcuts'), _('You can type "d" to create a "do" block, "r" to create a "re" block, etc.'), 'header-icons/type-icon.svg'],
        [_('Guide'), _('A detailed guide to Music Blocks is available.'), 'activity/activity-icon-mouse-color.svg', 'https://sugarlabs.github.io/musicblocks/guide', _('Music Blocks Guide')],
        [_('Congratulations.'), _('You have finished the tour. Please enjoy Music Blocks!'), 'activity/activity-icon-mouse-color.svg']
    ];
};
<|endoftext|>


<commit_before>// Dependencies
var Fs = require("fs")
  , Path = require("path")
  , ExecLimiter = require("exec-limiter")
  , Ul = require("ul")
  ;

/**
 * Gry
 * Creates a new `Gry` instance.
 *
 * @name Gry
 * @function
 * @param {Object} options An object containing the following fields:
 *
 *  - `path` (String): The path to the git repository.
 *  - `limit` (Number): The limit of commands to run same time.
 *
 * @return {Gry} The `Gry` instance.
 */
function Gry (options) {

    var self = this;

    if (typeof options === "string") {
        options = {
            path: options
        };
    }

    options = Ul.merge({
        limit: 30
    }, options);

    options.path = Path.resolve(options.path);

    self.options = options;
    self.cwd = options.path;

    self.limiter = new ExecLimiter(options.limit);
}

/**
 * exec
 * Executes a git command in the repository directory.
 *
 * @name exec
 * @function
 * @param {String} command The git command that should be executed in the repository directory.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.exec = function (command, callback) {

    this.limiter.add("git " + command.trim(), [{ cwd: this.cwd }], function (err, stdout) {
        if (err) { return callback(err); }
        callback(null, stdout.trimRight());
    });

    return this;
};

/**
 * init
 * Inits the git repository.
 *
 * @name init
 * @function
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.init = function (callback) {
    return this.exec("init", callback);
};

/**
 * create
 * Creates a git repository.
 *
 * @name create
 * @function
 * @param {String} path The path of the repository.
 * @param {Function} callback The callback function
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.create = function (callback) {
    var self = this;
    Fs.exists(self.cwd, function (e) {
        if (e) {
            callback(new Error("A directory already exists."));
            return self;
        }
        Fs.mkdir(self.cwd, function (err) {
            if (err) {
                callback(err);
                return self;
            }
            self.init(callback);
        });
    });
    return self;
};

/**
 * commit
 * Creates a commit, providing the `message`.
 *
 * @name commit
 * @function
 * @param {String} message The commit message
 * @param {String} options Additional options passed to the commit command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.commit = function (message, options, callback) {
    message = message.replace(/\"/g, "\\");
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("commit -m \"" + message + "\" " + options, callback)
};

/**
 * pull
 * Runs `git pull`.
 *
 * @name pull
 * @function
 * @param {String} options Additional options passed to the `pull` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.pull = function (options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("pull " + options, callback);
};

/**
 * add
 * Runs `git add`.
 *
 * @name add
 * @function
 * @param {String} options Additional options passed to the `add` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.add = function (options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = ".";
    }
    return this.exec("add " + options, callback);
};

/**
 * branch
 * Runs `git branch`.
 *
 * @name branch
 * @function
 * @param {String} options Additional options passed to the `branch` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.branch = function (options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("branch " + options, callback);
};

/**
 * checkout
 * Runs `git checkout`.
 *
 * @name checkout
 * @function
 * @param {String} options Additional options passed to the `checkout` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.checkout = function (options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("checkout " + options, callback);
};

/**
 * clone
 * Runs `git clone`.
 *
 * @name clone
 * @function
 * @param {String} gitUrl The git url of the repository that should be cloned.
 * @param {String} options Additional options passed to the `checkout` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.clone = function (gitUrl, options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("clone " + gitUrl + " " + options, callback);
};

module.exports = Gry;
<commit_msg>Initial commit.<commit_after>// Dependencies
var Fs = require("fs")
  , Path = require("path")
  , ExecLimiter = require("exec-limiter")
  , Ul = require("ul")
  ;

/**
 * Gry
 * Creates a new `Gry` instance.
 *
 * @name Gry
 * @function
 * @param {Object} options An object containing the following fields:
 *
 *  - `path` (String): The path to the git repository.
 *  - `limit` (Number): The limit of commands to run same time.
 *
 * @return {Gry} The `Gry` instance.
 */
function Gry (options) {

    var self = this;

    if (typeof options === "string") {
        options = {
            path: options
        };
    }

    options = Ul.merge({
        limit: 30
    }, options);

    options.path = Path.resolve(options.path);

    self.options = options;
    self.cwd = options.path;

    self.limiter = new ExecLimiter(options.limit);
}

/**
 * exec
 * Executes a git command in the repository directory.
 *
 * @name exec
 * @function
 * @param {String} command The git command that should be executed in the repository directory.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.exec = function (command, callback) {

    debugger
    this.limiter.add("git " + command.trim(), [{ cwd: this.cwd }], function (err, stdout) {
        if (err) { return callback(err); }
        callback(null, stdout.trimRight());
    });

    return this;
};

/**
 * init
 * Inits the git repository.
 *
 * @name init
 * @function
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.init = function (callback) {
    return this.exec("init", callback);
};

/**
 * create
 * Creates a git repository.
 *
 * @name create
 * @function
 * @param {String} path The path of the repository.
 * @param {Function} callback The callback function
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.create = function (callback) {
    var self = this;
    Fs.exists(self.cwd, function (e) {
        if (e) {
            callback(new Error("A directory already exists."));
            return self;
        }
        Fs.mkdir(self.cwd, function (err) {
            if (err) {
                callback(err);
                return self;
            }
            self.init(callback);
        });
    });
    return self;
};

/**
 * commit
 * Creates a commit, providing the `message`.
 *
 * @name commit
 * @function
 * @param {String} message The commit message
 * @param {String} options Additional options passed to the commit command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.commit = function (message, options, callback) {
    message = message.replace(/\"/g, "\\");
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("commit -m \"" + message + "\" " + options, callback)
};

/**
 * pull
 * Runs `git pull`.
 *
 * @name pull
 * @function
 * @param {String} options Additional options passed to the `pull` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.pull = function (options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("pull " + options, callback);
};

/**
 * add
 * Runs `git add`.
 *
 * @name add
 * @function
 * @param {String} options Additional options passed to the `add` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.add = function (options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = ".";
    }
    return this.exec("add " + options, callback);
};

/**
 * branch
 * Runs `git branch`.
 *
 * @name branch
 * @function
 * @param {String} options Additional options passed to the `branch` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.branch = function (options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("branch " + options, callback);
};

/**
 * checkout
 * Runs `git checkout`.
 *
 * @name checkout
 * @function
 * @param {String} options Additional options passed to the `checkout` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.checkout = function (options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("checkout " + options, callback);
};

/**
 * clone
 * Runs `git clone`.
 *
 * @name clone
 * @function
 * @param {String} gitUrl The git url of the repository that should be cloned.
 * @param {String} options Additional options passed to the `checkout` command.
 * @param {Function} callback The callback function.
 * @return {Gry} The `Gry` intance.
 */
Gry.prototype.clone = function (gitUrl, options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = "";
    }
    return this.exec("clone " + gitUrl + " " + options, callback);
};

module.exports = Gry;
<|endoftext|>


<commit_before>/** Bars **/
Flotr.addType('bars', {

  options: {
    show: false,           // => setting to true will show bars, false will hide
    lineWidth: 2,          // => in pixels
    barWidth: 1,           // => in units of the x axis
    fill: true,            // => true to fill the area from the line to the x axis, false for (transparent) no fill
    fillColor: null,       // => fill color
    fillOpacity: 0.4,      // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
    horizontal: false,     // => horizontal bars (x and y inverted)
    stacked: false,        // => stacked bar charts
    centered: true         // => center the bars to their x axis value
  },

  draw : function (options) {
    var
      context = options.context;

    context.save();
    context.translate(options.offsetLeft, options.offsetTop);
    context.lineJoin = 'miter';
    // @TODO linewidth not interpreted the right way.
    context.lineWidth = Math.min(options.lineWidth, options.barWidth);
    context.strokeStyle = options.color;
    if (options.fill) context.fillStyle = options.fillStyle

    this.plot(options);

    context.restore();
  },

  getEmptyStack : function () {
    return {
      positive : [],
      negative : [],
      _positive : [], // Shadow
      _negative : []  // Shadow
    };
  },

  plot : function (options) {

    var
      data            = options.data,
      context         = options.context,
      barWidth        = options.barWidth,
      shadowSize      = options.shadowSize,
      horizontal      = options.horizontal,
      centered        = options.centered,
      stack           = options.stack,
      xIndex          = horizontal ? 1 : 0,
      yIndex          = horizontal ? 0 : 1,
      xScale          = horizontal ? options.yScale : options.xScale,
      yScale          = horizontal ? options.xScale : options.yScale,
      stackOffset     = 0,
      bisection,
      width, height,
      left, right, top, bottom,
      i, x, y;

    if (data.length < 1) return;

    if (horizontal) {
      context.rotate(-Math.PI / 2)
      context.scale(-1, 1);
    }

    for (i = 0; i < data.length; i++) {

      x = data[i][xIndex];
      y = data[i][yIndex];

      if (y === null) continue;

      // Stacked bars
      if (stack) {
        if (y > 0) {
          stackOffset = stack.positive[x] || stackOffset;
          stack.positive[x] = stackOffset + y;
        } else {
          stackOffset = stack.negative[x] || stackOffset;
          stack.negative[x] = stackOffset + y;
        }
      }

      // edge values
      bisection = centered ? barWidth/2 : 0;
      top       = yScale(y + stackOffset);
      bottom    = yScale(stackOffset);
      left      = xScale(x - bisection);
      right     = xScale(x + barWidth - bisection);

      // TODO for test passing... probably looks better without this
      if (bottom < 0) bottom = 0;

      width     = right - left;
      height    = bottom - top;

      // TODO Skipping...
      // if (right < xa.min || left > xa.max || top < ya.min || bottom > ya.max) continue;

      if (options.fill) context.fillRect(left, top, width, height);
      if (shadowSize) {
        context.save();
        context.fillStyle = 'rgba(0,0,0,0.05)';
        context.fillRect(left + shadowSize, top + shadowSize, width, height);
        context.restore();
      }
      if (options.lineWidth != 0) {
        context.strokeRect(left, top, width, height);
      }
    }
  },

  extendXRange : function (axis, data, options, bars) {
    this._extendRange(axis, data, options, bars);
  },

  extendYRange : function (axis, data, options, bars) {
    this._extendRange(axis, data, options, bars);
  },
  _extendRange: function (axis, data, options, bars) {

    var
      max = axis.options.max;

    if (_.isNumber(max) || _.isString(max)) return;

    var
      newmin = axis.min,
      newmax = axis.max,
      orientation = axis.orientation,
      positiveSums = bars.positiveSums || {},
      negativeSums = bars.negativeSums || {},
      value, datum, index, j;

    // Sides of bars
    if ((orientation == 1 && !options.horizontal) || (orientation == -1 && options.horizontal)) {
      if (options.centered) {
        newmax = Math.max(axis.datamax + 0.5, newmax);
        newmin = Math.min(axis.datamin - 0.5, newmin);
      }
    }

    // End of bars
    if ((orientation == 1 && options.horizontal) || (orientation == -1 && !options.horizontal)) {
      if (options.barWidth + axis.datamax >= newmax)
        newmax = axis.max + (options.centered ? options.barWidth/2 : options.barWidth);
    }

    if (options.stacked &&
        ((orientation == 1 && options.horizontal) || (orientation == -1 && !options.horizontal))){

      for (j = data.length; j--;) {
        value = data[j][(orientation == 1 ? 1 : 0)]+'';
        datum = data[j][(orientation == 1 ? 0 : 1)];

        // Positive
        if (datum > 0) {
          positiveSums[value] = (positiveSums[value] || 0) + datum;
          newmax = Math.max(newmax, positiveSums[value]);
        }

        // Negative
        else {
          negativeSums[value] = (negativeSums[value] || 0) + datum;
          newmin = Math.min(newmin, negativeSums[value]);
        }
      }
    }

    bars.negativeSums = negativeSums;
    bars.positiveSums = positiveSums;

    axis.max = newmax;
    axis.min = newmin;
  },

  drawHit: function (n) {
    var octx = this.octx,
      s = n.series,
      xa = n.xaxis,
      ya = n.yaxis,
      lx, rx, ly, uy;

    octx.save();
    octx.translate(this.plotOffset.left, this.plotOffset.top);
    octx.beginPath();

    if (s.mouse.trackAll) {
      octx.moveTo(xa.d2p(n.x), ya.d2p(0));
      octx.lineTo(xa.d2p(n.x), ya.d2p(n.yaxis.max));
    }
    else {
      var bw = s.bars.barWidth,
        y = ya.d2p(n.y),
        x = xa.d2p(n.x);

      if(!s.bars.horizontal){ //vertical bars (default)
        ly = ya.d2p(ya.min<0? 0 : ya.min); //lower vertex y value (in points)

        if(s.bars.centered){
          lx = xa.d2p(n.x-(bw/2));
          rx = xa.d2p(n.x+(bw/2));

          octx.moveTo(lx, ly);
          octx.lineTo(lx, y);
          octx.lineTo(rx, y);
          octx.lineTo(rx, ly);
        } else {
          rx = xa.d2p(n.x+bw); //right vertex x value (in points)

          octx.moveTo(x, ly);
          octx.lineTo(x, y);
          octx.lineTo(rx, y);
          octx.lineTo(rx, ly);
        }
      } else { //horizontal bars
        lx = xa.d2p(xa.min<0? 0 : xa.min); //left vertex y value (in points)

        if(s.bars.centered){
          ly = ya.d2p(n.y-(bw/2));
          uy = ya.d2p(n.y+(bw/2));

          octx.moveTo(lx, ly);
          octx.lineTo(x, ly);
          octx.lineTo(x, uy);
          octx.lineTo(lx, uy);
        } else {
          uy = ya.d2p(n.y+bw); //upper vertex y value (in points)

          octx.moveTo(lx, y);
          octx.lineTo(x, y);
          octx.lineTo(x, uy);
          octx.lineTo(lx, uy);
        }
      }

      if(s.mouse.fillColor) octx.fill();
    }

    octx.stroke();
    octx.closePath();
    octx.restore();
  },

  clearHit: function() {
    var prevHit = this.prevHit,
      plotOffset = this.plotOffset,
      s = prevHit.series,
      xa = prevHit.xaxis,
      ya = prevHit.yaxis,
      lw = s.bars.lineWidth,
      bw = s.bars.barWidth;

    if(!s.bars.horizontal){ // vertical bars (default)
      var lastY = ya.d2p(prevHit.y >= 0 ? prevHit.y : 0);
      if(s.bars.centered) {
        this.octx.clearRect(
            xa.d2p(prevHit.x - bw/2) + plotOffset.left - lw,
            lastY + plotOffset.top - lw,
            xa.d2p(bw + xa.min) + lw * 2,
            ya.d2p(prevHit.y < 0 ? prevHit.y : 0) - lastY + lw * 2
        );
      } else {
        this.octx.clearRect(
            xa.d2p(prevHit.x) + plotOffset.left - lw,
            lastY + plotOffset.top - lw,
            xa.d2p(bw + xa.min) + lw * 2,
            ya.d2p(prevHit.y < 0 ? prevHit.y : 0) - lastY + lw * 2
        );
      }
    } else { // horizontal bars
      var lastX = xa.d2p(prevHit.x >= 0 ? prevHit.x : 0);
      if(s.bars.centered) {
        this.octx.clearRect(
            lastX + plotOffset.left + lw,
            ya.d2p(prevHit.y + bw/2) + plotOffset.top - lw,
            xa.d2p(prevHit.x < 0 ? prevHit.x : 0) - lastX - lw*2,
            ya.d2p(bw + ya.min) + lw * 2
        );
      } else {
        this.octx.clearRect(
            lastX + plotOffset.left + lw,
            ya.d2p(prevHit.y + bw) + plotOffset.top - lw,
            xa.d2p(prevHit.x < 0 ? prevHit.x : 0) - lastX - lw*2,
            ya.d2p(bw + ya.min) + lw * 2
        );
      }
    }
  }
});
<commit_msg>Initial bar geometry method.<commit_after>/** Bars **/
Flotr.addType('bars', {

  options: {
    show: false,           // => setting to true will show bars, false will hide
    lineWidth: 2,          // => in pixels
    barWidth: 1,           // => in units of the x axis
    fill: true,            // => true to fill the area from the line to the x axis, false for (transparent) no fill
    fillColor: null,       // => fill color
    fillOpacity: 0.4,      // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
    horizontal: false,     // => horizontal bars (x and y inverted)
    stacked: false,        // => stacked bar charts
    centered: true         // => center the bars to their x axis value
  },

  draw : function (options) {
    var
      context = options.context;

    context.save();
    context.translate(options.offsetLeft, options.offsetTop);
    context.lineJoin = 'miter';
    // @TODO linewidth not interpreted the right way.
    context.lineWidth = Math.min(options.lineWidth, options.barWidth);
    context.strokeStyle = options.color;
    if (options.fill) context.fillStyle = options.fillStyle

    this.plot(options);

    context.restore();
  },

  getEmptyStack : function () {
    return {
      positive : [],
      negative : [],
      _positive : [], // Shadow
      _negative : []  // Shadow
    };
  },

  plot : function (options) {

    var
      data            = options.data,
      context         = options.context,
      barWidth        = options.barWidth,
      shadowSize      = options.shadowSize,
      horizontal      = options.horizontal,
      centered        = options.centered,
      stack           = options.stack,
      xIndex          = horizontal ? 1 : 0,
      yIndex          = horizontal ? 0 : 1,
      xScale          = horizontal ? options.yScale : options.xScale,
      yScale          = horizontal ? options.xScale : options.yScale,
      stackOffset     = 0,
      bisection,
      width, height,
      left, right, top, bottom,
      i, x, y;

    if (data.length < 1) return;

    if (horizontal) {
      context.rotate(-Math.PI / 2)
      context.scale(-1, 1);
    }

    for (i = 0; i < data.length; i++) {

      x = data[i][xIndex];
      y = data[i][yIndex];

      if (y === null) continue;

      // Stacked bars
      if (stack) {
        if (y > 0) {
          stackOffset = stack.positive[x] || stackOffset;
          stack.positive[x] = stackOffset + y;
        } else {
          stackOffset = stack.negative[x] || stackOffset;
          stack.negative[x] = stackOffset + y;
        }
      }

      // edge values
      bisection = centered ? barWidth/2 : 0;
      top       = yScale(y + stackOffset);
      bottom    = yScale(stackOffset);
      left      = xScale(x - bisection);
      right     = xScale(x + barWidth - bisection);

      // TODO for test passing... probably looks better without this
      if (bottom < 0) bottom = 0;

      width     = right - left;
      height    = bottom - top;

      // TODO Skipping...
      // if (right < xa.min || left > xa.max || top < ya.min || bottom > ya.max) continue;

      if (options.fill) context.fillRect(left, top, width, height);
      if (shadowSize) {
        context.save();
        context.fillStyle = 'rgba(0,0,0,0.05)';
        context.fillRect(left + shadowSize, top + shadowSize, width, height);
        context.restore();
      }
      if (options.lineWidth != 0) {
        context.strokeRect(left, top, width, height);
      }
    }
  },

  getBarGeometry : function (x, y, options) {
    var
      barWidth        = options.barWidth,
      centered        = options.centered,
      bisection       = centered ? barWidth / 2 : 0,
      x, y, width, height;

    return {
      top       : yScale(y + stackOffset),
      bottom    : yScale(stackOffset),
      left      : xScale(x - bisection),
      right     : xScale(x + barWidth - bisection)
    };
  },

  extendXRange : function (axis, data, options, bars) {
    this._extendRange(axis, data, options, bars);
  },

  extendYRange : function (axis, data, options, bars) {
    this._extendRange(axis, data, options, bars);
  },
  _extendRange: function (axis, data, options, bars) {

    var
      max = axis.options.max;

    if (_.isNumber(max) || _.isString(max)) return;

    var
      newmin = axis.min,
      newmax = axis.max,
      orientation = axis.orientation,
      positiveSums = bars.positiveSums || {},
      negativeSums = bars.negativeSums || {},
      value, datum, index, j;

    // Sides of bars
    if ((orientation == 1 && !options.horizontal) || (orientation == -1 && options.horizontal)) {
      if (options.centered) {
        newmax = Math.max(axis.datamax + 0.5, newmax);
        newmin = Math.min(axis.datamin - 0.5, newmin);
      }
    }

    // End of bars
    if ((orientation == 1 && options.horizontal) || (orientation == -1 && !options.horizontal)) {
      if (options.barWidth + axis.datamax >= newmax)
        newmax = axis.max + (options.centered ? options.barWidth/2 : options.barWidth);
    }

    if (options.stacked &&
        ((orientation == 1 && options.horizontal) || (orientation == -1 && !options.horizontal))){

      for (j = data.length; j--;) {
        value = data[j][(orientation == 1 ? 1 : 0)]+'';
        datum = data[j][(orientation == 1 ? 0 : 1)];

        // Positive
        if (datum > 0) {
          positiveSums[value] = (positiveSums[value] || 0) + datum;
          newmax = Math.max(newmax, positiveSums[value]);
        }

        // Negative
        else {
          negativeSums[value] = (negativeSums[value] || 0) + datum;
          newmin = Math.min(newmin, negativeSums[value]);
        }
      }
    }

    bars.negativeSums = negativeSums;
    bars.positiveSums = positiveSums;

    axis.max = newmax;
    axis.min = newmin;
  },

  drawHit: function (n) {
    var octx = this.octx,
      s = n.series,
      xa = n.xaxis,
      ya = n.yaxis,
      lx, rx, ly, uy;

    octx.save();
    octx.translate(this.plotOffset.left, this.plotOffset.top);
    octx.beginPath();

    if (s.mouse.trackAll) {
      octx.moveTo(xa.d2p(n.x), ya.d2p(0));
      octx.lineTo(xa.d2p(n.x), ya.d2p(n.yaxis.max));
    }
    else {
      var bw = s.bars.barWidth,
        y = ya.d2p(n.y),
        x = xa.d2p(n.x);

      if(!s.bars.horizontal){ //vertical bars (default)
        ly = ya.d2p(ya.min<0? 0 : ya.min); //lower vertex y value (in points)

        if(s.bars.centered){
          lx = xa.d2p(n.x-(bw/2));
          rx = xa.d2p(n.x+(bw/2));

          octx.moveTo(lx, ly);
          octx.lineTo(lx, y);
          octx.lineTo(rx, y);
          octx.lineTo(rx, ly);
        } else {
          rx = xa.d2p(n.x+bw); //right vertex x value (in points)

          octx.moveTo(x, ly);
          octx.lineTo(x, y);
          octx.lineTo(rx, y);
          octx.lineTo(rx, ly);
        }
      } else { //horizontal bars
        lx = xa.d2p(xa.min<0? 0 : xa.min); //left vertex y value (in points)

        if(s.bars.centered){
          ly = ya.d2p(n.y-(bw/2));
          uy = ya.d2p(n.y+(bw/2));

          octx.moveTo(lx, ly);
          octx.lineTo(x, ly);
          octx.lineTo(x, uy);
          octx.lineTo(lx, uy);
        } else {
          uy = ya.d2p(n.y+bw); //upper vertex y value (in points)

          octx.moveTo(lx, y);
          octx.lineTo(x, y);
          octx.lineTo(x, uy);
          octx.lineTo(lx, uy);
        }
      }

      if(s.mouse.fillColor) octx.fill();
    }

    octx.stroke();
    octx.closePath();
    octx.restore();
  },

  clearHit: function() {
    var prevHit = this.prevHit,
      plotOffset = this.plotOffset,
      s = prevHit.series,
      xa = prevHit.xaxis,
      ya = prevHit.yaxis,
      lw = s.bars.lineWidth,
      bw = s.bars.barWidth;

    if(!s.bars.horizontal){ // vertical bars (default)
      var lastY = ya.d2p(prevHit.y >= 0 ? prevHit.y : 0);
      if(s.bars.centered) {
        this.octx.clearRect(
            xa.d2p(prevHit.x - bw/2) + plotOffset.left - lw,
            lastY + plotOffset.top - lw,
            xa.d2p(bw + xa.min) + lw * 2,
            ya.d2p(prevHit.y < 0 ? prevHit.y : 0) - lastY + lw * 2
        );
      } else {
        this.octx.clearRect(
            xa.d2p(prevHit.x) + plotOffset.left - lw,
            lastY + plotOffset.top - lw,
            xa.d2p(bw + xa.min) + lw * 2,
            ya.d2p(prevHit.y < 0 ? prevHit.y : 0) - lastY + lw * 2
        );
      }
    } else { // horizontal bars
      var lastX = xa.d2p(prevHit.x >= 0 ? prevHit.x : 0);
      if(s.bars.centered) {
        this.octx.clearRect(
            lastX + plotOffset.left + lw,
            ya.d2p(prevHit.y + bw/2) + plotOffset.top - lw,
            xa.d2p(prevHit.x < 0 ? prevHit.x : 0) - lastX - lw*2,
            ya.d2p(bw + ya.min) + lw * 2
        );
      } else {
        this.octx.clearRect(
            lastX + plotOffset.left + lw,
            ya.d2p(prevHit.y + bw) + plotOffset.top - lw,
            xa.d2p(prevHit.x < 0 ? prevHit.x : 0) - lastX - lw*2,
            ya.d2p(bw + ya.min) + lw * 2
        );
      }
    }
  }
});
<|endoftext|>


<commit_before>var termops = require('./util/termops'),
    ops = require('./util/ops'),
    _ = require('underscore'),
    DEBUG = process.env.DEBUG;

// # Store
module.exports = function index(source, docs, callback) {
    indexFreqs(function(err, freq) {
        if (err) return callback(err);
        indexDocs(freq[0], freq, callback);
    });

    // First pass over docs.
    // - Creates termsets (one or more arrays of termids) from document text.
    // - Tallies frequency of termids against current frequencies compiling a
    //   final in-memory frequency count of all terms involved with this set of
    //   documents to be indexed.
    // - Stores new frequencies.
    function indexFreqs(callback) {
        var freq = {};

        // Uses freq[0] as a convention for storing total # of docs.
        // @TODO determine whether 0 can really ever be a relevant term
        // when using fnv1a.
        freq[0] = [0];

        for (var i = 0; i < docs.length; i++) {
            var doc = docs[i];
            var phrases = [];
            var termsets = [];
            var termsmaps = [];
            var texts = doc.text.split(',');
            for (var x = 0; x < texts.length; x++) {
                if (!termops.tokenize(texts[x]).length) continue;
                phrases.push(termops.phrase(texts[x]));
                termsets.push(termops.terms(texts[x]));
                termsmaps.push(termops.termsMap(texts[x]));
            }
            for (var j = 0; j < termsets.length; j++) {
                var terms = termsets[j];
                for (var k = 0; k < terms.length; k++) {
                    var id = terms[k];
                    freq[id] = freq[id] || [0];
                    freq[id][0]++;
                    freq[0][0]++;
                }
            }
            doc.phrases = phrases;
            doc.termsets = termsets;
            doc.termsmaps = termsmaps;
        }

        // Ensures all shards are loaded.
        var ids = Object.keys(freq).map(function(v) { return parseInt(v,10); });
        source._geocoder.getall(source.getCarmen.bind(source), 'freq', ids, function(err) {
            if (err) return callback(err);
            for (var i = 0; i < ids.length; i++) {
                var id = ids[i];
                freq[id][0] = (source._geocoder.get('freq', id) || [0])[0] + freq[id][0];
                source._geocoder.set('freq', id, freq[id]);
            }
            callback(null, freq);
        });
    }

    // Second pass over docs.
    // - Create term => docid index. Uses calculated frequencies to index only
    //   significant terms for each document.
    // - Create id => grid zxy index.
    function indexDocs(approxdocs, freq, callback) {
        var patch = { grid: {}, term: {}, phrase: {}, degen: {} };
        var degenerated = {};

        docs.forEach(loadDoc);

        function loadDoc(doc) {
            doc.id = parseInt(doc.id,10);
            doc.zxy = doc.zxy ? doc.zxy.map(function(zxy) {
                return ops.zxy(doc.id, zxy);
            }) : [];

            var phrases = doc.phrases;
            var termsets = doc.termsets;
            var termsmaps = doc.termsmaps;

            phrases.forEach(function(id, x) {
                patch.phrase[id] = patch.phrase[id] || termsets[x];
                patch.grid[id] = patch.grid[id] || [];
                patch.grid[id].push.apply(patch.grid[id], doc.zxy);
            });

            termsets.forEach(loadTerm);

            function loadTerm(terms, x) {
                var id;
                var termsmap = termsmaps[x];
                var name = phrases[x];
                var weights = [];
                var total = 0;

                for (var i = 0; i < terms.length; i++) {
                    id = terms[i];
                    var weight = Math.log(1 + freq[0][0]/freq[id][0]);
                    weights.push([id, weight]);
                    total += weight;

                    // Degenerate terms are indexed for all terms
                    // (not just significant ones).
                    if (degenerated[id]) continue;
                    degenerated[id] = true;
                    var degens = termops.degens(termsmap[id]);
                    var keys = Object.keys(degens);
                    for (var j = 0; j < keys.length; j++) {
                        var d = keys[j];
                        patch.degen[d] = patch.degen[d] || [];
                        patch.degen[d].push(degens[d]);
                    }
                }

                // Limit indexing to the *most* significant terms for a
                // document. Currently uses rough heuristic (floor+sqrt) to
                // determine how many of the top words to grab.
                weights.sort(function(a,b) {
                    return a[1] > b[1] ? -1 : a[1] < b[1] ? 1 : 0;
                });
                var sigterms = [];
                var limit = Math.floor(Math.sqrt(weights.length));
                for (i = 0; i < limit; i++) sigterms.push(weights[i][0]);

                // Debug significant term selection.
                if (DEBUG) {
                    var debug = termsmap;
                    var oldtext = terms.map(function(id) { return debug[id]; }).join(' ');
                    var sigtext = sigterms.map(function(id) { return debug[id]; }).join(' ');
                    if (oldtext !== sigtext)  console.log('%s => %s', oldtext, sigtext);
                }

                for (i = 0; i < sigterms.length; i++) {
                    id = sigterms[i];
                    patch.term[id] = patch.term[id] || [];
                    patch.term[id].push(name);
                }
            }
        }

        var remaining = docs.length;
        remaining++; // term
        remaining++; // phrase
        remaining++; // grid

        _(docs).each(function(doc) {
            source.putFeature(doc.id, doc.doc, function(err) {
                if (err && remaining > 0) {
                    remaining = -1;
                    return callback(err);
                }
                if (!--remaining) callback(null);
            });
        });

        _(patch).each(function(data, type) {
            var ids = Object.keys(data);
            source._geocoder.getall(source.getCarmen.bind(source), type, ids, function(err) {
                if (err && remaining > 0) {
                    remaining = -1;
                    return callback(err);
                }
                for (var i = 0; i < ids.length; i++) {
                    var id = ids[i];
                    // This merges new entries on top of old ones.
                    switch (type) {
                    case 'term':
                    case 'grid':
                    case 'degen':
                        var current = source._geocoder.get(type, id) || [];
                        current.push.apply(current, data[id]);
                        source._geocoder.set(type, id, current);
                        break;
                    case 'phrase':
                        source._geocoder.set(type, id, data[id]);
                        break;
                    }
                }
                if (!--remaining) callback(null);
            });
        });
    }
};
<commit_msg>Simplify index - this is just an iife anyway<commit_after>var termops = require('./util/termops'),
    ops = require('./util/ops'),
    _ = require('underscore'),
    DEBUG = process.env.DEBUG;

// # Store
module.exports = function index(source, docs, callback) {

    // First pass over docs.
    // - Creates termsets (one or more arrays of termids) from document text.
    // - Tallies frequency of termids against current frequencies compiling a
    //   final in-memory frequency count of all terms involved with this set of
    //   documents to be indexed.
    // - Stores new frequencies.
    var freq = {};

    // Uses freq[0] as a convention for storing total # of docs.
    // @TODO determine whether 0 can really ever be a relevant term
    // when using fnv1a.
    freq[0] = [0];

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

        var doc = docs[i],
            phrases = [],
            termsets = [],
            termsmaps = [],
            texts = doc.text.split(',');

        for (var x = 0; x < texts.length; x++) {
            if (!termops.tokenize(texts[x]).length) continue;
            phrases.push(termops.phrase(texts[x]));
            termsets.push(termops.terms(texts[x]));
            termsmaps.push(termops.termsMap(texts[x]));
        }

        for (var j = 0; j < termsets.length; j++) {
            var terms = termsets[j];
            for (var k = 0; k < terms.length; k++) {
                var id = terms[k];
                freq[id] = freq[id] || [0];
                freq[id][0]++;
                freq[0][0]++;
            }
        }

        doc.phrases = phrases;
        doc.termsets = termsets;
        doc.termsmaps = termsmaps;
    }

    // Ensures all shards are loaded.
    var ids = Object.keys(freq).map(function(v) { return parseInt(v, 10); });
    source._geocoder.getall(source.getCarmen.bind(source), 'freq', ids, function(err) {
        if (err) return indexDocs(err);
        for (var i = 0; i < ids.length; i++) {
            var id = ids[i];
            freq[id][0] = (source._geocoder.get('freq', id) || [0])[0] + freq[id][0];
            source._geocoder.set('freq', id, freq[id]);
        }
        indexDocs(freq[0], freq, callback);
    });

    // Second pass over docs.
    // - Create term => docid index. Uses calculated frequencies to index only
    //   significant terms for each document.
    // - Create id => grid zxy index.
    function indexDocs(approxdocs, freq, callback) {
        var patch = { grid: {}, term: {}, phrase: {}, degen: {} };
        var degenerated = {};

        docs.forEach(loadDoc);

        function loadDoc(doc) {
            doc.id = parseInt(doc.id,10);
            doc.zxy = doc.zxy ? doc.zxy.map(function(zxy) {
                return ops.zxy(doc.id, zxy);
            }) : [];

            var phrases = doc.phrases;
            var termsets = doc.termsets;
            var termsmaps = doc.termsmaps;

            phrases.forEach(function(id, x) {
                patch.phrase[id] = patch.phrase[id] || termsets[x];
                patch.grid[id] = patch.grid[id] || [];
                patch.grid[id].push.apply(patch.grid[id], doc.zxy);
            });

            termsets.forEach(loadTerm);

            function loadTerm(terms, x) {
                var id;
                var termsmap = termsmaps[x];
                var name = phrases[x];
                var weights = [];
                var total = 0;

                for (var i = 0; i < terms.length; i++) {
                    id = terms[i];
                    var weight = Math.log(1 + freq[0][0]/freq[id][0]);
                    weights.push([id, weight]);
                    total += weight;

                    // Degenerate terms are indexed for all terms
                    // (not just significant ones).
                    if (degenerated[id]) continue;
                    degenerated[id] = true;
                    var degens = termops.degens(termsmap[id]);
                    var keys = Object.keys(degens);
                    for (var j = 0; j < keys.length; j++) {
                        var d = keys[j];
                        patch.degen[d] = patch.degen[d] || [];
                        patch.degen[d].push(degens[d]);
                    }
                }

                // Limit indexing to the *most* significant terms for a
                // document. Currently uses rough heuristic (floor+sqrt) to
                // determine how many of the top words to grab.
                weights.sort(function(a,b) {
                    return a[1] > b[1] ? -1 : a[1] < b[1] ? 1 : 0;
                });
                var sigterms = [];
                var limit = Math.floor(Math.sqrt(weights.length));
                for (i = 0; i < limit; i++) sigterms.push(weights[i][0]);

                // Debug significant term selection.
                if (DEBUG) {
                    var debug = termsmap;
                    var oldtext = terms.map(function(id) { return debug[id]; }).join(' ');
                    var sigtext = sigterms.map(function(id) { return debug[id]; }).join(' ');
                    if (oldtext !== sigtext)  console.log('%s => %s', oldtext, sigtext);
                }

                for (i = 0; i < sigterms.length; i++) {
                    id = sigterms[i];
                    patch.term[id] = patch.term[id] || [];
                    patch.term[id].push(name);
                }
            }
        }

        var remaining = docs.length;
        remaining++; // term
        remaining++; // phrase
        remaining++; // grid

        _(docs).each(function(doc) {
            source.putFeature(doc.id, doc.doc, function(err) {
                if (err && remaining > 0) {
                    remaining = -1;
                    return callback(err);
                }
                if (!--remaining) callback(null);
            });
        });

        _(patch).each(function(data, type) {
            var ids = Object.keys(data);
            source._geocoder.getall(source.getCarmen.bind(source), type, ids, function(err) {
                if (err && remaining > 0) {
                    remaining = -1;
                    return callback(err);
                }
                for (var i = 0; i < ids.length; i++) {
                    var id = ids[i];
                    // This merges new entries on top of old ones.
                    switch (type) {
                    case 'term':
                    case 'grid':
                    case 'degen':
                        var current = source._geocoder.get(type, id) || [];
                        current.push.apply(current, data[id]);
                        source._geocoder.set(type, id, current);
                        break;
                    case 'phrase':
                        source._geocoder.set(type, id, data[id]);
                        break;
                    }
                }
                if (!--remaining) callback(null);
            });
        });
    }
};
<|endoftext|>


<commit_before>import 'systemjs-hmr'
import io from 'socket.io-client'
import debug from 'debug'
import merge from 'deepmerge'

const d = debug('systemjs-hot-reloader')

export default (opts = {}) => {
  const options = merge({
    entries: [],
    host: `//${document.location.hostname}:5776`
  }, opts)

  const {host} = options

  const socket = io(host)

  const reloadPage = () => {
    d('whole page reload requested')
    document.location.reload(true)
  }

  const fileChanged = ({url, entries}) => {
    d('reloading', url)
    System.reload(SystemJS.baseURL + url, {entries: [...entries, ...options.entries]})
  }

  socket.on('connect', () => {
    d('connected to ', host)
    socket.emit('identification', navigator.userAgent)
  })

  socket.on('disconnect', () => {
    d('disconnected from', host)
  })

  // UNSTABLE NEW API - TIED TO systemjs-tools for the moment
  socket.on('*', (event) => {
    switch (event.type) {
      case 'hmr': {
        fileChanged(event)
        break
      }
    }
  })

  // support for old api
  {
    socket.on('reload', reloadPage)

    socket.on('change', (event) => {
      if (event.path === 'index.html') reloadPage()
      else fileChanged({url: event.path})
    })

    // emitting errors for jspm-dev-buddy
    window.onerror = (err) => {
      socket.emit('error', err)
    }
  }
}
<commit_msg>worker compatibility<commit_after>import 'systemjs-hmr'
import io from 'socket.io-client'
import debug from 'debug'
import merge from 'deepmerge'

const d = debug('systemjs-hot-reloader')

function isBrowser() {
    return typeof window !== 'undefined'
}

function isWorker() {
    return typeof WorkerGlobalScope !== 'undefined'
}

export default (opts = {}) => {
  const options = merge({
    entries: [],
    host: `//${location.hostname}:5776`
  }, opts)

  const {host} = options

  const socket = io(host)

  const reloadPage = () => {
    d('whole page reload requested')
    if (isBrowser()) {
      location.reload(true)
    }
  }

  const fileChanged = ({url, entries}) => {
    d('reloading', url)
    System.reload(SystemJS.baseURL + url, {entries: [...entries, ...options.entries]})
  }

  socket.on('connect', () => {
    d('connected to ', host)
    socket.emit('identification', navigator.userAgent)
  })

  socket.on('disconnect', () => {
    d('disconnected from', host)
  })

  // UNSTABLE NEW API - TIED TO systemjs-tools for the moment
  socket.on('*', (event) => {
    switch (event.type) {
      case 'hmr': {
        fileChanged(event)
        break
      }
    }
  })

  // support for old api
  {
    socket.on('reload', reloadPage)

    socket.on('change', (event) => {
      if (event.path === 'index.html') reloadPage()
      else fileChanged({url: event.path})
    })

    // emitting errors for jspm-dev-buddy
    if (isBrowser()) {
      window.onerror = (err) => {
        socket.emit('error', err)
      }
    } else (isWorker()) {
      self.onerror = (err) => {
        socket.emit('error', err)
      }
    }
  }
}
<|endoftext|>


<commit_before>(function(document, ionic) {
  'use strict';

  // Ionic CSS polyfills
  ionic.CSS = {};

  (function() {

    // transform
    var i, keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform',
                '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform'];

    for(i = 0; i < keys.length; i++) {
      if(document.documentElement.style[keys[i]] !== undefined) {
        ionic.CSS.TRANSFORM = keys[i];
        break;
      }
    }

    // transition
    keys = ['webkitTransition', 'mozTransition', 'transition'];
    for(i = 0; i < keys.length; i++) {
      if(document.documentElement.style[keys[i]] !== undefined) {
        ionic.CSS.TRANSITION = keys[i];
        break;
      }
    }

  })();

  // classList polyfill for them older Androids
  // https://gist.github.com/devongovett/1381839
  if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') {
    Object.defineProperty(HTMLElement.prototype, 'classList', {
      get: function() {
        var self = this;
        function update(fn) {
          return function() {
            var x, classes = self.className.split(/\s+/);

            for(x=0; x<arguments.length; x++) {
              fn(classes, classes.indexOf(arguments[x]), arguments[x]);
            }

            self.className = classes.join(" ");
          };
        }

        return {
          add: update(function(classes, index, value) {
            ~index || classes.push(value);
          }),

          remove: update(function(classes, index) {
            ~index && classes.splice(index, 1);
          }),

          toggle: update(function(classes, index, value) {
            ~index ? classes.splice(index, 1) : classes.push(value);
          }),

          contains: function(value) {
            return !!~self.className.split(/\s+/).indexOf(value);
          },

          item: function(i) {
            return self.className.split(/\s+/)[i] || null;
          }
        };

      }
    });
  }

})(document, ionic);
<commit_msg>add msTransform and msTransition to CSS polyfill<commit_after>(function(document, ionic) {
  'use strict';

  // Ionic CSS polyfills
  ionic.CSS = {};

  (function() {

    // transform
    var i, keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform',
                   '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform', 'msTransform'];

    for(i = 0; i < keys.length; i++) {
      if(document.documentElement.style[keys[i]] !== undefined) {
        ionic.CSS.TRANSFORM = keys[i];
        break;
      }
    }

    // transition
    keys = ['webkitTransition', 'mozTransition', 'msTransition', 'transition'];
    for(i = 0; i < keys.length; i++) {
      if(document.documentElement.style[keys[i]] !== undefined) {
        ionic.CSS.TRANSITION = keys[i];
        break;
      }
    }

  })();

  // classList polyfill for them older Androids
  // https://gist.github.com/devongovett/1381839
  if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') {
    Object.defineProperty(HTMLElement.prototype, 'classList', {
      get: function() {
        var self = this;
        function update(fn) {
          return function() {
            var x, classes = self.className.split(/\s+/);

            for(x=0; x<arguments.length; x++) {
              fn(classes, classes.indexOf(arguments[x]), arguments[x]);
            }

            self.className = classes.join(" ");
          };
        }

        return {
          add: update(function(classes, index, value) {
            ~index || classes.push(value);
          }),

          remove: update(function(classes, index) {
            ~index && classes.splice(index, 1);
          }),

          toggle: update(function(classes, index, value) {
            ~index ? classes.splice(index, 1) : classes.push(value);
          }),

          contains: function(value) {
            return !!~self.className.split(/\s+/).indexOf(value);
          },

          item: function(i) {
            return self.className.split(/\s+/)[i] || null;
          }
        };

      }
    });
  }

})(document, ionic);
<|endoftext|>


<commit_before>'use strict';

var api = angular.module('service.api', []);

api.factory('userService', function($http) {
    return {
        activity : function(user_id, callback){
            $http({method: 'GET', url: 'http://localhost:3000/user/' + user_id + '/activity'}).success(function(response, status, headers, config) {
                callback(response.result);
            });
        },
        books : function(user_id, callback){
            $http({method: 'GET', url: 'http://localhost:3000/user/' + user_id + '/word-lookup/books'}).success(function(response, status, headers, config) {
                callback(response.result);
            });
        },
        wordLookups : function(user_id, callback){
            $http({method: 'GET', url: 'http://localhost:3000/user/' + user_id + '/word-lookup'}).success(function(response, status, headers, config) {
                callback(response.result);
            });
        }
    }
});

api.factory('activityService', function($http) {
    return {

    }
});

api.factory('wordLookupService', function($http) {
    return {
        save: function(word, callback){
            $http({
                url: "http://localhost:3000/word-lookup/" + word.word_lookup_id,
                method: "POST",
                data: word
            }).success(function(data, status, headers, config) {
                    callback(true);
                });
        }
    }
});

api.factory('member', function($http) {
    return {
        login : function(user, callback){
            $http.post('http://localhost:3000/user/login', user).
                success(function(response) {
                    callback(true, response);
                }).error(function(response){
                    callback(false, response);
                });
        },
        register : function(user, callback){
            $http.post('http://localhost:3000/user/register', user).
                success(function(response) {
                    callback(true, response);
                }).error(function(response){
                    callback(false, response);
                });;
        }
    }
});

<commit_msg>main app - refactored api service<commit_after>'use strict';

var api = angular.module('service.api', []);

api.factory('userService', function($http, serverOptions) {
    return {
        activity : function(user_id, callback){
            $http({method: 'GET', url: serverOptions.getUrl() + '/user/' + user_id + '/activity'}).success(function(response, status, headers, config) {
                callback(response.result);
            });
        },
        books : function(user_id, callback){
            $http({method: 'GET', url: serverOptions.getUrl() + '/user/' + user_id + '/word-lookup/books'}).success(function(response, status, headers, config) {
                callback(response.result);
            });
        },
        wordLookups : function(user_id, callback){
            $http({method: 'GET', url: serverOptions.getUrl() + '/user/' + user_id + '/word-lookup'}).success(function(response, status, headers, config) {
                callback(response.result);
            });
        }
    }
});

api.factory('activityService', function($http, serverOptions) {
    return {

    }
});

api.factory('wordLookupService', function($http, serverOptions) {
    return {
        save: function(word, callback){
            $http({
                url: serverOptions.getUrl() + "/word-lookup/" + word.word_lookup_id,
                method: "POST",
                data: word
            }).success(function(data, status, headers, config) {
                    callback(true);
                });
        }
    }
});

api.factory('member', function($http, serverOptions) {
    return {
        login : function(user, callback){
            $http.post(serverOptions.getUrl() + '/user/login', user).
                success(function(response) {
                    callback(true, response);
                }).error(function(response){
                    callback(false, response);
                });
        },
        register : function(user, callback){
            $http.post(serverOptions.getUrl() + '/user/register', user).
                success(function(response) {
                    callback(true, response);
                }).error(function(response){
                    callback(false, response);
                });;
        }
    }
});

<|endoftext|>