<commit_before>import Vue from 'vue'
import Vuex from 'vuex'
import createLogger from 'vuex/dist/logger'
import co from 'co'
import Axios from 'axios'
import toast from './vuex/toast'

Vue.use(Vuex)

const state = {

  loading: false,

  chain: [],

  mempool: [],

  wallets: [],

  stats: [],

  mining: false,

  demoMode: false,

}

const mutations = {

  GET_STATUS (state) {
    state.loading = true
  },

  GET_STATUS_OK (state, status) {
    state.loading = false
    state.chain = status.chain
    state.mempool = status.mempool
    state.wallets = status.wallets
    state.mining = status.mining
    state.demoMode = status.demoMode
  },

  ERROR (state) {
    state.loading = false
  },

  ADD_BLOCK (state, block) {
    state.chain.push(block)
    state.chain = state.chain.slice(Math.max(state.chain.length - 5, 0))
  },

  ADD_TRANSACTION (state, transaction) {
    state.mempool.push(transaction)
    state.mempool = state.mempool.slice(Math.max(state.mempool.length - 5, 0))
  },

  CLEAN_MEMPOOL (state, transactions) {
    transactions.forEach(tx => {
      let index = state.mempool.findIndex(t => t.id === tx.id)
      if (index !== - 1) state.mempool.splice(index, 1)
    })
  },

  UPDATE_BALANCE (state, balance) {
    const index = state.wallets.findIndex(w => w.public === balance.public)
    if (index === -1) return console.error('Cant find wallet to update balance')
    state.wallets[index].balance = balance.balance
  },

  MINE_START (state) {
    state.mining = true
  },

  MINE_STOP (state) {
    state.mining = false
  },

  RECIEVED_FUNDS (state, data) {
    const index = state.wallets.findIndex(w => w.public === data.public)
    if (index === -1) return console.error('Cant find wallet to update balance')
    state.wallets[index].balance = data.balance
  },
}

const actions = {

  getState ({commit}) {
    commit('GET_STATUS')

    return co(function* () {
      const resp = yield Axios.get('/v1/status')
      commit('GET_STATUS_OK', resp.data)
    }).catch(e => commit('ERROR', e))
  },

  startMine ({commit}) {
    return co(function* () {
      yield Axios.get('/v1/mine-start')
    }).catch(e => commit('ERROR', e))
  },

  stopMine ({commit}) {
    return co(function* () {
      yield Axios.get('/v1/mine-stop')
    }).catch(e => commit('ERROR', e))
  },

  sendFunds ({commit}, {from, to, amount}) {
    return co(function* () {
      yield Axios.get(`/v1/send/${from}/${to}/${amount}`)
    }).catch(e => commit('ERROR', e))
  },
}

const debug = process.env.NODE_ENV !== 'production'

const store = new Vuex.Store({
  strict: debug,
  plugins: debug ? [createLogger()] : [],
  state,
  mutations,
  actions,
  modules: {toast},
})

Axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response
}, function (error) {
  store.dispatch('addToastMessage', {type: 'danger', text: error.response.data})
  return Promise.reject(error)
})

export default store
<commit_msg>Fixed lint error<commit_after>import Vue from 'vue'
import Vuex from 'vuex'
import createLogger from 'vuex/dist/logger'
import co from 'co'
import Axios from 'axios'
import toast from './vuex/toast'

Vue.use(Vuex)

const state = {

  loading: false,

  chain: [],

  mempool: [],

  wallets: [],

  stats: [],

  mining: false,

  demoMode: false,

}

const mutations = {

  GET_STATUS (state) {
    state.loading = true
  },

  GET_STATUS_OK (state, status) {
    state.loading = false
    state.chain = status.chain
    state.mempool = status.mempool
    state.wallets = status.wallets
    state.mining = status.mining
    state.demoMode = status.demoMode
  },

  ERROR (state) {
    state.loading = false
  },

  ADD_BLOCK (state, block) {
    state.chain.push(block)
    state.chain = state.chain.slice(Math.max(state.chain.length - 5, 0))
  },

  ADD_TRANSACTION (state, transaction) {
    state.mempool.push(transaction)
    state.mempool = state.mempool.slice(Math.max(state.mempool.length - 5, 0))
  },

  CLEAN_MEMPOOL (state, transactions) {
    transactions.forEach(tx => {
      let index = state.mempool.findIndex(t => t.id === tx.id)
      if (index !== -1) state.mempool.splice(index, 1)
    })
  },

  UPDATE_BALANCE (state, balance) {
    const index = state.wallets.findIndex(w => w.public === balance.public)
    if (index === -1) return console.error('Cant find wallet to update balance')
    state.wallets[index].balance = balance.balance
  },

  MINE_START (state) {
    state.mining = true
  },

  MINE_STOP (state) {
    state.mining = false
  },

  RECIEVED_FUNDS (state, data) {
    const index = state.wallets.findIndex(w => w.public === data.public)
    if (index === -1) return console.error('Cant find wallet to update balance')
    state.wallets[index].balance = data.balance
  },
}

const actions = {

  getState ({commit}) {
    commit('GET_STATUS')

    return co(function* () {
      const resp = yield Axios.get('/v1/status')
      commit('GET_STATUS_OK', resp.data)
    }).catch(e => commit('ERROR', e))
  },

  startMine ({commit}) {
    return co(function* () {
      yield Axios.get('/v1/mine-start')
    }).catch(e => commit('ERROR', e))
  },

  stopMine ({commit}) {
    return co(function* () {
      yield Axios.get('/v1/mine-stop')
    }).catch(e => commit('ERROR', e))
  },

  sendFunds ({commit}, {from, to, amount}) {
    return co(function* () {
      yield Axios.get(`/v1/send/${from}/${to}/${amount}`)
    }).catch(e => commit('ERROR', e))
  },
}

const debug = process.env.NODE_ENV !== 'production'

const store = new Vuex.Store({
  strict: debug,
  plugins: debug ? [createLogger()] : [],
  state,
  mutations,
  actions,
  modules: {toast},
})

Axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response
}, function (error) {
  store.dispatch('addToastMessage', {type: 'danger', text: error.response.data})
  return Promise.reject(error)
})

export default store
<|endoftext|>


