<commit_before>var LABEL_REGEX = /^\d+-(\w+)/;
mynunjucks = new nunjucks.Environment();
mynunjucks.addFilter('removeIndex', function (str) {
  var matched = LABEL_REGEX.exec(str);
  return matched && matched.pop() || str;
});
mynunjucks.addFilter('dayFromNow', function (str) {
  return Math.floor((new Date(str) - new Date()) / (1000 * 60 * 60 * 24));
});
mynunjucks.addFilter('hasIndex', function (str) {
  return /\d+-.*/.test(str);
});
github = new Github('jcouyang','gira');

var Gira = function (username, repo, github, milestone) {
  this.username = username;
  this.repo = repo;
  this.owner = username;
  this.milestone = milestone || '';
  this.last_label = '';
  this.github = github;
  this.milestones = {};
  this.owners = {};
};

// if (!github.checkLogin()) {
//   $(".site.clearfix").html(nunjucks.render('src/templates/index.html'));
//   $('#try-gira').click(function () {
//     var userrepo = $(".marketing-section-enterprise input[name=username]").val().split('/');
//     gira = new Gira(userrepo[0], userrepo[1], github);
//     gira.render();
//   });
// }
gira = new Gira("jcouyang", "gira", github);
// github.getAccessToken().then(function () {
//   gira.render();
// }, function (error) {
//   console.log("invalid token", error);
// });

var View = Gira.View = function(){
	this.initialize.apply(this, arguments);
};

var delegateEventSplitter = /^(\S+)\s*(.*)$/;

View.extend = function(props){
	var parent = this;
	var child;
	if (props && _.has(props, 'constructor')) {
      child = props.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }
	_.extend(child, parent);
	var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
  child.prototype = new Surrogate;

	_.extend(child.prototype,props);
	child.__super__ = parent.prototype;
	return child;
};

_.extend(View.prototype, {
	el:$('body'),
	templateName:"index.html",
	templateEngine:mynunjucks,
	modelReady:{},
	initialize:function(){
		this.render();
	},
	render: function(){
		var self = this;
		this.modelReady().then(function(model){
			console.log(model);
			$(self.el).html(self.templateEngine.render(self.templateName,model));
			self.delegateEvents();
		}).catch(function(error){
			console.log(error);
			$(self.el).html(self.templateEngine.render(self.templateName));
		});

	},
	delegateEvents:function(){
		var self = this;
		var events = _.result(this, 'events');
		if (!events) return this;
		_.each(_(events).keys(),function(key){
			var match = key.match(delegateEventSplitter);
			var eventName = match[1], selector = match[2];
			if (selector=='')
				$(self.el).on(eventName, _.bind(self[events[key]],self));
			else
				$(self.el).find(selector).on(eventName, _.bind(self[events[key]],self));
		});
	}
});

var HeaderView = View.extend({
	el:"#header",
	templateName:"src/templates/header.html",
	modelReady: function(){
		return github.getUser();
	},
	events: {
		"click .octicon.octicon-log-out": "logout"
	},
	logout: function(){
		github.logout();
	}
});

var KanbanView = View.extend({
	el:"#contributions-calendar",
	templateName:"src/templates/gira.html",
	modelReady: function(){
    var that = this;
    return Q.all([github.getIssues(this.milestone), github.getLabels()]).then(function (data) {
      var issues = data[0];
      var labels = _(data[1]).filter(function (label) {
        return LABEL_REGEX.test(label.name);
      });
      var groupIssue = _(issues).groupBy(function (issue) {
        var column = _(issue.labels).find(function (label) {
          return LABEL_REGEX.test(label.name);
        });
        if (column) {
          return column.name;
        }
        return "0-Backlog";
      });
      issues = _.chain(labels.concat({name: "0-Backlog"}))
        .sortBy(function (label) {
          return label.name;
        })
        .uniq(true, function (label) {
          return label.name;
        })
        .tap(function (label) {
          that.last_label = label[label.length - 1].name;
        })
        .map(function (label) {
          return [label.name, groupIssue[label.name]];
        }).value();
			return {issuesWithLabel: issues, last_label: that.last_label};
    }).catch(function (error) {
      // that.renderError(JSON.parse(error.responseText).message);
    });
	},
	events:{
		"click a[rel=facebox]": "renderFaceBox",
		"click .close.close-issue":"closeIssue"
	},
	renderFaceBox: function(){
		console.log("render popup");
	},
	closeIssue: function(e){
		var $close = $(e.target);
    github.getIssues(this.milestone, $close.data('issue'))
      .then(function (issue) {
        issue.state = 'close';
        issue.assignee = issue.assignee && issue.assignee.login;
        issue.milestone = issue.milestone && issue.milestone.number;

        github.newIssue(issue, issue.number)
          .then(function () {
            $('#' + $close.data('issue')).remove();
          });
      });
	},
	  draggablify: function () {
    var that = this;
    var $issues = $('#contributions-calendar .contrib-details.grid .col .lbl div[draggable=true]');
    $issues.on('dragstart', function (e) {
      e.originalEvent.dataTransfer.effectAllowed = 'move';
      e.originalEvent.dataTransfer.setData('text/plain', this.id);
    });
    $(".col").on('dragover',function (e) {
      if (e.preventDefault) e.preventDefault(); // allows us to drop
      $(this).removeClass("over").addClass('over');
      e.originalEvent.dataTransfer.dropEffect = 'move';
      return false;
    }).on('drop', function (e) {
      if (e.stopPropagation) e.stopPropagation();
      var column = this;
      var $issue = $('#' + e.originalEvent.dataTransfer.getData('text/plain'));
      that.github.deleteLabel($issue.attr('id'), $issue.data('label'))
        .then(function (labels) {
          that.github.addLabel($issue.attr('id'), _(labels).pluck('name').concat(column.id));
        });
      $(this).removeClass("over")
        .find('span.lbl')
        .append($($issue));
      return false;
    });
  }
});

var RepoSelectorView = View.extend({
	repo:'gira',
	owner:'jcouyang',
	el: ".pagehead.repohead h1",
	templateName:"src/templates/repo-selector.html",
  changeOwner: function (event) {
    this.owner = $(event.target).attr('name');
    this.render();
  },
  changeRepo: function (event) {
    this.repo = $(event.target).attr('name');
    // this.renderKanban();
  },
	events:{
		"change .select-menu.owner-select-menu input[type=radio]":"changeOwner",
		"change .target-repo-menu.select-menu input[type=radio]":"changeRepo"
	},
	modelReady:function(){
		var self = this;
		return github.getRepos().then(function (repos) {
      var groupedRepo = _(repos).groupBy(function (repo) {
        return repo.owner.login;
      });
      self.repo = self.repo || groupedRepo[self.owner][0].name;
      return {checked: self.owner, checkedRepo: self.repo, owners: _(groupedRepo).map(function (repos) {
        return repos[0].owner;
      }), repos: groupedRepo[self.owner]};
    });
	}
});

var MilestoneView = View.extend({
	milestone:"1.0.0",
	el:".pagehead.repohead div.sidebar-milestone-widget",
	templateName: "src/templates/milestones.html",
	events:{
		"click .sidebar-milestone-widget .select-menu a.select-menu-item":
	},
	changeMilestone:function (e) {
    e.preventDefault();
    this.milestone = $(this).data('milestone');
    this.render();
    return false;
  },
	modelReady:function(){
		var self = this;
		return github.getMilestones().then(function (milestones) {
			return {
          selected: self.milestone && _(milestones).find(function (milestone) {
            return milestone.number === self.milestone;
          }),
          milestones: milestones
        };
    });
	}
});

var EditIssueView = View.extend({
	edit:true,
	el:".facebox-content",
	templateName:"src/templates/edit-issue.html",
	events:{
		"submit form":"createIssue",
		"click #jk-preview":"preview",
		"click .sidebar .color-label":"addLabels",
	},
	addLabels: function(e){
      e.preventDefault();
      $(e.target).toggleClass('selected');
	},
	preview: function () {
    var data = {text: $('#issue_body').val()};
    that.github.markdown(data).then(function (result) {
      $('.comment-body.markdown-body.js-comment-body p').html(result);
    });
  },
	modelReady:function(){
		var tasks = [this.edit&&github.getIssues(null,$(this).data("issue-id")), github.getAssignees(), github.getMilestones(),this.edit&&github.getLabels()];
		return Q.all(tasks).then(function(data) {
      console.log(data);
      var context = data[0];
      context.assignees = data[1];
      context.milestones = data[2];
      context.all_labels = data[3];
			context.comments = data[4];
			return context;
    });
	},
	createIssue: function() {
    var that = this;
    var form = $('form:visible');
    github.newIssue({
      title: form.find("input[name='issue[title]']").val(),
      body: form.find("textarea[name='issue[body]']").val(),
      assignee: form.find(".assignee input[type=radio]:checked").val(),
      milestone: form.find(".milestone input[type=radio]:checked").val(),
      labels: form.find("a.selected input").get().map(function (input) {
        return input.value;
      })
    }, form.data('issue-id')).then(function () {
      that.render();
      $(".facebox-close").click();
    });
    return false;
  }
});

$(function(){
	var header = new HeaderView;
	var kanban = new KanbanView;
	var reposelector = new RepoSelectorView;
	var milestone = new MilestoneView;

});

// Gira.prototype = {
// 	renderError: function(message) {
// 		$('.notification').html(nunjucks.render("src/templates/error.html",{message:message}));
// 		window.setTimeout(function(){
// 			$('.notification .close.js-flash-close').click();
// 		}, 2000);

// 	},

function createLabel() {
    var that = this;
    return function () {
      var form = $('form:visible');
      that.github.createLabel(that.owner, that.repo, {
        color: form.find('input[name=color]').val().replace('#', ''),
        name: (parseInt(/^(\d+)-\w+/.exec(that.last_label).pop()) + 1) + '-' + form.find('input[name=label]').val()
      }).then(function () {
        that.render();
        $(".facebox-close").click();
      });
      return false;
    };
  }
