<commit_before>var _ = require('lodash')
var Chance = require('chance')
var random_name = require('node-random-name');
var Firebase = require('firebase');
var ref_Group = new Firebase("https://wetravel.firebaseio.com/Groups")
var ref_User = new Firebase("https://wetravel.firebaseio.com/Users")
//get the current time for message useage
var d = new Date()
var hour = d.getHours()
var minute = d.getMinutes()
var time = hour+':'+minute

// simualate a random person entering, staying for a duration, and leaving
function simulate(){
  // random user name
  var chance = new Chance()
  var name = random_name()
  var duration = 1 + 5 * Math.random()
  var user = {
    name: name,
    status: 'online'
  }
   login(user)
   joinGroup(user, 'CS_Grad_Trip')

  // random message
  var message = chance.word() + " " + chance.word() + " " +chance.word()
  // random schedule
  var Day = "Day" + Math.floor(duration).toString()
  var budget = Math.random()*50+1
  var place = chance.word() + " " + chance.word()
  var startTime  = Math.floor(Math.random()*22)+1
  var endTime  = startTime+2
  var time = startTime.toString() + ':' + endTime.toString()
  var traffic = ['Rent car', 'Taxi', 'Bus', 'Metro', 'Bike', 'Walk']
  var transportation = traffic[Math.floor(Math.random()*traffic.length)]
  var schedule = {
    Day: Day,
    budget: budget,
    place: place,
    time: time,
    transportation: transportation
  }
  setTimeout(function(){
    chat('CS_Grad_Trip',user, message, time)
    addSchedule('CS_Grad_Trip', schedule)

    canvas('CS_Grad_Trip')
    //clickonMap()
  }, duration * 1000)

  // simulate this person login
  // simulate this person logout after 'duration' seconds
  setTimeout(function(){
    //clickonMap()
   }, duration * 1000)

  // simulate this person login
  // simulate this person logout after 'duration' seconds
   setTimeout(function(){
    logout(user)
  }, duration * 1000)

}
function login(user){
  console.log('login', user)
  ref_User.once('value', function(snapshot){
    var users = snapshot.val()
    users = Object.keys(users)
    if (user in users){
      ref_User.child(user.name).update({status:online})
    }
    else{
      ref_User.child(user.name).set({
        name: user.name,
        status: user.status
      })
    }
  })

}

function logout(user){
  console.log('logout', user)
  ref_User.child(user.name).update({status: 'offline'});
}

function joinGroup(user, group){
  ref_User.child(group).child('member').child(user.name).set({
    name: user.name,
    status: user.status
  })
}

function chat(group,user, message, time){
  console.log('chat', group,user,message,time)
  var chance = new Chance()
  ref_Group.child(group).child('Message').child(chance.word()).set({
  message: message,
  time: time,
  username:user.name
  })
}

function canvas(group){
  var x = Math.floor(Math.random() * (120 + 1));
  var y = Math.floor(Math.random() * (105 + 1));
  var curColor = randColor();
  var curSize = randSize();
  var curTool = randTool();
  if(curTool == 'Eraser'){
    curColor = 'fff';
    ref_Group.child(group).child('drawing').child(x+':'+y).set({
      curColor: curColor,
      curSize : curSize,
      curTool : curTool
    })
  }else if(curTool == 'Refresh'){
    ref_Group.child(group).child('drawing').remove();
  }else{
    ref_Group.child(group).child('drawing').child(x+':'+y).set({
      curColor: curColor,
      curSize : curSize,
      curTool : curTool
    })
  }
  console.log('canvas', x, ':', y, 'color:', curColor, 'size:', curSize, 'tool:', curTool)
}

function randSize(){
  var size = [
    'Small',
    'Medium',
    'Large'
  ];
  var rand = Math.floor(Math.random()*size.length);
  return size[rand]
}

function randTool(){
  var tool = [
    'Eraser',
    'Marker',
    'Refresh'
  ];
  var rand = Math.floor(Math.random()*tool.length);
  return tool[rand]
}

function randColor(){
  var colors = ["fff","000","f00","0f0","00f","88f","f8d","f88","f05","f80","0f8","cf0","08f","408","ff8","8ff", "aed081", "eee"];

  var rand = Math.floor(Math.random()*colors.length);
  return colors[rand]
}

function addSchedule(group, schedule){
  console.log('schedule', schedule)
  ref_Group.child(group).child('Schedule').once('value', function(snapshot){
    var D = snapshot.val()
    var key = Object.keys(D)
    if (key.indexOf(schedule.Day)>-1){
      ref_Group.child(group).child('Schedule').child(schedule.Day).child(schedule.time).set({
        budget: schedule.budget,
        place: schedule.place,
        transportation: schedule.transportation
      })
    }
    else{
      ref_Group.child(group).child('Schedule').child(schedule.Day).set(
        schedule.time)
      ref_Group.child(group).child('Schedule').child(schedule.Day).child(schedule.time).set({
          budget: schedule.budget,
          place: schedule.place,
          transportation: schedule.transportation
        })
    }
  })
}
// function clickonMap()
///-------------------------------------------------------------------------
// function Make_Group(groupName, key, userName){

//   ref_Group.child(groupName).set({
//     GroupName: groupName
//     Activation_key: key
//     Message: {
//       time: "Welcome to "+groupName
//     }
//     member: {
//       userName: userName
//       current_status: online
//     }
//   })
// }
// function Join_Group(groupName, key, userName){
//   ref_Group.child(groupName).child(Activation_key).once('value',function(snapshot){
//     var gold_answer = snapshot.value()
//   })
//   if(key != gold_answer){
//     alert('wrong password')
//   }
//   else{
//     ref_Group.child(groupName).child(member).child(userName).set({
//       userName: userName
//       current_status: online
//     })
//     if (ref_User.child(userName).child('groups')!=null){
//       ref_User.child(userName).child('groups').once('value',function(snapshot){
//         var key = snapshot.val()
//         key.push(groupName)
//         ref_User.child(userName).child('groups').set(key)
//       })
//     }
//     else{
//       ref_User.child(userName).child('groups').set([groupName])
//     }

// }

// run each second
setInterval(simulate, 2000)<commit_msg>week8 re<commit_after>var _ = require('lodash')
var Chance = require('chance')
var random_name = require('node-random-name');
var Firebase = require('firebase');
var ref_Group = new Firebase("https://wetravel.firebaseio.com/Groups")
var ref_User = new Firebase("https://wetravel.firebaseio.com/Users")
//get the current time for message useage
var d = new Date()
var hour = d.getHours()
var minute = d.getMinutes()
var time = hour+':'+minute

// simualate a random person entering, staying for a duration, and leaving
function simulate(){
  // random user name
  var chance = new Chance()
  var name = random_name()
  var duration = 1 + 5 * Math.random()
  var user = {
    name: name,
    status: 'online'
  }
   login(user)
   joinGroup(user, 'CS_Grad_Trip')

  // random message
  var message = chance.word() + " " + chance.word() + " " +chance.word()
  // random schedule
  var Day = "Day" + Math.floor(duration).toString()
  var budget = Math.random()*50+1
  var place = chance.word() + " " + chance.word()
  var startTime  = Math.floor(Math.random()*22)+1
  var endTime  = startTime+2
  var time = startTime.toString() + ':' + endTime.toString()
  var traffic = ['Rent car', 'Taxi', 'Bus', 'Metro', 'Bike', 'Walk']
  var transportation = traffic[Math.floor(Math.random()*traffic.length)]
  var schedule = {
    Day: Day,
    budget: budget,
    place: place,
    time: time,
    transportation: transportation
  }
  setTimeout(function(){
    chat('CS_Grad_Trip',user, message, time)
    addSchedule('CS_Grad_Trip', schedule)

    canvas('CS_Grad_Trip')
    //clickonMap()
  }, duration * 1000)

  // simulate this person login
  // simulate this person logout after 'duration' seconds
  setTimeout(function(){
    //clickonMap()
   }, duration * 1000)

  // simulate this person login
  // simulate this person logout after 'duration' seconds
   setTimeout(function(){
    logout(user)
  }, duration * 1000)

}
function login(user){
  console.log('login', user)
  ref_User.once('value', function(snapshot){
    var users = snapshot.val()
    users = Object.keys(users)
    if (user in users){
      ref_User.child(user.name).update({status:online})
    }
    else{
      ref_User.child(user.name).set({
        name: user.name,
        status: user.status
      })
    }
  })

}

function logout(user){
  console.log('logout', user)
  ref_User.child(user.name).update({status: 'offline'});
}

function joinGroup(user, group){
  ref_Group.child(group).child('member').child(user.name).set({
    name: user.name,
    status: user.status
  })
}

function chat(group,user, message, time){
  console.log('chat', group,user,message,time)
  var chance = new Chance()
  ref_Group.child(group).child('Message').child(chance.word()).set({
  message: message,
  time: time,
  username:user.name
  })
}

function canvas(group){
  var x = Math.floor(Math.random() * (120 + 1));
  var y = Math.floor(Math.random() * (105 + 1));
  var curColor = randColor();
  var curSize = randSize();
  var curTool = randTool();
  if(curTool == 'Eraser'){
    curColor = 'fff';
    ref_Group.child(group).child('drawing').child(x+':'+y).set({
      curColor: curColor,
      curSize : curSize,
      curTool : curTool
    })
  }else if(curTool == 'Refresh'){
    ref_Group.child(group).child('drawing').remove();
  }else{
    ref_Group.child(group).child('drawing').child(x+':'+y).set({
      curColor: curColor,
      curSize : curSize,
      curTool : curTool
    })
  }
  console.log('canvas', x, ':', y, 'color:', curColor, 'size:', curSize, 'tool:', curTool)
}

function randSize(){
  var size = [
    'Small',
    'Medium',
    'Large'
  ];
  var rand = Math.floor(Math.random()*size.length);
  return size[rand]
}

function randTool(){
  var tool = [
    'Eraser',
    'Marker',
    'Refresh'
  ];
  var rand = Math.floor(Math.random()*tool.length);
  return tool[rand]
}

function randColor(){
  var colors = ["fff","000","f00","0f0","00f","88f","f8d","f88","f05","f80","0f8","cf0","08f","408","ff8","8ff", "aed081", "eee"];

  var rand = Math.floor(Math.random()*colors.length);
  return colors[rand]
}

function addSchedule(group, schedule){
  console.log('schedule', schedule)
  ref_Group.child(group).child('Schedule').once('value', function(snapshot){
    var D = snapshot.val()
    var key = Object.keys(D)
    if (key.indexOf(schedule.Day)>-1){
      ref_Group.child(group).child('Schedule').child(schedule.Day).child(schedule.time).set({
        budget: schedule.budget,
        place: schedule.place,
        transportation: schedule.transportation
      })
    }
    else{
      ref_Group.child(group).child('Schedule').child(schedule.Day).set(
        schedule.time)
      ref_Group.child(group).child('Schedule').child(schedule.Day).child(schedule.time).set({
          budget: schedule.budget,
          place: schedule.place,
          transportation: schedule.transportation
        })
    }
  })
}
// function clickonMap()
///-------------------------------------------------------------------------
// function Make_Group(groupName, key, userName){

//   ref_Group.child(groupName).set({
//     GroupName: groupName
//     Activation_key: key
//     Message: {
//       time: "Welcome to "+groupName
//     }
//     member: {
//       userName: userName
//       current_status: online
//     }
//   })
// }
// function Join_Group(groupName, key, userName){
//   ref_Group.child(groupName).child(Activation_key).once('value',function(snapshot){
//     var gold_answer = snapshot.value()
//   })
//   if(key != gold_answer){
//     alert('wrong password')
//   }
//   else{
//     ref_Group.child(groupName).child(member).child(userName).set({
//       userName: userName
//       current_status: online
//     })
//     if (ref_User.child(userName).child('groups')!=null){
//       ref_User.child(userName).child('groups').once('value',function(snapshot){
//         var key = snapshot.val()
//         key.push(groupName)
//         ref_User.child(userName).child('groups').set(key)
//       })
//     }
//     else{
//       ref_User.child(userName).child('groups').set([groupName])
//     }

// }

// run each second
setInterval(simulate, 2000)<|endoftext|>