<commit_before>/* global wp, _ */
wp.customize.controlConstructor['kirki-image'] = wp.customize.kirkiDynamicControl.extend( {

	initKirkiControl: function() {

		var control = this,
		    value   = _.defaults( control.setting._value, control.params['default'] ),
		    saveAs,
		    preview,
		    previewImage,
		    removeButton,
		    defaultButton;

		control.addHTML();

		preview       = control.container.find( '.placeholder, .thumbnail' );
	    previewImage  = ( 'array' === saveAs ) ? value.url : value;
	    removeButton  = control.container.find( '.image-upload-remove-button' );
	    defaultButton = control.container.find( '.image-default-button' );

		control.container.find( '.kirki-controls-loading-spinner' ).hide();

		// Tweaks for save_as = id.
		if ( ( 'id' === saveAs || 'ID' === saveAs ) && '' !== value ) {
			wp.media.attachment( value ).fetch().then( function( mediaData ) {
				setTimeout( function() {
					var url = wp.media.attachment( value ).get( 'url' );
					preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '' );
				}, 700 );
			} );
		}

		// If value is not empty, hide the "default" button.
		if ( ( 'url' === saveAs && '' !== value ) || ( 'array' === saveAs && ! _.isUndefined( value.url ) && '' !== value.url ) ) {
			control.container.find( 'image-default-button' ).hide();
		}

		// If value is empty, hide the "remove" button.
		if ( ( 'url' === saveAs && '' === value ) || ( 'array' === saveAs && ( _.isUndefined( value.url ) || '' === value.url ) ) ) {
			removeButton.hide();
		}

		// If value is default, hide the default button.
		if ( value === control.params['default'] ) {
			control.container.find( 'image-default-button' ).hide();
		}

		if ( '' !== previewImage ) {
			preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '' );
		}

		control.container.on( 'click', '.image-upload-button', function( e ) {
			var image = wp.media( { multiple: false } ).open().on( 'select', function() {

					// This will return the selected image from the Media Uploader, the result is an object.
					var uploadedImage = image.state().get( 'selection' ).first(),
					    previewImage  = uploadedImage.toJSON().sizes.full.url;

					if ( ! _.isUndefined( uploadedImage.toJSON().sizes.medium ) ) {
						previewImage = uploadedImage.toJSON().sizes.medium.url;
					} else if ( ! _.isUndefined( uploadedImage.toJSON().sizes.thumbnail ) ) {
						previewImage = uploadedImage.toJSON().sizes.thumbnail.url;
					}

					if ( 'array' === saveAs ) {
						control.kirkiSetValue( uploadedImage.toJSON().id, 'id' );
						control.kirkiSetValue( uploadedImage.toJSON().sizes.full.url, 'url' );
						control.kirkiSetValue( uploadedImage.toJSON().width, 'width' );
						control.kirkiSetValue( uploadedImage.toJSON().height, 'height' );
					} else if ( 'id' === saveAs ) {
						control.kirkiSetValue( uploadedImage.toJSON().id, 'id' );
					} else {
						control.kirkiSetValue( uploadedImage.toJSON().sizes.full.url, 'url' );
					}

					if ( preview.length ) {
						preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '' );
					}
					if ( removeButton.length ) {
						removeButton.show();
						defaultButton.hide();
					}
			    } );

			e.preventDefault();
		} );

		control.container.on( 'click', '.image-upload-remove-button', function( e ) {

			var preview,
			    removeButton,
			    defaultButton;

			e.preventDefault();

			control.kirkiSetValue( '', 'id' );
			control.kirkiSetValue( '', 'url' );
			control.kirkiSetValue( '', 'width' );
			control.kirkiSetValue( '', 'height' );

			preview       = control.container.find( '.placeholder, .thumbnail' );
			removeButton  = control.container.find( '.image-upload-remove-button' );
			defaultButton = control.container.find( '.image-default-button' );

			if ( preview.length ) {
				preview.removeClass().addClass( 'placeholder' ).html( 'No file selected' );
			}
			if ( removeButton.length ) {
				removeButton.hide();
				if ( jQuery( defaultButton ).hasClass( 'button' ) ) {
					defaultButton.show();
				}
			}
		} );

		control.container.on( 'click', '.image-default-button', function( e ) {

			var preview,
			    removeButton,
			    defaultButton;

			e.preventDefault();

			control.kirkiSetValue( 'url', control.params['default'] );

			preview       = control.container.find( '.placeholder, .thumbnail' );
			removeButton  = control.container.find( '.image-upload-remove-button' );
			defaultButton = control.container.find( '.image-default-button' );

			if ( preview.length ) {
				preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '' );
			}
			if ( removeButton.length ) {
				removeButton.show();
				defaultButton.hide();
			}
		} );
	},

	addHTML: function() {
		var control = this,
		    html = '',
		    saveAs,
		    url;

		saveAs = ( ! _.isUndefined( control.params.choices ) && ! _.isUndefined( control.params.choices.save_as ) ) ? control.params.choices.save_as : 'url';

		url = control.params.value;
		url = ( _.isObject( control.params.value ) && ! _.isUndefined( control.params.value.url ) ) ? control.params.value.url : url;

		html += '';
		html += '' + control.params.label + '';
		html += '' + control.params.description + '';
		html += '';
		html += '
';
		if ( '' !== url ) {
			html += '

';
		} else {
			html += '
' + control.params.l10n.noFileSelected + '
';
		}
		html += '
';
		html += '<button class="button image-upload-remove-button' + ( '' === url ? ' hidden' : '' ) + '">' + control.params.l10n.remove + '</button>';
		if ( control.params['default'] && '' !== control.params['default'] ) {
			html += '<button type="button" class="button image-default-button"' + ( ( control.params['default'] === control.params.value || ( ! _.isUndefined( control.params.value.url ) && control.params['default'] === control.params.value.url ) ) ? ' style="display:none;' : '' ) + '">' + control.params.l10n.defaultImage + '</button>';
		}
		html += '<button type="button" class="button image-upload-button">' + control.params.l10n.selectFile + '</button>';
		html += '

';

		control.container.html( html );
	}
} );
<commit_msg>Refactor Image controls.<commit_after>/* global wp, _ */
wp.customize.controlConstructor['kirki-image'] = wp.customize.kirkiDynamicControl.extend( {

	initKirkiControl: function() {

		var control = this,
		    value   = _.defaults( control.setting._value, control.params['default'] );

		control.addHTML();
		control.kirkiSetControlValue( value );

		control.kirkiAddImage();
		control.kirkiRemoveImage();
	},

	kirkiAddImage: function() {
		var control = this,
		    saveAs  = ( _.isUndefined( control.params.choices ) || _.isUndefined( control.params.choices.save_as ) ) ? 'url' : control.params.choices.save_as,
		    image,
		    uploadedImage;

		control.container.on( 'click', '.image-upload-button', function( e ) {
			image = wp.media( { multiple: false } ).open().on( 'select', function() {
				uploadedImage = image.state().get( 'selection' ).first();

				// Save the value.
				if ( 'id' === saveAs ) {
					control.kirkiSetValue( uploadedImage.toJSON().id );
				} else if ( 'array' === saveAs ) {
					control.kirkiSetValue({
						id: uploadedImage.toJSON().id,
						url: uploadedImage.toJSON().sizes.full.url,
						width: uploadedImage.toJSON().width,
						height: uploadedImage.toJSON().height
					});
				} else {
					control.kirkiSetValue( uploadedImage.toJSON().sizes.full.url );
				}

				// Add the image to the placeholder.
				if ( control.container.find( '.placeholder, .thumbnail' ).length ) {
					control.container.find( '.placeholder, .thumbnail' ).removeClass().addClass( 'thumbnail thumbnail-image' ).html( '' );
				}

				// Add the remove button.
				if ( control.container.find( '.image-upload-remove-button' ).length ) {
					control.container.find( '.image-upload-remove-button' ).show();
				}
		    } );
			e.preventDefault();
		} );
	},

	kirkiRemoveImage: function() {
		var control = this,
		    saveAs  = ( _.isUndefined( control.params.choices ) || _.isUndefined( control.params.choices.save_as ) ) ? 'url' : control.params.choices.save_as;

		control.container.on( 'click', '.image-upload-remove-button', function( e ) {
			e.preventDefault();

			// Update the value.
			if ( 'array' === saveAs ) {
				control.kirkiSetValue( {
					id: '',
					url: '',
					width: '',
					height: ''
				} );
			} else {
				control.kirkiSetValue( '' );
			}

			// Remove image and add placeholder text.
			if ( control.container.find( '.placeholder, .thumbnail' ).length ) {
				control.container.find( '.placeholder, .thumbnail' ).removeClass().addClass( 'placeholder' ).html( 'No file selected' );
			}

			// Hide the "Remove" button.
			if ( control.container.find( '.image-upload-remove-button' ).length ) {
				control.container.find( '.image-upload-remove-button' ).hide();
			}
		} );
	},

	kirkiDefaultImage: function() {
		var control = this,
		    saveAs  = ( _.isUndefined( control.params.choices ) || _.isUndefined( control.params.choices.save_as ) ) ? 'url' : control.params.choices.save_as;

		control.container.on( 'click', '.image-default-button', function( e ) {
			e.preventDefault();

			// Update the value both in the settings and visually.
			control.kirkiSetValue( control.params['default'], 'url' );
			control.kirkiSetControlValue( control.params['default'] );

			if ( control.container.find( '.image-upload-remove-button' ).length ) {
				control.container.find( '.image-upload-remove-button' ).show();
				control.container.find( '.image-default-button' ).hide();
			}
		} );
	},

	addHTML: function() {
		var control = this,
		    html    = '',
		    saveAs  = ( _.isUndefined( control.params.choices ) || _.isUndefined( control.params.choices.save_as ) ) ? 'url' : control.params.choices.save_as,
		    value   = control.params.value,
		    url     = value;

		html += '';
			html += '' + control.params.label + '';
			html += '' + control.params.description + '';
		html += '';
		html += '
';
			html += '
';
				html += '
';
					html += '

';
					html += '
';
						html += '<button class="button image-upload-remove-button' + ( ! control.params.value ? ' hidden' : '' ) + '">' + control.params.l10n.remove + '</button> ';
						html += '<button type="button" class="button image-upload-button">' + control.params.l10n.selectFile + '</button> ';
						if ( control.params['default'] && '' !== control.params['default'] ) {
							html += '<button type="button" class="button image-default-button"' + ( ( control.params['default'] === control.params.value || ( ! _.isUndefined( control.params.value.url ) && control.params['default'] === control.params.value.url ) ) ? ' style="display:none;' : '' ) + '">' + control.params.l10n.defaultImage + '</button>';
						}
					html += '
';
				html += '
';
			html += '
';
		html += '
';

		control.container.html( html );
	},

	kirkiSetValue: function( value, property ) {
		// TODO
		var control = this;
		control.setting.set( value );
	},

	kirkiSetControlValue: function( value ) {
		var control = this,
			saveAs  = ( _.isUndefined( control.params.choices ) || _.isUndefined( control.params.choices.save_as ) ) ? 'url' : control.params.choices.save_as,
			url     = value;

		if ( _.isObject( value ) && ! _.isUndefined( value.url ) ) {
			jQuery( control.container.find( '.' + control.id + '-image' ) ).prop( 'src', value.url );
		} else if ( 'id' === saveAs && ! isNaN( value ) ) {
			wp.media.attachment( value ).fetch().then( function( mediaData ) {
				setTimeout( function() {
					jQuery( control.container.find( '.' + control.id + '-image' ) ).prop( 'src', wp.media.attachment( value ).get( 'url' ) );
				}, 500 );
			} );
		} else {
			jQuery( control.container.find( '.' + control.id + '-image' ) ).prop( 'src', value );
		}
	}
} );
<|endoftext|>


<commit_before>const debianInstaller = require('electron-installer-debian')

const packageFile = require('./../package.json')
const version = packageFile.version

require('./createPackage.js')('linux').then(function (appPaths) {
  var installerOptions = {
    src: appPaths[0],
    dest: 'dist/app',
    arch: 'amd64',
    productName: 'Min',
    genericName: 'Web Browser',
    version: version,
    section: 'web',
    homepage: 'https://minbrowser.github.io/min/',
    icon: 'icons/icon256.png',
    categories: ['Network', 'WebBrowser'],
    mimeType: ['x-scheme-handler/http', 'x-scheme-handler/https', 'text/html'],
    maintainer: 'Min Developers <280953907a@zoho.com>',
    description: 'Min is a fast, minimal browser that protects your privacy.',
    productDescription: 'A web browser with smarter search, improved tab management, and built-in ad blocking. Includes full-text history search, instant answers from DuckDuckGo, the ability to split tabs into groups, and more.',
    depends: [
      'gconf2',
      'gconf-service',
      'gvfs-bin',
      'libc6',
      'libcap2',
      'libgtk2.0-0',
      'libudev0 | libudev1',
      'libgcrypt11 | libgcrypt20',
      'libnotify4',
      'libnss3',
      'libxtst6',
      'python',
      'xdg-utils'
    ]
  }

  console.log('Creating package (this may take a while)')

  debianInstaller(installerOptions)
    .then(() => console.log('Successfully created package.'))
    .catch(err => {
      console.error(err, err.stack)
      process.exit(1)
    })
})
<commit_msg>add missing packages<commit_after>const debianInstaller = require('electron-installer-debian')

const packageFile = require('./../package.json')
const version = packageFile.version

require('./createPackage.js')('linux').then(function (appPaths) {
  var installerOptions = {
    src: appPaths[0],
    dest: 'dist/app',
    arch: 'amd64',
    productName: 'Min',
    genericName: 'Web Browser',
    version: version,
    section: 'web',
    homepage: 'https://minbrowser.github.io/min/',
    icon: 'icons/icon256.png',
    categories: ['Network', 'WebBrowser'],
    mimeType: ['x-scheme-handler/http', 'x-scheme-handler/https', 'text/html'],
    maintainer: 'Min Developers <280953907a@zoho.com>',
    description: 'Min is a fast, minimal browser that protects your privacy.',
    productDescription: 'A web browser with smarter search, improved tab management, and built-in ad blocking. Includes full-text history search, instant answers from DuckDuckGo, the ability to split tabs into groups, and more.',
    depends: [
      'gconf2',
      'gconf-service',
      'gvfs-bin',
      'libasound2',
      'libc6',
      'libcap2',
      'libgtk2.0-0',
      'libudev0 | libudev1',
      'libgcrypt11 | libgcrypt20',
      'libnotify4',
      'libnss3',
      'libxssl1',
      'libxtst6',
      'python',
      'xdg-utils'
    ]
  }

  console.log('Creating package (this may take a while)')

  debianInstaller(installerOptions)
    .then(() => console.log('Successfully created package.'))
    .catch(err => {
      console.error(err, err.stack)
      process.exit(1)
    })
})
<|endoftext|>