//   bindUploadImageEvent: function() {
// 		var that = this;
//     $('input[type=file]').on("change", function(){
// 			var file = this.files[0];
// 			var data = {};
// 			data.path="images/" + file.name.replace(' ','-');
// 			data.message = "upload" + file.name;
// 			var reader  = new FileReader();
// 			reader.onloadend = function () {
// 				data.content = reader.result;
// 				data.branch = "gira-images";
// 				data.content = data.content.slice(data.content.indexOf(',')+1);
// 				that.github.getRefSha(that.owner,that.repo).then(function(refs){
// 					var _refs = _(refs);
// 					if(_refs.find(function(ref){return ref.ref==="refs/heads/gira-images";})){
// 						return that.github.uploadImage(that.owner,that.repo,data);
// 					}
// 					else{
// 						return that.github.createBranch(that.owner,that.repo,"refs/heads/gira-images", _refs.first().object.sha).then(function(){
// 							that.github.uploadImage(that.owner,that.repo,data);
// 						});
// 					}
// 				})
// 					.then(function(resp){
// 					var selectionStart = $('#issue_body')[0].selectionStart;
// 					var selectionEnd = $('#issue_body')[0].selectionEnd;

// 					$('#issue_body').val($('#issue_body').val() + '![]('+ resp.content.html_url + '?raw=true)');

// 					$('#issue_body')[0].selectionStart = selectionStart;
// 					$('#issue_body')[0].selectionEnd = selectionEnd;
// 					},function(error){
// 						console.log("exist",error);
// 					});
// 			};

// 			if (file) {
// 				reader.readAsDataURL(file);
// 			} else {
// 				data.content = "";
// 			}
// 		});
//   },
//   closeButton: function () {
//     var that = this;
//     $('.remove-lane').on('click', function (event) {
//       event.preventDefault();
//       var label = $(this).attr('data');
//       that.github.deleteLane(that.owner, that.repo, label);
//       that.render();
//     });
//   },
//   render: function () {
//     var that = this;
//     that.renderHeader();
//     return that.renderRepoSelector()
//       .then(that.renderMilestone.bind(that))
//       .then(that.renderKanban.bind(that))
//       .then(that.closeButton.bind(that))
//       .catch(function (error) {
//         console.log(error);
//       });
//   }
// };

<commit_msg>almost created all Views, what next? :turtle: Model<commit_after>var LABEL_REGEX = /^\d+-(\w+)/;
mynunjucks = new nunjucks.Environment();
mynunjucks.addFilter('removeIndex', function (str) {
  var matched = LABEL_REGEX.exec(str);
  return matched && matched.pop() || str;
});
mynunjucks.addFilter('dayFromNow', function (str) {
  return Math.floor((new Date(str) - new Date()) / (1000 * 60 * 60 * 24));
});
mynunjucks.addFilter('hasIndex', function (str) {
  return /\d+-.*/.test(str);
});
github = new Github('jcouyang','gira');

var Gira = function (username, repo, github, milestone) {
  this.username = username;
  this.repo = repo;
  this.owner = username;
  this.milestone = milestone || '';
  this.last_label = '';
  this.github = github;
  this.milestones = {};
  this.owners = {};
};

// if (!github.checkLogin()) {
//   $(".site.clearfix").html(nunjucks.render('src/templates/index.html'));
//   $('#try-gira').click(function () {
//     var userrepo = $(".marketing-section-enterprise input[name=username]").val().split('/');
//     gira = new Gira(userrepo[0], userrepo[1], github);
//     gira.render();
//   });
// }
gira = new Gira("jcouyang", "gira", github);
// github.getAccessToken().then(function () {
//   gira.render();
// }, function (error) {
//   console.log("invalid token", error);
// });

var View = Gira.View = function(){
	this.initialize.apply(this, arguments);
};

var delegateEventSplitter = /^(\S+)\s*(.*)$/;

View.extend = function(props){
	var parent = this;
	var child;
	if (props && _.has(props, 'constructor')) {
      child = props.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }
	_.extend(child, parent);
	var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
  child.prototype = new Surrogate;

	_.extend(child.prototype,props);
	child.__super__ = parent.prototype;
	return child;
};

_.extend(View.prototype, {
	el:$('body'),
	templateName:"index.html",
	templateEngine:mynunjucks,
	modelReady:{},
	initialize:function(){
		this.render();
	},
	render: function(){
		var self = this;
		this.modelReady().then(function(model){
			console.log(model);
			$(self.el).html(self.templateEngine.render(self.templateName,model));
			self.delegateEvents();
		}).catch(function(error){
			console.log(error);
			$(self.el).html(self.templateEngine.render(self.templateName));
		});

	},
	delegateEvents:function(){
		var self = this;
		var events = _.result(this, 'events');
		if (!events) return this;
		_.each(_(events).keys(),function(key){
			var match = key.match(delegateEventSplitter);
			var eventName = match[1], selector = match[2];
			if (selector=='')
				$(self.el).on(eventName, _.bind(self[events[key]],self));
			else
				$(self.el).find(selector).on(eventName, _.bind(self[events[key]],self));
		});
	}
});

var HeaderView = View.extend({
	el:"#header",
	templateName:"src/templates/header.html",
	modelReady: function(){
		return github.getUser();
	},
	events: {
		"click .octicon.octicon-log-out": "logout"
	},
	logout: function(){
		github.logout();
	}
});

var KanbanView = View.extend({
	el:"#contributions-calendar",
	templateName:"src/templates/gira.html",
	modelReady: function(){
    var that = this;
    return Q.all([github.getIssues(this.milestone), github.getLabels()]).then(function (data) {
      var issues = data[0];
      var labels = _(data[1]).filter(function (label) {
        return LABEL_REGEX.test(label.name);
      });
      var groupIssue = _(issues).groupBy(function (issue) {
        var column = _(issue.labels).find(function (label) {
          return LABEL_REGEX.test(label.name);
        });
        if (column) {
          return column.name;
        }
        return "0-Backlog";
      });
      issues = _.chain(labels.concat({name: "0-Backlog"}))
        .sortBy(function (label) {
          return label.name;
        })
        .uniq(true, function (label) {
          return label.name;
        })
        .tap(function (label) {
          that.last_label = label[label.length - 1].name;
        })
        .map(function (label) {
          return [label.name, groupIssue[label.name]];
        }).value();
			return {issuesWithLabel: issues, last_label: that.last_label};
    }).catch(function (error) {
      // that.renderError(JSON.parse(error.responseText).message);
    });
	},
	events:{
		"click a[rel=facebox]": "renderFaceBox",
		"click .close.close-issue":"closeIssue"
	},
	renderFaceBox: function(){
		console.log("render popup");
	},
	closeIssue: function(e){
		var $close = $(e.target);
    github.getIssues(this.milestone, $close.data('issue'))
      .then(function (issue) {
        issue.state = 'close';
        issue.assignee = issue.assignee && issue.assignee.login;
        issue.milestone = issue.milestone && issue.milestone.number;

        github.newIssue(issue, issue.number)
          .then(function () {
            $('#' + $close.data('issue')).remove();
          });
      });
	},
	  draggablify: function () {
    var that = this;
    var $issues = $('#contributions-calendar .contrib-details.grid .col .lbl div[draggable=true]');
    $issues.on('dragstart', function (e) {
      e.originalEvent.dataTransfer.effectAllowed = 'move';
      e.originalEvent.dataTransfer.setData('text/plain', this.id);
    });
    $(".col").on('dragover',function (e) {
      if (e.preventDefault) e.preventDefault(); // allows us to drop
      $(this).removeClass("over").addClass('over');
      e.originalEvent.dataTransfer.dropEffect = 'move';
      return false;
    }).on('drop', function (e) {
      if (e.stopPropagation) e.stopPropagation();
      var column = this;
      var $issue = $('#' + e.originalEvent.dataTransfer.getData('text/plain'));
      that.github.deleteLabel($issue.attr('id'), $issue.data('label'))
        .then(function (labels) {
          that.github.addLabel($issue.attr('id'), _(labels).pluck('name').concat(column.id));
        });
      $(this).removeClass("over")
        .find('span.lbl')
        .append($($issue));
      return false;
    });
  }
});

var RepoSelectorView = View.extend({
	repo:'gira',
	owner:'jcouyang',
	el: ".pagehead.repohead h1",
	templateName:"src/templates/repo-selector.html",
  changeOwner: function (event) {
    this.owner = $(event.target).attr('name');
    this.render();
  },
  changeRepo: function (event) {
    this.repo = $(event.target).attr('name');
    // this.renderKanban();
  },
	events:{
		"change .select-menu.owner-select-menu input[type=radio]":"changeOwner",
		"change .target-repo-menu.select-menu input[type=radio]":"changeRepo"
	},
	modelReady:function(){
		var self = this;
		return github.getRepos().then(function (repos) {
      var groupedRepo = _(repos).groupBy(function (repo) {
        return repo.owner.login;
      });
      self.repo = self.repo || groupedRepo[self.owner][0].name;
      return {checked: self.owner, checkedRepo: self.repo, owners: _(groupedRepo).map(function (repos) {
        return repos[0].owner;
      }), repos: groupedRepo[self.owner]};
    });
	}
});

var MilestoneView = View.extend({
	milestone:"1.0.0",
	el:".pagehead.repohead div.sidebar-milestone-widget",
	templateName: "src/templates/milestones.html",
	events:{
		"click .sidebar-milestone-widget .select-menu a.select-menu-item":
	},
	changeMilestone:function (e) {
    e.preventDefault();
    this.milestone = $(this).data('milestone');
    this.render();
    return false;
  },
	modelReady:function(){
		var self = this;
		return github.getMilestones().then(function (milestones) {
			return {
          selected: self.milestone && _(milestones).find(function (milestone) {
            return milestone.number === self.milestone;
          }),
          milestones: milestones
        };
    });
	}
});