<commit_before>/**
 * @name ContextProvider
 * @constructor
 * @extends Component
 * @param {object} props
 * @param {object} context
 */
function ContextProvider (props, context) {
	Component.call(this, props, context)
}
ContextProvider[SharedSitePrototype] = ObjectCreate(Component[SharedSitePrototype], {
	/**
	 * @alias ContextProvider#constructor
	 * @memberof ContextProvider
	 * @type {function}
	 * @this {Component}
	 */
	constructor: {
		value: ContextProvider
	},
	/**
	 * @alias ContextProvider#getInitialState
	 * @memberof ContextProvider
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @param {object} state
	 * @param {object} context
	 * @return {object}
	 */
	getInitialState: {
		value: function (props, state, context) {
			return this[SymbolForElement].cache = {provider: this, consumers: new List()}
		}
	},
	/**
	 * @alias ContextProvider#render
	 * @memberof ContextProvider
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @return {any}
	 */
	render: {
		value: function (props) {
			return props.children
		}
	},
	/**
	 * @alias ContextProvider#componentDidUpdate
	 * @memberof ContextProvider
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @param {object}
	 */
	componentDidUpdate: {
		value: function (props) {
			!is(this.props.value, props.value) && this.state.consumers.forEach(this.componentChildUpdate)
		}
	},
	/**
	 * @alias ContextProvider#componentChildUpdate
	 * @memberof ContextProvider
	 * @type {function}
	 * @param {Component} consumer
	 */
	componentChildUpdate: {
		value: function (consumer) {
			consumer.didUpdate = consumer.didUpdate ? false : !!consumer[SharedSiteForceUpdate]()
		}
	}
})

/**
 * @name ContextConsumer
 * @constructor
 * @extends Component
 * @param {object} props
 * @param {object} context
 */
function ContextConsumer (props, context) {
	Component.call(this, props, context)
}
ContextConsumer[SharedSitePrototype] = ObjectCreate(Component[SharedSitePrototype], {
	/**
	 * @alias ContextConsumer#constructor
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 */
	constructor: {
		value: ContextConsumer
	},
	/**
	 * @alias ContextConsumer#getInitialState
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @return {object}
	 */
	getInitialState: {
		value: function (props) {
			return this[SymbolForContext] || {provider: this}
		}
	},
	/**
	 * @alias ContextConsumer#render
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @param {object} state
	 * @return {any}
	 */
	render: {
		value: function (props, state) {
			return props.children(state.provider.props.value)
		}
	},
	/**
	 * @alias ContextConsumer#componentWillReceiveProps
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 */
	componentWillReceiveProps: {
		value: function () {
			this.didUpdate = true
		}
	},
	/**
	 * @alias ContextConsumer#componentDidMount
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 */
	componentDidMount: {
		value: function () {
			this.state.consumers && this.state.consumers.insert(this, this.state.consumers)
		}
	},
	/**
	 * @alias ContextConsumer#componentWillUnmount
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 */
	componentWillUnmount: {
		value: function () {
			this.state.consumers && this.state.consumers.remove(this)
		}
	}
})

/**
 * @param {any} value
 * @return {{Provider, Consumer}}
 * @public
 */
function createContext (value) {
	var
		Provider = createElement(ContextProvider, {value: value}),
		Consumer = createElement(ContextConsumer, {value: value, children: noop})

	Object.defineProperty(Provider, SharedPropTypes, {
		get: function () {
			return Provider.type[SharedPropTypes]
		},

		set: function (propTypes) {
			Provider.type[SharedPropTypes] = propTypes
		}
	})

	return {
		/**
		 * @type {Element}
		 */
		Provider: Provider,
		/**
		 * @type {Element}
		 */
		Consumer: Consumer
	}
}
<commit_msg>#76 fixed bug in Context.js<commit_after>/**
 * @name ContextProvider
 * @constructor
 * @extends Component
 * @param {object} props
 * @param {object} context
 */
function ContextProvider (props, context) {
	Component.call(this, props, context)
}
ContextProvider[SharedSitePrototype] = ObjectCreate(Component[SharedSitePrototype], {
	/**
	 * @alias ContextProvider#constructor
	 * @memberof ContextProvider
	 * @type {function}
	 * @this {Component}
	 */
	constructor: {
		value: ContextProvider
	},
	/**
	 * @alias ContextProvider#getInitialState
	 * @memberof ContextProvider
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @param {object} state
	 * @param {object} context
	 * @return {object}
	 */
	getInitialState: {
		value: function (props, state, context) {
			return this[SymbolForElement].cache = {provider: this, consumers: new List()}
		}
	},
	/**
	 * @alias ContextProvider#render
	 * @memberof ContextProvider
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @return {any}
	 */
	render: {
		value: function (props) {
			return props.children
		}
	},
	/**
	 * @alias ContextProvider#componentDidUpdate
	 * @memberof ContextProvider
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @param {object}
	 */
	componentDidUpdate: {
		value: function (props) {
			!is(this.props.value, props.value) && this.state.consumers.forEach(this.componentChildUpdate)
		}
	},
	/**
	 * @alias ContextProvider#componentChildUpdate
	 * @memberof ContextProvider
	 * @type {function}
	 * @param {Component} consumer
	 */
	componentChildUpdate: {
		value: function (consumer) {
			consumer.didUpdate = consumer.didUpdate ? false : !!consumer[SharedSiteForceUpdate]()
		}
	}
})

/**
 * @name ContextConsumer
 * @constructor
 * @extends Component
 * @param {object} props
 * @param {object} context
 */
function ContextConsumer (props, context) {
	Component.call(this, props, context)
}
ContextConsumer[SharedSitePrototype] = ObjectCreate(Component[SharedSitePrototype], {
	/**
	 * @alias ContextConsumer#constructor
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 */
	constructor: {
		value: ContextConsumer
	},
	/**
	 * @alias ContextConsumer#getInitialState
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @return {object}
	 */
	getInitialState: {
		value: function (props) {
			return this[SymbolForContext] || {provider: this}
		}
	},
	/**
	 * @alias ContextConsumer#render
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 * @param {object} props
	 * @param {object} state
	 * @return {any}
	 */
	render: {
		value: function (props, state) {
			return props.children(state.provider.props.value)
		}
	},
	/**
	 * @alias ContextConsumer#componentWillReceiveProps
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 */
	componentWillReceiveProps: {
		value: function () {
			this.didUpdate = true
		}
	},
	/**
	 * @alias ContextConsumer#componentDidMount
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 */
	componentDidMount: {
		value: function () {
			this.state.consumers && this.state.consumers.insert(this, this.state.consumers)
		}
	},
	/**
	 * @alias ContextConsumer#componentWillUnmount
	 * @memberof ContextConsumer
	 * @type {function}
	 * @this {Component}
	 */
	componentWillUnmount: {
		value: function () {
			this.state.consumers && this.state.consumers.remove(this)
		}
	}
})

/**
 * @param {any} value
 * @return {{Provider, Consumer}}
 * @public
 */
function createContext (value) {
	var CustomContextProvider, Provider, Consumer

	CustomContextProvider = function (props, context) {
		ContextProvider.call(this, props, context)
	}

	CustomContextProvider[SharedSitePrototype] =
		ObjectCreate(ContextProvider[SharedSitePrototype])

	CustomContextProvider.displayName = 'ContextProvider'

	Provider = createElement(CustomContextProvider, {value: value}),
	Consumer = createElement(ContextConsumer, {value: value, children: noop})

	Object.defineProperty(Provider, SharedPropTypes, {
		get: function () {
			return CustomContextProvider[SharedPropTypes]
		},

		set: function (propTypes) {
			CustomContextProvider[SharedPropTypes] = propTypes
		}
	})

	return {
		/**
		 * @type {Element}
		 */
		Provider: Provider,
		/**
		 * @type {Element}
		 */
		Consumer: Consumer
	}
}
<|endoftext|>