<commit_before>var crypto = require('crypto');
var config = require('cloud/config/weixin.js');
var debug = require('debug')('AV:weixin');

exports.exec = function(params, cb) {
  if (params.signature) {
    checkSignature(params.signature, params.timestamp, params.nonce, params.echostr, cb);
  } else {
    receiveMessage(params, cb)
  }
}

// 验证签名
var checkSignature = function(signature, timestamp, nonce, echostr, cb) {
  var oriStr = [config.token, timestamp, nonce].sort().join('')
  var code = crypto.createHash('sha1').update(oriStr).digest('hex');
  debug('code:', code)
  if (code == signature) {
    cb(null, echostr);
  } else {
    var err = new Error('Unauthorized');
    err.code = 401;
    cb(err);
  }
}

// 接收普通消息
var receiveMessage = function(msg, cb) {

    //console.log('weixin Event:', msg.xml.Event);

    var content = '';
    if(msg.xml.MsgType == 'event')//操作事件
    {
        if (msg.xml.Event == 'CLICK')
        {
            if(msg.xml.EventKey == 'KEY_I_LIKE')
            {
                content = '谢谢点赞！'

            }else if(msg.xml.EventKey == 'KEY_USER_GUID')
            {
                content = '爆料方式简单、迅速，全程使用微信操作。\n\n第一步，拍摄实物照片（可以拍摄多张照片，至少1张，最多5张）\n\n第二步，发送当前门店所在的位置信息，以便准确前往。\n\n第三步，用简短的文字描述一下优惠内容。如（蛇口沃尔玛旁氏洗面奶满50减20活动，速来。）'

            }else if(msg.xml.EventKey == 'KEY_INPUT_TEXT')
            {
                content = '↙点击左下角的键盘图标可切换输入模式 :)';
            }

        }
    }else if(msg.xml.MsgType == 'image')
    {
        var fs = require('fs');
        console.log(msg.xml.FromUserName, msg.xml.PicUrl);
        var file = AV.File.withURL(msg.xml.FromUserName, msg.xml.PicUrl);
        console.log(file);
        file.save().then(function(result){console.log(result)},function(error){console.log(error)})

        content = '(1/3) 收到您的照片，如果有多个，请继续拍摄，最多不超过5张。发送当前门店地理位置进行下一步。';

    }else if(msg.xml.MsgType == 'text')
    {
        content = '(2/3) 爆料成功！你可以在菜单[我自己->我的爆料]查看，审核通过后即出现在优惠榜单上。';

    }else if(msg.xml.MsgType == 'location')
    {
        content = '(3/3) 请用简短的文字描述一下优惠内容。如（蛇口沃尔玛洗面奶满50减20活动，速来。）';
    }

  var result = {
    xml: {
      ToUserName: msg.xml.FromUserName[0],
      FromUserName: '' + msg.xml.ToUserName + '',
      CreateTime: new Date().getTime(),
      MsgType: 'text',
      Content: content
    }
  }
  cb(null, result);
}
<commit_msg>debug log<commit_after>var crypto = require('crypto');
var config = require('cloud/config/weixin.js');
var debug = require('debug')('AV:weixin');

exports.exec = function(params, cb) {
  if (params.signature) {
    checkSignature(params.signature, params.timestamp, params.nonce, params.echostr, cb);
  } else {
    receiveMessage(params, cb)
  }
}

// 验证签名
var checkSignature = function(signature, timestamp, nonce, echostr, cb) {
  var oriStr = [config.token, timestamp, nonce].sort().join('')
  var code = crypto.createHash('sha1').update(oriStr).digest('hex');
  debug('code:', code)
  if (code == signature) {
    cb(null, echostr);
  } else {
    var err = new Error('Unauthorized');
    err.code = 401;
    cb(err);
  }
}

// 接收普通消息
var receiveMessage = function(msg, cb) {

    //console.log('weixin Event:', msg.xml.Event);

    var content = '';
    if(msg.xml.MsgType == 'event')//操作事件
    {
        if (msg.xml.Event == 'CLICK')
        {
            if(msg.xml.EventKey == 'KEY_I_LIKE')
            {
                content = '谢谢点赞！'

            }else if(msg.xml.EventKey == 'KEY_USER_GUID')
            {
                content = '爆料方式简单、迅速，全程使用微信操作。\n\n第一步，拍摄实物照片（可以拍摄多张照片，至少1张，最多5张）\n\n第二步，发送当前门店所在的位置信息，以便准确前往。\n\n第三步，用简短的文字描述一下优惠内容。如（蛇口沃尔玛旁氏洗面奶满50减20活动，速来。）'

            }else if(msg.xml.EventKey == 'KEY_INPUT_TEXT')
            {
                content = '↙点击左下角的键盘图标可切换输入模式 :)';
            }

        }
    }else if(msg.xml.MsgType == 'image')
    {
        var fs = require('fs');
        console.log(msg.xml.FromUserName, msg.xml.PicUrl);
        var file = AV.File.withURL(msg.xml.FromUserName, msg.xml.PicUrl);
        console.log('file',file);
        file.save().then(function(result){console.log('result',result)},function(error){console.log('error',error)})

        content = '(1/3) 收到您的照片，如果有多个，请继续拍摄，最多不超过5张。发送当前门店地理位置进行下一步。';

    }else if(msg.xml.MsgType == 'text')
    {
        content = '(2/3) 爆料成功！你可以在菜单[我自己->我的爆料]查看，审核通过后即出现在优惠榜单上。';

    }else if(msg.xml.MsgType == 'location')
    {
        content = '(3/3) 请用简短的文字描述一下优惠内容。如（蛇口沃尔玛洗面奶满50减20活动，速来。）';
    }

  var result = {
    xml: {
      ToUserName: msg.xml.FromUserName[0],
      FromUserName: '' + msg.xml.ToUserName + '',
      CreateTime: new Date().getTime(),
      MsgType: 'text',
      Content: content
    }
  }
  cb(null, result);
}
<|endoftext|>


<commit_before>var MenuItemProperties = function(obj,initial){
	var lock = false;
	var menuItemId = null;
	var properties = {
		id: "",
		type: "entry",
		contexts: ["page"],
		disabled: false,
		title: "",
		icon: "",
		documentURLPatterns: null,
		targetURLPatterns: null,
		parent: null
	};
	var allowedContexts = ["all", "page", "frame", "selection", "link", "editable", "image", "video", "audio"];
	var changed = function(){
		if(!lock)obj.dispatchEvent(new MenuEvent('change',{},obj));
	}
	var update = function(props){
		if(lock)return;

		lock = true;

		if(props!=undefined)for(var name in props)if(properties[name]!==undefined){
			if(name === "type"){

				if(["entry", "folder", "line"].indexOf(String(props.type).toLowerCase())!=-1)properties.type = String(props.type);

			} else if(name === "parent"){
				if(props.parent === null || props.parent instanceof OMenuContext)properties.parent = props.parent;
				else throw new TypeError();

			} else if(name === "id")properties.id = String(props.id);
			else obj[name] = props[name];
		};

		lock = false;
		//update

		if(properties.disabled==true||properties.parent==null){

			if(menuItemId!=null){
				chrome.contextMenus.remove(menuItemId);
				menuItemId = null;
			};

		} else {

			var updateProperties = {
				title: properties.title.length==0?chrome.app.getDetails().name:properties.title,
				type: properties.type.toLowerCase()=="line"?"separator":"normal" //"normal", "checkbox", "radio", "separator"
			};

			var contexts = properties.contexts.join(',').toLowerCase().split(',').filter(function(element){
				return allowedContexts.indexOf(element.toLowerCase())!=-1;
			});

			if(contexts.length==0)updateProperties.contexts = ["page"];
			else updateProperties.contexts = contexts;

			if(properties.parent instanceof MenuItem && properties.parent.menuItemId!=undefined){
				updateProperties.parentId = properties.parent.menuItemId;
			};

			if(menuItemId==null){
				if(properties.id != "")updateProperties.id = properties.id;//set id
				menuItemId = chrome.contextMenus.create(updateProperties);
			} else chrome.contextMenus.update(menuItemId,updateProperties);

			/* unsafe code
			if(
				this.properties.parent instanceof MenuContext && this.properties.icon.length>0 //has icon
				&& !(chrome.app.getDetails().icons && chrome.app.getDetails().icons[16]) // no global 16x16 icon
			){//set custom root icon
				chrome.browserAction.setIcon({path: this.properties.icon });
			};
			*/

		};

	};

	var nosetter = function(value){};

	Object.defineProperty(obj,'id',{enumerable: true,  configurable: false,  get: function(){return properties.id;}, set: nosetter});
	Object.defineProperty(obj,'type',{enumerable: true,  configurable: false,  get: function(){return properties.type;}, set: nosetter});

	Object.defineProperty(obj,'contexts',{enumerable: true,  configurable: false,  get: function(){return properties.contexts;}, set: function(value){
		if(!Array.isArray(value)){
			throw new TypeError();
			return;
		};

		properties.contexts = value.length==0?value:value.join(',').split(',');
		changed();

	}});

	Object.defineProperty(obj,'disabled',{enumerable: true,  configurable: false,  get: function(){return properties.disabled;}, set: function(value){
		properties.disabled = Boolean(value);
		changed();
	}});

	Object.defineProperty(obj,'title',{enumerable: true,  configurable: false,  get: function(){return properties.title;}, set: function(value){
		properties.title = String(value);
		changed();
	}});

	Object.defineProperty(obj,'icon',{enumerable: true,  configurable: false,  get: function(){return properties.icon;}, set: function(value){
		if(typeof value === "string"){
			properties.icon = value;

			if(properties.icon.indexOf(':')==-1&&properties.icon.indexOf('/')==-1&&properties.icon.length>0)properties.icon = '/'+properties.icon;
		};

		changed();
	}});

	Object.defineProperty(obj,'documentURLPatterns',{enumerable: true,  configurable: false,  get: function(){return properties.documentURLPatterns;}, set: function(value){

		if(Array.isArray(value)){
			properties.documentURLPatterns = [];
			for(var i=0;i<value.length;i++)properties.documentURLPatterns.push(String(value[i]).toLowerCase());
		};

		changed();
	}});

	Object.defineProperty(obj,'targetURLPatterns',{enumerable: true,  configurable: false,  get: function(){return properties.targetURLPatterns;}, set: function(value){

		if(Array.isArray(value)){
			properties.targetURLPatterns = [];
			for(var i=0;i<value.length;i++)properties.targetURLPatterns.push(String(value[i]).toLowerCase());
		};

		changed();
	}});

	Object.defineProperty(obj,'menuItemId',{enumerable: false,  configurable: false,  get: function(){return menuItemId;},set: nosetter});

	Object.defineProperty(obj,'parent',{enumerable: true,  configurable: false,  get: function(){
			return properties.parent;
	}, set: nosetter	});

	if(initial!=undefined)update(initial);

	return update;
};