var EditIssueView = View.extend({
	edit:true,
	el:".facebox-content",
	templateName:"src/templates/edit-issue.html",
	events:{
		"submit form":"createIssue",
		"click #jk-preview":"preview",
		"click .sidebar .color-label":"addLabels",
		"change input[type=file]": "uploadImage"
	},
	uploadImage:function(){
		var file = e.target.files[0];
		var data = {};
		data.path="images/" + file.name.replace(' ','-');
		data.message = "upload" + file.name;
		var reader  = new FileReader();
		reader.onloadend = function () {
			data.content = reader.result;
			data.branch = "gira-images";
			data.content = data.content.slice(data.content.indexOf(',')+1);
			github.getRefSha().then(function(refs){
				var _refs = _(refs);
				if(_refs.find(function(ref){return ref.ref==="refs/heads/gira-images";})){
					return github.uploadImage(data);
				}
				else{
					return github.createBranch("refs/heads/gira-images", _refs.first().object.sha).then(function(){
						github.uploadImage(data);
					});
				}
			})
				.then(function(resp){
					var selectionStart = $('#issue_body')[0].selectionStart;
					var selectionEnd = $('#issue_body')[0].selectionEnd;

					$('#issue_body').val($('#issue_body').val() + '![]('+ resp.content.html_url + '?raw=true)');

					$('#issue_body')[0].selectionStart = selectionStart;
					$('#issue_body')[0].selectionEnd = selectionEnd;
				},function(error){
					console.log("exist",error);
				});
		};

		if (file) {
			reader.readAsDataURL(file);
		} else {
			data.content = "";
		}
	},
	addLabels: function(e){
      e.preventDefault();
      $(e.target).toggleClass('selected');
	},
	preview: function () {
    var data = {text: $('#issue_body').val()};
    github.markdown(data).then(function (result) {
      $('.comment-body.markdown-body.js-comment-body p').html(result);
    });
  },
	modelReady:function(){
		var tasks = [this.edit&&github.getIssues(null,$(this).data("issue-id")), github.getAssignees(), github.getMilestones(),this.edit&&github.getLabels()];
		return Q.all(tasks).then(function(data) {
      console.log(data);
      var context = data[0];
      context.assignees = data[1];
      context.milestones = data[2];
      context.all_labels = data[3];
			context.comments = data[4];
			return context;
    });
	},
	createIssue: function() {
    var that = this;
    var form = $('form:visible');
    github.newIssue({
      title: form.find("input[name='issue[title]']").val(),
      body: form.find("textarea[name='issue[body]']").val(),
      assignee: form.find(".assignee input[type=radio]:checked").val(),
      milestone: form.find(".milestone input[type=radio]:checked").val(),
      labels: form.find("a.selected input").get().map(function (input) {
        return input.value;
      })
    }, form.data('issue-id')).then(function () {
      that.render();
      $(".facebox-close").click();
    });
    return false;
  }
});

$(function(){
	var header = new HeaderView;
	var kanban = new KanbanView;
	var reposelector = new RepoSelectorView;
	var milestone = new MilestoneView;

});

// Gira.prototype = {
// 	renderError: function(message) {
// 		$('.notification').html(nunjucks.render("src/templates/error.html",{message:message}));
// 		window.setTimeout(function(){
// 			$('.notification .close.js-flash-close').click();
// 		}, 2000);

// 	},

function createLabel() {
    var that = this;
    return function () {
      var form = $('form:visible');
      github.createLabel( {
        color: form.find('input[name=color]').val().replace('#', ''),
        name: (parseInt(/^(\d+)-\w+/.exec(that.last_label).pop()) + 1) + '-' + form.find('input[name=label]').val()
      }).then(function () {
        // that.render();
        $(".facebox-close").click();
      });
      return false;
    };
  }

<|endoftext|>


<commit_before>var http = require('http');
var querystring = require('querystring');

var Q = require("q"),
    _ = require("lodash");

var Gremlin = require('./gremlin');
var Graph = require("./graph");
var classes = require("./classes");

var ResultFormatter = require("./resultformatter");
var ArgumentHandler = require("./arguments/argumenthandler");

var defaultOptions = {
  'host': 'localhost',
  'port': 8182,
  'graph': 'tinkergraph',
  'idRegex': false // OrientDB id regex -> /^[0-9]+:[0-9]+$/
};

module.exports = (function(){
  function Grex(options) {
    this.options = _.defaults(options, defaultOptions);

    this.resultFormatter = new ResultFormatter();
    this.argumentHandler = new ArgumentHandler(this.options);

    _.extend(this, classes);
    this.ClassTypes = classes;
  }

  Grex.prototype.connect = function(options, callback) {
    if(typeof options === 'function'){
      callback = options;
      options = undefined;
    } else if (typeof options === 'object') {
      this.options = _.defaults(options, this.options);
    } else {
      // Set options to previously setup options or switch back to the defaults
      this.options = this.options || defaultOptions;
    }

    return Q.fcall(function() {
      return this;
    }.bind(this))
    .nodeify(callback);
  };

  /**
   * Send a Gremlin script for execution on the server, fetch and format
   * results.
   *
   * @param {String} script A raw Gremlin (Groovy) script to execute
   */
  Grex.prototype.exec = function(script) {
    var deferred = Q.defer();

    var qs = {
      script: script,
      'rexster.showTypes': true
    };

    var options = {
      hostname: this.options.host,
      port: this.options.port,
      path: '/graphs/' + this.options.graph + '/tp/gremlin?' + querystring.stringify(qs),
      headers: {
        'Content-type': 'application/json'
      }
    };

    var req = http.get(options, function(res) {
      var body = '';

      res.on('data', function(chunk) {
        body += chunk;
      });

      res.on('end', function() {
        body = JSON.parse(body);
        var transformedResults = this.transformResults(body.results);
        body.results = transformedResults.results;
        body.typeMap = transformedResults.typeMap;
        return deferred.resolve(body);
      }.bind(this));

    }.bind(this));

    req.on('error', function() {
      return deferred.reject(e);
    });

    return deferred.promise;
  };

  Grex.prototype.gremlin = function(options) {
    var gremlin = new Gremlin(this, options);

    return gremlin;
  };

  Grex.prototype.transformResults = function(results) {
    return this.resultFormatter.formatResults(results);
  };

  return Grex;
})();
<commit_msg>Escape $ characters<commit_after>var http = require('http');
var querystring = require('querystring');

var Q = require("q"),
    _ = require("lodash");

var Gremlin = require('./gremlin');
var Graph = require("./graph");
var classes = require("./classes");

var ResultFormatter = require("./resultformatter");
var ArgumentHandler = require("./arguments/argumenthandler");

var defaultOptions = {
  'host': 'localhost',
  'port': 8182,
  'graph': 'tinkergraph',
  'idRegex': false // OrientDB id regex -> /^[0-9]+:[0-9]+$/
};

module.exports = (function(){
  function Grex(options) {
    this.options = _.defaults(options, defaultOptions);

    this.resultFormatter = new ResultFormatter();
    this.argumentHandler = new ArgumentHandler(this.options);

    _.extend(this, classes);
    this.ClassTypes = classes;
  }

  Grex.prototype.connect = function(options, callback) {
    if(typeof options === 'function'){
      callback = options;
      options = undefined;
    } else if (typeof options === 'object') {
      this.options = _.defaults(options, this.options);
    } else {
      // Set options to previously setup options or switch back to the defaults
      this.options = this.options || defaultOptions;
    }

    return Q.fcall(function() {
      return this;
    }.bind(this))
    .nodeify(callback);
  };

  /**
   * Send a Gremlin script for execution on the server, fetch and format
   * results.
   *
   * @param {String} script A raw Gremlin (Groovy) script to execute
   */
  Grex.prototype.exec = function(script) {
    var deferred = Q.defer();

    var qs = {
      script: script.replace(/\$/g, "\\$"),
      'rexster.showTypes': true
    };

    var options = {
      hostname: this.options.host,
      port: this.options.port,
      path: '/graphs/' + this.options.graph + '/tp/gremlin?' + querystring.stringify(qs),
      headers: {
        'Content-type': 'application/json'
      }
    };

    var req = http.get(options, function(res) {
      var body = '';

      res.on('data', function(chunk) {
        body += chunk;
      });

      res.on('end', function() {
        body = JSON.parse(body);
        var transformedResults = this.transformResults(body.results);
        body.results = transformedResults.results;
        body.typeMap = transformedResults.typeMap;
        return deferred.resolve(body);
      }.bind(this));

    }.bind(this));

    req.on('error', function() {
      return deferred.reject(e);
    });

    return deferred.promise;
  };

  Grex.prototype.gremlin = function(options) {
    var gremlin = new Gremlin(this, options);

    return gremlin;
  };

  Grex.prototype.transformResults = function(results) {
    return this.resultFormatter.formatResults(results);
  };

  return Grex;
})();
<|endoftext|>


<commit_before>/*
Created On: 09/24/2006
Created By: Nicholas Schlueter -- http://www.simpltry.com
version: .5

This is freely available for noncommercial and commerical use.	I am not responsible for support and
if this script causes harm directly or indirectly I am not liable for any damages.	Using any part of this
Code means you agree to the aformentioned conditions.  Please alter this code however you see fit. I do
ask that you leave every from this point up in tact.

Dependencies:
	Prototype: 1.5.0_rc0+
	script.aculo.us
	    -builder
	simpltry
	    -tooltip
*/

if(!Simpltry) var Simpltry = {};
Simpltry.DataGrid = Class.create();

Simpltry.DataGrid.css = {
    dataGrid: "simpltryDataGrid",
    headerRow: "simpltryDataGridHeaderRow",
    dataRow: "simpltryDataGridDataRow",
    oddRow: "simpltryDataGridOddRow",
    evenRow: "simpltryDataGridEvenRow",
    sorted: "simpltryDataGridSorted",
    sortedReverse: "simpltryDataGridSortedReverse",
    headerControl: "simpltryDataGridHeaderControl"
}