<commit_before>
jQuery(document).ready(function($) {
    var jcrop_api;

    $.ajaxSetup({
        type: "POST",
        url: _hh_ajax_fe_profile.ajaxurl
    });

    if ( $('#profile-editor-container').length ) hh_profile_edit_ajax_load_template();

    $(document).on('submit','.hh-update-profile',function(e) {
        e.preventDefault();

        var formfield = $(this).attr('data-meta_key');
        var $formfield = $('#main-'+formfield);
        var meta_key = $formfield.attr('data-meta_key');  console.log('meta_key: '+meta_key);
        var nonce = $formfield.attr('data-nonce');  console.log('nonce: '+nonce);
        var meta_value = $('#input-'+meta_key).val();  console.log('meta_value: '+meta_value);

        $.ajax({
            dataType : "json",
            data : {action: "hh_update_user_profile", meta_key : meta_key, meta_value : meta_value, nonce: nonce},
            beforeSend: function() {
                edit_stop(meta_key);
                edit_alert_show(meta_key,'info','Submitting Request...',true);
                $('.edit-field').addClass('disabled');
            },
            complete: function() {
                edit_stop(meta_key);
                $('#message-'+meta_key).hide();
            },
            success: function(response) {
                var $data = $('#data-'+meta_key);
                $data.html(response.new_value);
                $('Updated').insertAfter('#data-'+meta_key);
                $('.fadeOut').fadeOut(1600,function(){
                    $(this).remove();
                    $('.edit-field').removeClass('disabled');
                });
            },
            error: function () {
                var $data = $('#data-'+meta_key);
                $('Failed!!').insertAfter('#data-'+meta_key);
                $('.fadeOut').fadeOut(2600,function(){
                    $(this).remove();
                    $('.edit-field').removeClass('disabled');
                });
            }
        });
    });

    $(document).on('click','.edit-field', function() {
        if ( $(this).hasClass('disabled') ) return;
        edit_start($(this).attr('data-meta_key'));
    });

    $(document).on('click','.pr-cancel', function() {
        edit_stop($(this).attr('data-meta_key'));
    });

    function edit_start(meta_key) {
        $('#current_meta_key').val(meta_key);
        $('#'+meta_key).show();
        $('#main-'+meta_key).addClass('edit-highlight');
        $('#swap-'+meta_key).hide();
        $('#pad-'+meta_key).addClass('field-highlight').css('padding','0');
        $('#controls-'+meta_key).show().css('height','auto');
        $('#input-'+meta_key).focus();
    }
    function edit_stop(meta_key) {
        $('#'+meta_key).removeAttr('style');
        $('#input-'+meta_key).val($('#data-'+meta_key).text());
        $('#main-'+meta_key).removeClass('edit-highlight').removeAttr('style');
        $('#pad-'+meta_key).removeClass('field-highlight').removeAttr('style');
        $('#swap-'+meta_key).removeAttr('style');
        $('#controls-'+meta_key).removeAttr('style');
    }

    function edit_alert_show(meta_key,type,message,show_process) {
        $('#main-'+meta_key).addClass('disabled');
        $('#pad-'+meta_key).hide();
        var processing_img = $('#hh_update_profile').attr('data-processing-uri');
        var msg  = '
';
        msg  += '
'+message+'
';
        if (show_process) {
            msg += '';
        }
        msg += '
';
        $('#message-'+meta_key).html(msg).show();
    }

    $(document).on('click','#hh-change-profile-photo',function(e) {
        e.preventDefault();
        $('#fileUpload-container').show();
        $('.edit-field').addClass('disabled');
    });

    $(document).on('click','.close-fileUpload-container',function() {
        var previewFields = $('.fileUpload-preview');
        var selectFields = $('.fileUpload-select');
        var errorFields = $('.fileUpload-error');
        var cropFields = $('.fileUpload-crop');
        selectFields.hide();
        cropFields.hide();
        $('#fileUpload-canvas').removeAttr('style');
        previewFields.hide().removeAttr('style');
        errorFields.hide();
        selectFields.show();
        jcrop_api.destroy();
        $('#fileUpload-container').hide();
        $('.edit-field').removeClass('disabled');
    });

    $(document).on('click','.reset-fileUpload-container',function() {
        var previewFields = $('.fileUpload-preview');
        var selectFields = $('.fileUpload-select');
        var errorFields = $('.fileUpload-error');
        var cropFields = $('.fileUpload-crop');
        selectFields.hide();
        cropFields.hide();
        previewFields.hide().removeAttr('style');
        $('#fileUpload-canvas').removeAttr('style');
        errorFields.hide();
        selectFields.show();
        if (jcrop_api) {
            jcrop_api.destroy();
        }

    });

    $(document).on('change','#fileUpload-file', function() {
        if (jcrop_api) {
            jcrop_api.destroy();
        }
        var fileData = $('#fileUpload-fileData');
        var filePreview = $('#fileUpload-preview');
        var previewFields = $('.fileUpload-preview');
        var selectFields = $('.fileUpload-select');
        var errorFields = $('.fileUpload-error');
        var cropFields = $('.fileUpload-crop');
        selectFields.hide();
        cropFields.hide();
        previewFields.hide();
        errorFields.hide();
        filePreview.removeAttr('style');

        var file = this.files[0];
        var valid_exts = ['jpeg', 'jpg', 'png', 'gif']; // valid extensions
        var ext = file.name.split('.').pop().toLowerCase();
        if (valid_exts.indexOf(ext) > -1) {
            if (file.size < 1048576) {
                fileData.html(file.name+' ('+bytesToSize(file.size)+')');
                /* html FileRender Api */
                var oFReader = new FileReader();
                oFReader.readAsDataURL(document.getElementById("fileUpload-file").files[0]);
                oFReader.onload = function (oFREvent) {
                    previewFields.show();
                    filePreview.css('visibility', 'visible');
                    filePreview.attr('src', oFREvent.target.result).fadeIn();
                    cropFields.show();
                    $editImage = $('#fileUpload-preview');
                    $canvas = $('#fileUpload-canvas');
                    $editImage.Jcrop({
                        setSelect: [100,100,400,400],
                        minSize: [150,150],
                        aspectRatio: 1,
                        boxHeight: $canvas.height(),
                        boxWidth: $canvas.width()
                    },function() {
                        jcrop_api = this;
                        $canvas.width(jcrop_api.getWidgetSize()[0]);
                        $canvas.height(jcrop_api.getWidgetSize()[1]);
                    });

                }
            } else {
                errorFields.fadeIn();
                $('#fileUpload-errorMessage').html('Too big!
 (Your file must be less than 1MB in size)');
            }
        } else {
            errorFields.fadeIn();
            $('#fileUpload-errorMessage').html('Invalid Filetype!
 (Only jpeg, jpg, png, gif are supported)');
        }
    });

    /**
     * Save Cropped Photo
     */
    $(document).on('submit','.hh-update-profile-photo',function(e) {

        //close the cropping tool.

        //ajax save the cropped file - hh_save_profile_pic()

        //ajax return the new file to the form

    });

});

window.hh_profile_edit_ajax_load_template = function () {
    jQuery(document).ready(function($) {
        $.ajax({
            dataType : "html",
            data: { action: "hh_ajax_load_profile_editor" },
            success: function (data) {
                $('#profile-editor-preloader').fadeOut('fast');
                $('#profile-editor-container').fadeIn('slow').html(data);
            }
        });

    });
};

window.fileUpload_select = function () {
    jQuery.trigger('#fileUpload-file','click')
}<commit_msg>size box<commit_after>
jQuery(document).ready(function($) {
    var jcrop_api;

    $.ajaxSetup({
        type: "POST",
        url: _hh_ajax_fe_profile.ajaxurl
    });

    if ( $('#profile-editor-container').length ) hh_profile_edit_ajax_load_template();

    $(document).on('submit','.hh-update-profile',function(e) {
        e.preventDefault();

        var formfield = $(this).attr('data-meta_key');
        var $formfield = $('#main-'+formfield);
        var meta_key = $formfield.attr('data-meta_key');  console.log('meta_key: '+meta_key);
        var nonce = $formfield.attr('data-nonce');  console.log('nonce: '+nonce);
        var meta_value = $('#input-'+meta_key).val();  console.log('meta_value: '+meta_value);

        $.ajax({
            dataType : "json",
            data : {action: "hh_update_user_profile", meta_key : meta_key, meta_value : meta_value, nonce: nonce},
            beforeSend: function() {
                edit_stop(meta_key);
                edit_alert_show(meta_key,'info','Submitting Request...',true);
                $('.edit-field').addClass('disabled');
            },
            complete: function() {
                edit_stop(meta_key);
                $('#message-'+meta_key).hide();
            },
            success: function(response) {
                var $data = $('#data-'+meta_key);
                $data.html(response.new_value);
                $('Updated').insertAfter('#data-'+meta_key);
                $('.fadeOut').fadeOut(1600,function(){
                    $(this).remove();
                    $('.edit-field').removeClass('disabled');
                });
            },
            error: function () {
                var $data = $('#data-'+meta_key);
                $('Failed!!').insertAfter('#data-'+meta_key);
                $('.fadeOut').fadeOut(2600,function(){
                    $(this).remove();
                    $('.edit-field').removeClass('disabled');
                });
            }
        });
    });

    $(document).on('click','.edit-field', function() {
        if ( $(this).hasClass('disabled') ) return;
        edit_start($(this).attr('data-meta_key'));
    });

    $(document).on('click','.pr-cancel', function() {
        edit_stop($(this).attr('data-meta_key'));
    });

    function edit_start(meta_key) {
        $('#current_meta_key').val(meta_key);
        $('#'+meta_key).show();
        $('#main-'+meta_key).addClass('edit-highlight');
        $('#swap-'+meta_key).hide();
        $('#pad-'+meta_key).addClass('field-highlight').css('padding','0');
        $('#controls-'+meta_key).show().css('height','auto');
        $('#input-'+meta_key).focus();
    }
    function edit_stop(meta_key) {
        $('#'+meta_key).removeAttr('style');
        $('#input-'+meta_key).val($('#data-'+meta_key).text());
        $('#main-'+meta_key).removeClass('edit-highlight').removeAttr('style');
        $('#pad-'+meta_key).removeClass('field-highlight').removeAttr('style');
        $('#swap-'+meta_key).removeAttr('style');
        $('#controls-'+meta_key).removeAttr('style');
    }

    function edit_alert_show(meta_key,type,message,show_process) {
        $('#main-'+meta_key).addClass('disabled');
        $('#pad-'+meta_key).hide();
        var processing_img = $('#hh_update_profile').attr('data-processing-uri');
        var msg  = '
';
        msg  += '
'+message+'
';
        if (show_process) {
            msg += '';
        }
        msg += '
';
        $('#message-'+meta_key).html(msg).show();
    }

    $(document).on('click','#hh-change-profile-photo',function(e) {
        e.preventDefault();
        $('#fileUpload-container').show();
        $('.edit-field').addClass('disabled');
    });

    $(document).on('click','.close-fileUpload-container',function() {
        var previewFields = $('.fileUpload-preview');
        var selectFields = $('.fileUpload-select');
        var errorFields = $('.fileUpload-error');
        var cropFields = $('.fileUpload-crop');
        selectFields.hide();
        cropFields.hide();
        $('#fileUpload-canvas').removeAttr('style');
        previewFields.hide().removeAttr('style');
        errorFields.hide();
        selectFields.show();
        jcrop_api.destroy();
        $('#fileUpload-container').hide();
        $('.edit-field').removeClass('disabled');
    });

    $(document).on('click','.reset-fileUpload-container',function() {
        var previewFields = $('.fileUpload-preview');
        var selectFields = $('.fileUpload-select');
        var errorFields = $('.fileUpload-error');
        var cropFields = $('.fileUpload-crop');
        selectFields.hide();
        cropFields.hide();
        previewFields.hide().removeAttr('style');
        $('#fileUpload-canvas').removeAttr('style');
        errorFields.hide();
        selectFields.show();
        if (jcrop_api) {
            jcrop_api.destroy();
        }

    });

    $(document).on('change','#fileUpload-file', function() {
        if (jcrop_api) {
            jcrop_api.destroy();
        }
        var fileData = $('#fileUpload-fileData');
        var filePreview = $('#fileUpload-preview');
        var previewFields = $('.fileUpload-preview');
        var selectFields = $('.fileUpload-select');
        var errorFields = $('.fileUpload-error');
        var cropFields = $('.fileUpload-crop');
        selectFields.hide();
        cropFields.hide();
        previewFields.hide();
        errorFields.hide();
        filePreview.removeAttr('style');

        var file = this.files[0];
        var valid_exts = ['jpeg', 'jpg', 'png', 'gif']; // valid extensions
        var ext = file.name.split('.').pop().toLowerCase();
        if (valid_exts.indexOf(ext) > -1) {
            if (file.size < 1048576) {
                fileData.html(file.name+' ('+bytesToSize(file.size)+')');
                /* html FileRender Api */
                var oFReader = new FileReader();
                oFReader.readAsDataURL(document.getElementById("fileUpload-file").files[0]);
                oFReader.onload = function (oFREvent) {
                    previewFields.show();
                    filePreview.css('visibility', 'visible');
                    filePreview.attr('src', oFREvent.target.result).fadeIn();
                    cropFields.show();
                    $editImage = $('#fileUpload-preview');
                    $canvas = $('#fileUpload-canvas');
                    $editImage.Jcrop({
                        setSelect: [100,100,400,400],
                        minSize: [150,150],
                        aspectRatio: 1,
                        boxWidth: $canvas.width()
                    },function() {
                        jcrop_api = this;
                        $canvas.width(jcrop_api.getWidgetSize()[0]);
                        $canvas.height(jcrop_api.getWidgetSize()[1]);
                    });

                }
            } else {
                errorFields.fadeIn();
                $('#fileUpload-errorMessage').html('Too big!
 (Your file must be less than 1MB in size)');
            }
        } else {
            errorFields.fadeIn();
            $('#fileUpload-errorMessage').html('Invalid Filetype!
 (Only jpeg, jpg, png, gif are supported)');
        }
    });

    /**
     * Save Cropped Photo
     */
    $(document).on('submit','.hh-update-profile-photo',function(e) {

        //close the cropping tool.

        //ajax save the cropped file - hh_save_profile_pic()

        //ajax return the new file to the form

    });

});

window.hh_profile_edit_ajax_load_template = function () {
    jQuery(document).ready(function($) {
        $.ajax({
            dataType : "html",
            data: { action: "hh_ajax_load_profile_editor" },
            success: function (data) {
                $('#profile-editor-preloader').fadeOut('fast');
                $('#profile-editor-container').fadeIn('slow').html(data);
            }
        });

    });
};

window.fileUpload_select = function () {
    jQuery.trigger('#fileUpload-file','click')
}<|endoftext|>


<commit_before>var dataRef = new Firebase("https://sudarshan.firebaseio.com/");
var ytplayer = null;
var mp4player = null;

var roomName = null;
var tokboxSession = null;
var tokboxToken = null;

var disableUntil;

var last_in = null;

function makeRoom (name) {
  $.getJSON("http://www.smuralidhar.com/pennapps2014s/generate.php", function(res){
    dataRef = dataRef.root();
    dataRef = dataRef.child(name);
    dataRef.on('value', incoming);
    dataRef.update(
      {"type": null, "video": null, seek: 0, timestamp: now(), playing: false, "sessionId": res.sessionId, "token": res.token}
  );
  });
}

function joinRoom (name) {
  dataRef = dataRef.root();
  dataRef = dataRef.child(name);
  dataRef.on('value', incoming);
}

function incoming (fb) {
  var data = fb.val();
  last_in = data;
  console.log("inc");
  console.log(data);

  if (data == null){
    alert("room does not exist");
  }

  if (roomName == null){
    roomName = name;
    tokboxSession = data.sessionId;
    tokboxToken = data.token;
    showWelcomeMessage();
  }

  if (data.type == "YT") {
    if (ytplayer == null)
      makeYtPlayer(data.video);
    else
      handleYtInc(data);
  }
  else if (data.type == "mp4"){
    if (mp4player == null)
      makeMp4Player(data);
    else
      handleMp4Inc(data);
  }
}

function outgoing (playing, seek) {
  console.log("out");
  console.log({playing:playing, seek:seek});
  dataRef.update(
    {playing: playing, seek: seek, timestamp: now()}
  );
}

function showWelcomeMessage () {
  $("#inputs").html("Choose a video: "+
    "<input id='vid' type='text' placeholder='Choose a video'></input>" +
    "<button id='choose'>Load</button>");
  $("#choose").click(function(){
    var vid = $("#vid")[0].value + "#";
    if (vid.indexOf("youtube.com")>-1){
      var key = vid.substring(vid.indexOf("v=")+2, vid.indexOf("#"));
      var type = "YT";
      dataRef.update({type: type, video: key});
    }
    else if (vid.indexOf(".mp4") > -1){
      dataRef.update({type:"mp4", video: $("#vid")[0].value});
    }
    else
      alert ("link not recognized");
  });
}

function makeYtPlayer(vid) {
  disableUntil = -1;
  var params = { allowScriptAccess: "always" };
  var atts = { id: "myytplayer" };
  swfobject.embedSWF("http://www.youtube.com/v/" + vid + "?version=3&controls=1&enablejsapi=1&playerapiid=ytplayer&allowfullscreen=1",
    "ytapiplayer", "80%", "80%", "8", null, null, params, atts);
}
function makeMp4Player(data) {
  disableUntil = null;
  jwplayer("ytapiplayer").setup({file: data.video, width: "100%", height: "100%"});
  mp4player = jwplayer();
  mp4player.onReady(function() {
    var instastop = true;
    mp4player.onPlay(function(){
      if (instastop){
        console.log('setup');
        instastop = false;
        mp4player.pause(true);

        //mp4player.onSeek(mp4SeekListener);
        mp4player.onPlay(function() {mp4PlayPauseListener(true)});
        mp4player.onPause(function() {mp4PlayPauseListener(false)});

        handleMp4Inc(data);
      }
    })
    mp4player.play(true);
  })
}

function onYouTubePlayerReady(playerId) {
  ytplayer = $("#myytplayer")[0];
  ytplayer.addEventListener("onStateChange", "ytListener");

  handleYtInc(last_in);

  setInterval(function(){
    dataRef.once('value', function(data){
      var pres = now();
      var curr = ytplayer.getCurrentTime();
      data = data.val();
      if (data.playing)
        loc = data.seek + pres - data.timestamp;
      else
        loc = data.seek;
      var playing = ytplayer.getPlayerState() == 1;

      //console.log(curr - loc);
      if (Math.abs (curr - loc) > 0.5 ||
          data.playing != playing)
        handleYtInc(data);
    })
  }, 2000);
}

function handleYtInc(data) {
  // disable the listener until state is correct
  if (data.playing)
    disableUntil = 1;
  else
    disableUntil = 2;

  if (data.playing)
    data.seek += now() - data.timestamp;

  ytplayer.seekTo(data.seek);

  if (data.playing)
    ytplayer.playVideo();
  else
    ytplayer.pauseVideo();
}

function handleMp4Inc(data) {
  console.log("HANDLE");
  disableUntil = data.playing;
  if (data.playing)
    data.seek += now() - data.timestamp;

  //mp4player.seek(data.seek);

  mp4player.play(data.playing);

  setTimeout(hack, 100);

  function hack (){
    console.log("hacking");
    if (disableUntil == data.playing){
      mp4player.play(data.playing);
      setTimeout(hack, 100);
    }
  }

  console.log('done handle');
}

function ytListener (value){
  if (disableUntil > -1){
    console.log("ignoring- " + value);
    if (disableUntil == value)
      disableUntil = -1;
    return;
  }
  switch (value) {
    case -1:
      console.log("unstarted");
      disableUntil = 2;
      ytplayer.seekTo(0);
      ytplayer.pauseVideo();
      break;
    case 0:
      console.log("ended");
      break;
    case 1:
      console.log("playing");
      disableUntil = 1;
      ytplayer.pauseVideo();
      outgoing (true, ytplayer.getCurrentTime());
      break;
    case 2:
      console.log("paused");
      disableUntil = 2;
      ytplayer.playVideo();
      outgoing (false, ytplayer.getCurrentTime());
      break;
    case 3:
      console.log("buffering");
      break;
    case 5:
      console.log("cued");
      break;
  }
}

function mp4PlayPauseListener (play){
  if (disableUntil != null){
    console.log("ignoring " + play)
    if (disableUntil == play)
      disableUntil = null;
    return;
  }

  console.log(play);
  disableUntil = play;

  mp4player.pause(play);
  outgoing (play, mp4player.getPosition());
}

function now () {
  return new Date().getTime() / 1000;
}

$(document).ready (function() {
  $("#create").click(function() {
    makeRoom($("#room")[0].value)
  });
  $("#join").click(function() {
    joinRoom($("#room")[0].value)
  });
})
<commit_msg>youtube div<commit_after>var dataRef = new Firebase("https://sudarshan.firebaseio.com/");
var ytplayer = null;
var mp4player = null;

var roomName = null;
var tokboxSession = null;
var tokboxToken = null;

var disableUntil;

var last_in = null;

function makeRoom (name) {
  $.getJSON("http://www.smuralidhar.com/pennapps2014s/generate.php", function(res){
    dataRef = dataRef.root();
    dataRef = dataRef.child(name);
    dataRef.on('value', incoming);
    dataRef.update(
      {"type": null, "video": null, seek: 0, timestamp: now(), playing: false, "sessionId": res.sessionId, "token": res.token}
  );
  });
}

function joinRoom (name) {
  dataRef = dataRef.root();
  dataRef = dataRef.child(name);
  dataRef.on('value', incoming);
}

function incoming (fb) {
  var data = fb.val();
  last_in = data;
  console.log("inc");
  console.log(data);

  if (data == null){
    alert("room does not exist");
  }

  if (roomName == null){
    roomName = name;
    tokboxSession = data.sessionId;
    tokboxToken = data.token;
    showWelcomeMessage();
  }

  if (data.type == "YT") {
    if (ytplayer == null)
      makeYtPlayer(data.video);
    else
      handleYtInc(data);
  }
  else if (data.type == "mp4"){
    if (mp4player == null)
      makeMp4Player(data);
    else
      handleMp4Inc(data);
  }
}

function outgoing (playing, seek) {
  console.log("out");
  console.log({playing:playing, seek:seek});
  dataRef.update(
    {playing: playing, seek: seek, timestamp: now()}
  );
}

function showWelcomeMessage () {
  $("#inputs").html("Choose a video: "+
    "<input id='vid' type='text' placeholder='Choose a video'></input>" +
    "<button id='choose'>Load</button>");
  $("#choose").click(function(){
    var vid = $("#vid")[0].value + "#";
    if (vid.indexOf("youtube.com")>-1){
      var key = vid.substring(vid.indexOf("v=")+2, vid.indexOf("#"));
      var type = "YT";
      dataRef.update({type: type, video: key});
    }
    else if (vid.indexOf(".mp4") > -1){
      dataRef.update({type:"mp4", video: $("#vid")[0].value});
    }
    else
      alert ("link not recognized");
  });
}

function makeYtPlayer(vid) {
  disableUntil = -1;
  var params = { allowScriptAccess: "always" };
  var atts = { id: "myytplayer" };
  swfobject.embedSWF("http://www.youtube.com/v/" + vid + "?version=3&controls=1&enablejsapi=1&playerapiid=ytplayer&allowfullscreen=1",
    "ytapiplayer", "100%", "100%", "8", null, null, params, atts);
}
function makeMp4Player(data) {
  disableUntil = null;
  jwplayer("ytapiplayer").setup({file: data.video, width: "80%", height: "80%"});
  mp4player = jwplayer();
  mp4player.onReady(function() {
    var instastop = true;
    mp4player.onPlay(function(){
      if (instastop){
        console.log('setup');
        instastop = false;
        mp4player.pause(true);

        //mp4player.onSeek(mp4SeekListener);
        mp4player.onPlay(function() {mp4PlayPauseListener(true)});
        mp4player.onPause(function() {mp4PlayPauseListener(false)});

        handleMp4Inc(data);
      }
    })
    mp4player.play(true);
  })
}

function onYouTubePlayerReady(playerId) {
  ytplayer = $("#myytplayer")[0];
  ytplayer.addEventListener("onStateChange", "ytListener");

  handleYtInc(last_in);

  setInterval(function(){
    dataRef.once('value', function(data){
      var pres = now();
      var curr = ytplayer.getCurrentTime();
      data = data.val();
      if (data.playing)
        loc = data.seek + pres - data.timestamp;
      else
        loc = data.seek;
      var playing = ytplayer.getPlayerState() == 1;

      //console.log(curr - loc);
      if (Math.abs (curr - loc) > 0.5 ||
          data.playing != playing)
        handleYtInc(data);
    })
  }, 2000);
}

function handleYtInc(data) {
  // disable the listener until state is correct
  if (data.playing)
    disableUntil = 1;
  else
    disableUntil = 2;

  if (data.playing)
    data.seek += now() - data.timestamp;

  ytplayer.seekTo(data.seek);

  if (data.playing)
    ytplayer.playVideo();
  else
    ytplayer.pauseVideo();
}

function handleMp4Inc(data) {
  console.log("HANDLE");
  disableUntil = data.playing;
  if (data.playing)
    data.seek += now() - data.timestamp;

  //mp4player.seek(data.seek);

  mp4player.play(data.playing);

  setTimeout(hack, 100);

  function hack (){
    console.log("hacking");
    if (disableUntil == data.playing){
      mp4player.play(data.playing);
      setTimeout(hack, 100);
    }
  }

  console.log('done handle');
}

function ytListener (value){
  if (disableUntil > -1){
    console.log("ignoring- " + value);
    if (disableUntil == value)
      disableUntil = -1;
    return;
  }
  switch (value) {
    case -1:
      console.log("unstarted");
      disableUntil = 2;
      ytplayer.seekTo(0);
      ytplayer.pauseVideo();
      break;
    case 0:
      console.log("ended");
      break;
    case 1:
      console.log("playing");
      disableUntil = 1;
      ytplayer.pauseVideo();
      outgoing (true, ytplayer.getCurrentTime());
      break;
    case 2:
      console.log("paused");
      disableUntil = 2;
      ytplayer.playVideo();
      outgoing (false, ytplayer.getCurrentTime());
      break;
    case 3:
      console.log("buffering");
      break;
    case 5:
      console.log("cued");
      break;
  }
}

function mp4PlayPauseListener (play){
  if (disableUntil != null){
    console.log("ignoring " + play)
    if (disableUntil == play)
      disableUntil = null;
    return;
  }

  console.log(play);
  disableUntil = play;

  mp4player.pause(play);
  outgoing (play, mp4player.getPosition());
}

function now () {
  return new Date().getTime() / 1000;
}

$(document).ready (function() {
  $("#create").click(function() {
    makeRoom($("#room")[0].value)
  });
  $("#join").click(function() {
    joinRoom($("#room")[0].value)
  });
})
<|endoftext|>


<commit_before>const path = require('path')
const { src, dest, parallel } = require('gulp')
const modify = require('gulp-modify-file')
const rename = require('gulp-rename')
const zip = require('gulp-zip')
const { promisifyVinyl } = require('./util')

/*
assumes everything already built
*/
exports.archive = parallel(
  writeStandardArchive,
  writePremiumArchive
)

function writeStandardArchive() {
  return writeArchive({
    archiveName: 'fullcalendar',
    pkgFiles: [
      'packages/*/dist/**'
    ],
    exampleHtmlFiles: [
      '*.html',
      '!*+(resource|timeline)*.html',
      '!_*.html'
    ],
    exampleOtherFiles: [
      'js/*',
      'json/*',
      '!json/*resource*.json',
      'php/*'
    ],
    topLevelFiles: [
      'README.md',
      'LICENSE.txt'
    ]
  })
}

function writePremiumArchive() {
  return writeArchive({
    archiveName: 'fullcalendar-scheduler',
    pkgFiles: [
      'packages?(-premium)/*/dist/**'
    ],
    exampleHtmlFiles: [
      '*+(resource|timeline)*.html',
      '!_*.html'
    ],
    exampleOtherFiles: [
      'js/*',
      'json/*'
    ],
    topLevelFiles: [
      'packages-premium/README.md',
      'packages-premium/LICENSE.md'
    ]
  })
}

function writeArchive(options) {
  let version = require(path.join(process.cwd(), 'package.json')).version

  return writeArchiveFiles(options).then(function(tmpDir) {
    return promisifyVinyl(
      src(tmpDir + '/**')
        .pipe(zip(options.archiveName + '-' + version + '.zip'))
        .pipe(dest('archives'))
    )
  })
}

function writeArchiveFiles(options) {
  let tmpDir = path.join('tmp/archives', options.archiveName)

  // packages/whatever/dist/file.js -> packages/whatever/file.js
  let writingPkgs = promisifyVinyl(
    src(
      options.pkgFiles.concat([ '!**/dist' ]), // hack to prevent empty dist dir
      { base: '.' }
    ).pipe(
      rename((pathParts) => {
        pathParts.dirname = transformPkgPath(pathParts.dirname)
      })
    ).pipe(dest(tmpDir))
  )

  let writingOtherExampleFiles = promisifyVinyl(
    src(options.exampleOtherFiles, { cwd: 'examples', base: '.' })
      .pipe(dest(tmpDir))
  )

  let writingTopLevelFiles = promisifyVinyl(
    src(options.topLevelFiles)
      .pipe(dest(tmpDir))
  )

  return Promise.all([
    writingPkgs,
    writeExampleHtmlAndVendor(options.exampleHtmlFiles, tmpDir),
    writingOtherExampleFiles,
    writingTopLevelFiles
  ]).then(function() {
    return tmpDir
  })
}

function writeExampleHtmlAndVendor(exampleHtmlFiles, tmpDir) {
  let vendorPaths = []

  let writingExampleHtmlFiles = promisifyVinyl(
    src(exampleHtmlFiles, { cwd: 'examples', base: '.' })
      .pipe(modify(replaceContent))
      .pipe(dest(tmpDir))
  )

  function replaceContent(content) {
    return content.replace(
      /((?:src|href)=['"])([^'"]*)(['"])/g,
      function(m0, m1, m2, m3) {
        return m1 + transformResourcePath(m2) + m3
      }
    )
  }

  function transformResourcePath(resourcePath) {

    if (resourcePath.indexOf('../packages') === 0) { // one of our package files
      resourcePath = transformPkgPath(resourcePath)
    }

    resourcePath = resourcePath.replace(
      /^\.\.\/(node_modules\/.*\/([^/]+))$/,
      function(m0, m1, m2) {
        vendorPaths.push(m1) // the path on the filesystem from proj root
        return '../vendor/' + m2 // how the html file will reference it
      }
    )

    return resourcePath
  }

  return writingExampleHtmlFiles.then(function() {
    if (vendorPaths.length) {
      return promisifyVinyl(
        src(vendorPaths)
          .pipe(dest(tmpDir + '/vendor'))
      )
    }
  })
}

function transformPkgPath(path) {
  return path.replace(/(^|\/)dist(\/|$)/, '$2')
}
<commit_msg>adjust archive script<commit_after>const path = require('path')
const { src, dest, parallel } = require('gulp')
const modify = require('gulp-modify-file')
const rename = require('gulp-rename')
const zip = require('gulp-zip')
const { promisifyVinyl } = require('./util')

/*
assumes everything already built
*/
exports.archive = parallel(
  writeStandardArchive,
  writePremiumArchive
)

function writeStandardArchive() {
  return writeArchive({
    archiveName: 'fullcalendar',
    bundleDir: 'packages/bundle',
    exampleHtmlFiles: [
      '*.html',
      '!*+(resource|timeline)*.html',
      '!_*.html'
    ],
    exampleOtherFiles: [
      'js/*',
      'json/*',
      '!json/*resource*.json',
      'php/*'
    ],
    topLevelFiles: [
      'README.md',
      'LICENSE.txt'
    ]
  })
}

/*
TODO: for examples, instead of looking for (resource|timeline) in the filename,
leverage whether the html file includes packages-premium/bundle or not.
*/
function writePremiumArchive() {
  return writeArchive({
    archiveName: 'fullcalendar-scheduler',
    bundleDir: 'packages-premium/bundle',
    exampleHtmlFiles: [
      '*+(resource|timeline)*.html',
      '!_*.html'
    ],
    exampleOtherFiles: [
      'js/*',
      'json/*'
    ],
    topLevelFiles: [
      'packages-premium/README.md',
      'packages-premium/LICENSE.md'
    ]
  })
}

function writeArchive(options) {
  let version = require(path.join(process.cwd(), 'package.json')).version

  return writeArchiveFiles(options).then(function(tmpDir) {
    return promisifyVinyl(
      src(tmpDir + '/**')
        .pipe(zip(options.archiveName + '-' + version + '.zip'))
        .pipe(dest('archives'))
    )
  })
}

function writeArchiveFiles(options) {
  let bundleDistDir = path.join(options.bundleDir, 'dist')
  let tmpDir = path.join('tmp/archives', options.archiveName)

  let writingPkgs = promisifyVinyl(
    src('**', { cwd: bundleDistDir, base: bundleDistDir }).pipe(
      dest(path.join(tmpDir, 'lib'))
    )
  )

  let writingOtherExampleFiles = promisifyVinyl(
    src(options.exampleOtherFiles, { cwd: 'examples', base: '.' })
      .pipe(dest(tmpDir))
  )

  let writingTopLevelFiles = promisifyVinyl(
    src(options.topLevelFiles)
      .pipe(dest(tmpDir))
  )

  return Promise.all([
    writingPkgs,
    writeExampleHtmlAndVendor(options.exampleHtmlFiles, tmpDir),
    writingOtherExampleFiles,
    writingTopLevelFiles
  ]).then(function() {
    return tmpDir
  })
}

function writeExampleHtmlAndVendor(exampleHtmlFiles, tmpDir) {
  let vendorPaths = []

  let writingExampleHtmlFiles = promisifyVinyl(
    src(exampleHtmlFiles, { cwd: 'examples', base: '.' })
      .pipe(modify(replaceContent))
      .pipe(dest(tmpDir))
  )

  function replaceContent(content) {
    return content.replace(
      /((?:src|href)=['"])([^'"]*)(['"])/g,
      function(m0, m1, m2, m3) {
        return m1 + transformResourcePath(m2) + m3
      }
    )
  }

  function transformResourcePath(resourcePath) {

    resourcePath = resourcePath.replace(
      /^\.\.\/packages(-premium)?\/bundle\/dist\b/,
      '../lib'
    )

    resourcePath = resourcePath.replace(
      /^\.\.\/(node_modules\/.*\/([^/]+))$/,
      function(m0, m1, m2) {
        vendorPaths.push(m1) // the path on the filesystem from proj root
        return '../vendor/' + m2 // how the html file will reference it
      }
    )

    return resourcePath
  }

  return writingExampleHtmlFiles.then(function() {
    if (vendorPaths.length) {
      return promisifyVinyl(
        src(vendorPaths)
          .pipe(dest(tmpDir + '/vendor'))
      )
    }
  })
}
<|endoftext|>


<commit_before>const symbolDesc = require('symbol-description')
const clone = require('clone')

const contextSymbol = Symbol('context')
const wrapperSymbol = Symbol('wrapper')

const nullWrapper = {
  [wrapperSymbol]: true,
  valueOf () {
    return null
  }
}

const undefinedWrapper = {
  [wrapperSymbol]: true,
  valueOf () {
    return undefined
  }
}

const defaultDocs = {
  descriptions: [],
  required: undefined,
  nullable: undefined,
  fixed: undefined,
  fixedType: undefined,
  possibleValues: [],
  defaultValue: undefined,
  sampleValues: [],
  statusCode: undefined
}

function isWrapperType (obj) {
  return obj instanceof Number ||
    obj instanceof String ||
    obj instanceof Boolean ||
    obj[wrapperSymbol]
}

function wrap (object) {
  if (object === null) return nullWrapper
  if (object === undefined) return undefinedWrapper
  return Object(object)
}

function capture (object, path, contextToMerge) {
  let context
  if (contextToMerge) {
    context = {
      object: object,
      path: path,
      propertyProxies: {},
      docs: clone(contextToMerge.docs)
    }
    for (const property of Object.keys(contextToMerge.propertyProxies)) {
      const propertyContext = contextToMerge.propertyProxies[property][contextSymbol]
      context.propertyProxies[property] = capture(propertyContext.object, [...path, property], propertyContext)
    }
  } else {
    context = {
      object,
      path: path || [],
      propertyProxies: {},
      docs: clone(defaultDocs)
    }
  }
  object = wrap(object)
  const docDescriptor = Object.assign(Object.create(Object.getPrototypeOf(object)), {
    desc (...descriptions) {
      context.docs.descriptions = descriptions
      return context.proxy
    },
    required () {
      context.docs.required = true
      return context.proxy
    },
    optional () {
      context.docs.required = false
      return context.proxy
    },
    nullable (nullable = true) {
      context.docs.nullable = nullable
      return context.proxy
    },
    fixed (fixed = true) {
      context.docs.fixed = fixed
      return context.proxy
    },
    fixedType (fixedType = true) {
      context.docs.fixedType = fixedType
      return context.proxy
    },
    enum (...possibleValues) {
      context.docs.possibleValues = possibleValues
      return context.proxy
    },
    default (defaultValue) {
      context.docs.defaultValue = defaultValue
      return context.proxy
    },
    sample (...sampleValues) {
      context.docs.sampleValues = sampleValues
      return context.proxy
    },
    status (statusCode) {
      context.docs.statusCode = statusCode
      return context.proxy
    }
  })
  for (const propertySymbol of [Symbol('valueOf'), Symbol('toString')]) {
    docDescriptor[propertySymbol] = docDescriptor[symbolDesc(propertySymbol)]
    Object.defineProperty(docDescriptor, symbolDesc(propertySymbol), {
      get: function () {
        return this[propertySymbol].bind(this)
      }
    })
  }
  Object.setPrototypeOf(object, docDescriptor)
  context.proxy = new Proxy(object, {
    get (target, property) {
      if (property === contextSymbol) return context
      if (isWrapperType(target) || !target.hasOwnProperty(property)) return target[property]
      if (!context.propertyProxies[property]) {
        const path = [...context.path, property]
        if (Object(target[property])[contextSymbol]) {
          const targetContext = target[property][contextSymbol]
          context.propertyProxies[property] = capture(targetContext.object, path, targetContext)
        } else {
          context.propertyProxies[property] = capture(target[property], path)
        }
      }
      return context.propertyProxies[property]
    }
  })
  return context.proxy
}

function typeOf (target) {
  target = Object(target)
  if (target instanceof Array) return 'array'
  if (target instanceof Number) return 'number'
  if (target instanceof Boolean) return 'boolean'
  if (target instanceof String) return 'string'
  return 'object'
}

function traverse (object, visitFn, map = false) {
  function childrenOf (node) {
    let children = []
    node.valueType = typeOf(node.value)
    if (node.valueType === 'object' && node.value) {
      children = Object.keys(node.value).map(key => {
        return {
          key: key,
          value: node.value[key],
          depth: node.depth + 1,
          parent: node
        }
      })
    } else if (node.valueType === 'array') {
      children = node.value.map((item, index) => {
        return {
          index,
          value: item,
          depth: node.depth + 1,
          parent: node
        }
      })
    }
    return children
  }

  const stack = [{ value: object, depth: 0 }]
  while (stack.length) {
    const node = stack.shift()
    let children = childrenOf(node)
    if (!children.length) node.isLeaf = true

    let newObject = visitFn(node)
    if (map) {
      const newObjectType = typeOf(newObject)
      if (newObjectType === 'object' && newObject) newObject = Object.assign({}, newObject)
      else if (newObjectType === 'array') newObject = newObject.slice()
      if (node.depth === 0) {
        object = newObject
      } else {
        node.parent.value[node.key || node.index] = newObject
      }
      children = childrenOf(Object.assign(node, { value: newObject }))
    }
    stack.unshift(...children)
  }
  return object
}

function uncapture (object) {
  return traverse(object, node => {
    if (node.value === null || node.value === undefined) return node.value
    const nodeContext = node.value[contextSymbol]
    if (nodeContext) return nodeContext.object
    return node.value
  }, true)
}

function docs (object) {
  if (object === null || object === undefined) return clone(defaultDocs)
  const context = object[contextSymbol]
  return context ? context.docs : clone(defaultDocs)
}

module.exports = capture
module.exports.undo = uncapture
module.exports.docs = docs
module.exports.typeOf = typeOf
module.exports.traverse = traverse
<commit_msg>Add uncapture() method to captured object<commit_after>const symbolDesc = require('symbol-description')
const clone = require('clone')

const contextSymbol = Symbol('context')
const wrapperSymbol = Symbol('wrapper')

const nullWrapper = {
  [wrapperSymbol]: true,
  valueOf () {
    return null
  }
}

const undefinedWrapper = {
  [wrapperSymbol]: true,
  valueOf () {
    return undefined
  }
}

const defaultDocs = {
  descriptions: [],
  required: undefined,
  nullable: undefined,
  fixed: undefined,
  fixedType: undefined,
  possibleValues: [],
  defaultValue: undefined,
  sampleValues: [],
  statusCode: undefined
}

function isWrapperType (obj) {
  return obj instanceof Number ||
    obj instanceof String ||
    obj instanceof Boolean ||
    obj[wrapperSymbol]
}

function wrap (object) {
  if (object === null) return nullWrapper
  if (object === undefined) return undefinedWrapper
  return Object(object)
}

function capture (object, path, contextToMerge) {
  let context
  if (contextToMerge) {
    context = {
      object: object,
      path: path,
      propertyProxies: {},
      docs: clone(contextToMerge.docs)
    }
    for (const property of Object.keys(contextToMerge.propertyProxies)) {
      const propertyContext = contextToMerge.propertyProxies[property][contextSymbol]
      context.propertyProxies[property] = capture(propertyContext.object, [...path, property], propertyContext)
    }
  } else {
    context = {
      object,
      path: path || [],
      propertyProxies: {},
      docs: clone(defaultDocs)
    }
  }
  object = wrap(object)
  const docDescriptor = Object.assign(Object.create(Object.getPrototypeOf(object)), {
    desc (...descriptions) {
      context.docs.descriptions = descriptions
      return context.proxy
    },
    required () {
      context.docs.required = true
      return context.proxy
    },
    optional () {
      context.docs.required = false
      return context.proxy
    },
    nullable (nullable = true) {
      context.docs.nullable = nullable
      return context.proxy
    },
    fixed (fixed = true) {
      context.docs.fixed = fixed
      return context.proxy
    },
    fixedType (fixedType = true) {
      context.docs.fixedType = fixedType
      return context.proxy
    },
    enum (...possibleValues) {
      context.docs.possibleValues = possibleValues
      return context.proxy
    },
    default (defaultValue) {
      context.docs.defaultValue = defaultValue
      return context.proxy
    },
    sample (...sampleValues) {
      context.docs.sampleValues = sampleValues
      return context.proxy
    },
    status (statusCode) {
      context.docs.statusCode = statusCode
      return context.proxy
    },
    uncapture () {
      return uncapture(context.proxy)
    }
  })
  for (const propertySymbol of [Symbol('valueOf'), Symbol('toString')]) {
    docDescriptor[propertySymbol] = docDescriptor[symbolDesc(propertySymbol)]
    Object.defineProperty(docDescriptor, symbolDesc(propertySymbol), {
      get: function () {
        return this[propertySymbol].bind(this)
      }
    })
  }
  Object.setPrototypeOf(object, docDescriptor)
  context.proxy = new Proxy(object, {
    get (target, property) {
      if (property === contextSymbol) return context
      if (isWrapperType(target) || !target.hasOwnProperty(property)) return target[property]
      if (!context.propertyProxies[property]) {
        const path = [...context.path, property]
        if (Object(target[property])[contextSymbol]) {
          const targetContext = target[property][contextSymbol]
          context.propertyProxies[property] = capture(targetContext.object, path, targetContext)
        } else {
          context.propertyProxies[property] = capture(target[property], path)
        }
      }
      return context.propertyProxies[property]
    }
  })
  return context.proxy
}

function typeOf (target) {
  target = Object(target)
  if (target instanceof Array) return 'array'
  if (target instanceof Number) return 'number'
  if (target instanceof Boolean) return 'boolean'
  if (target instanceof String) return 'string'
  return 'object'
}

function traverse (object, visitFn, map = false) {
  function childrenOf (node) {
    let children = []
    node.valueType = typeOf(node.value)
    if (node.valueType === 'object' && node.value) {
      children = Object.keys(node.value).map(key => {
        return {
          key: key,
          value: node.value[key],
          depth: node.depth + 1,
          parent: node
        }
      })
    } else if (node.valueType === 'array') {
      children = node.value.map((item, index) => {
        return {
          index,
          value: item,
          depth: node.depth + 1,
          parent: node
        }
      })
    }
    return children
  }

  const stack = [{ value: object, depth: 0 }]
  while (stack.length) {
    const node = stack.shift()
    let children = childrenOf(node)
    if (!children.length) node.isLeaf = true

    let newObject = visitFn(node)
    if (map) {
      const newObjectType = typeOf(newObject)
      if (newObjectType === 'object' && newObject) newObject = Object.assign({}, newObject)
      else if (newObjectType === 'array') newObject = newObject.slice()
      if (node.depth === 0) {
        object = newObject
      } else {
        node.parent.value[node.key || node.index] = newObject
      }
      children = childrenOf(Object.assign(node, { value: newObject }))
    }
    stack.unshift(...children)
  }
  return object
}

function uncapture (object) {
  return traverse(object, node => {
    if (node.value === null || node.value === undefined) return node.value
    const nodeContext = node.value[contextSymbol]
    if (nodeContext) return nodeContext.object
    return node.value
  }, true)
}

function docs (object) {
  if (object === null || object === undefined) return clone(defaultDocs)
  const context = object[contextSymbol]
  return context ? context.docs : clone(defaultDocs)
}

module.exports = capture
module.exports.undo = uncapture
module.exports.docs = docs
module.exports.typeOf = typeOf
module.exports.traverse = traverse
<|endoftext|>


<commit_before>var net = require('net');
var tls = require('tls');
var url = require('url');
var path = require('path');
var EventEmitter = require('events').EventEmitter;
var connect = require('../proxy/connect');
var util = require('../../util');
var rules = require('../rules');
var parseReq = require('../proxy/parse-req');
var cert = require('./cert');
var serverAgent = require('./util').serverAgent;
var DEFAULT_CERT = cert.DEFAULT_CERT;
var LOCALHOST = '127.0.0.1';
var ports = {};
var config, app;

function getFullUrl(socket, wss) {
	return (wss ? 'wss:' : 'ws:') + '//' + socket.headers.host + socket.url;
}

function getRequestEmitter(socket, wss) {
	var reqEmitter = new EventEmitter();
	reqEmitter.url = getFullUrl(socket, wss);
	reqEmitter.ip = socket.remoteAddress;
	reqEmitter.method = socket.method;
	reqEmitter.headers = socket.headers;
	reqEmitter.httpVersion = socket.httpVersion;
	return reqEmitter;
}

function handleWebsocket(socket, wss, callback) {
	var reqEmitter = app.reqEmitter;
	var headers = socket.headers;
	var host = headers.host;
	var fullUrl = socket.fullUrl = getFullUrl(socket, wss);
	var options = url.parse(fullUrl);
	var _rules = reqEmitter.rules = rules.resolveRules(fullUrl);
	var proxyUrl = util.rule.getMatcher(_rules.proxy);
	var reqSocket, options, matchedUrl;
	var now = Date.now();
	var timeout, done;

	function destroy(err) {
		clearTimeout(timeout);
		socket.destroy();
		reqSocket && reqSocket.destroy();
		util.emitError(reqEmitter, err || new Error('aborted'));
	}

	function abortIfUnavailable(socket) {
		return socket.on('error', destroy)
			.on('close', destroy);
	}

	function execCallback(err, socket) {
		if (done) {
			return;
		}
		done = true;
		err && util.emitError(reqEmitter, err);
		callback(err, socket);
	}

	timeout = setTimeout(function() {
		destroy(new Error('timeout'));
	}, config.timeout);

	if (proxyUrl) {
		proxyUrl = (wss ? 'wss:' : 'ws:') + util.removeProtocol(proxyUrl);
		rules.resolveHost(proxyUrl, function(err, ip, customHost) {
			reqEmitter.customHost = customHost;
			if (err || !ip) {
				return execCallback(err || new Error('lookup DNS faild: ' + proxyUrl));
			}

			options = url.parse(proxyUrl);
			socket.options = {
					host: ip,
					port: options.port,
					isWs: !wss
			};
			reqEmitter.host = ip;
			reqEmitter.dnsTime = Date.now() - now;
			reqEmitter.emit('send');
			if (util.isLocalAddress(ip) && (!options.port || options.port == config.port)) {
				return execCallback(new Error('Unable to agent to itself( ' + ip + ':' + config.port + ')'));
			}
			connect(socket, function(err, proxySocket) {
				if (err) {
					return execCallback(err);
				}

				if (wss) {
					reqSocket = tls.connect({
				        rejectUnauthorized: false,
				        socket: proxySocket
				    }, pipeData);
					abortIfUnavailable(reqSocket);
				} else {
					reqSocket = proxySocket;
					pipeData();
				}

			});

		}, true);
	} else {
		matchedUrl = util.rule.getUrl(_rules.rule);
		if (/^wss?:\/\//.test(matchedUrl)) {
			reqEmitter.realUrl = fullUrl = matchedUrl;
		} else {
			matchedUrl = null;
		}

		options = url.parse(fullUrl);

		rules.resolveHost(fullUrl, function(err, ip, customHost) {
			reqEmitter.customHost = customHost;
			if (err || !ip) {
				return execCallback(err || new Error('lookup DNS faild: ' + fullUrl));
			}
			reqEmitter.host = ip;
			reqEmitter.dnsTime = Date.now() - now;
			reqEmitter.emit('send');

			var isWss = options.protocol == 'wss';
			reqSocket = (isWss ? tls : net).connect({
				rejectUnauthorized: false,
				host: ip,
				port: options.port || (isWss ? 443 : 80)
			}, pipeData);
			abortIfUnavailable(reqSocket);
		}, true);
	}

	function pipeData() {
		clearTimeout(timeout);
		var headers = socket.headers;
		var origin;
		if (matchedUrl) {
			headers.host = options.host;
			origin = headers.origin;
			headers.origin = (options.protocol == 'wss' ? 'https://' : 'http://') + options.host;
		}

		reqSocket.write(socket.getBuffer(matchedUrl ? headers : null));
		socket.pipe(reqSocket);
		parseReq(reqSocket, function(err, res) {
			if (err) {
				return execCallback(err);
			}

			headers = res.headers;
			if (matchedUrl) {
				headers['access-control-allow-origin'] = origin;
			}
			socket.write(res.getBuffer(matchedUrl ? headers : null));
			res.pipe(socket);
			reqEmitter.emit('response', {
				headers: headers,
				realUrl: matchedUrl,
				statusCode: res.statusCode
			});
			execCallback(null, reqSocket);
		}, true);
	}
}

function handleTlsSocket(socket) {
	var reqSocket;
	function destroy() {
		socket.destroy();
		reqSocket && reqSocket.destroy();
	}

	function abortIfUnavailable(socket) {
		return socket.on('error', destroy)
			.on('close', destroy);
	}

	abortIfUnavailable(socket);
	parseReq(socket, function(err, socket) {
		if (err) {
			return destroy();
		}
		//wss
		var clientIp = ports[socket.remotePort];
		var headers = socket.headers;
		if (headers.upgrade && headers.upgrade.toLowerCase() == 'websocket') {
			var reqEmitter = getRequestEmitter(socket, true);
			reqEmitter.ip = clientIp;
			app.emit('websocket', reqEmitter);
			app.reqEmitter = reqEmitter;
			handleWebsocket(socket, true, function(err, req) {
				if (err) {
					return destroy();
				}
				reqSocket = req;
				abortIfUnavailable(reqSocket);
			});
		} else {
			//https
			reqSocket = net.connect(config.port, LOCALHOST, function() {
				headers[util.HTTPS_FIELD] = 1;
				headers[util.CLIENT_IP_HEAD] = clientIp;
				reqSocket.write(socket.getBuffer(headers));
				socket.pipe(reqSocket).pipe(socket);
	        });
			abortIfUnavailable(reqSocket);
		}
	}, true);

}

module.exports = function dispatch(socket, hostname, _app) {
	app = _app;
	config = app.config;

	var reqSocket, buffer;
	function destroy() {
		socket.destroy();
		reqSocket && reqSocket.destroy();
	}

	function abortIfUnavailable(socket) {
		return socket.on('error', destroy)
			.on('close', destroy);
	}

	abortIfUnavailable(socket);
	socket.on('data', request);
	socket.on('end', request);

	function request(chunk) {
		socket.removeListener('data', request);
		socket.removeListener('end', request);
		if (!chunk) {//没有数据
			return destroy();
		}

		buffer = buffer ? Buffer.concat([buffer, chunk]) : chunk;
		if (/upgrade\s*:\s*websocket/i.test(buffer && buffer.toString())) { //ws
			parseReq(socket, function(err, socket) {
				if (err) {
					return destroy();
				}
				var reqEmitter = getRequestEmitter(socket);
				app.emit('websocket', reqEmitter);
				app.reqEmitter = reqEmitter;
				handleWebsocket(socket, false, function(err, req) {
					if (err) {
						return destroy();
					}
					abortIfUnavailable(reqSocket = req);
				});
			}, buffer, true);
			buffer = null;
		} else {
			cert.createCert(hostname, function(err) {
				serverAgent.createServer(hostname, handleTlsSocket, function(port) {
					reqSocket = net.connect(port, LOCALHOST, function() {
						ports[reqSocket.localPort] = socket.remoteAddress;
						reqSocket.write(buffer);
			            reqSocket.pipe(socket).pipe(reqSocket);
			            buffer = null;
			        });
					abortIfUnavailable(reqSocket);
				});
			});
		}
	}

};

<commit_msg>stack<commit_after>var net = require('net');
var tls = require('tls');
var url = require('url');
var path = require('path');
var EventEmitter = require('events').EventEmitter;
var connect = require('../proxy/connect');
var util = require('../../util');
var rules = require('../rules');
var parseReq = require('../proxy/parse-req');
var cert = require('./cert');
var serverAgent = require('./util').serverAgent;
var DEFAULT_CERT = cert.DEFAULT_CERT;
var LOCALHOST = '127.0.0.1';
var ports = {};
var config, app;

function getFullUrl(socket, wss) {
	return (wss ? 'wss:' : 'ws:') + '//' + socket.headers.host + socket.url;
}

function getRequestEmitter(socket, wss) {
	var reqEmitter = new EventEmitter();
	reqEmitter.url = getFullUrl(socket, wss);
	reqEmitter.ip = socket.remoteAddress;
	reqEmitter.method = socket.method;
	reqEmitter.headers = socket.headers;
	reqEmitter.httpVersion = socket.httpVersion;
	return reqEmitter;
}

function handleWebsocket(socket, wss, callback) {
	var reqEmitter = app.reqEmitter;
	var headers = socket.headers;
	var host = headers.host;
	var fullUrl = socket.fullUrl = getFullUrl(socket, wss);
	var options = url.parse(fullUrl);
	var _rules = reqEmitter.rules = rules.resolveRules(fullUrl);
	var proxyUrl = util.rule.getMatcher(_rules.proxy);
	var reqSocket, options, matchedUrl;
	var now = Date.now();
	var timeout, done;

	function destroy(err) {
		clearTimeout(timeout);
		socket.destroy();
		reqSocket && reqSocket.destroy();
		util.emitError(reqEmitter, err || new Error('aborted'));
	}

	function abortIfUnavailable(socket) {
		return socket.on('error', destroy)
			.on('close', destroy);
	}

	function execCallback(err, socket) {
		if (done) {
			return;
		}
		done = true;
		err && util.emitError(reqEmitter, err);
		callback(err, socket);
	}

	timeout = setTimeout(function() {
		destroy(new Error('timeout'));
	}, config.timeout);

	if (proxyUrl) {
		proxyUrl = (wss ? 'wss:' : 'ws:') + util.removeProtocol(proxyUrl);
		rules.resolveHost(proxyUrl, function(err, ip, customHost) {
			reqEmitter.customHost = customHost;
			if (err || !ip) {
				return execCallback(err || new Error('lookup DNS faild: ' + proxyUrl));
			}

			options = url.parse(proxyUrl);
			socket.options = {
					host: ip,
					port: options.port,
					isWs: !wss
			};
			reqEmitter.host = ip;
			reqEmitter.dnsTime = Date.now() - now;
			reqEmitter.emit('send');
			if (util.isLocalAddress(ip) && (!options.port || options.port == config.port)) {
				return execCallback(new Error('Unable to agent to itself (' + ip + ':' + config.port + ')'));
			}
			connect(socket, function(err, proxySocket) {
				if (err) {
					return execCallback(err);
				}

				if (wss) {
					reqSocket = tls.connect({
				        rejectUnauthorized: false,
				        socket: proxySocket
				    }, pipeData);
					abortIfUnavailable(reqSocket);
				} else {
					reqSocket = proxySocket;
					pipeData();
				}

			});

		}, true);
	} else {
		matchedUrl = util.rule.getUrl(_rules.rule);
		if (/^wss?:\/\//.test(matchedUrl)) {
			reqEmitter.realUrl = fullUrl = matchedUrl;
		} else {
			matchedUrl = null;
		}

		options = url.parse(fullUrl);

		rules.resolveHost(fullUrl, function(err, ip, customHost) {
			reqEmitter.customHost = customHost;
			if (err || !ip) {
				return execCallback(err || new Error('lookup DNS faild: ' + fullUrl));
			}
			reqEmitter.host = ip;
			reqEmitter.dnsTime = Date.now() - now;
			reqEmitter.emit('send');

			var isWss = options.protocol == 'wss';
			reqSocket = (isWss ? tls : net).connect({
				rejectUnauthorized: false,
				host: ip,
				port: options.port || (isWss ? 443 : 80)
			}, pipeData);
			abortIfUnavailable(reqSocket);
		}, true);
	}

	function pipeData() {
		clearTimeout(timeout);
		var headers = socket.headers;
		var origin;
		if (matchedUrl) {
			headers.host = options.host;
			origin = headers.origin;
			headers.origin = (options.protocol == 'wss' ? 'https://' : 'http://') + options.host;
		}

		reqSocket.write(socket.getBuffer(matchedUrl ? headers : null));
		socket.pipe(reqSocket);
		parseReq(reqSocket, function(err, res) {
			if (err) {
				return execCallback(err);
			}

			headers = res.headers;
			if (matchedUrl) {
				headers['access-control-allow-origin'] = origin;
			}
			socket.write(res.getBuffer(matchedUrl ? headers : null));
			res.pipe(socket);
			reqEmitter.emit('response', {
				headers: headers,
				realUrl: matchedUrl,
				statusCode: res.statusCode
			});
			execCallback(null, reqSocket);
		}, true);
	}
}

function handleTlsSocket(socket) {
	var reqSocket;
	function destroy() {
		socket.destroy();
		reqSocket && reqSocket.destroy();
	}

	function abortIfUnavailable(socket) {
		return socket.on('error', destroy)
			.on('close', destroy);
	}

	abortIfUnavailable(socket);
	parseReq(socket, function(err, socket) {
		if (err) {
			return destroy();
		}
		//wss
		var clientIp = ports[socket.remotePort];
		var headers = socket.headers;
		if (headers.upgrade && headers.upgrade.toLowerCase() == 'websocket') {
			var reqEmitter = getRequestEmitter(socket, true);
			reqEmitter.ip = clientIp;
			app.emit('websocket', reqEmitter);
			app.reqEmitter = reqEmitter;
			handleWebsocket(socket, true, function(err, req) {
				if (err) {
					return destroy();
				}
				reqSocket = req;
				abortIfUnavailable(reqSocket);
			});
		} else {
			//https
			reqSocket = net.connect(config.port, LOCALHOST, function() {
				headers[util.HTTPS_FIELD] = 1;
				headers[util.CLIENT_IP_HEAD] = clientIp;
				reqSocket.write(socket.getBuffer(headers));
				socket.pipe(reqSocket).pipe(socket);
	        });
			abortIfUnavailable(reqSocket);
		}
	}, true);

}

module.exports = function dispatch(socket, hostname, _app) {
	app = _app;
	config = app.config;

	var reqSocket, buffer;
	function destroy() {
		socket.destroy();
		reqSocket && reqSocket.destroy();
	}

	function abortIfUnavailable(socket) {
		return socket.on('error', destroy)
			.on('close', destroy);
	}

	abortIfUnavailable(socket);
	socket.on('data', request);
	socket.on('end', request);

	function request(chunk) {
		socket.removeListener('data', request);
		socket.removeListener('end', request);
		if (!chunk) {//没有数据
			return destroy();
		}

		buffer = buffer ? Buffer.concat([buffer, chunk]) : chunk;
		if (/upgrade\s*:\s*websocket/i.test(buffer && buffer.toString())) { //ws
			parseReq(socket, function(err, socket) {
				if (err) {
					return destroy();
				}
				var reqEmitter = getRequestEmitter(socket);
				app.emit('websocket', reqEmitter);
				app.reqEmitter = reqEmitter;
				handleWebsocket(socket, false, function(err, req) {
					if (err) {
						return destroy();
					}
					abortIfUnavailable(reqSocket = req);
				});
			}, buffer, true);
			buffer = null;
		} else {
			cert.createCert(hostname, function(err) {
				serverAgent.createServer(hostname, handleTlsSocket, function(port) {
					reqSocket = net.connect(port, LOCALHOST, function() {
						ports[reqSocket.localPort] = socket.remoteAddress;
						reqSocket.write(buffer);
			            reqSocket.pipe(socket).pipe(reqSocket);
			            buffer = null;
			        });
					abortIfUnavailable(reqSocket);
				});
			});
		}
	}

};

<|endoftext|>


<commit_before>'use strict'

//cache DOM
var slider = document.getElementById('slider');
var slideContainer = document.querySelectorAll('#slides');
var slides = document.getElementsByClassName('slide');
var slideDistance = document.getElementById('slides');
var currentSlide = 1;
// configureation
var width = 720;
var animationSpeed = 1000;
var pause = 6000;

    setInterval(function() {
      Velocity(slideContainer, { marginLeft: '-='+width }, animationSpeed, function() {
        currentSlide++;
        if(currentSlide === slides.length) {
          currentSlide = 1;
          Velocity(slideContainer, { marginLeft: '0'}, 0.0001);
        }
      });
    }, pause);
    // setInterval
      // animate margin-left
      // if it's last slide, go to position 1 (0px);

      // listen for mouse enter and pause
      // resume on mouseleave

<commit_msg>adds stop on hover and stop on hover switch<commit_after>'use strict'

//cache DOM
var slider = document.getElementById('slider');
var slideContainer = document.querySelectorAll('#slides');
var slides = document.getElementsByClassName('slide');
var slideDistance = document.getElementById('slides');
var currentSlide = 1;
// configureation
var width = 720;
var animationSpeed = 1000;
var pause = 6000;
var interval;
var hover = true;
document.addEventListener('DOMContentLoaded', startSlider());
function startSlider(){
    console.log("slider starting!")
   interval = setInterval(function() {
      Velocity(slideContainer, { marginLeft: '-='+width }, animationSpeed, function() {
        currentSlide++;
        if(currentSlide === slides.length) {
          currentSlide = 1;
          Velocity(slideContainer, { marginLeft: '0'}, 0.0001);
        }
      });
    }, pause);
  }

  function stopSlider(){
    clearInterval(interval);
  }
  if(hover){
  slider.addEventListener("mouseover", stopSlider);
  slider.addEventListener("mouseleave", startSlider);
  }
    // setInterval
      // animate margin-left
      // if it's last slide, go to position 1 (0px);

      // listen for mouse enter and pause
      // resume on mouseleave

<|endoftext|>


<commit_before>module.exports = data => {
  return data.reduce((a, b) => {
    a.push({ name: b._id === null ? 'Folkehelse' : b._id, total: b.total })
    return a
  }, [])
}
<commit_msg>Updates summary to match new stats (patch)<commit_after>module.exports = data => {
  return data.reduce((accumulator, current) => {
    const { total } = current
    const name = /folkehelse/.test(current._id) ? 'Folkehelse' : 'Kultur'
    accumulator.push({ name, total })
    return accumulator
  }, [])
}
<|endoftext|>


<commit_before>// TODO

const {h, Component} = require('preact')

const Goban = require('./Goban')
const PlayBar = require('./bars/PlayBar')
const EditBar = require('./bars/EditBar')
const GuessBar = require('./bars/GuessBar')
const AutoplayBar = require('./bars/AutoplayBar')
const ScoringBar = require('./bars/ScoringBar')
const FindBar = require('./bars/FindBar')

const gametree = require('../modules/gametree')
const helper = require('../modules/helper')

class MainView extends Component {
    constructor() {
        super()

        this.handleTogglePlayer = () => sabaki.setPlayer(...this.props.treePosition, -this.props.currentPlayer)

        this.handleToolButtonClick = evt => {
            sabaki.setState({selectedTool: evt.tool})
        }

        this.handleFindButtonClick = evt => sabaki.findMove(evt.step, {
            vertex: this.props.findVertex,
            text: this.props.findText
        })

        this.handleGobanVertexClick = this.handleGobanVertexClick.bind(this)
        this.handleGobanLineDraw = this.handleGobanLineDraw.bind(this)
    }

    componentDidMount() {
        // Pressing Ctrl should show crosshair cursor on Goban in edit mode

        document.addEventListener('keydown', evt => {
            if (evt.key !== 'Control' || evt.key !== 'Meta') return

            if (this.props.mode === 'edit') {
                this.setState({gobanCrosshair: true})
            }
        })

        document.addEventListener('keyup', evt => {
            if (evt.key !== 'Control') return

            if (this.props.mode === 'edit') {
                this.setState({gobanCrosshair: false})
            }
        })
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.mode !== 'edit') {
            this.setState({gobanCrosshair: false})
        }
    }

    handleGobanVertexClick(evt) {
        sabaki.clickVertex(evt.vertex, evt)
    }

    handleGobanLineDraw(evt) {
        let {v1, v2} = evt.line
        sabaki.useTool(this.props.selectedTool, v1, v2)
        sabaki.editVertexData = null
    }

    render({
        mode,
        treePosition,
        rootTree,
        currentPlayer,
        gameInfo,
        attachedEngines,
        analysisTreePosition,

        deadStones,
        scoringMethod,
        scoreBoard,
        playVariation,
        analysis,
        areaMap,
        blockedGuesses,

        highlightVertices,
        showCoordinates,
        showMoveColorization,
        showNextMoves,
        showSiblings,
        fuzzyStonePlacement,
        animateStonePlacement,

        undoable,
        undoText,
        selectedTool,
        findText,
        findVertex,

        showLeftSidebar,
        showSidebar,
        sidebarWidth,
        leftSidebarWidth
    }, {
        width,
        height,
        gobanCrosshair
    }) {
        let [tree, index] = treePosition
        let board = gametree.getBoard(tree, index)
        let node = tree.nodes[index]
        let komi = +gametree.getRootProperty(rootTree, 'KM', 0)
        let handicap = +gametree.getRootProperty(rootTree, 'HA', 0)
        let paintMap

        if (['scoring', 'estimator'].includes(mode)) {
            paintMap = areaMap
        } else if (mode === 'guess') {
            paintMap = [...Array(board.height)].map(_ => Array(board.width).fill(0))

            for (let [x, y] of blockedGuesses) {
                paintMap[y][x] = 1
            }
        }

        return h('section',
            {
                id: 'main',
                style: {
                    left: showLeftSidebar ? leftSidebarWidth : null,
                    right: showSidebar ? sidebarWidth : null
                }
            },

            h('main',
                {
                    ref: el => this.mainElement = el,
                    style: {width, height}
                },

                h(Goban, {
                    treePosition,
                    board,
                    highlightVertices: findVertex && mode === 'find'
                        ? [findVertex]
                        : highlightVertices,
                    analysis: mode === 'play'
                        && analysisTreePosition != null
                        && helper.vertexEquals(analysisTreePosition, treePosition)
                        ? analysis
                        : null,
                    paintMap,
                    dimmedStones: ['scoring', 'estimator'].includes(mode) ? deadStones : [],

                    crosshair: gobanCrosshair,
                    showCoordinates,
                    showMoveColorization,
                    showNextMoves: mode !== 'guess' && showNextMoves,
                    showSiblings: mode !== 'guess' && showSiblings,
                    fuzzyStonePlacement,
                    animateStonePlacement,

                    playVariation,
                    drawLineMode: mode === 'edit' && ['arrow', 'line'].includes(selectedTool)
                        ? selectedTool : null,

                    onVertexClick: this.handleGobanVertexClick,
                    onLineDraw: this.handleGobanLineDraw
                })
            ),

            h('section', {id: 'bar'},
                h(PlayBar, {
                    mode,
                    attachedEngines,
                    playerNames: gameInfo.playerNames,
                    playerRanks: gameInfo.playerRanks,
                    playerCaptures: board.captures,
                    currentPlayer,
                    showHotspot: 'HO' in node,
                    undoable,
                    undoText,
                    onCurrentPlayerClick: this.handleTogglePlayer
                }),

                h(EditBar, {
                    mode,
                    selectedTool,
                    onToolButtonClick: this.handleToolButtonClick
                }),

                h(GuessBar, {
                    mode,
                    treePosition
                }),

                h(AutoplayBar, {
                    mode,
                    treePosition
                }),

                h(ScoringBar, {
                    type: 'scoring',
                    mode,
                    method: scoringMethod,
                    scoreBoard,
                    areaMap,
                    komi,
                    handicap
                }, 'Please select dead stones.'),

                h(ScoringBar, {
                    type: 'estimator',
                    mode,
                    method: scoringMethod,
                    scoreBoard,
                    areaMap,
                    komi,
                    handicap
                }, 'Toggle group status.'),

                h(FindBar, {
                    mode,
                    findText,
                    onButtonClick: this.handleFindButtonClick,
                })
            )
        )
    }
}

module.exports = MainView
<commit_msg>Adapt MainView<commit_after>const {h, Component} = require('preact')

const Goban = require('./Goban')
const PlayBar = require('./bars/PlayBar')
const EditBar = require('./bars/EditBar')
const GuessBar = require('./bars/GuessBar')
const AutoplayBar = require('./bars/AutoplayBar')
const ScoringBar = require('./bars/ScoringBar')
const FindBar = require('./bars/FindBar')

const gametree = require('../modules/gametree')
const helper = require('../modules/helper')

class MainView extends Component {
    constructor() {
        super()

        this.handleTogglePlayer = () => {
            let {gameTree, treePosition, currentPlayer} = this.props
            sabaki.setPlayer(gameTree, treePosition, -currentPlayer)
        }

        this.handleToolButtonClick = evt => {
            sabaki.setState({selectedTool: evt.tool})
        }

        this.handleFindButtonClick = evt => sabaki.findMove(evt.step, {
            vertex: this.props.findVertex,
            text: this.props.findText
        })

        this.handleGobanVertexClick = this.handleGobanVertexClick.bind(this)
        this.handleGobanLineDraw = this.handleGobanLineDraw.bind(this)
    }

    componentDidMount() {
        // Pressing Ctrl should show crosshair cursor on Goban in edit mode

        document.addEventListener('keydown', evt => {
            if (evt.key !== 'Control' || evt.key !== 'Meta') return

            if (this.props.mode === 'edit') {
                this.setState({gobanCrosshair: true})
            }
        })

        document.addEventListener('keyup', evt => {
            if (evt.key !== 'Control') return

            if (this.props.mode === 'edit') {
                this.setState({gobanCrosshair: false})
            }
        })
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.mode !== 'edit') {
            this.setState({gobanCrosshair: false})
        }
    }

    handleGobanVertexClick(evt) {
        sabaki.clickVertex(evt.vertex, evt)
    }

    handleGobanLineDraw(evt) {
        let {v1, v2} = evt.line
        sabaki.useTool(this.props.selectedTool, v1, v2)
        sabaki.editVertexData = null
    }

    render({
        mode,
        gameTree,
        treePosition,
        currentPlayer,
        gameInfo,
        attachedEngines,
        analysisTreePosition,

        deadStones,
        scoringMethod,
        scoreBoard,
        playVariation,
        analysis,
        areaMap,
        blockedGuesses,

        highlightVertices,
        showCoordinates,
        showMoveColorization,
        showNextMoves,
        showSiblings,
        fuzzyStonePlacement,
        animateStonePlacement,

        undoable,
        undoText,
        selectedTool,
        findText,
        findVertex,

        showLeftSidebar,
        showSidebar,
        sidebarWidth,
        leftSidebarWidth
    }, {
        width,
        height,
        gobanCrosshair
    }) {
        let node = gameTree.get(treePosition)
        let board = gametree.getBoard(gameTree, treePosition)
        let komi = +gametree.getRootProperty(gameTree, 'KM', 0)
        let handicap = +gametree.getRootProperty(gameTree, 'HA', 0)
        let paintMap

        if (['scoring', 'estimator'].includes(mode)) {
            paintMap = areaMap
        } else if (mode === 'guess') {
            paintMap = [...Array(board.height)].map(_ => Array(board.width).fill(0))

            for (let [x, y] of blockedGuesses) {
                paintMap[y][x] = 1
            }
        }

        return h('section',
            {
                id: 'main',
                style: {
                    left: showLeftSidebar ? leftSidebarWidth : null,
                    right: showSidebar ? sidebarWidth : null
                }
            },

            h('main',
                {
                    ref: el => this.mainElement = el,
                    style: {width, height}
                },

                h(Goban, {
                    gameTree,
                    treePosition,
                    board,
                    highlightVertices: findVertex && mode === 'find'
                        ? [findVertex]
                        : highlightVertices,
                    analysis: mode === 'play'
                        && analysisTreePosition != null
                        && helper.vertexEquals(analysisTreePosition, treePosition)
                        ? analysis
                        : null,
                    paintMap,
                    dimmedStones: ['scoring', 'estimator'].includes(mode) ? deadStones : [],

                    crosshair: gobanCrosshair,
                    showCoordinates,
                    showMoveColorization,
                    showNextMoves: mode !== 'guess' && showNextMoves,
                    showSiblings: mode !== 'guess' && showSiblings,
                    fuzzyStonePlacement,
                    animateStonePlacement,

                    playVariation,
                    drawLineMode: mode === 'edit' && ['arrow', 'line'].includes(selectedTool)
                        ? selectedTool : null,

                    onVertexClick: this.handleGobanVertexClick,
                    onLineDraw: this.handleGobanLineDraw
                })
            ),

            h('section', {id: 'bar'},
                h(PlayBar, {
                    mode,
                    attachedEngines,
                    playerNames: gameInfo.playerNames,
                    playerRanks: gameInfo.playerRanks,
                    playerCaptures: board.captures,
                    currentPlayer,
                    showHotspot: node.data.HO != null,
                    undoable,
                    undoText,
                    onCurrentPlayerClick: this.handleTogglePlayer
                }),

                h(EditBar, {
                    mode,
                    selectedTool,
                    onToolButtonClick: this.handleToolButtonClick
                }),

                h(GuessBar, {
                    mode,
                    treePosition
                }),

                h(AutoplayBar, {
                    mode,
                    gameTree,
                    treePosition
                }),

                h(ScoringBar, {
                    type: 'scoring',
                    mode,
                    method: scoringMethod,
                    scoreBoard,
                    areaMap,
                    komi,
                    handicap
                }, 'Please select dead stones.'),

                h(ScoringBar, {
                    type: 'estimator',
                    mode,
                    method: scoringMethod,
                    scoreBoard,
                    areaMap,
                    komi,
                    handicap
                }, 'Toggle group status.'),

                h(FindBar, {
                    mode,
                    findText,
                    onButtonClick: this.handleFindButtonClick,
                })
            )
        )
    }
}

module.exports = MainView
<|endoftext|>