var MenuItem = function(internal,properties ) {
	OMenuContext.apply( this, [internal] );

	var _apply = MenuItemProperties(this,properties);

	//click event
	if(properties.onclick!=undefined)this.onclick = properties.onclick;//set initial click handler

	if(this.type.toLowerCase() === 'entry')chrome.contextMenus.onClicked.addListener(function(_info,_tab) {
    if(this.menuItemId == null || !(this.menuItemId === _info.menuItemId || this.id === _info.menuItemId))return;

    this.dispatchEvent( new MenuEvent('click', {info: _info, tab: _tab},this) );

		var event = new MenuEvent('click', {info: _info, tab: _tab},this);

    OEC.menu.dispatchEvent(event);

		event.source.postMessage({
			"action": "___O_MenuItem_Click",
			"info": _info,
			"menuItemId": this.id
		});

  }.bind(this));

	this.addEventListener('change',function(e){
		if(e.target === this)_apply(e.properties);
		else _apply();

		for(var i=0;i<this.length;i++)this[i].dispatchEvent(new MenuEvent('change',{properties: e.properties},e.target));

	},false);

	Object.defineProperty(this,'toString',{enumerable: false,  configurable: false, writable: false, value: function(event){
		return "[object MenuItem]";
	}});

};

MenuItem.prototype = Object.create( OMenuContext.prototype );

<commit_msg>menuitem remove fix<commit_after>var MenuItemProperties = function(obj,initial){
	var lock = false;
	var menuItemId = null;
	var properties = {
		id: "",
		type: "entry",
		contexts: ["page"],
		disabled: false,
		title: "",
		icon: "",
		documentURLPatterns: null,
		targetURLPatterns: null,
		parent: null
	};
	var allowedContexts = ["all", "page", "frame", "selection", "link", "editable", "image", "video", "audio"];
	var changed = function(){
		if(!lock)obj.dispatchEvent(new MenuEvent('change',{},obj));
	}
	var update = function(props){
		if(lock)return;

		lock = true;

		if(props!=undefined)for(var name in props)if(properties[name]!==undefined){
			if(name === "type"){

				if(["entry", "folder", "line"].indexOf(String(props.type).toLowerCase())!=-1)properties.type = String(props.type);

			} else if(name === "parent"){
				if(props.parent === null || props.parent instanceof OMenuContext)properties.parent = props.parent;
				else throw new TypeError();

			} else if(name === "id")properties.id = String(props.id);
			else obj[name] = props[name];
		};

		lock = false;
		//update

		if(properties.parent==null || (properties.parent instanceof MenuItem && properties.parent.menuItemId!=null) ){

			if(menuItemId!=null){
				chrome.contextMenus.remove(menuItemId);
				menuItemId = null;
			};

		} else if(properties.disabled==true){

			if(menuItemId!=null){
				chrome.contextMenus.remove(menuItemId);
				menuItemId = null;
			};

		} else {

			var updateProperties = {
				title: properties.title.length==0?chrome.app.getDetails().name:properties.title,
				type: properties.type.toLowerCase()=="line"?"separator":"normal" //"normal", "checkbox", "radio", "separator"
			};

			var contexts = properties.contexts.join(',').toLowerCase().split(',').filter(function(element){
				return allowedContexts.indexOf(element.toLowerCase())!=-1;
			});

			if(contexts.length==0)updateProperties.contexts = ["page"];
			else updateProperties.contexts = contexts;

			if(properties.parent instanceof MenuItem && properties.parent.menuItemId!=null){
				updateProperties.parentId = properties.parent.menuItemId;
			};

			if(menuItemId==null){
				if(properties.id != "")updateProperties.id = properties.id;//set id
				menuItemId = chrome.contextMenus.create(updateProperties);
			} else chrome.contextMenus.update(menuItemId,updateProperties);

			/* unsafe code
			if(
				this.properties.parent instanceof MenuContext && this.properties.icon.length>0 //has icon
				&& !(chrome.app.getDetails().icons && chrome.app.getDetails().icons[16]) // no global 16x16 icon
			){//set custom root icon
				chrome.browserAction.setIcon({path: this.properties.icon });
			};
			*/

		};

	};

	var nosetter = function(value){};

	Object.defineProperty(obj,'id',{enumerable: true,  configurable: false,  get: function(){return properties.id;}, set: nosetter});
	Object.defineProperty(obj,'type',{enumerable: true,  configurable: false,  get: function(){return properties.type;}, set: nosetter});

	Object.defineProperty(obj,'contexts',{enumerable: true,  configurable: false,  get: function(){return properties.contexts;}, set: function(value){
		if(!Array.isArray(value)){
			throw new TypeError();
			return;
		};

		properties.contexts = value.length==0?value:value.join(',').split(',');
		changed();

	}});

	Object.defineProperty(obj,'disabled',{enumerable: true,  configurable: false,  get: function(){return properties.disabled;}, set: function(value){
		properties.disabled = Boolean(value);
		changed();
	}});

	Object.defineProperty(obj,'title',{enumerable: true,  configurable: false,  get: function(){return properties.title;}, set: function(value){
		properties.title = String(value);
		changed();
	}});

	Object.defineProperty(obj,'icon',{enumerable: true,  configurable: false,  get: function(){return properties.icon;}, set: function(value){
		if(typeof value === "string"){
			properties.icon = value;

			if(properties.icon.indexOf(':')==-1&&properties.icon.indexOf('/')==-1&&properties.icon.length>0)properties.icon = '/'+properties.icon;
		};

		changed();
	}});

	Object.defineProperty(obj,'documentURLPatterns',{enumerable: true,  configurable: false,  get: function(){return properties.documentURLPatterns;}, set: function(value){

		if(Array.isArray(value)){
			properties.documentURLPatterns = [];
			for(var i=0;i<value.length;i++)properties.documentURLPatterns.push(String(value[i]).toLowerCase());
		};

		changed();
	}});

	Object.defineProperty(obj,'targetURLPatterns',{enumerable: true,  configurable: false,  get: function(){return properties.targetURLPatterns;}, set: function(value){

		if(Array.isArray(value)){
			properties.targetURLPatterns = [];
			for(var i=0;i<value.length;i++)properties.targetURLPatterns.push(String(value[i]).toLowerCase());
		};

		changed();
	}});

	Object.defineProperty(obj,'menuItemId',{enumerable: false,  configurable: false,  get: function(){return menuItemId;},set: nosetter});

	Object.defineProperty(obj,'parent',{enumerable: true,  configurable: false,  get: function(){
			return properties.parent;
	}, set: nosetter	});

	if(initial!=undefined)update(initial);

	return update;
};

var MenuItem = function(internal,properties ) {
	OMenuContext.apply( this, [internal] );

	var _apply = MenuItemProperties(this,properties);

	//click event
	if(properties.onclick!=undefined)this.onclick = properties.onclick;//set initial click handler

	if(this.type.toLowerCase() === 'entry')chrome.contextMenus.onClicked.addListener(function(_info,_tab) {
    if(this.menuItemId == null || !(this.menuItemId === _info.menuItemId || this.id === _info.menuItemId))return;

    this.dispatchEvent( new MenuEvent('click', {info: _info, tab: _tab},this) );

		var event = new MenuEvent('click', {info: _info, tab: _tab},this);

    OEC.menu.dispatchEvent(event);

		event.source.postMessage({
			"action": "___O_MenuItem_Click",
			"info": _info,
			"menuItemId": this.id
		});

  }.bind(this));

	this.addEventListener('change',function(e){
		if(e.target === this)_apply(e.properties);
		else _apply();

		for(var i=0;i<this.length;i++)this[i].dispatchEvent(new MenuEvent('change',{properties: e.properties},e.target));

	},false);

	Object.defineProperty(this,'toString',{enumerable: false,  configurable: false, writable: false, value: function(event){
		return "[object MenuItem]";
	}});

};

MenuItem.prototype = Object.create( OMenuContext.prototype );

<|endoftext|>


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

require('es5-shim');
require('es5-sham');

require('jquery');
var angular = require('angular');
require('angular-resource');
require('angular-route');
require('angular-ui-router');
require('angular-ui-bootstrap');
require('angular-ui-bootstrap-tpls');
require('jolokia');

var springBootAdmin = angular.module('springBootAdmin', [
    'ngResource',
    'ngRoute',
    'ui.router',
    'ui.bootstrap'
]);

require('./controller');
require('./service');
require('./filter');
require('./directive');

springBootAdmin.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider
        .when('/', '/overview')
        .otherwise('/');

    $stateProvider
        .state('overview', {
            url: '/overview',
            templateUrl: 'views/overview.html',
            controller: 'overviewCtrl'
        })
        .state('about', {
            url: '/about',
            templateUrl: 'views/about.html'
        })
        .state('apps', {
            abstract: true,
            url: '/apps/:id',
            controller: 'appsCtrl',
            templateUrl: 'views/apps.html',
            resolve: {
                application: function ($stateParams, Application) {
                    return Application.get({
                        id: $stateParams.id
                    }).$promise;
                }
            }
        })
        .state('apps.details', {
            url: '/details',
            templateUrl: 'views/apps/details.html',
            controller: 'detailsCtrl'
        })
        .state('apps.details.metrics', {
            url: '/metrics',
            templateUrl: 'views/apps/details/metrics.html',
            controller: 'detailsMetricsCtrl'
        })
        .state('apps.details.classpath', {
            url: '/classpath',
            templateUrl: 'views/apps/details/classpath.html',
            controller: 'detailsClasspathCtrl'
        })
        .state('apps.env', {
            url: '/env',
            templateUrl: 'views/apps/environment.html',
            controller: 'environmentCtrl'
        })
        .state('apps.activiti', {
            url: '/activiti',
            templateUrl: 'views/apps/activiti.html',
            controller: 'activitiCtrl'
        })
        .state('apps.logging', {
            url: '/logging',
            templateUrl: 'views/apps/logging.html',
            controller: 'loggingCtrl'
        })
        .state('apps.jmx', {
            url: '/jmx',
            templateUrl: 'views/apps/jmx.html',
            controller: 'jmxCtrl'
        })
        .state('apps.threads', {
            url: '/threads',
            templateUrl: 'views/apps/threads.html',
            controller: 'threadsCtrl'
        })
        .state('apps.trace', {
            url: '/trace',
            templateUrl: 'views/apps/trace.html',
            controller: 'traceCtrl'
        })
       .state('journal', {
            url: '/journal',
            templateUrl: 'views/journal.html',
            controller: 'journalCtrl'
        });
});