Simpltry.DataGrid.prototype = {
	initialize: function(container, data) {
		this.container = $(container);
		this.data = data || {};
		this.removedColumns = {};
		this.numberColumn = {};
		this.resetDefaults();
		this.footerData = {};
		if(this.data.rows.length > 0) {
        	this.sum = {};
        	this.average = {};
        	var numCols = this.data.rows[0].length - 1;
        	$R(0, numCols, false).each(function(i) {
        	    this.numberColumn[i] = true;
        	    this.footerData[i] = null;
        	}.bind(this));
        	this.data.rows.each(function(row) {
        	    $R(0, numCols, false).each(function(i) {
            	    if(this.numberColumn[i] && isNaN(parseFloat(row[i]))) {
            	        this.numberColumn[i] = false;
            	    }
        	    }.bind(this));
        	}.bind(this));
			this.render();
		}
	},

	resetDefaults: function(){
    	this.sortedBy = null;
    	this.sortedReverse = false;
    	this.groupedBy = null;
	},

	buildThead: function(headers){
	    var thead = Builder.node('thead');
	    var tr = Builder.node('tr', {className: Simpltry.DataGrid.css.headerRow});
	    headers.each(function(header, i) {
	        if(!this.removedColumns[i]) {
    	        var th = Builder.node("th", {}, [header]);
    	        if(this.sortedBy == i) {
    	            if(this.sortedReverse) {
    	                th.addClassName(Simpltry.DataGrid.css.sortedReverse);
    	            } else {
    	                th.addClassName(Simpltry.DataGrid.css.sorted);
    	            }
    	        }
    	        th.onclick = this.sort.bind(this,i, (this.sortedBy == i && !this.sortedReverse));
    	        tr.appendChild(th);
	        }
	    }.bind(this));
	    thead.appendChild(tr);
	    return thead;
	},

	buildTbody: function(rows) {
	    var tbody = Builder.node('tbody');
	    rows.each(function(row,i) {
	        var tr = Builder.node('tr', {className: Simpltry.DataGrid.css.dataRow + " " + (i%2 != 0 ? Simpltry.DataGrid.css.evenRow : Simpltry.DataGrid.css.oddRow)});
	        row.each(function(cell, k) {
	            if(!this.removedColumns[k]) {
    	            var td = Builder.node('td', {}, [cell]);
    	            tr.appendChild(td);
    	        }
	        }.bind(this));
	        if(this.groupedBy != null && rows.length > i + 1 && rows[i][this.groupedBy] != rows[i+1][this.groupedBy]) {
	            $A(tr.getElementsByTagName('TD')).each(function(td) {
	                td.style.paddingBottom = "13px";
                });
	        }
	        tbody.appendChild(tr);
		}.bind(this));
		return tbody;
	},

	buildTfoot: function(footerData){
	    var renderFooter = false;
	    var tfoot = Builder.node('tfoot');
	    var tr = Builder.node('tr');
	    tfoot.appendChild(tr);
    	var numCols = this.data.rows[0].length - 1;
	    $R(0, numCols, false).each(function(i) {
            if(!this.removedColumns[i]) {
    	        var td = Builder.node('td', {}, [footerData[i] || ""]);
    	        if(footerData[i]) renderFooter = true;
    	        tr.appendChild(td)
	        }
        }.bind(this));
        if(renderFooter) {
            return tfoot;
        } else {
            return false;
        }
	},

	sortData: function(column){
	    this.data.rows = this.data.rows.sortBy(function(v){
		    if(this.numberColumn[column]) {
		        return parseFloat(v[column]);
		    } else {
		        return v[column].toLowerCase();
		    }
		}.bind(this));
	},

	sort: function(column, reverse) {
	    this.resetDefaults();

		this.sortData(column);

		if(reverse) {
		    this.data.rows = this.data.rows.reverse();
		}

		this.sortedBy = column;
		this.sortedReverse = reverse;

		this.render();
	},

	group: function(column){
	    this.resetDefaults();
	    this.headerControl[column].close();
		this.sortData(column);

		this.groupedBy = column;

		this.render();
	},

	remove: function(column){
	    this.removedColumns[column] = true;
	    this.headerControl[column].close();
	    this.render();
	},

	sumColumn: function(column){
	   var sum = 0;
	   this.data.rows.collect(function(row) {return row[column]}).each(function(cell) {sum += parseFloat(cell)});
	   this.footerData[column] = "sum: " + sum;
	   this.render();
	},

	averageColumn: function(column){
	   var sum = 0;
	   this.data.rows.collect(function(row) {return row[column]}).each(function(cell) {sum += parseFloat(cell)});
	   this.footerData[column] = "average: " + Math.round((sum / this.data.rows.length) * 100)/100;
	   this.render();
	},

    addHeaderControls: function(){
        this.headerControl = {};
        var displayedCols = [];
        var numCols = this.data.rows[0].length - 1;
        $R(0, numCols, false).each(function(i) {
            if(!this.removedColumns[i]) {
                displayedCols.push(i);
            }
        }.bind(this));
        $$("#" + this.container.id + " ." + Simpltry.DataGrid.css.headerRow + " th").each(function(header, i) {
            if(header.id == null || header.id == "") header.id = this.container.id + "_header" + i;
            var headerControl = Builder.node("div", {className: Simpltry.DataGrid.css.headerControl, style: "display:none"});
            headerControl.id = header.id + "_tooltip";
            var ul = Builder.node("ul");
            var groupLi = Builder.node("li", {}, ['group by']);
            groupLi.onclick = this.group.bind(this, displayedCols[i]);
            ul.appendChild(groupLi);
            var removeLi = Builder.node("li", {}, ['remove']);
            removeLi.onclick = this.remove.bind(this, displayedCols[i]);
            headerControl.appendChild(ul);
            if(this.numberColumn[displayedCols[i]]) {
                var sumLi = Builder.node("li", {}, ['sum']);
                sumLi.onclick = this.sumColumn.bind(this, displayedCols[i]);
                ul.appendChild(sumLi);
                var averageLi = Builder.node("li", {}, ['average']);
                averageLi.onclick = this.averageColumn.bind(this, displayedCols[i]);
                ul.appendChild(averageLi);
            }
            ul.appendChild(removeLi);
            document.body.appendChild(headerControl);
            this.headerControl[displayedCols[i]] = new Simpltry.PopupTooltip(header);
        }.bind(this));
    },

    removeHeaderControls: function(){
        $$("#" + this.container.id + " ." + Simpltry.DataGrid.css.headerRow + " th").each(function(header, i) {
            var popup = $(header.id + "_tooltip");
            if(popup) {
                popup.remove();
            }
        });
    },

	render: function() {
	    this.removeHeaderControls();
		this.container.innerHTML = '';
		var table = Builder.node('table', {className:Simpltry.DataGrid.css.dataGrid});
		table.appendChild(this.buildThead(this.data.headers));
		table.appendChild(this.buildTbody(this.data.rows));
		var footer = this.buildTfoot(this.footerData);
		if(footer) {
		    table.appendChild(footer);
		}
		this.container.appendChild(table);
		this.addHeaderControls();
	},

};
<commit_msg>fixed bug in safari<commit_after>/*
Created On: 09/24/2006
Created By: Nicholas Schlueter -- http://www.simpltry.com
version: .5

This is freely available for noncommercial and commerical use.	I am not responsible for support and
if this script causes harm directly or indirectly I am not liable for any damages.	Using any part of this
Code means you agree to the aformentioned conditions.  Please alter this code however you see fit. I do
ask that you leave every from this point up in tact.

Dependencies:
	Prototype: 1.5.0_rc0+
	script.aculo.us
	    -builder
	simpltry
	    -tooltip
*/

if(!Simpltry) var Simpltry = {};
Simpltry.DataGrid = Class.create();

Simpltry.DataGrid.css = {
    dataGrid: "simpltryDataGrid",
    headerRow: "simpltryDataGridHeaderRow",
    dataRow: "simpltryDataGridDataRow",
    oddRow: "simpltryDataGridOddRow",
    evenRow: "simpltryDataGridEvenRow",
    sorted: "simpltryDataGridSorted",
    sortedReverse: "simpltryDataGridSortedReverse",
    headerControl: "simpltryDataGridHeaderControl"
}

Simpltry.DataGrid.prototype = {
	initialize: function(container, data) {
		this.container = $(container);
		this.data = data || {};
		this.removedColumns = {};
		this.numberColumn = {};
		this.resetDefaults();
		this.footerData = {};
		if(this.data.rows.length > 0) {
        	this.sum = {};
        	this.average = {};
        	var numCols = this.data.rows[0].length - 1;
        	$R(0, numCols, false).each(function(i) {
        	    this.numberColumn[i] = true;
        	    this.footerData[i] = null;
        	}.bind(this));
        	this.data.rows.each(function(row) {
        	    $R(0, numCols, false).each(function(i) {
            	    if(this.numberColumn[i] && isNaN(parseFloat(row[i]))) {
            	        this.numberColumn[i] = false;
            	    }
        	    }.bind(this));
        	}.bind(this));
			this.render();
		}
	},

	resetDefaults: function(){
    	this.sortedBy = null;
    	this.sortedReverse = false;
    	this.groupedBy = null;
	},

	buildThead: function(headers){
	    var thead = Builder.node('thead');
	    var tr = Builder.node('tr', {className: Simpltry.DataGrid.css.headerRow});
	    headers.each(function(header, i) {
	        if(!this.removedColumns[i]) {
    	        var th = Builder.node("th", {}, [header]);
    	        if(this.sortedBy == i) {
    	            if(this.sortedReverse) {
    	                th.addClassName(Simpltry.DataGrid.css.sortedReverse);
    	            } else {
    	                th.addClassName(Simpltry.DataGrid.css.sorted);
    	            }
    	        }
    	        th.onclick = this.sort.bind(this,i, (this.sortedBy == i && !this.sortedReverse));
    	        tr.appendChild(th);
	        }
	    }.bind(this));
	    thead.appendChild(tr);
	    return thead;
	},

	buildTbody: function(rows) {
	    var tbody = Builder.node('tbody');
	    rows.each(function(row,i) {
	        var tr = Builder.node('tr', {className: Simpltry.DataGrid.css.dataRow + " " + (i%2 != 0 ? Simpltry.DataGrid.css.evenRow : Simpltry.DataGrid.css.oddRow)});
	        row.each(function(cell, k) {
	            if(!this.removedColumns[k]) {
    	            var td = Builder.node('td', {}, [cell]);
    	            tr.appendChild(td);
    	        }
	        }.bind(this));
	        if(this.groupedBy != null && rows.length > i + 1 && rows[i][this.groupedBy] != rows[i+1][this.groupedBy]) {
	            $A(tr.getElementsByTagName('TD')).each(function(td) {
	                td.style.paddingBottom = "13px";
                });
	        }
	        tbody.appendChild(tr);
		}.bind(this));
		return tbody;
	},

	buildTfoot: function(footerData){
	    var renderFooter = false;
	    var tfoot = Builder.node('tfoot');
	    var tr = Builder.node('tr');
	    tfoot.appendChild(tr);
    	var numCols = this.data.rows[0].length - 1;
	    $R(0, numCols, false).each(function(i) {
            if(!this.removedColumns[i]) {
    	        var td = Builder.node('td', {}, [footerData[i] || ""]);
    	        if(footerData[i]) renderFooter = true;
    	        tr.appendChild(td)
	        }
        }.bind(this));
        if(renderFooter) {
            return tfoot;
        } else {
            return false;
        }
	},

	sortData: function(column){
	    this.data.rows = this.data.rows.sortBy(function(v){
		    if(this.numberColumn[column]) {
		        return parseFloat(v[column]);
		    } else {
		        return v[column].toLowerCase();
		    }
		}.bind(this));
	},

	sort: function(column, reverse) {
	    this.resetDefaults();

		this.sortData(column);

		if(reverse) {
		    this.data.rows = this.data.rows.reverse();
		}

		this.sortedBy = column;
		this.sortedReverse = reverse;

		this.render();
	},

	group: function(column){
	    this.resetDefaults();
	    this.headerControl[column].close();
		this.sortData(column);

		this.groupedBy = column;

		this.render();
	},

	remove: function(column){
	    this.removedColumns[column] = true;
	    this.headerControl[column].close();
	    this.render();
	},

	sumColumn: function(column){
	   var sum = 0;
	   this.data.rows.collect(function(row) {return row[column]}).each(function(cell) {sum += parseFloat(cell)});
	   this.footerData[column] = "sum: " + sum;
	   this.render();
	},

	averageColumn: function(column){
	   var sum = 0;
	   this.data.rows.collect(function(row) {return row[column]}).each(function(cell) {sum += parseFloat(cell)});
	   this.footerData[column] = "average: " + Math.round((sum / this.data.rows.length) * 100)/100;
	   this.render();
	},

    addHeaderControls: function(){
        this.headerControl = {};
        var displayedCols = [];
        var numCols = this.data.rows[0].length - 1;
        $R(0, numCols, false).each(function(i) {
            if(!this.removedColumns[i]) {
                displayedCols.push(i);
            }
        }.bind(this));
        $$("#" + this.container.id + " ." + Simpltry.DataGrid.css.headerRow + " th").each(function(header, i) {
            if(header.id == null || header.id == "") header.id = this.container.id + "_header" + i;
            var headerControl = Builder.node("div", {className: Simpltry.DataGrid.css.headerControl, style: "display:none"});
            headerControl.id = header.id + "_tooltip";
            var ul = Builder.node("ul");
            var groupLi = Builder.node("li", {}, ['group by']);
            groupLi.onclick = this.group.bind(this, displayedCols[i]);
            ul.appendChild(groupLi);
            var removeLi = Builder.node("li", {}, ['remove']);
            removeLi.onclick = this.remove.bind(this, displayedCols[i]);
            headerControl.appendChild(ul);
            if(this.numberColumn[displayedCols[i]]) {
                var sumLi = Builder.node("li", {}, ['sum']);
                sumLi.onclick = this.sumColumn.bind(this, displayedCols[i]);
                ul.appendChild(sumLi);
                var averageLi = Builder.node("li", {}, ['average']);
                averageLi.onclick = this.averageColumn.bind(this, displayedCols[i]);
                ul.appendChild(averageLi);
            }
            ul.appendChild(removeLi);
            document.body.appendChild(headerControl);
            this.headerControl[displayedCols[i]] = new Simpltry.PopupTooltip(header);
        }.bind(this));
    },

    removeHeaderControls: function(){
        $$("#" + this.container.id + " ." + Simpltry.DataGrid.css.headerRow + " th").each(function(header, i) {
            var popup = $(header.id + "_tooltip");
            if(popup) {
                popup.remove();
            }
        });
    },

	render: function() {
	    this.removeHeaderControls();
		this.container.innerHTML = '';
		var table = Builder.node('table', {className:Simpltry.DataGrid.css.dataGrid});
		table.appendChild(this.buildThead(this.data.headers));
		table.appendChild(this.buildTbody(this.data.rows));
		var footer = this.buildTfoot(this.footerData);
		if(footer) {
		    table.appendChild(footer);
		}
		this.container.appendChild(table);
		this.addHeaderControls();
	}

};
<|endoftext|>


<commit_before>/**
 * #Midi#
 */

/**
 * global vars for midi
 * @type {Object}
 * @private
 */
var _midi_access = null,
    _midi_inputs = null,
    _midi_outputs = null;

/**
 * Is midi supported?
 * @public
 * @returns {boolean}
 */
cracked.midi_supported = function(){
    return typeof navigator.requestMIDIAccess === "function";
};

/**
 * Midi input. Bind handler for the onMIDIMessage event.
 * @param {Function} callback
 * @public
 */
cracked.midi_receive = function(callback){
    if(_midi_access && __.isFun(callback)) {
        var inputs = _midi_inputs.values();
        // loop over all available inputs and listen for any MIDI input
        for (var input = inputs.next(); input && !input.done; input = inputs.next()) {
            // each time there is a midi message call the onMIDIMessage function
            input.value.onmidimessage = callback;
        }
    } else {
        console.error("midi_receive: midi not available");
    }
};

/**
 * Initialize midi. Callback is invoked when ready.
 * @param {Function} callback
 * @public
 */
cracked.midi_init = function(callback) {
    if(_midi_access) {
        //midi already initialized
        callback.apply(cracked,[true]);
    } else if(__.midi_supported()) {
        navigator.requestMIDIAccess().then( function(access) {
            _midi_access = access;
            _midi_inputs = access.inputs; // inputs = MIDIInputMaps, you can retrieve the inputs with iterators
            _midi_outputs = access.outputs; // outputs = MIDIOutputMaps, you can retrieve the outputs with iterators
            callback.apply(cracked,[true]);
        }, function( err ) {
            console.error( "midi_init: Initialization failed. Error code: " + err.code );
            callback.apply(cracked,[false]);
        } );
    } else {
        console.error("midi_init: Failed. Midi not supported by your browser");
        callback.apply(cracked,[false]);
    }
};<commit_msg>add midi noteon/off/cc bindings<commit_after>/**
 * #Midi#
 */

/**
 * global vars for midi
 * @type {Object}
 * @private
 */
var _midi_access = null,
    _midi_inputs = null,
    _midi_outputs = null;

/**
 * Is midi supported?
 * @public
 * @returns {boolean}
 */
cracked.midi_supported = function(){
    return typeof navigator.requestMIDIAccess === "function";
};

/**
 * Initialize midi. Callback is invoked when ready.
 * @param {Function} callback
 * @public
 */
cracked.midi_init = function(callback) {
    if(_midi_access) {
        //midi already initialized
        callback.apply(cracked,[true]);
    } else if(__.midi_supported()) {
        navigator.requestMIDIAccess().then( function(access) {
            _midi_access = access;
            _midi_inputs = access.inputs; // inputs = MIDIInputMaps, you can retrieve the inputs with iterators
            _midi_outputs = access.outputs; // outputs = MIDIOutputMaps, you can retrieve the outputs with iterators
            callback.apply(cracked,[true]);
        }, function( err ) {
            console.error( "midi_init: Initialization failed. Error code: " + err.code );
            callback.apply(cracked,[false]);
        } );
    } else {
        console.error("midi_init: Failed. Midi not supported by your browser");
        callback.apply(cracked,[false]);
    }
};

/**
 * Midi input. Bind handler for the onMIDIMessage event.
 * @param {Function} callback
 * @public
 */
cracked.midi_receive = function(callback){
    if(_midi_access && __.isFun(callback)) {
        var inputs = _midi_inputs.values();
        // loop over all available inputs and listen for any MIDI input
        for (var input = inputs.next(); input && !input.done; input = inputs.next()) {
            // each time there is a midi message call the onMIDIMessage function
            input.value.onmidimessage = callback;
        }
    } else {
        console.error("midi_receive: midi not available");
    }
};

/**
 * Midi input. Shorthand binding for note ons
 * @param {Function} callback
 * @public
 */
cracked.midi_noteon = function(callback) {
    cracked.midi_receive(function(ev){
        if(ev.data && ev.data[0]===144) {
            callback(ev.data);
        }
    });
};

/**
 * Midi input. Shorthand binding for note offs
 * @param {Function} callback
 * @public
 */
cracked.midi_noteoff = function(callback) {
    cracked.midi_receive(function(ev){
        if(ev.data && ev.data[0]===128) {
            callback(ev.data);
        }
    });
};

/**
 * Midi input. Shorthand binding for midi control messages
 * @param {Function} callback
 * @public
 */
cracked.midi_control = function(callback) {
    cracked.midi_receive(function(ev){
        if(ev.data && ev.data[0]===176) {
            callback(ev.data);
        }
    });
};

<|endoftext|>


<commit_before>/** @license MIT License (c) copyright 2015 original author or authors */
/** @author Brian Cavalier */
'use strict';

import MulticastSource from 'most/lib/source/MulticastSource';

// hold :: Stream a -> Stream a
export default stream => new stream.constructor(new MulticastSource(new Hold(stream.source)));

class Hold {
    constructor(source) {
        this.source = source;
        this.time = -Infinity;
        this.value = void 0;
    }