springBootAdmin.run(function ($rootScope, $state, $log, $filter, Notification, Application ) {
    $rootScope.$state = $state;
    $rootScope.applications = [];
    $rootScope.indexOfApplication = function (id) {
       for (var i = 0; i <  $rootScope.applications.length; i++) {
            if ($rootScope.applications[i].id === id) {
                return i;
            }
       }
       return -1;
    };

    var refresh = function(application) {
        application.info = {};
        application.refreshing = true;
        application.getCapabilities();
        application.getInfo().then(function(info) {
            application.version = info.version;
            application.infoDetails = null;
            application.infoShort = '';
            delete info.version;
            var infoYml = $filter('yaml')(info);
            if (infoYml !== '{}\n') {
                application.infoShort = $filter('limitLines')(infoYml, 3);
                if (application.infoShort !== infoYml) {
                     application.infoDetails = $filter('limitLines')(infoYml, 32000, 3);
                }
            }
          }).finally(function(){
              application.refreshing = false;
          });
    };

    Application.query(function (applications) {
        for (var i = 0; i < applications.length; i++) {
                refresh(applications[i]);
        }
        $rootScope.applications = applications;
    });

    //setups up the sse-reciever
    var journalEventSource = new EventSource('api/journal');
    journalEventSource.onmessage = function(message) {
        var event = JSON.parse(message.data);
        Object.setPrototypeOf(event.application, Application.prototype);

        var options = { tag: event.application.id,
                        body: 'Instance ' + event.application.id + '\n' + event.application.healthUrl,
                        icon: 'img/unknown.png',
                        timeout: 10000,
                        url: $state.href('apps.details', {id: event.application.id}) };
        var title = event.application.name;
        var index = $rootScope.indexOfApplication(event.application.id);

        if (event.type === 'REGISTRATION') {
            if (index === -1) {
                $rootScope.applications.push(event.application);
            }

            title += ' instance registered.';
            options.tag = event.application.id + '-REGISTRY';
        } else if (event.type === 'DEREGISTRATION') {
            if (index > -1) {
                $rootScope.applications.splice(index, 1);
            }

            title += ' instance removed.';
            options.tag = event.application.id + '-REGISTRY';
        } else if (event.type === 'STATUS_CHANGE') {
            refresh(event.application);
            if (index > -1) {
                $rootScope.applications[index] = event.application;
            } else {
                $rootScope.applications.push(event.application);
            }

            title += ' instance is ' + event.to.status;
            options.tag = event.application.id + '-STATUS';
            options.icon = event.to.status !== 'UP' ? 'img/error.png' : 'img/ok.png';
            options.body = event.from.status + ' --> ' + event.to.status + '\n' + options.body;
        }

        $rootScope.$apply();
        Notification.notify(title, options);
    };

    journalEventSource.onerror = function(event) {
        $log.error('Could not read server sent event!', event);
    };
});
<commit_msg>Fix needed page refresh when first app showed up<commit_after>/*
 * Copyright 2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

require('es5-shim');
require('es5-sham');

require('jquery');
var angular = require('angular');
require('angular-resource');
require('angular-route');
require('angular-ui-router');
require('angular-ui-bootstrap');
require('angular-ui-bootstrap-tpls');
require('jolokia');

var springBootAdmin = angular.module('springBootAdmin', [
    'ngResource',
    'ngRoute',
    'ui.router',
    'ui.bootstrap'
]);

require('./controller');
require('./service');
require('./filter');
require('./directive');

springBootAdmin.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider
        .when('/', '/overview')
        .otherwise('/');

    $stateProvider
        .state('overview', {
            url: '/overview',
            templateUrl: 'views/overview.html',
            controller: 'overviewCtrl'
        })
        .state('about', {
            url: '/about',
            templateUrl: 'views/about.html'
        })
        .state('apps', {
            abstract: true,
            url: '/apps/:id',
            controller: 'appsCtrl',
            templateUrl: 'views/apps.html',
            resolve: {
                application: function ($stateParams, Application) {
                    return Application.get({
                        id: $stateParams.id
                    }).$promise;
                }
            }
        })
        .state('apps.details', {
            url: '/details',
            templateUrl: 'views/apps/details.html',
            controller: 'detailsCtrl'
        })
        .state('apps.details.metrics', {
            url: '/metrics',
            templateUrl: 'views/apps/details/metrics.html',
            controller: 'detailsMetricsCtrl'
        })
        .state('apps.details.classpath', {
            url: '/classpath',
            templateUrl: 'views/apps/details/classpath.html',
            controller: 'detailsClasspathCtrl'
        })
        .state('apps.env', {
            url: '/env',
            templateUrl: 'views/apps/environment.html',
            controller: 'environmentCtrl'
        })
        .state('apps.activiti', {
            url: '/activiti',
            templateUrl: 'views/apps/activiti.html',
            controller: 'activitiCtrl'
        })
        .state('apps.logging', {
            url: '/logging',
            templateUrl: 'views/apps/logging.html',
            controller: 'loggingCtrl'
        })
        .state('apps.jmx', {
            url: '/jmx',
            templateUrl: 'views/apps/jmx.html',
            controller: 'jmxCtrl'
        })
        .state('apps.threads', {
            url: '/threads',
            templateUrl: 'views/apps/threads.html',
            controller: 'threadsCtrl'
        })
        .state('apps.trace', {
            url: '/trace',
            templateUrl: 'views/apps/trace.html',
            controller: 'traceCtrl'
        })
       .state('journal', {
            url: '/journal',
            templateUrl: 'views/journal.html',
            controller: 'journalCtrl'
        });
});

springBootAdmin.run(function ($rootScope, $state, $log, $filter, Notification, Application ) {
    $rootScope.$state = $state;
    $rootScope.applications = [];

    $rootScope.indexOfApplication = function (id) {
       for (var i = 0; i <  $rootScope.applications.length; i++) {
            if ($rootScope.applications[i].id === id) {
                return i;
            }
       }
       return -1;
    };

    var refresh = function(application) {
        application.info = {};
        application.refreshing = true;
        application.getCapabilities();
        application.getInfo().then(function(info) {
            application.version = info.version;
            application.infoDetails = null;
            application.infoShort = '';
            delete info.version;
            var infoYml = $filter('yaml')(info);
            if (infoYml !== '{}\n') {
                application.infoShort = $filter('limitLines')(infoYml, 3);
                if (application.infoShort !== infoYml) {
                     application.infoDetails = $filter('limitLines')(infoYml, 32000, 3);
                }
            }
          }).finally(function(){
              application.refreshing = false;
          });
    };

    Application.query(function (applications) {
        for (var i = 0; i < applications.length; i++) {
            refresh(applications[i]);
            $rootScope.applications.push(applications[i]);
        }
    });

    //setups up the sse-reciever
    var journalEventSource = new EventSource('api/journal');
    journalEventSource.onmessage = function(message) {
        var event = JSON.parse(message.data);
        Object.setPrototypeOf(event.application, Application.prototype);

        var options = { tag: event.application.id,
                        body: 'Instance ' + event.application.id + '\n' + event.application.healthUrl,
                        icon: 'img/unknown.png',
                        timeout: 10000,
                        url: $state.href('apps.details', {id: event.application.id}) };
        var title = event.application.name;
        var index = $rootScope.indexOfApplication(event.application.id);

        if (event.type === 'REGISTRATION') {
            if (index === -1) {
                $rootScope.applications.push(event.application);
            }

            title += ' instance registered.';
            options.tag = event.application.id + '-REGISTRY';
        } else if (event.type === 'DEREGISTRATION') {
            if (index > -1) {
                $rootScope.applications.splice(index, 1);
            }

            title += ' instance removed.';
            options.tag = event.application.id + '-REGISTRY';
        } else if (event.type === 'STATUS_CHANGE') {
            refresh(event.application);
            if (index > -1) {
                $rootScope.applications[index] = event.application;
            } else {
                $rootScope.applications.push(event.application);
            }

            title += ' instance is ' + event.to.status;
            options.tag = event.application.id + '-STATUS';
            options.icon = event.to.status !== 'UP' ? 'img/error.png' : 'img/ok.png';
            options.body = event.from.status + ' --> ' + event.to.status + '\n' + options.body;
        }

        $rootScope.$apply();
        Notification.notify(title, options);
    };

    journalEventSource.onerror = function(event) {
        $log.error('Could not read server sent event!', event);
    };
});
<|endoftext|>


<commit_before>// Config
var enterKey = 13;
var deleteKey = 44;
var multipleKeys = [
	{ 'code': 97,  'characters': [ 'a', 'á' ] },
	{ 'code': 101, 'characters': [ 'e', 'é' ] },
	{ 'code': 105, 'characters': [ 'i', 'í' ] },
	{ 'code': 111, 'characters': [ 'o', 'ó' ] },
	{ 'code': 117, 'characters': [ 'u', 'ú' ] },
	{ 'code': 161, 'characters': [ '¡', '!' ] },
	{ 'code': 39,  'characters': [ '¿', '?' ] },
	{ 'code': 49,  'characters': [ '1', ':' ] },
	{ 'code': 50,  'characters': [ '2', ',' ] },
	{ 'code': 45,  'characters': [ '-', '_' ] }
];
var timeToMultiple = 1000;

// Functions
function play (url)
{
	new Audio (url).play ();
}
function showKey (selector, delay)
{
	// Hide all others
	$('.keys').not (selector)
		.finish ()
		.hide ();

	if ($(selector).is(':visible'))
		$(selector)
			.finish()
			.show();
	else
		$(selector).show ('fade');

	$(selector)
		.delay (delay)
		.hide ('fade');
}
function showPressed (s)
{
	$('#pressed')
		.text (s);
	showKey ('#pressed', 400);
}
function showPressedSpecial (name)
{
	showKey (name, 400);
}
function showPressedMultiple (item, charIndex, first)
{
	// First?
	if (first)
	{
		// Clear and add keys
		$('#multiple > .container')
			.empty();
		$.each (item.characters, function (i, item)
		{
			$('#multiple > .container').append ($('<div>').text (item));
		});
	}

	// Highlight selected
	$('#multiple > .container > div')
		.removeClass ('selected')
		.eq (charIndex).addClass ('selected');

	// Animate progress
	$('#multiple > .progressContainer > div')
		.finish ()
		.css ('width', '0%')
		.animate ({ 'width': '100%'}, timeToMultiple);

	showKey ('#multiple', timeToMultiple);
}
function addChar (s)
{
	$('#textbox span').append (s);
	showPressed (s);
}
function deleteChar ()
{
	var $span = $('#textbox span');
	var currentText = $span.text();
	var newText = currentText.substr (0, currentText.length - 1);
	$span.text (newText);
}

$(function ()
{
	// Variables
	var last = 0;
	var lastChar = null;
	var multipleIndex = 0;
	$('.keys').hide();

	// Event
	$(document).keypress (function (event)
	{
		console.log (event.charCode);
		// Enter
		if (event.charCode == enterKey)
		{
			showPressedSpecial (".specialKey.enter");
			$('#textbox span').empty();
			play ('audio/enter.wav');
			lastChar = event.charCode;
			return;
		}

		play ('audio/key.wav');

		// Delete
		if (event.charCode == deleteKey)
		{
			showPressedSpecial (".specialKey.backspace");
			deleteChar();
			lastChar = event.charCode;
			return;
		}

		// Multiple
		var found = Enumerable.From (multipleKeys)
			.Where (function (x) { return x.code == event.charCode; })
			.FirstOrDefault();
		if (found !== undefined)
		{
			var now = (new Date()).getTime();
			var isFirst = (lastChar != event.charCode || now - last > timeToMultiple);
			if (isFirst)
				multipleIndex = 0;
			else
				deleteChar();
			var indexToShow = multipleIndex++ % found.characters.length;
			$('#textbox span').append (found.characters [indexToShow]);
			showPressedMultiple (found, indexToShow, isFirst);
			last = now;
			lastChar = event.charCode;
			return;
		}

		// Normal key
		lastChar = event.charCode;
		addChar (String.fromCharCode (event.charCode));
	});
});
<commit_msg>Using keydown instead of keypress<commit_after>// Config
var enterKey = 13;
var deleteKey = 8;
var shiftKey = 16;
var mapedKeys = [
	{ 'code': 186, 'character': 'ñ' }
];
var multipleKeys = [
	{ 'code': 65, 'characters': [ 'a', 'á' ] },
	{ 'code': 69, 'characters': [ 'e', 'é' ] },
	{ 'code': 105, 'characters': [ 'i', 'í' ] },
	{ 'code': 111, 'characters': [ 'o', 'ó' ] },
	{ 'code': 117, 'characters': [ 'u', 'ú' ] },
	{ 'code': 187, 'characters': [ '¡', '!' ] },
	{ 'code': 189, 'characters': [ '¿', '?' ] },
	{ 'code': 49,  'characters': [ '1', ':' ] },
	{ 'code': 50,  'characters': [ '2', ',' ] },
	{ 'code': 45,  'characters': [ '-', '_' ] }
];
var timeToMultiple = 1000;

// Functions
function play (url)
{
	new Audio (url).play ();
}
function showKey (selector, delay)
{
	// Hide all others
	$('.keys').not (selector)
		.finish ()
		.hide ();

	if ($(selector).is(':visible'))
		$(selector)
			.finish()
			.show();
	else
		$(selector).show ('fade');

	$(selector)
		.delay (delay)
		.hide ('fade');
}
function showPressed (s)
{
	$('#pressed')
		.text (s);
	showKey ('#pressed', 400);
	$('#shift').hide ();
}
function showPressedSpecial (name)
{
	showKey (name, 400);
}
function showPressedMultiple (item, charIndex, first)
{
	// First?
	if (first)
	{
		// Clear and add keys
		$('#multiple > .container')
			.empty();
		$.each (item.characters, function (i, item)
		{
			$('#multiple > .container').append ($('<div>').text (item));
		});
	}

	// Highlight selected
	$('#multiple > .container > div')
		.removeClass ('selected')
		.eq (charIndex).addClass ('selected');

	// Animate progress
	$('#multiple > .progressContainer > div')
		.finish ()
		.css ('width', '0%')
		.animate ({ 'width': '100%'}, timeToMultiple);

	showKey ('#multiple', timeToMultiple);
}
function addChar (s)
{
	$('#textbox span').append (s);
	showPressed (s);
}
function deleteChar ()
{
	var $span = $('#textbox span');
	var currentText = $span.text();
	var newText = currentText.substr (0, currentText.length - 1);
	$span.text (newText);
}

$(function ()
{
	// Variables
	var last = 0;
	var lastChar = null;
	var multipleIndex = 0;
	$('.keys').hide();
	$('#shift').hide();

	// Event
	$(document).keydown (function (event)
	{
		console.log (event.keyCode);
		// Enter
		if (event.keyCode == enterKey)
		{
			showPressedSpecial (".specialKey.enter");
			$('#textbox span').empty();
			play ('audio/enter.wav');
			lastChar = event.keyCode;
			return;
		}

		play ('audio/key.wav');

		// Delete
		if (event.keyCode == deleteKey)
		{
			showPressedSpecial (".specialKey.backspace");
			deleteChar();
			lastChar = event.keyCode;
			return;
		}

		// Mapped
		var foundMapped = Enumerable.From (mapedKeys)
			.Where (function (x) { return x.code == event.keyCode; })
			.FirstOrDefault ();
		if (foundMapped)
		{
			lastChar = event.keyCode
			addChar (foundMapped.character);
			return;
		}

		// Multiple
		var found = Enumerable.From (multipleKeys)
			.Where (function (x) { return x.code == event.keyCode; })
			.FirstOrDefault();
		if (found !== undefined)
		{
			var now = (new Date()).getTime();
			var isFirst = (lastChar != event.keyCode || now - last > timeToMultiple);
			if (isFirst)
				multipleIndex = 0;
			else
				deleteChar();
			var indexToShow = multipleIndex++ % found.characters.length;
			$('#textbox span').append (found.characters [indexToShow]);
			showPressedMultiple (found, indexToShow, isFirst);
			last = now;
			lastChar = event.keyCode;
			return;
		}

		// Shift
		if (event.keyCode == shiftKey)
		{
			$('#shift').toggle ();
			return;
		}

		// Normal key
		var s = String.fromCharCode (event.keyCode);
		lastChar = event.keyCode;
		addChar (s);
	});
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { observer as globalObserver } from '../../../common/utils/observer';
import { translate } from '../../../common/i18n';
import Summary from './Summary';
import TradeTable from './TradeTable';
import RunButton from './RunButton';

const resetAnimation = () => {
    $('.circle-wrapper')
        .removeClass('active')
        .removeClass('complete');
    $('.line')
        .removeClass('active')
        .removeClass('complete');
    $('.stage-tooltip:not(.top)').removeClass('active');
};

const activateStage = index => {
    if (index > 0) {
        $(`.circle-wrapper:eq(${index - 1})`).removeClass('active');
        $(`.circle-wrapper:eq(${index - 1})`).addClass('complete');
    }
    $(`.circle-wrapper:eq(${index})`).addClass('active');
    $(`.stage-tooltip.bottom:eq(${index})`).addClass('active');
};

class AnimateTrade extends Component {
    constructor() {
        super();
        this.indicatorMessages = {
            notRunning: translate('Bot is not running.'),
            running   : translate('Bot is running...'),
            stopping  : translate('Bot is stopping...'),
            stopped   : translate('Bot has stopped.'),
        };
        this.state = {
            indicatorMessage: this.indicatorMessages.notRunning,
            stopMessage     : this.indicatorMessages.stopped,
        };
    }
    componentWillMount() {
        globalObserver.register('bot.stop', () => {
            $('.stage-tooltip.top:eq(0)').removeClass('running');
            this.setState({ indicatorMessage: this.indicatorMessages.stopped });
        });
        $('#stopButton').click(() => {
            $('.stage-tooltip.top:eq(0)').removeClass('running');
            this.setState({ indicatorMessage: this.state.stopMessage });
        });
        $('#runButton').click(() => {
            resetAnimation();
            $('.stage-tooltip.top:eq(0)').addClass('running');
            this.setState({ indicatorMessage: this.indicatorMessages.running });
            globalObserver.register('contract.status', contractStatus => {
                this.animateStage(contractStatus);
            });
        });
    }
    animateStage(contractStatus) {
        if (contractStatus.id === 'contract.purchase_sent') {
            resetAnimation();
            activateStage(0);
            this.setState({ buy_price: contractStatus.data, stopMessage: this.indicatorMessages.stopping });
        } else if (contractStatus.id === 'contract.purchase_recieved') {
            $('.line').addClass('active');
            activateStage(1);
            this.setState({ buy_id: contractStatus.data });
        } else if (contractStatus.id === 'contract.sold') {
            $('.line').addClass('complete');
            activateStage(2);
            this.setState({ sell_id: contractStatus.data, stopMessage: this.indicatorMessages.stopped });
        }
        activateStage(contractStatus.id);
    }
    render() {
        return (

{translate('Attempting to Buy')}

                                {translate('Buy amount')}: {this.state.buy_price || 0}

{this.state.indicatorMessage}

{translate('Buy succeeded')}

                                {translate('ID')}: {this.state.buy_id || ''}

{translate('Contract closed')}

                                {translate('ID')}: {this.state.sell_id || ''}

        );
    }
}

export default class TradeInfoPanel extends Component {
    constructor() {
        super();
        this.state = { accountID: '', accountIDList: [], currentAccountID: '' };
    }
    componentWillMount() {
        globalObserver.register('bot.info', ({ accountID }) => {
            const { accountIDList } = this.state;
            if (!accountIDList.includes(accountID)) {
                this.setState({ accountIDList: [...accountIDList, accountID] });
            }
            if (!this.state.accountID) {
                this.setState({ accountID });
            }
            this.setState({ currentAccountID: accountID });
        });
    }
    render() {
        const { accountID } = this.state;

        return (

                        <RunButton />

                        <AnimateTrade />

                        <TradeTable accountID={accountID} />

                            {translate(
                                'Stopping the bot will prevent further trades. Any ongoing trades will be completed by our system. Please be aware that some completed transactions may not be displayed in the table if the bot is stopped while placing trades. You may refer to the Binary.com statement page for details of all completed transactions.'
                            )}

        );
    }
}
<commit_msg>Add ClearButton to TradeInfoPanel, wrap RunButton+ClearButton in summary-toolbox<commit_after>import React, { Component } from 'react';
import { observer as globalObserver } from '../../../common/utils/observer';
import { translate } from '../../../common/i18n';
import Summary from './Summary';
import TradeTable from './TradeTable';
import RunButton from './RunButton';
import ClearButton from './ClearButton';

const resetAnimation = () => {
    $('.circle-wrapper')
        .removeClass('active')
        .removeClass('complete');
    $('.line')
        .removeClass('active')
        .removeClass('complete');
    $('.stage-tooltip:not(.top)').removeClass('active');
};

const activateStage = index => {
    if (index > 0) {
        $(`.circle-wrapper:eq(${index - 1})`).removeClass('active');
        $(`.circle-wrapper:eq(${index - 1})`).addClass('complete');
    }
    $(`.circle-wrapper:eq(${index})`).addClass('active');
    $(`.stage-tooltip.bottom:eq(${index})`).addClass('active');
};

class AnimateTrade extends Component {
    constructor() {
        super();
        this.indicatorMessages = {
            notRunning: translate('Bot is not running.'),
            running   : translate('Bot is running...'),
            stopping  : translate('Bot is stopping...'),
            stopped   : translate('Bot has stopped.'),
        };
        this.state = {
            indicatorMessage: this.indicatorMessages.notRunning,
            stopMessage     : this.indicatorMessages.stopped,
        };
    }
    componentWillMount() {
        globalObserver.register('bot.stop', () => {
            $('.stage-tooltip.top:eq(0)').removeClass('running');
            this.setState({ indicatorMessage: this.indicatorMessages.stopped });
        });
        $('#stopButton').click(() => {
            $('.stage-tooltip.top:eq(0)').removeClass('running');
            this.setState({ indicatorMessage: this.state.stopMessage });
        });
        $('#runButton').click(() => {
            resetAnimation();
            $('.stage-tooltip.top:eq(0)').addClass('running');
            this.setState({ indicatorMessage: this.indicatorMessages.running });
            globalObserver.register('contract.status', contractStatus => {
                this.animateStage(contractStatus);
            });
        });
    }
    animateStage(contractStatus) {
        if (contractStatus.id === 'contract.purchase_sent') {
            resetAnimation();
            activateStage(0);
            this.setState({ buy_price: contractStatus.data, stopMessage: this.indicatorMessages.stopping });
        } else if (contractStatus.id === 'contract.purchase_recieved') {
            $('.line').addClass('active');
            activateStage(1);
            this.setState({ buy_id: contractStatus.data });
        } else if (contractStatus.id === 'contract.sold') {
            $('.line').addClass('complete');
            activateStage(2);
            this.setState({ sell_id: contractStatus.data, stopMessage: this.indicatorMessages.stopped });
        }
        activateStage(contractStatus.id);
    }
    render() {
        return (

{translate('Attempting to Buy')}

                                {translate('Buy amount')}: {this.state.buy_price || 0}

{this.state.indicatorMessage}

{translate('Buy succeeded')}

                                {translate('ID')}: {this.state.buy_id || ''}

{translate('Contract closed')}

                                {translate('ID')}: {this.state.sell_id || ''}

        );
    }
}

export default class TradeInfoPanel extends Component {
    constructor() {
        super();
        this.state = { accountID: '', accountIDList: [], currentAccountID: '' };
    }
    componentWillMount() {
        globalObserver.register('bot.info', ({ accountID }) => {
            const { accountIDList } = this.state;
            if (!accountIDList.includes(accountID)) {
                this.setState({ accountIDList: [...accountIDList, accountID] });
            }
            if (!this.state.accountID) {
                this.setState({ accountID });
            }
            this.setState({ currentAccountID: accountID });
        });
    }
    render() {
        const { accountID } = this.state;

        return (

                            <RunButton />
                            <ClearButton />

                        <AnimateTrade />

                        <TradeTable accountID={accountID} />

                            {translate(
                                'Stopping the bot will prevent further trades. Any ongoing trades will be completed by our system. Please be aware that some completed transactions may not be displayed in the table if the bot is stopped while placing trades. You may refer to the Binary.com statement page for details of all completed transactions.'
                            )}

        );
    }
}
<|endoftext|>


<commit_before>const PROJECTS = [
  {
    'title': 'Persona 5 Item Lookup',
    'url': 'https://quan.github.io/persona5_items/',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'Madotsuki Walker',
    'url': 'https://quan.github.io/madotsuki/',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'Inkwell',
    'url': 'https://quan.github.io/inkwell_website/',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'PolyRents',
    'url': 'https://polyrents.com',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'AsterRide',
    'url': 'https://www.asterride.com',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'Facebook vs. Fake News',
    'url': 'https://quan.github.io/facebook_fakenews/main.pdf',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }
]

function loadProjects (links) {
  const projectList = document.getElementById('project-list')

  for (let i in links) {
    const link = '
' + links[i].title + '
'
    projectList.innerHTML += link
  }
}

// main
window.onload = () => {
  loadProjects(PROJECTS)
}
<commit_msg>updated link name for persona 5 items<commit_after>const PROJECTS = [
  {
    'title': 'Persona 5 Item Listings',
    'url': 'https://quan.github.io/persona5-items/',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'Madotsuki Walker',
    'url': 'https://quan.github.io/madotsuki/',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'Inkwell',
    'url': 'https://quan.github.io/inkwell_website/',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'PolyRents',
    'url': 'https://polyrents.com',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'AsterRide',
    'url': 'https://www.asterride.com',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }, {
    'title': 'Facebook vs. Fake News',
    'url': 'https://quan.github.io/facebook_fakenews/main.pdf',
    'image': '',
    'description': {
      'short': '',
      'long': ''
    },
    'tech-stack': ''
  }
]

function loadProjects (links) {
  const projectList = document.getElementById('project-list')

  for (let i in links) {
    const link = '
' + links[i].title + '
'
    projectList.innerHTML += link
  }
}

// main
window.onload = () => {
  loadProjects(PROJECTS)
}
<|endoftext|>


<commit_before>var ref = new Firebase("https://paktutor.firebaseio.com");
var user;

function loginGoogle() {
	ref.authWithOAuthRedirect("google", function(error) {
		if (error) {
			console.log("Authentication Failed!", error);
		}
	}, {
		remember: "sessionOnly"
	});
}

// Logged in
ref.onAuth(function(authData) {
	if(authData)
	{
		user = new Firebase("https://paktutor.firebaseio.com/users/" + authData.uid);
		user.update({"name": authData.google.displayName});
		$("#navMenu span").append("Hi, " + authData.google.displayName);
		setTimeout(function() {
			window.location = "home.html";
		}, 2000);
	}
});
//

$(document).ready(function() {
	var src = $("#googleLogin").attr("src");

	$("#googleLogin").hover(function() {
		$(this).attr("src", "google/google_light_focus.png");

		$("#googleLogin").mousedown(function() {
			$(this).attr("src", "google/google_light_pressed.png");
		});
		$("#googleLogin").mouseup(function() {
			$(this).attr("src", "google/google_light_focus.png");
			loginGoogle();
		});
		}, function() {
			$(this).attr("src", src);
	});
});

<commit_msg>Delete index.js<commit_after><|endoftext|>


<commit_before>
var sitewidth = 1000,
		siteheight = 800;

var rangeToRange = function(oldVal, oldMax, oldMin, newMax, newMin){
	return ( ( ( oldVal - oldMin ) * ( newMax - newMin ) ) / ( oldMax - oldMin ) ) + newMin;
};

	// Animates the Spider for the halloween landing page

	var $spider = $('#spider'),
		spiderWidth = $spider.width(),
		spiderHeight = $spider.height();

	var ps = function(x, y){

		var values = {
			x: rangeToRange(x, 100, 0, sitewidth + spiderWidth, 0),
			y: rangeToRange(y, 100, 0, siteheight + spiderHeight, 0)
		};

		return values;

	};

	var spiderAnimate = function(){

		TweenMax
			.to($spider, 8, {
				bezier: {
					type: 'soft',
					values: [
						ps(0, 10),
						ps(20, 30),
						ps(60, -10)
					],
					autoRotate: true
				},
				ease: Power1.easeInOut,
				force3D: true
			});

		TweenMax
			.to($spider, 8, {
				bezier: {
					type: 'soft',
					values: [
						ps(0, 40),
						ps(110, 40)
					],
					autoRotate: true
				},
				ease: Power1.easeInOut,
				delay: 7,
				force3D: true,
				onComplete: function(){

					TweenMax
						.set($spider, {
							x: 0,
							y: 0
						});

					setTimeout(spiderAnimate, 2000);

				}
			});

	};

	spiderAnimate();
<commit_msg>Delete index.js<commit_after><|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);

    }

};
function bootme() {
        console.log('ready');
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
    }

    function gotFS(fileSystem) {
        console.log('gotfs');
        fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
    }

    function gotFileEntry(fileEntry) {
        fileEntry.createWriter(gotFileWriter, fail);
    }

    function gotFileWriter(writer) {
        writer.onwriteend = function(evt) {
            console.log('appended');
        };
        writer.seek(writer.length);
        writer.write("\r\nsome sample text2");
    }

    function fail(error) {
        console.log(error.code);
    }<commit_msg>Debug file saving<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);

    }

};
/*function bootme() {
        console.log('ready');
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
    }

    function gotFS(fileSystem) {
        console.log('gotfs');
        fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
    }

    function gotFileEntry(fileEntry) {
        fileEntry.createWriter(gotFileWriter, fail);
    }

    function gotFileWriter(writer) {
        writer.onwriteend = function(evt) {
            console.log('appended');
        };
        writer.seek(writer.length);
        writer.write("\r\nsome sample text2");
    }

    function fail(error) {
        console.log(error.code);
    }*/<|endoftext|>