    run(sink, scheduler) {
        if (sink._hold !== this) {
            sink._hold = this;
            sink._holdAdd = sink.add;
            sink.add = holdAdd;

            sink._holdEvent = sink.event;
            sink.event = holdEvent;
        }

        return this.source.run(sink, scheduler);
    }
}

function holdAdd(sink) {
    const len = this._holdAdd(sink);
    if (this._hold.time >= 0) {
        sink.event(this._hold.time, this._hold.value);
    }
    return len;
}

function holdEvent(t, x) {
    if (t >= this._hold.time) {
        this._hold.time = t;
        this._hold.value = x;
    }
    return this._holdEvent(t, x);
}
<commit_msg>Update copyright<commit_after>/** @license MIT License (c) copyright 2015-2016 original author or authors */
/** @author Brian Cavalier */
'use strict';

import MulticastSource from 'most/lib/source/MulticastSource';

// hold :: Stream a -> Stream a
export default stream => new stream.constructor(new MulticastSource(new Hold(stream.source)));

class Hold {
    constructor(source) {
        this.source = source;
        this.time = -Infinity;
        this.value = void 0;
    }

    run(sink, scheduler) {
        if (sink._hold !== this) {
            sink._hold = this;
            sink._holdAdd = sink.add;
            sink.add = holdAdd;

            sink._holdEvent = sink.event;
            sink.event = holdEvent;
        }

        return this.source.run(sink, scheduler);
    }
}

function holdAdd(sink) {
    const len = this._holdAdd(sink);
    if (this._hold.time >= 0) {
        sink.event(this._hold.time, this._hold.value);
    }
    return len;
}

function holdEvent(t, x) {
    if (t >= this._hold.time) {
        this._hold.time = t;
        this._hold.value = x;
    }
    return this._holdEvent(t, x);
}
<|endoftext|>


<commit_before>import later from 'later';
import defaults from './defaults';
import { BaseHook, deepGet, getTimeStamp } from 'redibox';

export default class Scheduler extends BaseHook {
  constructor() {
    super('schedule');
  }

  /**
   *
   * @returns {Promise.<T>}
   */
  initialize() {
    for (let i = 0, len = this.options.schedules.length; i < len; i++) {
      const schedule = this.options.schedules[i];
      this.options.laterSchedules[i] = later.parse.text(schedule.interval);
      this.options.laterTimers[i] = later.setInterval(
        this.scheduleWrapper.bind(this, i),
        this.options.laterSchedules[i]
      );
    }
    return Promise.resolve();
  }

  /**
   *
   * @param i
   */
  scheduleWrapper(i) {
    return this
      .client
      .set(this.core.toKey(`schedules:${i}`), i, 'NX', 'EX', this.options.minInterval)
      .then(res => {
        if (!res) return Promise.resolve();
        const schedule = this.options.schedules[i];
        if (!schedule.runs) throw new Error('Schedule is missing a runs parameter.');
        const runner = deepGet(global, schedule.runs);
        return runner(schedule)
          .then(this.successLogger.bind(this, schedule))
          .catch(this.errorLogger.bind(this, schedule));
      });

  }

  /**
   *
   * @param schedule
   */
  successLogger(schedule) {
    this.log.info(`${getTimeStamp()}: Schedule for '${schedule.runs}' has completed successfully.`);
  }

  /**
   *
   * @param schedule
   * @param error
   */
  errorLogger(schedule, error) {
    this.log.error(`${getTimeStamp()}: Schedule for '${schedule.runs}' has failed to complete.`);
    this.log.error(error);
  }

  // noinspection JSUnusedGlobalSymbols,JSMethodCanBeStatic
  /**
   * Default config for scheduler
   * @returns {{someDefaultThing: string}}
   */
  defaults() {
    return defaults;
  }

}
<commit_msg>basic version just PoC<commit_after>import later from 'later';
import defaults from './defaults';
import { BaseHook, deepGet, getTimeStamp } from 'redibox';

export default class Scheduler extends BaseHook {
  constructor() {
    super('schedule');
  }

  /**
   *
   * @returns {Promise.<T>}
   */
  initialize() {
    for (let i = 0, len = this.options.schedules.length; i < len; i++) {
      const schedule = this.options.schedules[i];
      this.options.laterSchedules[i] = later.parse.text(schedule.interval);
      this.options.laterTimers[i] = later.setInterval(
        this.scheduleWrapper.bind(this, i),
        this.options.laterSchedules[i]
      );
    }
    return Promise.resolve();
  }

  /**
   *
   * @param i
   */
  scheduleWrapper(i) {
    return this
      .client
      .set(this.core.toKey(`schedules:${i}`), i, 'NX', 'EX', this.options.minInterval)
      .then(res => {
        if (!res) return Promise.resolve();
        const schedule = this.options.schedules[i];
        if (!schedule.runs) throw new Error('Schedule is missing a runs parameter.');
        const runner = deepGet(global, schedule.runs);
        return runner(schedule)
          .then(this.successLogger.bind(this, schedule))
          .catch(this.errorLogger.bind(this, schedule));
      });
  }

  /**
   *
   * @param schedule
   */
  successLogger(schedule) {
    this.log.info(`${getTimeStamp()}: Schedule for '${schedule.runs}' has completed successfully.`);
  }

  /**
   *
   * @param schedule
   * @param error
   */
  errorLogger(schedule, error) {
    this.log.error(`${getTimeStamp()}: Schedule for '${schedule.runs}' has failed to complete.`);
    this.log.error(error);
  }

  // noinspection JSUnusedGlobalSymbols,JSMethodCanBeStatic
  /**
   * Default config for scheduler
   * @returns {{someDefaultThing: string}}
   */
  defaults() {
    return defaults;
  }

}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

let stylesStr;
if (process.env.NODE_ENV === `production`) {
  try {
    stylesStr = require('!raw-loader!../public/styles.css');
  } catch (e) {
    console.error(e); // eslint-disable-line no-console
  }
}

module.exports = class HTML extends React.Component {
  static propTypes = {
    headComponents: PropTypes.node,
    preBodyComponents: PropTypes.node,
    body: PropTypes.node,
    postBodyComponents: PropTypes.node
  };

  render() {
    let css;
    if (process.env.NODE_ENV === `production`) {
      css = (
        <style
          id="gatsby-inlined-css"
          dangerouslySetInnerHTML={{ __html: stylesStr }}
        />
      );
    }
    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          {this.props.headComponents}
          {css}
        </head>
        <body>
          {this.props.preBodyComponents}
          <div
            key={`body`}
            id="___gatsby"
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}
        </body>
      </html>
    );
  }
};
<commit_msg>whoops, realized this never made it in since I added it to the public files...<commit_after>import React from 'react';
import PropTypes from 'prop-types';

let stylesStr;
if (process.env.NODE_ENV === `production`) {
  try {
    stylesStr = require('!raw-loader!../public/styles.css');
  } catch (e) {
    console.error(e); // eslint-disable-line no-console
  }
}

module.exports = class HTML extends React.Component {
  static propTypes = {
    headComponents: PropTypes.node,
    preBodyComponents: PropTypes.node,
    body: PropTypes.node,
    postBodyComponents: PropTypes.node
  };

  render() {
    let css;
    if (process.env.NODE_ENV === `production`) {
      css = (
        <style
          id="gatsby-inlined-css"
          dangerouslySetInnerHTML={{ __html: stylesStr }}
        />
      );
    }
    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <link
            href="https://fonts.googleapis.com/css?family=Source+Code+Pro|Source+Serif+Pro"
            rel="stylesheet"
          />
          {this.props.headComponents}
          {css}
        </head>
        <body>
          {this.props.preBodyComponents}
          <div
            key={`body`}
            id="___gatsby"
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}
        </body>
      </html>
    );
  }
};
<|endoftext|>


<commit_before>/// http.js --- Deals with HTTP requests in the browser
//
// Copyright (c) 2012 Quildreen Motta
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/// Module iris.http

//// -- Dependencies ----------------------------------------------------------
var utils  = require('./utils')
var cassie = require('cassie')

//// -- Aliases ---------------------------------------------------------------
var keys               = Object.keys
var call               = Function.prototype.call
var to_array           = call.bind([].slice)
var class_of           = call.bind({}.toString)
var serialise          = utils.serialise
var build_query_string = utils.build_query_string
var register           = cassie.register
var Promise            = cassie.Promise

//// -- Helpers ---------------------------------------------------------------
var make_xhr = function() {
                 return 'XMLHttpRequest' in this?
                        /* W3C? */ function() {
                                     return new XMLHttpRequest() }
                        :
                        /* IE? */  function() {
                                     return new ActiveXObject('Microsoft.XMLHTTP') }}()

var support_timeout_p = 'timeout' in make_xhr()

var success = /2\d{2}/
var error   = /[45]\d{2}/

var statuses = [ 'information'
               , 'success'
               , 'redirected'
               , 'client-error'
               , 'server-error' ]

var state_map = [ 'unsent'
                , 'opened'
                , 'headers-received'
                , 'loading'
                , 'completed' ]

function object_p(subject) {
  return class_of(subject) == '[object Object]' }

function status_type(status) {
  var type = status.toString().charAt(0) - 1
  return statuses[type] }

function serialise_for_type(mime, data) {
  return mime == 'application/json'?  JSON.stringify(data)
  :      /* otherwise */              serialise(data) }

//// -- Public interface ------------------------------------------------------
var active = []