<commit_before>/*!
 * Elevator.js
 *
 * MIT licensed
 * Copyright (C) 2015 Tim Holman, http://tholman.com
 */

/*********************************************
 * Elevator.js
 *********************************************/

var Elevator = function(options) {

    'use strict';

    // Elements
    var body = null;

    // Scroll vars
    var animation = null;
    var duration = null; // ms
    var customDuration = false;
    var startTime = null;
    var startPosition = null;
    var endPosition = 0;
    var targetElement = null;
    var elevating = false;

    var startCallback;
    var mainAudio;
    var endAudio;
    var endCallback;

    var that = this;

    /**
     * Utils
     */

    // Thanks Mr Penner - http://robertpenner.com/easing/
    function easeInOutQuad( t, b, c, d ) {
        t /= d / 2;
        if ( t < 1 ) return c / 2 * t * t + b;
        t--;
        return -c / 2 * ( t * ( t -2 ) - 1 ) + b;
    }

    function extendParameters(options, defaults){
        for( var option in defaults ){
            var t = options[option] === undefined && typeof option !== "function";
            if(t){
                options[option] = defaults[option];
            }
        }
        return options;
    }

    function getVerticalOffset(element) {
        var verticalOffset = 0;
        while( element ){
            verticalOffset += element.offsetTop || 0;
            element = element.offsetParent;
        }
        return verticalOffset;
    }

    /**
     * Main
     */

    // Time is passed through requestAnimationFrame, what a world!
    function animateLoop( time ) {
        if ( !startTime ) {
            startTime = time;
        }

        var timeSoFar = time - startTime;
        var easedPosition = easeInOutQuad(timeSoFar, startPosition, endPosition - startPosition, duration);

        window.scrollTo(0, easedPosition);

        if( timeSoFar < duration ) {
            animation = requestAnimationFrame(animateLoop);
        } else {
            animationFinished();
        }
    }

//            ELEVATE!
//              /
//         ____
//       .'    '=====<0
//       |======|
//       |======|
//       [IIIIII[\--()
//       |_______|
//       C O O O D
//      C O  O  O D
//     C  O  O  O  D
//     C__O__O__O__D
//    [_____________]
    this.elevate = function() {

        if( elevating ) {
            return;
        }

        elevating = true;
        startPosition = (document.documentElement.scrollTop || body.scrollTop);
        updateEndPosition();

        // No custom duration set, so we travel at pixels per millisecond. (0.75px per ms)
        if( !customDuration ) {
            duration = ( Math.abs(endPosition - startPosition) * 1.5);
        }

        requestAnimationFrame( animateLoop );

        // Start music!
        if( mainAudio ) {
            mainAudio.play();
        }

        if( startCallback ) {
            startCallback();
        }
    };

    function browserMeetsRequirements() {
        return window.requestAnimationFrame && window.Audio && window.addEventListener;
    }

    function resetPositions() {
        startTime = null;
        startPosition = null;
        elevating = false;
    }

    function updateEndPosition() {
        if(targetElement){
            endPosition = getVerticalOffset(targetElement);
        }
    }

    function animationFinished() {

        resetPositions();

        // Stop music!
        if( mainAudio ) {
            mainAudio.pause();
            mainAudio.currentTime = 0;
        }

        if( endAudio ) {
            endAudio.play();
        }

        if( endCallback ) {
            endCallback();
        }
    }

    function onWindowBlur() {

        // If animating, go straight to the top. And play no more music.
        if( elevating ) {

            cancelAnimationFrame( animation );
            resetPositions();

            if( mainAudio ) {
                mainAudio.pause();
                mainAudio.currentTime = 0;
            }

            updateEndPosition();
            window.scrollTo(0, endPosition);
        }
    }

    function bindElevateToElement( element ) {
        if( element.addEventListener ) {
            element.addEventListener('click', that.elevate, false);
        } else {
            // Older browsers
            element.attachEvent('onclick', function() {
                updateEndPosition();
                document.documentElement.scrollTop = endPosition;
                document.body.scrollTop = endPosition;
                window.scroll(0, endPosition);
            });
        }
    }

    function init( _options ) {
        // Bind to element click event, if need be.
        body = document.body;

        var defaults = {
            duration: undefined,
            mainAudio: false,
            endAudio: false,
            preloadAudio: true,
            loopAudio: true,
            startCallback: null,
            endCallback: null
        };

        _options = extendParameters(_options, defaults);

        if( _options.element ) {
            bindElevateToElement( _options.element );
        }

        // Take the stairs instead
        if( !browserMeetsRequirements() ) {
            return;
        }

        if( _options.duration ) {
            customDuration = true;
            duration = _options.duration;
        }

        if( _options.targetElement ) {
            targetElement = _options.targetElement;
        }

        window.addEventListener('blur', onWindowBlur, false);

        if( _options.mainAudio ) {
            mainAudio = new Audio( _options.mainAudio );
            mainAudio.setAttribute( 'preload', _options.preloadAudio );
            mainAudio.setAttribute( 'loop', _options.loopAudio );
        }

        if( _options.endAudio ) {
            endAudio = new Audio( _options.endAudio );
            endAudio.setAttribute( 'preload', 'true' );
        }

        if( _options.endCallback ) {
            endCallback = _options.endCallback;
        }

        if( _options.startCallback ) {
            startCallback = _options.startCallback;
        }
    }

    init(options);
};