var PromiseP = Promise.derive({
  init:
  function _init(client, uri, options) {
    Promise.init.call(this)
    this.client  = client
    this.uri     = uri
    this.options = options

    return this }

, fire:
  function _fire(event) {
    var args, callbacks, i, len
    args      = to_array(arguments, 1)
    callbacks = this.callbacks[event] || []

    for (i = 0, len = callbacks.length; i < len; ++i)
      callbacks[i].apply(this, args)

    return this }

, forget:
  function _forget() {
    this.client.abort()
    return Promise.forget.call(this) }

, timeout: support_timeout_p?  function _timeout(delay) {
                                 this.timeout = delay * 1000
                                 return this }

         : /* otherwise */     function _timeout(delay) {
                                 this.clear_timer()
                                 this.timer = setTimeout( function() {
                                                            this.abort()
                                                            this.flush('timeouted')
                                                                .fail(Promise.TIMEOUTED) }.bind(this)
                                                        , delay * 1000 )}

, clear_timer: support_timeout_p?  function _clear_timer() {
                                     this.timeout = 0
                                     return this }

             : /* otherwise */     Promise.clear_timer

// Generalised HTTP statuses
, information  : register('status:information')
, success      : register('status:success')
, redirected   : register('status:redirected')
, client_error : register('status:client-error')
, server_error : register('status:server-error')

// Ready states
, unsent           : register('state:unsent')
, opened           : register('state:opened')
, headers_received : register('state:headers-received')
, loading          : register('state:loading')
, completed        : register('state:completed')
})

function request(uri, options) {
  var client, promise, method, serialise_body_p, mime
  options          = options         || {}
  options.headers  = options.headers || {}
  method           = (options.method || 'GET').toUpperCase()
  uri              = build_uri(uri, options.query, options.body)

  options.headers['X-Requested-With'] = 'XMLHttpRequest'

  serialise_body_p = object_p(options.body)
  if (serialise_body_p) {
    mime = options.headers['Content-Type'] || 'application/x-www-form-urlencoded'
    options.body = serialise_for_type(mime, options.body)
    options.headers['Content-Type'] = mime }

  client  = make_xhr()
  promise = PromiseP.make(client, uri, options)

  setup_listeners()

  setTimeout(function() {
    client.open(method, uri, true, options.username, options.password)
    setup_headers(options.headers || {})
    client.send(options.body) })

  active.push(promise)

  return promise

  function build_uri(uri, query, body) {
    uri = build_query_string(uri, query)
    return method == 'GET'?  build_query_string(uri, body)
    :      /* otherwise */   uri }

  function setup_headers(headers) {
    keys(headers).forEach(function(key) {
      client.setRequestHeader(key, headers[key]) })}

  function setup_listeners() {
    client.onerror            = function(ev){ promise.fail('errored', ev)       }
    client.onabort            = function(ev){ promise.fail('aborted', ev)       }
    client.ontimeout          = function(ev){ promise.fail('timeouted', ev)     }
    client.onloadstart        = function(ev){ promise.fire('load:start', ev)    }
    client.onprogress         = function(ev){ promise.fire('load:progress', ev) }
    client.onloadend          = function(ev){ promise.fire('load:end', ev)      }
    client.onload             = function(ev){ promise.fire('load:success', ev)  }
    client.onreadystatechange = function(  ){
                                  var response, status, state
                                  response = client.responseText
                                  state    = client.readyState

                                  promise.fire('state:' + state_map[state], response, status)

                                  if (state == 4) {
                                    status   = client.status
                                    active.splice(active.indexOf(promise), 1)
                                    promise.flush('status:' + status)
                                           .flush('status:' + status_type(status))

                                      success.test(status)?  promise.bind(response, status)
                                    : error.test(status)?    promise.fail(response, status)
                                    : /* otherwise */        promise.done([response, status]) }}}
}

function request_with_method(method) { return function(uri, options) {
  options = options || { }
  options.method = method.toUpperCase()
  return request(uri, options) }}

//// -- Exports ---------------------------------------------------------------
module.exports = { PromiseP: PromiseP
                 , request:  request
                 , active:   active
                 , get:      request_with_method('GET')
                 , post:     request_with_method('POST')
                 , put:      request_with_method('PUT')
                 , head:     request_with_method('HEAD')
                 , delete_:  request_with_method('DELETE')
                 , options:  request_with_method('OPTIONS')

                 , internal: { make_xhr: make_xhr }}
<commit_msg>Adds shortcuts for registering for failure statuses.<commit_after>/// http.js --- Deals with HTTP requests in the browser
//
// Copyright (c) 2012 Quildreen Motta
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/// Module iris.http

//// -- Dependencies ----------------------------------------------------------
var utils  = require('./utils')
var cassie = require('cassie')

//// -- Aliases ---------------------------------------------------------------
var keys               = Object.keys
var call               = Function.prototype.call
var to_array           = call.bind([].slice)
var class_of           = call.bind({}.toString)
var serialise          = utils.serialise
var build_query_string = utils.build_query_string
var register           = cassie.register
var Promise            = cassie.Promise

//// -- Helpers ---------------------------------------------------------------
var make_xhr = function() {
                 return 'XMLHttpRequest' in this?
                        /* W3C? */ function() {
                                     return new XMLHttpRequest() }
                        :
                        /* IE? */  function() {
                                     return new ActiveXObject('Microsoft.XMLHTTP') }}()

var support_timeout_p = 'timeout' in make_xhr()

var success = /2\d{2}/
var error   = /[45]\d{2}/

var statuses = [ 'information'
               , 'success'
               , 'redirected'
               , 'client-error'
               , 'server-error' ]

var state_map = [ 'unsent'
                , 'opened'
                , 'headers-received'
                , 'loading'
                , 'completed' ]

function object_p(subject) {
  return class_of(subject) == '[object Object]' }

function status_type(status) {
  var type = status.toString().charAt(0) - 1
  return statuses[type] }

function serialise_for_type(mime, data) {
  return mime == 'application/json'?  JSON.stringify(data)
  :      /* otherwise */              serialise(data) }

//// -- Public interface ------------------------------------------------------
var active = []

var PromiseP = Promise.derive({
  init:
  function _init(client, uri, options) {
    Promise.init.call(this)
    this.client  = client
    this.uri     = uri
    this.options = options

    return this }

, fire:
  function _fire(event) {
    var args, callbacks, i, len
    args      = to_array(arguments, 1)
    callbacks = this.callbacks[event] || []

    for (i = 0, len = callbacks.length; i < len; ++i)
      callbacks[i].apply(this, args)

    return this }

, forget:
  function _forget() {
    this.client.abort()
    return Promise.forget.call(this) }

, timeout: support_timeout_p?  function _timeout(delay) {
                                 this.timeout = delay * 1000
                                 return this }

         : /* otherwise */     function _timeout(delay) {
                                 this.clear_timer()
                                 this.timer = setTimeout( function() {
                                                            this.abort()
                                                            this.flush('timeouted')
                                                                .fail(Promise.TIMEOUTED) }.bind(this)
                                                        , delay * 1000 )}

, clear_timer: support_timeout_p?  function _clear_timer() {
                                     this.timeout = 0
                                     return this }

             : /* otherwise */     Promise.clear_timer

// Generalised HTTP statuses
, information  : register('status:information')
, success      : register('status:success')
, redirected   : register('status:redirected')
, client_error : register('status:client-error')
, server_error : register('status:server-error')

// Ready states
, unsent           : register('state:unsent')
, opened           : register('state:opened')
, headers_received : register('state:headers-received')
, loading          : register('state:loading')
, completed        : register('state:completed')

// General failure statuses
, aborted : register('aborted')
, errored : register('errored')
})

function request(uri, options) {
  var client, promise, method, serialise_body_p, mime
  options          = options         || {}
  options.headers  = options.headers || {}
  method           = (options.method || 'GET').toUpperCase()
  uri              = build_uri(uri, options.query, options.body)

  options.headers['X-Requested-With'] = 'XMLHttpRequest'

  serialise_body_p = object_p(options.body)
  if (serialise_body_p) {
    mime = options.headers['Content-Type'] || 'application/x-www-form-urlencoded'
    options.body = serialise_for_type(mime, options.body)
    options.headers['Content-Type'] = mime }

  client  = make_xhr()
  promise = PromiseP.make(client, uri, options)

  setup_listeners()

  setTimeout(function() {
    client.open(method, uri, true, options.username, options.password)
    setup_headers(options.headers || {})
    client.send(options.body) })

  active.push(promise)

  return promise

  function build_uri(uri, query, body) {
    uri = build_query_string(uri, query)
    return method == 'GET'?  build_query_string(uri, body)
    :      /* otherwise */   uri }

  function setup_headers(headers) {
    keys(headers).forEach(function(key) {
      client.setRequestHeader(key, headers[key]) })}

  function setup_listeners() {
    client.onerror            = function(ev){ promise.fail('errored', ev)       }
    client.onabort            = function(ev){ promise.fail('aborted', ev)       }
    client.ontimeout          = function(ev){ promise.fail('timeouted', ev)     }
    client.onloadstart        = function(ev){ promise.fire('load:start', ev)    }
    client.onprogress         = function(ev){ promise.fire('load:progress', ev) }
    client.onloadend          = function(ev){ promise.fire('load:end', ev)      }
    client.onload             = function(ev){ promise.fire('load:success', ev)  }
    client.onreadystatechange = function(  ){
                                  var response, status, state
                                  response = client.responseText
                                  state    = client.readyState

                                  promise.fire('state:' + state_map[state], response, status)

                                  if (state == 4) {
                                    status   = client.status
                                    active.splice(active.indexOf(promise), 1)
                                    promise.flush('status:' + status)
                                           .flush('status:' + status_type(status))

                                      success.test(status)?  promise.bind(response, status)
                                    : error.test(status)?    promise.fail(response, status)
                                    : /* otherwise */        promise.done([response, status]) }}}
}

function request_with_method(method) { return function(uri, options) {
  options = options || { }
  options.method = method.toUpperCase()
  return request(uri, options) }}

//// -- Exports ---------------------------------------------------------------
module.exports = { PromiseP: PromiseP
                 , request:  request
                 , active:   active
                 , get:      request_with_method('GET')
                 , post:     request_with_method('POST')
                 , put:      request_with_method('PUT')
                 , head:     request_with_method('HEAD')
                 , delete_:  request_with_method('DELETE')
                 , options:  request_with_method('OPTIONS')

                 , internal: { make_xhr: make_xhr }}
<|endoftext|>


<commit_before>module.exports = function (Vue) {

    var _ = require('./util')(Vue);
    var jsonType = { 'Content-Type': 'application/json;charset=utf-8' };

    /**
     * Http provides a service for sending XMLHttpRequests.
     */

    function Http (url, options) {

        var self = this, headers, promise;

        options = options || {};

        if (_.isPlainObject(url)) {
            options = url;
            url = '';
        }

        headers = _.extend({},
            Http.headers.common,
            Http.headers[options.method.toLowerCase()]
        );

        options = _.extend(true, {url: url, headers: headers},
            Http.options, _.options('http', this, options)
        );

        if (_.isObject(options.data) && /FormData/i.test(options.data.toString())) {
            delete options.headers['Content-Type'];
        }

        promise = new _.Promise((options.method.toLowerCase() == 'jsonp' ? jsonp : xhr).bind(this, (this.$url || Vue.url), options));

        _.extend(promise, {

            success: function (onSuccess) {

                this.then(function (request) {
                    onSuccess.apply(self, parseReq(request));
                }, function () {});

                return this;
            },

            error: function (onError) {

                this.catch(function (request) {
                    onError.apply(self, parseReq(request));
                });

                return this;
            },

            always: function (onAlways) {

                var cb = function (request) {
                    onAlways.apply(self, parseReq(request));
                };

                this.then(cb, cb);

                return this;
            }

        });

        if (options.success) {
            promise.success(options.success);
        }

        if (options.error) {
            promise.error(options.error);
        }

        return promise;
    }

    function xhr(url, options, resolve, reject) {

        var request = new XMLHttpRequest();

        if (_.isFunction(options.beforeSend)) {
            options.beforeSend(request, options);
        }

        if (options.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(options.method)) {
            options.headers['X-HTTP-Method-Override'] = options.method;
            options.method = 'POST';
        }

        if (options.emulateJSON && _.isPlainObject(options.data)) {
            options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
            options.data = Vue.url.params(options.data);
        }

        if (_.isPlainObject(options.data)) {
            options.data = JSON.stringify(options.data);
        }

        request.open(options.method, url(options), true);

        _.each(options.headers, function (value, header) {
            request.setRequestHeader(header, value);
        });

        request.onreadystatechange = function () {

            if (this.readyState === 4) {

                if (this.status >= 200 && this.status < 300) {
                    resolve(this);
                } else {
                    reject(this);
                }
            }
        };

        request.send(options.data);
    }

    function jsonp(url, options, resolve, reject) {

        var callback = '_jsonp' + Math.random().toString(36).substr(2), script, result;

        _.extend(options.params, options.data);
        options.params[options.jsonp] = callback;

        if (_.isFunction(options.beforeSend)) {
            options.beforeSend({}, options);
        }

        script = document.createElement('script');
        script.src = url(options.url, options.params);
        script.type = 'text/javascript';
        script.async = true;

        window[callback] = function (data) {
            result = data;
        };

        var handler = function (event) {

            delete window[callback];
            document.body.removeChild(script);

            if (event.type === 'load' && !result) {
                event.type = 'error';
            }

            var text = result ? result : event.type, status = event.type === 'error' ? 404 : 200;

            (status === 200 ? resolve : reject)({ responseText: text, status: status });
        };

        script.onload = handler;
        script.onerror = handler;

        document.body.appendChild(script);
    }

    function parseReq(request) {

        var result;

        try {
            result = JSON.parse(request.responseText);
        } catch (e) {
            result = request.responseText;
        }

        return [result, request.status, request];
    }

    Http.options = {
        method: 'GET',
        params: {},
        data: '',
        jsonp: 'callback',
        beforeSend: null,
        emulateHTTP: false,
        emulateJSON: false,
    };

    Http.headers = {
        put: jsonType,
        post: jsonType,
        patch: jsonType,
        delete: jsonType,
        common: { 'Accept': 'application/json, text/plain, */*' }
    };

    ['get', 'put', 'post', 'patch', 'delete', 'jsonp'].forEach(function (method) {

        Http[method] = function (url, data, success, options) {

            if (_.isFunction(data)) {
                options = success;
                success = data;
                data = undefined;
            }

            return this(url, _.extend({method: method, data: data, success: success}, options));
        };
    });

    Object.defineProperty(Vue.prototype, '$http', {

        get: function () {
            return _.extend(Http.bind(this), Http);
        }

    });

    return Http;
};
<commit_msg>Added missing "X-Requested-With" header<commit_after>module.exports = function (Vue) {

    var _ = require('./util')(Vue);
    var jsonType = { 'Content-Type': 'application/json;charset=utf-8' };

    /**
     * Http provides a service for sending XMLHttpRequests.
     */

    function Http (url, options) {

        var self = this, headers, promise;

        options = options || {};

        if (_.isPlainObject(url)) {
            options = url;
            url = '';
        }

        headers = _.extend({},
            Http.headers.common,
            Http.headers[options.method.toLowerCase()]
        );

        options = _.extend(true, {url: url, headers: headers},
            Http.options, _.options('http', this, options)
        );

        if (_.isObject(options.data) && /FormData/i.test(options.data.toString())) {
            delete options.headers['Content-Type'];
        }

        promise = new _.Promise((options.method.toLowerCase() == 'jsonp' ? jsonp : xhr).bind(this, (this.$url || Vue.url), options));

        _.extend(promise, {

            success: function (onSuccess) {

                this.then(function (request) {
                    onSuccess.apply(self, parseReq(request));
                }, function () {});

                return this;
            },

            error: function (onError) {

                this.catch(function (request) {
                    onError.apply(self, parseReq(request));
                });

                return this;
            },

            always: function (onAlways) {

                var cb = function (request) {
                    onAlways.apply(self, parseReq(request));
                };

                this.then(cb, cb);

                return this;
            }

        });

        if (options.success) {
            promise.success(options.success);
        }

        if (options.error) {
            promise.error(options.error);
        }

        return promise;
    }

    function xhr(url, options, resolve, reject) {

        var request = new XMLHttpRequest();

        if (_.isFunction(options.beforeSend)) {
            options.beforeSend(request, options);
        }

        if (options.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(options.method)) {
            options.headers['X-HTTP-Method-Override'] = options.method;
            options.method = 'POST';
        }

        if (options.emulateJSON && _.isPlainObject(options.data)) {
            options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
            options.data = Vue.url.params(options.data);
        }

        if (_.isPlainObject(options.data)) {
            options.data = JSON.stringify(options.data);
        }

        request.open(options.method, url(options), true);

        _.each(options.headers, function (value, header) {
            request.setRequestHeader(header, value);
        });

        request.onreadystatechange = function () {

            if (this.readyState === 4) {

                if (this.status >= 200 && this.status < 300) {
                    resolve(this);
                } else {
                    reject(this);
                }
            }
        };

        request.send(options.data);
    }

    function jsonp(url, options, resolve, reject) {

        var callback = '_jsonp' + Math.random().toString(36).substr(2), script, result;

        _.extend(options.params, options.data);
        options.params[options.jsonp] = callback;

        if (_.isFunction(options.beforeSend)) {
            options.beforeSend({}, options);
        }

        script = document.createElement('script');
        script.src = url(options.url, options.params);
        script.type = 'text/javascript';
        script.async = true;

        window[callback] = function (data) {
            result = data;
        };

        var handler = function (event) {

            delete window[callback];
            document.body.removeChild(script);

            if (event.type === 'load' && !result) {
                event.type = 'error';
            }

            var text = result ? result : event.type, status = event.type === 'error' ? 404 : 200;

            (status === 200 ? resolve : reject)({ responseText: text, status: status });
        };

        script.onload = handler;
        script.onerror = handler;

        document.body.appendChild(script);
    }

    function parseReq(request) {

        var result;

        try {
            result = JSON.parse(request.responseText);
        } catch (e) {
            result = request.responseText;
        }

        return [result, request.status, request];
    }

    Http.options = {
        method: 'GET',
        params: {},
        data: '',
        jsonp: 'callback',
        beforeSend: null,
        emulateHTTP: false,
        emulateJSON: false,
    };

    Http.headers = {
        put: jsonType,
        post: jsonType,
        patch: jsonType,
        delete: jsonType,
        common: {
            'Accept': 'application/json, text/plain, */*',
            'X-Requested-With': 'XMLHttpRequest'
        }
    };

    ['get', 'put', 'post', 'patch', 'delete', 'jsonp'].forEach(function (method) {

        Http[method] = function (url, data, success, options) {

            if (_.isFunction(data)) {
                options = success;
                success = data;
                data = undefined;
            }

            return this(url, _.extend({method: method, data: data, success: success}, options));
        };
    });

    Object.defineProperty(Vue.prototype, '$http', {

        get: function () {
            return _.extend(Http.bind(this), Http);
        }

    });

    return Http;
};
<|endoftext|>


<commit_before>import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import { reactI18nextModule } from 'react-i18next';

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(reactI18nextModule)
  .init({
    detection: {
      order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
      lookupQuerystring: 'lang',
    },
    fallbackLng: 'en',

    // have a common namespace used around the full app
    ns: ['translations'],
    defaultNS: 'translations',

    debug: true,

    interpolation: {
      escapeValue: false, // not needed for react!!
    },

    react: {
      wait: true,
    },
  });

export default i18n;
<commit_msg>domain based language set (#16)<commit_after>import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import { reactI18nextModule } from 'react-i18next';

const languageDetector = new LanguageDetector();
languageDetector.addDetector({
  name: 'languageByDomain',
  lookup: (options) => options.hostname.match(/\.im$/i) ? 'ru' : 'en',
});

i18n
  .use(Backend)
  .use(languageDetector)
  .use(reactI18nextModule)
  .init({
    detection: {
      order: ['languageByDomain', 'querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
      lookupQuerystring: 'lang',
      hostname: window.location.hostname,
    },
    fallbackLng: 'en',

    // have a common namespace used around the full app
    ns: ['translations'],
    defaultNS: 'translations',

    debug: false,

    interpolation: {
      escapeValue: false, // not needed for react!!
    },

    react: {
      wait: true,
    },
  });

export default i18n;
<|endoftext|>