function thanks(){
  var nameVal = document.getElementById('name').checkValidity();
  var emailVal = document.getElementById('email').checkValidity();
  var textareaVal = document.getElementById('message').checkValidity();
  if(nameVal && emailVal && textareaVal){
    document.getElementById('sendButton').setAttribute('style','width: 97px;');
    document.getElementById('sendButton').setAttribute('value','thanks!');
  }
}
<commit_msg>width issue<commit_after>/*!
 * Elevator.js
 *
 * MIT licensed
 * Copyright (C) 2015 Tim Holman, http://tholman.com
 */

/*********************************************
 * Elevator.js
 *********************************************/

var Elevator = function(options) {

    'use strict';

    // Elements
    var body = null;

    // Scroll vars
    var animation = null;
    var duration = null; // ms
    var customDuration = false;
    var startTime = null;
    var startPosition = null;
    var endPosition = 0;
    var targetElement = null;
    var elevating = false;

    var startCallback;
    var mainAudio;
    var endAudio;
    var endCallback;

    var that = this;

    /**
     * Utils
     */

    // Thanks Mr Penner - http://robertpenner.com/easing/
    function easeInOutQuad( t, b, c, d ) {
        t /= d / 2;
        if ( t < 1 ) return c / 2 * t * t + b;
        t--;
        return -c / 2 * ( t * ( t -2 ) - 1 ) + b;
    }

    function extendParameters(options, defaults){
        for( var option in defaults ){
            var t = options[option] === undefined && typeof option !== "function";
            if(t){
                options[option] = defaults[option];
            }
        }
        return options;
    }

    function getVerticalOffset(element) {
        var verticalOffset = 0;
        while( element ){
            verticalOffset += element.offsetTop || 0;
            element = element.offsetParent;
        }
        return verticalOffset;
    }

    /**
     * Main
     */

    // Time is passed through requestAnimationFrame, what a world!
    function animateLoop( time ) {
        if ( !startTime ) {
            startTime = time;
        }

        var timeSoFar = time - startTime;
        var easedPosition = easeInOutQuad(timeSoFar, startPosition, endPosition - startPosition, duration);

        window.scrollTo(0, easedPosition);

        if( timeSoFar < duration ) {
            animation = requestAnimationFrame(animateLoop);
        } else {
            animationFinished();
        }
    }

//            ELEVATE!
//              /
//         ____
//       .'    '=====<0
//       |======|
//       |======|
//       [IIIIII[\--()
//       |_______|
//       C O O O D
//      C O  O  O D
//     C  O  O  O  D
//     C__O__O__O__D
//    [_____________]
    this.elevate = function() {

        if( elevating ) {
            return;
        }

        elevating = true;
        startPosition = (document.documentElement.scrollTop || body.scrollTop);
        updateEndPosition();

        // No custom duration set, so we travel at pixels per millisecond. (0.75px per ms)
        if( !customDuration ) {
            duration = ( Math.abs(endPosition - startPosition) * 1.5);
        }

        requestAnimationFrame( animateLoop );

        // Start music!
        if( mainAudio ) {
            mainAudio.play();
        }

        if( startCallback ) {
            startCallback();
        }
    };

    function browserMeetsRequirements() {
        return window.requestAnimationFrame && window.Audio && window.addEventListener;
    }

    function resetPositions() {
        startTime = null;
        startPosition = null;
        elevating = false;
    }

    function updateEndPosition() {
        if(targetElement){
            endPosition = getVerticalOffset(targetElement);
        }
    }

    function animationFinished() {

        resetPositions();

        // Stop music!
        if( mainAudio ) {
            mainAudio.pause();
            mainAudio.currentTime = 0;
        }

        if( endAudio ) {
            endAudio.play();
        }

        if( endCallback ) {
            endCallback();
        }
    }

    function onWindowBlur() {

        // If animating, go straight to the top. And play no more music.
        if( elevating ) {

            cancelAnimationFrame( animation );
            resetPositions();

            if( mainAudio ) {
                mainAudio.pause();
                mainAudio.currentTime = 0;
            }

            updateEndPosition();
            window.scrollTo(0, endPosition);
        }
    }

    function bindElevateToElement( element ) {
        if( element.addEventListener ) {
            element.addEventListener('click', that.elevate, false);
        } else {
            // Older browsers
            element.attachEvent('onclick', function() {
                updateEndPosition();
                document.documentElement.scrollTop = endPosition;
                document.body.scrollTop = endPosition;
                window.scroll(0, endPosition);
            });
        }
    }

    function init( _options ) {
        // Bind to element click event, if need be.
        body = document.body;

        var defaults = {
            duration: undefined,
            mainAudio: false,
            endAudio: false,
            preloadAudio: true,
            loopAudio: true,
            startCallback: null,
            endCallback: null
        };

        _options = extendParameters(_options, defaults);

        if( _options.element ) {
            bindElevateToElement( _options.element );
        }

        // Take the stairs instead
        if( !browserMeetsRequirements() ) {
            return;
        }

        if( _options.duration ) {
            customDuration = true;
            duration = _options.duration;
        }

        if( _options.targetElement ) {
            targetElement = _options.targetElement;
        }

        window.addEventListener('blur', onWindowBlur, false);

        if( _options.mainAudio ) {
            mainAudio = new Audio( _options.mainAudio );
            mainAudio.setAttribute( 'preload', _options.preloadAudio );
            mainAudio.setAttribute( 'loop', _options.loopAudio );
        }

        if( _options.endAudio ) {
            endAudio = new Audio( _options.endAudio );
            endAudio.setAttribute( 'preload', 'true' );
        }

        if( _options.endCallback ) {
            endCallback = _options.endCallback;
        }

        if( _options.startCallback ) {
            startCallback = _options.startCallback;
        }
    }

    init(options);
};

function thanks(){
  var nameVal = document.getElementById('name').checkValidity();
  var emailVal = document.getElementById('email').checkValidity();
  var textareaVal = document.getElementById('message').checkValidity();
  if(nameVal && emailVal && textareaVal){
    document.getElementById('sendButton').style.width = "97px";
    document.getElementById('sendButton').setAttribute('value','thanks!');
  }
}
<|endoftext|>