<commit_before>var Twitter = require('twitter'),
    app = require('express')();

var client = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

function getTweets(req, res) {
    var params = {screen_name: req.params.screen_name},
        textOfTweets;

    client.get('statuses/user_timeline', params, function (error, tweets, response) {
        if (!error) {
            textOfTweets = tweets.map(function (tweet) {
                return tweet.text;
            });
            console.log(textOfTweets);
            res.json(textOfTweets);
        } else {
            console.error(error);
            res.status(500).json({error: 'Something went wrong!'});
        }
    });
}

// app routes:
app.get('/tweets/:screen_name', getTweets);

// start app listening
var port = process.env.VCAP_APP_PORT || 3000;
app.listen(port);
console.log('listening at:', port);
<commit_msg>Rename<commit_after>var Twitter = require('twitter'),
    app = require('express')();

var twitterClient = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

function getTweets(req, res) {
    var params = {screen_name: req.params.screen_name},
        textOfTweets;

    twitterClient.get('statuses/user_timeline', params, function (error, tweets, response) {
        if (!error) {
            textOfTweets = tweets.map(function (tweet) {
                return tweet.text;
            });
            console.log(textOfTweets);
            res.json(textOfTweets);
        } else {
            console.error(error);
            res.status(500).json({error: 'Something went wrong!'});
        }
    });
}

// app routes:
app.get('/tweets/:screen_name', getTweets);

// start app listening
var port = process.env.VCAP_APP_PORT || 3000;
app.listen(port);
console.log('listening at:', port);
<|endoftext|>


<commit_before>/**
 * Copyright 2015-2016, Google, Inc.
 * 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';

const config = require('../config/config');
const dataFetcher = require('../lib/data-fetcher');

const WEBPERFORMANCE_SERVER_URL = config.get('WEBPERFORMANCE_SERVER');
const WEBPERFORMANCE_SERVER_API_KEY = config.get('WEBPERFORMANCE_SERVER_API_KEY');
const WEBPERFORMANCE_SERVER_WEBPAGEURL = WEBPERFORMANCE_SERVER_URL + 'webpageurl';
const WEBPERFORMANCE_SERVER_PAGESPEED_REPORT = WEBPERFORMANCE_SERVER_URL + 'pagespeedreport/';
const WEBPERFORMANCE_SERVER_WEBPAGETEST_REPORT = WEBPERFORMANCE_SERVER_URL + 'webpagetestreport/';
const WEBPERFORMANCE_SERVER_LIGHTHOUSE_REPORT = WEBPERFORMANCE_SERVER_URL + 'lighthousereport/';

function submitToWebPerformanceService(pwa) {
  const body = {
    id: pwa.id,
    url: pwa.absoluteStartUrl,
    source: 'pwa-directory',
    description: pwa.description
  };
  return dataFetcher.postJson(
    WEBPERFORMANCE_SERVER_WEBPAGEURL + '?key=' + WEBPERFORMANCE_SERVER_API_KEY, body);
}

/**
 * Submit PWA to the WebPerformance service.
 *
 * @param {number} a PWA
 * @return {Promise<Lighthouse>}
 */
exports.submitWebPageUrl = function(pwa) {
  return new Promise((resolve, reject) => {
    submitToWebPerformanceService(pwa)
      .then(result => {
        return resolve(result);
      })
      .catch(err => {
        return reject(err);
      });
  });
};

/**
 * Get Report for PWA.
 *
 * @param {PWA} a PWA
 * @return {Promise<Json>}
 */
function getReport(url) {
  return dataFetcher.fetchWithUA(url)
    .then(response => {
      if (response.status === 200) {
        return response.json();
      } else if (response.status === 404) {
        return Promise.reject('not available yet');
      }
      return Promise.reject(response);
    })
    .catch(err => {
      return Promise.reject(err);
    });
}

/**
 * Get PageSpeed Report for PWA.
 *
 * @param {PWA} a PWA
 * @return {Promise<Json>}
 */
exports.getPageSpeedReport = function(pwa) {
  return getReport(WEBPERFORMANCE_SERVER_PAGESPEED_REPORT + pwa.id + '?limit=1');
};

/**
 * Get WebPageTest Report for PWA.
 *
 * @param {PWA} a PWA
 * @return {Promise<Json>}
 */
exports.getWebPageTestReport = function(pwa) {
  return getReport(WEBPERFORMANCE_SERVER_WEBPAGETEST_REPORT + pwa.id + '?limit=1');
};

/**
 * Get Lighthouse Report for PWA.
 *
 * @param {PWA} a PWA
 * @return {Promise<Json>}
 */
exports.getLighthouseReport = function(pwa) {
  return getReport(WEBPERFORMANCE_SERVER_LIGHTHOUSE_REPORT + pwa.id + '?limit=1');
};
<commit_msg>Add created to submitToWebPerformanceService<commit_after>/**
 * Copyright 2015-2016, Google, Inc.
 * 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';

const config = require('../config/config');
const dataFetcher = require('../lib/data-fetcher');

const WEBPERFORMANCE_SERVER_URL = config.get('WEBPERFORMANCE_SERVER');
const WEBPERFORMANCE_SERVER_API_KEY = config.get('WEBPERFORMANCE_SERVER_API_KEY');
const WEBPERFORMANCE_SERVER_WEBPAGEURL = WEBPERFORMANCE_SERVER_URL + 'webpageurl';
const WEBPERFORMANCE_SERVER_PAGESPEED_REPORT = WEBPERFORMANCE_SERVER_URL + 'pagespeedreport/';
const WEBPERFORMANCE_SERVER_WEBPAGETEST_REPORT = WEBPERFORMANCE_SERVER_URL + 'webpagetestreport/';
const WEBPERFORMANCE_SERVER_LIGHTHOUSE_REPORT = WEBPERFORMANCE_SERVER_URL + 'lighthousereport/';

function submitToWebPerformanceService(pwa) {
  const body = {
    id: pwa.id,
    url: pwa.absoluteStartUrl,
    source: 'pwa-directory',
    description: pwa.description,
    created: created
  };
  return dataFetcher.postJson(
    WEBPERFORMANCE_SERVER_WEBPAGEURL + '?key=' + WEBPERFORMANCE_SERVER_API_KEY, body);
}

/**
 * Submit PWA to the WebPerformance service.
 *
 * @param {number} a PWA
 * @return {Promise<Lighthouse>}
 */
exports.submitWebPageUrl = function(pwa) {
  return new Promise((resolve, reject) => {
    submitToWebPerformanceService(pwa)
      .then(result => {
        return resolve(result);
      })
      .catch(err => {
        return reject(err);
      });
  });
};

/**
 * Get Report for PWA.
 *
 * @param {PWA} a PWA
 * @return {Promise<Json>}
 */
function getReport(url) {
  return dataFetcher.fetchWithUA(url)
    .then(response => {
      if (response.status === 200) {
        return response.json();
      } else if (response.status === 404) {
        return Promise.reject('not available yet');
      }
      return Promise.reject(response);
    })
    .catch(err => {
      return Promise.reject(err);
    });
}

/**
 * Get PageSpeed Report for PWA.
 *
 * @param {PWA} a PWA
 * @return {Promise<Json>}
 */
exports.getPageSpeedReport = function(pwa) {
  return getReport(WEBPERFORMANCE_SERVER_PAGESPEED_REPORT + pwa.id + '?limit=1');
};

/**
 * Get WebPageTest Report for PWA.
 *
 * @param {PWA} a PWA
 * @return {Promise<Json>}
 */
exports.getWebPageTestReport = function(pwa) {
  return getReport(WEBPERFORMANCE_SERVER_WEBPAGETEST_REPORT + pwa.id + '?limit=1');
};

/**
 * Get Lighthouse Report for PWA.
 *
 * @param {PWA} a PWA
 * @return {Promise<Json>}
 */
exports.getLighthouseReport = function(pwa) {
  return getReport(WEBPERFORMANCE_SERVER_LIGHTHOUSE_REPORT + pwa.id + '?limit=1');
};
<|endoftext|>


<commit_before>'use strict';

var assign = require('object-assign');

var AppDispatcher = require('../dispatcher/AppDispatcher');
var SessionDAO = require('../dao/SessionDAO');
var SessionConstants = require('../constants/SessionConstants');
var UsersConstants = require('../constants/admin/UsersConstants');
var StoreListenBase = require('./StoreListenBase');
var PromiseHandlers = require('./PromiseHandlers');

var _session = false;

var SessionStore = assign({}, StoreListenBase, {
  getSession: function() {
    if (!_session) {
      this.refreshSession();
    }
    return _session;
  },
  refreshSession: function() {
    var actionType = SessionConstants.SESSION_UPDATE_FROM_SERVER;
    SessionDAO.getSession()
      .then(PromiseHandlers.handleSuccess.bind(null, actionType))
      .catch(PromiseHandlers.handleNotFound.bind(null, {}, actionType));
  }
});

AppDispatcher.register(function(payload) {
  var action = payload.action;

  //==========
  // Store refresh
  //
  if(payload.source == AppDispatcher.STORE_REFRESH) {
    switch (action.actionType) {
      case SessionConstants.SESSION_UPDATE_FROM_SERVER:
        _session = action.data;
        SessionStore.emitChange();
        break;
      default:
    }
  }
  //==========
  // Server action
  //
  else if(payload.source == AppDispatcher.SERVER_ACTION) {
    switch (action.actionType) {
      case UsersConstants.SAVE_USER:
        if(action.id == _session.id) {
          SessionStore.refreshSession();
        }
        break;
      default:
    }
  }
});

module.exports = SessionStore;
<commit_msg>Fix session update on user update<commit_after>'use strict';

var assign = require('object-assign');

var AppDispatcher = require('../dispatcher/AppDispatcher');
var SessionDAO = require('../dao/SessionDAO');
var SessionConstants = require('../constants/SessionConstants');
var UsersConstants = require('../constants/admin/UsersConstants');
var StoreListenBase = require('./StoreListenBase');
var PromiseHandlers = require('./PromiseHandlers');

var _session = false;

var SessionStore = assign({}, StoreListenBase, {
  getSession: function() {
    if (!_session) {
      this.refreshSession();
    }
    return _session;
  },
  refreshSession: function() {
    var actionType = SessionConstants.SESSION_UPDATE_FROM_SERVER;
    SessionDAO.getSession()
      .then(PromiseHandlers.handleSuccess.bind(null, actionType))
      .catch(PromiseHandlers.handleNotFound.bind(null, {}, actionType));
  }
});

AppDispatcher.register(function(payload) {
  var action = payload.action;

  //==========
  // Store refresh
  //
  if(payload.source == AppDispatcher.STORE_REFRESH) {
    switch (action.actionType) {
      case SessionConstants.SESSION_UPDATE_FROM_SERVER:
        _session = action.data;
        SessionStore.emitChange();
        break;
      case UsersConstants.SAVE_USER:
        if(action.data.id == _session.id) {
          SessionStore.refreshSession();
        }
        break;
      default:
    }
  }
  //==========
  // Server action
  //
  else if(payload.source == AppDispatcher.SERVER_ACTION) {
    switch (action.actionType) {
      default:
    }
  }
});

module.exports = SessionStore;
<|endoftext|>


<commit_before>var gameModule = angular.module('app', []).
	controller("gameTheoryControl", function gameTheoryControl($scope){

	    	function number(num){
	    		this.name = num;
	    		this.selected = false;
	    		return this;
	    	}

	    	$scope.numbers=[];
	    	$scope.solutions=[];

	    	function solution(x, parts){
	    		this.number = x;
	    		this.parts = parts;
	    	}

	    	$scope.amount = 10;

	    	$scope.newNumbers = function(){
			$scope.numbers = [];

			intAmount = parseInt($scope.amount);

			for(var i = 1; i < intAmount + 1; i++){
				$scope.numbers.push(new number(i));
			}
		}

		$scope.deleteSelected = function(){
			for(var num in $scope.numbers){
				if($scope.numbers[num].selected){
					$scope.numbers.splice(num, 1);
				}
			}
		}

		function sumOf(parts){
			var num = 0;
			for(var i = 0; i < parts.length; i++){
				num += parts[i];
			}
			return num;
		}

		function getSmallerNumbers(number){
			var newArray = [];
			for(var i = 0; i < $scope.numbers.length; i++){
				if($scope.numbers[i].name <= number){
					newArray.push($scope.numbers[i].name);
				}
				else{
					break;
				}
			}
			return newArray;
		}

		var getCombinations2 = function(firstParts, parts, solutions) {
			var results = [];
		    	for (var i = 0; i < parts.length; i++) {
			      solutions.push(firstParts.concat(parts[i]));
			      solutions.concat(getCombinations(firstParts.concat(parts[i]), parts.splice(i + 1)), solutions);
		    	}
		   return solutions;
		}

		var getCombinations = function(startArray, arrayOfNumbers){
			var results = [];
			for(var i = 0; i < arrayOfNumbers.length; i++){
				results.push(startArray.concat(arrayOfNumbers[i]));

				var tempArray = [];
				for(var j = 0; j < arrayOfNumbers.length; j++){
					if(i != j){
						tempArray.push(arrayOfNumbers[j]);
					}
				}

				results = results.concat(getCombinations(startArray.concat(arrayOfNumbers[i]), tempArray));
			}
			return results;
		}

		$scope.getSolutions = function(){
			$scope.solutions = [];
			var calculable = true;
			var currentNumber = 1;

			while(calculable){
				parts = [];

				var solved = false;

				var smallerNums = getSmallerNumbers(currentNumber);

				if(smallerNums.length == 0){
					calculable = false; break;
				}

				var combinations = getCombinations([], smallerNums);

					for(var i = 0; i < combinations.length; i++){
						if(sumOf(combinations[i]) == currentNumber){
							$scope.solutions.push(new solution(currentNumber, combinations[i]));
							solved = true;
							break;
						}
						if(solved){break;}
					}

				if(!solved){
					calculable = false; break;
				}

				currentNumber++;
			}
		}

		$scope.newNumbers();

	});
<commit_msg>Update gameTheoryController.js<commit_after>var gameModule = angular.module('app', []).
	controller("gameTheoryControl", function gameTheoryControl($scope){

	    	function number(num){
	    		this.name = num;
	    		this.selected = false;
	    		return this;
	    	}

	    	$scope.numbers=[];
	    	$scope.solutions=[];

	    	$scope.getStarter = function(){
	    		var isEven = ($scope.solutions % 2) == 0;

	    		if(isEven){
	    			return "Alice";
	    		}
	    		else{
	    			return "Bob";
	    		}
	    	}

	    	function solution(x, parts){
	    		this.number = x;
	    		this.parts = parts;
	    	}

	    	$scope.amount = 10;

	    	$scope.newNumbers = function(){
			$scope.numbers = [];

			intAmount = parseInt($scope.amount);

			for(var i = 1; i < intAmount + 1; i++){
				$scope.numbers.push(new number(i));
			}
		}

		$scope.deleteSelected = function(){
			for(var num in $scope.numbers){
				if($scope.numbers[num].selected){
					$scope.numbers.splice(num, 1);
				}
			}
		}

		function sumOf(parts){
			var num = 0;
			for(var i = 0; i < parts.length; i++){
				num += parts[i];
			}
			return num;
		}

		function getSmallerNumbers(number){
			var newArray = [];
			for(var i = 0; i < $scope.numbers.length; i++){
				if($scope.numbers[i].name <= number){
					newArray.push($scope.numbers[i].name);
				}
				else{
					break;
				}
			}
			return newArray;
		}

		var getCombinations2 = function(firstParts, parts, solutions) {
			var results = [];
		    	for (var i = 0; i < parts.length; i++) {
			      solutions.push(firstParts.concat(parts[i]));
			      solutions.concat(getCombinations(firstParts.concat(parts[i]), parts.splice(i + 1)), solutions);
		    	}
		   return solutions;
		}

		var getCombinations = function(startArray, arrayOfNumbers){
			var results = [];
			for(var i = 0; i < arrayOfNumbers.length; i++){
				results.push(startArray.concat(arrayOfNumbers[i]));

				var tempArray = [];
				for(var j = 0; j < arrayOfNumbers.length; j++){
					if(i != j){
						tempArray.push(arrayOfNumbers[j]);
					}
				}

				results = results.concat(getCombinations(startArray.concat(arrayOfNumbers[i]), tempArray));
			}
			return results;
		}

		$scope.getSolutions = function(){
			$scope.solutions = [];
			var calculable = true;
			var currentNumber = 1;

			while(calculable){
				parts = [];

				var solved = false;

				var smallerNums = getSmallerNumbers(currentNumber);

				if(smallerNums.length == 0){
					calculable = false; break;
				}

				var combinations = getCombinations([], smallerNums);

					for(var i = 0; i < combinations.length; i++){
						if(sumOf(combinations[i]) == currentNumber){
							$scope.solutions.push(new solution(currentNumber, combinations[i]));
							solved = true;
							break;
						}
						if(solved){break;}
					}

				if(!solved){
					calculable = false; break;
				}

				currentNumber++;
			}
		}

		$scope.newNumbers();

	});
<|endoftext|>


<commit_before>/*jslint bitwise: true*/
define(['jquery'], function($) {
    'use strict';
    function WebGlSpiral() {
        this.unboundDraw = $.proxy(this.draw, this);
        window.requestAnimationFrame = Modernizr.prefixed('requestAnimationFrame', window) || function(proc) { window.setTimeout(proc, 1000 / 30); };

        if (!Modernizr.webgl) {
            throw 'webgl unsupported';
        }
        this.canvas = document.createElement('canvas');
        this.context = this.canvas.getContext('webgl') || this.canvas.getContext('experimental-webgl');
        if (!this.context) {
            throw 'webgl unsupported';
        }
        $(this.canvas).attr({id: 'web-gl-spiral'}).prependTo(document.body);

        var psh = this.context.createShader(this.context.FRAGMENT_SHADER);
        var vsh = this.context.createShader(this.context.VERTEX_SHADER);
        this.context.shaderSource(psh, 'precision highp float;uniform vec4 color;varying vec2 ptexcoord;uniform sampler2D sampler;void main(void){gl_FragColor=color*texture2D(sampler,ptexcoord);}');
        this.context.shaderSource(vsh, 'attribute vec2 pos;attribute vec2 texcoord;uniform float rot;uniform vec2 scale;uniform vec2 aspect;varying vec2 ptexcoord;void main(void){vec2 scaled=scale*pos;float crot=cos(rot);float srot=sin(rot);gl_Position=vec4(aspect*vec2(scaled.x*crot-scaled.y*srot,scaled.x*srot+scaled.y*crot),0.0,1.0);ptexcoord=texcoord;}');
        this.context.compileShader(psh);
        this.context.compileShader(vsh);
        if (!this.context.getShaderParameter(psh, this.context.COMPILE_STATUS)) {
            console.log(this.context.getShaderInfoLog(psh));
            throw 'psh init failed';
        }
        if (!this.context.getShaderParameter(vsh, this.context.COMPILE_STATUS)) {
            console.log(this.context.getShaderInfoLog(vsh));
            throw 'vsh init failed';
        }
        this.shader = this.context.createProgram();
        this.context.attachShader(this.shader, vsh);
        this.context.attachShader(this.shader, psh);
        this.context.linkProgram(this.shader);
        if (!this.context.getProgramParameter(this.shader, this.context.LINK_STATUS)) {
            throw 'shader init failed';
        }
        this.context.useProgram(this.shader);
        this.shader.pos = this.context.getAttribLocation(this.shader, 'pos');
        this.context.enableVertexAttribArray(this.shader.pos);
        this.shader.texcoord = this.context.getAttribLocation(this.shader, 'texcoord');
        this.context.enableVertexAttribArray(this.shader.texcoord);
        this.shader.rot = this.context.getUniformLocation(this.shader, 'rot');
        this.shader.aspectScale = this.context.getUniformLocation(this.shader, 'aspect');
        this.shader.scale = this.context.getUniformLocation(this.shader, 'scale');
        this.shader.color = this.context.getUniformLocation(this.shader, 'color');
        this.shader.texture = this.context.getUniformLocation(this.shader, 'sampler');
        this.context.uniform2fv(this.shader.aspectScale, this.aspectScale);

        this.quad = this.context.createBuffer();
        this.context.bindBuffer(this.context.ARRAY_BUFFER, this.quad);
        this.context.bufferData(this.context.ARRAY_BUFFER, new Float32Array([
            1.0, 1.0,
            -1.0, 1.0,
            1.0, -1.0,
            -1.0, -1.0
        ]), this.context.STATIC_DRAW);
        this.context.vertexAttribPointer(this.shader.pos, 2, this.context.FLOAT, false, 0, 0);

        this.quadtex = this.context.createBuffer();
        this.context.bindBuffer(this.context.ARRAY_BUFFER, this.quadtex);
        this.context.bufferData(this.context.ARRAY_BUFFER, new Float32Array([
            1.0, 0.0,
            0.0, 0.0,
            1.0, 1.0,
            0.0, 1.0
        ]), this.context.STATIC_DRAW);
        this.context.vertexAttribPointer(this.shader.texcoord, 2, this.context.FLOAT, false, 0, 0);

        this.context.blendFunc(this.context.SRC_ALPHA, this.context.ONE_MINUS_SRC_ALPHA);
        this.context.enable(this.context.BLEND);

        this.setBackground([0, 0, 0]);

        this.spiralTexture = this.context.createTexture();
        this.imageTexture = this.context.createTexture();
        this.setSpiralImage(this.blankImageData);
        this.clearImage();

        $(window).resize({spiral: this}, function(event) { event.data.spiral.resize($(window).width(), $(window).height()); });
        this.resize($(window).width(), $(window).height());
        this.draw();
    }
    WebGlSpiral.prototype = {
        canvas: null,
        context: null,
        shader: null,
        spiralScale: [0.95, 0.95],
        imageScale: [0.95, 0.95],
        aspectScale: [0.5, 1.0],
        spiralColor: [1.0, 1.0, 1.0, 1.0],
        imageColor: [1.0, 1.0, 1.0, 1.0],
        spiralTexture: null,
        imageTexture: null,
        unboundDraw: null,
        baseTime: 0,
        baseRot: 0,
        rotPeriod: 10000,
        blankImageData: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQIHWNgYAAAAAMAAU9ICq8AAAAASUVORK5CYII=',
        draw: function() {
            window.requestAnimationFrame(this.unboundDraw);
            var context = this.context, canvas = this.canvas, shader = this.shader;

            context.viewport(0, 0, canvas.width, canvas.height);

            context.clear(context.COLOR_BUFFER_BIT);

            context.uniform2fv(shader.scale, this.imageScale);
            context.uniform1f(shader.rot, 0.0);
            context.uniform4fv(shader.color, this.imageColor);
            context.uniform1i(shader.texture, 1);
            context.drawArrays(context.TRIANGLE_STRIP, 0, 4);

            context.uniform2fv(shader.scale, this.spiralScale);
            context.uniform1f(shader.rot, this.baseRot + -2.0 * Math.PI * (($.now() - this.baseTime) % this.rotPeriod) / this.rotPeriod);
            context.uniform4fv(shader.color, this.spiralColor);
            context.uniform1i(shader.texture, 0);
            context.drawArrays(context.TRIANGLE_STRIP, 0, 4);
        },
        resize: function(w, h) {
            this.canvas.width = w;
            this.canvas.height = h;
            if (w > h) {
                this.aspectScale = [h / w, 1.0];
            } else {
                this.aspectScale = [1.0, w / h];
            }
            this.context.uniform2fv(this.shader.aspectScale, this.aspectScale);
        },
        loadTexture: function(texture, num, src) {
            var img = new Image();
            var context = this.context;
            $(img).load(function() {
                var bits = 0;
                // check for power of two
                for (var i = 0; i < 32; i++) {
                    bits += 1 & (img.width >> i);
                }
                if (img.width !== img.height || bits !== 1) {
                    var width = img.width;
                    var height = img.height;
                    var maxImg = Math.max(img.width, img.height);
                    var target = maxImg;
                    // convert to power of 2
                    for (i = 1; i < target; i = i << 1) {}
                    target = i;
                    // clamp
                    target = Math.min(target, context.getParameter(context.MAX_TEXTURE_SIZE));
                    width *= target / maxImg;
                    height *= target / maxImg;
                    var x = 0;
                    var y = 0;
                    if (width > height) {
                        y = (width - height) * 0.5;
                    } else {
                        x = (height - width) * 0.5;
                    }
                    console.log({x: x, y: y, width: width, height: height});
                    var canvas = document.createElement('canvas');
                    canvas.width = canvas.height = target;
                    var context2d = canvas.getContext('2d');
                    context2d.drawImage(img, x, y, width, height);
                    img = canvas;
                }
                context.activeTexture(num);
                context.bindTexture(context.TEXTURE_2D, texture);
                context.texImage2D(context.TEXTURE_2D, 0, context.RGBA, context.RGBA, context.UNSIGNED_BYTE, img);
                context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);
                context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR_MIPMAP_NEAREST);
                context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);
                context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);
                context.generateMipmap(context.TEXTURE_2D);
            });
            $(img).error({gls: this}, function(event) {
                event.data.gls.loadTexture(texture, num, event.data.gls.blankImageData);
            });
            img.src = src;
        },
        setBackground: function(r, g, b) {
            this.context.clearColor(r, g, b, 1.0);
        },
        setSpiralImage: function(img) {
            this.loadTexture(this.spiralTexture, this.context.TEXTURE0, img);
        },
        setImage: function(img) {
            this.loadTexture(this.imageTexture, this.context.TEXTURE1, img);
        },
        setSpiralColor: function(r, g, b) {
            this.spiralColor[0] = r;
            this.spiralColor[1] = g;
            this.spiralColor[2] = b;
        },
        setSpiralAlpha: function(a) {
            this.spiralColor[3] = a;
        },
        setImageColor: function(r, g, b) {
            this.imageColor[0] = r;
            this.imageColor[1] = g;
            this.imageColor[2] = b;
        },
        setImageAlpha: function(a) {
            this.imageColor[3] = a;
        },
        setSpiralScale: function(x, y) {
            this.imageScale[0] = x;
            this.imageScale[1] = y;
        },
        setImageScale: function(x, y) {
            this.imageScale[0] = x;
            this.imageScale[1] = y;
        },
        setRotationPeriod: function(wl) {
            var time = $.now();
            this.baseRot += -2.0 * Math.PI * ((time - this.baseTime) % this.rotPeriod) / this.rotPeriod;
            this.baseTime = time;
            while (this.baseRot < 0.0) {
                this.baseRot += 2.0 * Math.PI;
            }
            while (this.baseRot >= 2.0 * Math.PI) {
                this.baseRot -= 2.0 * Math.PI;
            }
            this.rotPeriod = wl * 1000;
        },
        clearImage: function() {
            this.setImage(this.blankImageData);
        }
    };
    return WebGlSpiral;
});
<commit_msg>allow mediump webgl<commit_after>/*jslint bitwise: true*/
define(['jquery'], function($) {
    'use strict';
    function WebGlSpiral() {
        this.unboundDraw = $.proxy(this.draw, this);
        window.requestAnimationFrame = Modernizr.prefixed('requestAnimationFrame', window) || function(proc) { window.setTimeout(proc, 1000 / 30); };

        if (!Modernizr.webgl) {
            throw 'webgl unsupported';
        }
        this.canvas = document.createElement('canvas');
        this.context = this.canvas.getContext('webgl') || this.canvas.getContext('experimental-webgl');
        if (!this.context) {
            throw 'webgl unsupported';
        }
        $(this.canvas).attr({id: 'web-gl-spiral'}).prependTo(document.body);

        var psh = this.context.createShader(this.context.FRAGMENT_SHADER);
        var vsh = this.context.createShader(this.context.VERTEX_SHADER);
        this.context.shaderSource(psh, '#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\nuniform vec4 color;varying vec2 ptexcoord;uniform sampler2D sampler;void main(void){gl_FragColor=color*texture2D(sampler,ptexcoord);}');
        this.context.shaderSource(vsh, 'attribute vec2 pos;attribute vec2 texcoord;uniform float rot;uniform vec2 scale;uniform vec2 aspect;varying vec2 ptexcoord;void main(void){vec2 scaled=scale*pos;float crot=cos(rot);float srot=sin(rot);gl_Position=vec4(aspect*vec2(scaled.x*crot-scaled.y*srot,scaled.x*srot+scaled.y*crot),0.0,1.0);ptexcoord=texcoord;}');
        this.context.compileShader(psh);
        this.context.compileShader(vsh);
        if (!this.context.getShaderParameter(psh, this.context.COMPILE_STATUS)) {
            console.log(this.context.getShaderInfoLog(psh));
            throw 'psh init failed';
        }
        if (!this.context.getShaderParameter(vsh, this.context.COMPILE_STATUS)) {
            console.log(this.context.getShaderInfoLog(vsh));
            throw 'vsh init failed';
        }
        this.shader = this.context.createProgram();
        this.context.attachShader(this.shader, vsh);
        this.context.attachShader(this.shader, psh);
        this.context.linkProgram(this.shader);
        if (!this.context.getProgramParameter(this.shader, this.context.LINK_STATUS)) {
            throw 'shader init failed';
        }
        this.context.useProgram(this.shader);
        this.shader.pos = this.context.getAttribLocation(this.shader, 'pos');
        this.context.enableVertexAttribArray(this.shader.pos);
        this.shader.texcoord = this.context.getAttribLocation(this.shader, 'texcoord');
        this.context.enableVertexAttribArray(this.shader.texcoord);
        this.shader.rot = this.context.getUniformLocation(this.shader, 'rot');
        this.shader.aspectScale = this.context.getUniformLocation(this.shader, 'aspect');
        this.shader.scale = this.context.getUniformLocation(this.shader, 'scale');
        this.shader.color = this.context.getUniformLocation(this.shader, 'color');
        this.shader.texture = this.context.getUniformLocation(this.shader, 'sampler');
        this.context.uniform2fv(this.shader.aspectScale, this.aspectScale);

        this.quad = this.context.createBuffer();
        this.context.bindBuffer(this.context.ARRAY_BUFFER, this.quad);
        this.context.bufferData(this.context.ARRAY_BUFFER, new Float32Array([
            1.0, 1.0,
            -1.0, 1.0,
            1.0, -1.0,
            -1.0, -1.0
        ]), this.context.STATIC_DRAW);
        this.context.vertexAttribPointer(this.shader.pos, 2, this.context.FLOAT, false, 0, 0);

        this.quadtex = this.context.createBuffer();
        this.context.bindBuffer(this.context.ARRAY_BUFFER, this.quadtex);
        this.context.bufferData(this.context.ARRAY_BUFFER, new Float32Array([
            1.0, 0.0,
            0.0, 0.0,
            1.0, 1.0,
            0.0, 1.0
        ]), this.context.STATIC_DRAW);
        this.context.vertexAttribPointer(this.shader.texcoord, 2, this.context.FLOAT, false, 0, 0);

        this.context.blendFunc(this.context.SRC_ALPHA, this.context.ONE_MINUS_SRC_ALPHA);
        this.context.enable(this.context.BLEND);

        this.setBackground([0, 0, 0]);

        this.spiralTexture = this.context.createTexture();
        this.imageTexture = this.context.createTexture();
        this.setSpiralImage(this.blankImageData);
        this.clearImage();

        $(window).resize({spiral: this}, function(event) { event.data.spiral.resize($(window).width(), $(window).height()); });
        this.resize($(window).width(), $(window).height());
        this.draw();
    }
    WebGlSpiral.prototype = {
        canvas: null,
        context: null,
        shader: null,
        spiralScale: [0.95, 0.95],
        imageScale: [0.95, 0.95],
        aspectScale: [0.5, 1.0],
        spiralColor: [1.0, 1.0, 1.0, 1.0],
        imageColor: [1.0, 1.0, 1.0, 1.0],
        spiralTexture: null,
        imageTexture: null,
        unboundDraw: null,
        baseTime: 0,
        baseRot: 0,
        rotPeriod: 10000,
        blankImageData: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQIHWNgYAAAAAMAAU9ICq8AAAAASUVORK5CYII=',
        draw: function() {
            window.requestAnimationFrame(this.unboundDraw);
            var context = this.context, canvas = this.canvas, shader = this.shader;

            context.viewport(0, 0, canvas.width, canvas.height);

            context.clear(context.COLOR_BUFFER_BIT);

            context.uniform2fv(shader.scale, this.imageScale);
            context.uniform1f(shader.rot, 0.0);
            context.uniform4fv(shader.color, this.imageColor);
            context.uniform1i(shader.texture, 1);
            context.drawArrays(context.TRIANGLE_STRIP, 0, 4);

            context.uniform2fv(shader.scale, this.spiralScale);
            context.uniform1f(shader.rot, this.baseRot + -2.0 * Math.PI * (($.now() - this.baseTime) % this.rotPeriod) / this.rotPeriod);
            context.uniform4fv(shader.color, this.spiralColor);
            context.uniform1i(shader.texture, 0);
            context.drawArrays(context.TRIANGLE_STRIP, 0, 4);
        },
        resize: function(w, h) {
            this.canvas.width = w;
            this.canvas.height = h;
            if (w > h) {
                this.aspectScale = [h / w, 1.0];
            } else {
                this.aspectScale = [1.0, w / h];
            }
            this.context.uniform2fv(this.shader.aspectScale, this.aspectScale);
        },
        loadTexture: function(texture, num, src) {
            var img = new Image();
            var context = this.context;
            $(img).load(function() {
                var bits = 0;
                // check for power of two
                for (var i = 0; i < 32; i++) {
                    bits += 1 & (img.width >> i);
                }
                if (img.width !== img.height || bits !== 1) {
                    var width = img.width;
                    var height = img.height;
                    var maxImg = Math.max(img.width, img.height);
                    var target = maxImg;
                    // convert to power of 2
                    for (i = 1; i < target; i = i << 1) {}
                    target = i;
                    // clamp
                    target = Math.min(target, context.getParameter(context.MAX_TEXTURE_SIZE));
                    width *= target / maxImg;
                    height *= target / maxImg;
                    var x = 0;
                    var y = 0;
                    if (width > height) {
                        y = (width - height) * 0.5;
                    } else {
                        x = (height - width) * 0.5;
                    }
                    console.log({x: x, y: y, width: width, height: height});
                    var canvas = document.createElement('canvas');
                    canvas.width = canvas.height = target;
                    var context2d = canvas.getContext('2d');
                    context2d.drawImage(img, x, y, width, height);
                    img = canvas;
                }
                context.activeTexture(num);
                context.bindTexture(context.TEXTURE_2D, texture);
                context.texImage2D(context.TEXTURE_2D, 0, context.RGBA, context.RGBA, context.UNSIGNED_BYTE, img);
                context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);
                context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR_MIPMAP_NEAREST);
                context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);
                context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);
                context.generateMipmap(context.TEXTURE_2D);
            });
            $(img).error({gls: this}, function(event) {
                event.data.gls.loadTexture(texture, num, event.data.gls.blankImageData);
            });
            img.src = src;
        },
        setBackground: function(r, g, b) {
            this.context.clearColor(r, g, b, 1.0);
        },
        setSpiralImage: function(img) {
            this.loadTexture(this.spiralTexture, this.context.TEXTURE0, img);
        },
        setImage: function(img) {
            this.loadTexture(this.imageTexture, this.context.TEXTURE1, img);
        },
        setSpiralColor: function(r, g, b) {
            this.spiralColor[0] = r;
            this.spiralColor[1] = g;
            this.spiralColor[2] = b;
        },
        setSpiralAlpha: function(a) {
            this.spiralColor[3] = a;
        },
        setImageColor: function(r, g, b) {
            this.imageColor[0] = r;
            this.imageColor[1] = g;
            this.imageColor[2] = b;
        },
        setImageAlpha: function(a) {
            this.imageColor[3] = a;
        },
        setSpiralScale: function(x, y) {
            this.imageScale[0] = x;
            this.imageScale[1] = y;
        },
        setImageScale: function(x, y) {
            this.imageScale[0] = x;
            this.imageScale[1] = y;
        },
        setRotationPeriod: function(wl) {
            var time = $.now();
            this.baseRot += -2.0 * Math.PI * ((time - this.baseTime) % this.rotPeriod) / this.rotPeriod;
            this.baseTime = time;
            while (this.baseRot < 0.0) {
                this.baseRot += 2.0 * Math.PI;
            }
            while (this.baseRot >= 2.0 * Math.PI) {
                this.baseRot -= 2.0 * Math.PI;
            }
            this.rotPeriod = wl * 1000;
        },
        clearImage: function() {
            this.setImage(this.blankImageData);
        }
    };
    return WebGlSpiral;
});
<|endoftext|>


<commit_before>//
// Mocha is a test runner https://mochajs.org/
//
// Chai is an assertion library http://chaijs.com/
//

// expect is behavior driven development (bdd) style assertions
const expect = chai.expect;

describe(`Mocha+Chai Inclass Fetch Exercise for "${inclass.author}"`, () => {
    const baseURL = 'https://webdev-dummy.herokuapp.com'
    const sample = `${baseURL}/sample`

    let longest = null

    const findLargest = (done) => {
        if (!longest) {
            try {
                inclass.countWords(sample).then(r => {
                    Object.keys(r).forEach(key => {
                        if (!longest) longest = key
                        if (r[key] > r[longest]) {
                            longest = key
                        }
                    })
                })
                .then(done)
            } catch (e) {
                done()
            }
        } else {
            done()
        }
    }

	beforeEach((done) => findLargest(done))

    it('author should be defined', () => {
        expect(inclass.author).to.be.ok
    })

	it('countWords should count the number of words in each article', (done) => {
        inclass.countWords(sample)
        .then(r => {
            expect(Object.keys(r).length).to.equal(15)
            Object.keys(r).forEach(key => {
                expect(r[key]).to.be.above(0)
            })
            done()
        })
        .catch(done)
	})

    it('countWords should pass through errors', (done) => {
        inclass.countWords(`${baseURL}/badURL`)
        .then(r => {
            done(new Error(`Received response instead of error ${r}`))
        })
        .catch(e => {
            done()
        })
    })

    it('getLargest should give me the id of the article with the most number of words', (done) => {
        inclass.getLargest(sample)
        .then(r => { expect(parseInt(r)).to.equal(parseInt(longest)); done() })
        .catch(done)
    })

    it('countWordsSafe should catch all errors and return an empty object', (done) => {
        inclass.countWordsSafe(`${baseURL}/badURL`)
        .then(r => { expect(Object.keys(r).length).to.equal(0); done() })
        .catch(done)
    })

    it('countWordsSafe should count the number of words in each article', (done) => {
        inclass.countWordsSafe(sample)
        .then(r => {
            expect(Object.keys(r).length).to.equal(15)
            Object.keys(r).forEach(key => {
                expect(r[key]).to.be.above(0)
            })
            done()
        })
        .catch(done)
    })

})
<commit_msg>update<commit_after>//
// Mocha is a test runner https://mochajs.org/
//
// Chai is an assertion library http://chaijs.com/
//

// expect is behavior driven development (bdd) style assertions
const expect = chai.expect;

describe(`Mocha+Chai Inclass Fetch Exercise for "${inclass.author}"`, () => {
    const baseURL = 'https://webdev-dummy.herokuapp.com'
    const sample = `${baseURL}/sample`

    let longest = null

    const findLargest = (done) => {
        if (!longest) {
            try {
                inclass.countWords(sample).then(r => {
                    Object.keys(r).forEach(key => {
                        if (!longest) longest = key
                        if (r[key] > r[longest]) {
                            longest = key
                        }
                    })
                })
                .then(done)
            } catch (e) {
                done()
            }
        } else {
            done()
        }
    }

	beforeEach((done) => findLargest(done))

    it('author should be defined', () => {
        expect(inclass.author).to.be.ok
    })

	it('countWords should count the number of words in each article', (done) => {
        inclass.countWords(sample)
        .then(r => {
            expect(Object.keys(r).length).to.equal(15)
            Object.keys(r).forEach(key => {
                expect(r[key]).to.be.above(0)
            })
            done()
        })
        .catch(done)
	})

    it('countWords should pass through errors', (done) => {
        inclass.countWords(`${baseURL}/badURL`)
        .then(r => {
            done(new Error(`Received response instead of error ${JSON.stringify(r)}`))
        })
        .catch(e => {
            done()
        })
    })

    it('getLargest should give me the id of the article with the most number of words', (done) => {
        inclass.getLargest(sample)
        .then(r => { expect(parseInt(r)).to.equal(parseInt(longest)); done() })
        .catch(done)
    })

    it('countWordsSafe should catch all errors and return an empty object', (done) => {
        inclass.countWordsSafe(`${baseURL}/badURL`)
        .then(r => { expect(Object.keys(r).length).to.equal(0); done() })
        .catch(done)
    })

    it('countWordsSafe should count the number of words in each article', (done) => {
        inclass.countWordsSafe(sample)
        .then(r => {
            expect(Object.keys(r).length).to.equal(15)
            Object.keys(r).forEach(key => {
                expect(r[key]).to.be.above(0)
            })
            done()
        })
        .catch(done)
    })

})
<|endoftext|>


<commit_before>// Mixins

import areaData from 'china-area-data';
import Loading from 'vue-spinner/src/ScaleLoader.vue';
import dateformat from 'dateformat';

import * as common from './components/_common';
import * as controls from './components/_control';
import * as modules from './components/_modules';
import api from './resource/api';

import choices from '../config/choices';
import config from '../config/config';

export default {
  mounted() {
    // Auto reload
    if (this.reload) {
      // console.log('mounted Reload', this.$route.name);
      this.reload();
    }
  },
  components: { Loading, ...common, ...controls, ...modules },
  computed: {
    choices() {
      return choices;
    },
    areaData() {
      return config.area_data || areaData;
    },
    me() {
      return this.$root.current_user;
    },
    modelUnderscore() {
      return this.model.replace(/([A-Z])/g, $1 => `_${$1.toLowerCase()}`).substr(1);
    },
    config() {
      return config;
    },
  },
  filters: {
    currency(value, note = '￥') {
      return `${note}${Number(value).toFixed(2)}`;
    },
    date(value, fmt = 'yyyy-mm-dd HH:MM:ss') {
      try {
        let val = value;
        if (/^\d\d\d\d-\d\d-\d\d \d\d:\d\d(:\d\d)?$/.test(val)) {
          // http://stackoverflow.com/q/13363673/2544762
          const date = new Date(value.replace(' ', 'T'));
          // timezone convert
          val = new Date(
            date.getUTCFullYear(),
            date.getUTCMonth(),
            date.getUTCDate(),
            date.getUTCHours(),
            date.getUTCMinutes(),
            date.getUTCSeconds(),
          );
        }
        return dateformat(val, fmt);
      } catch (e) {
        return value;
      }
    },
  },
  methods: {
    api(model = this.model, api_root = this.api_root || config.api_root) {
      return api(model, api_root);
    },
    authenticate(reload = false) {
      const vm = this.$root;
      // 可以从 config 函数钩出这个处理方法
      if (typeof(vm.config.action_authenticate) === 'function') {
        return vm.config.action_authenticate.apply(vm, [reload]);
      }
      if (vm.me && !reload) return Promise.resolve(vm.me);
      // debugger; // eslint-disable-line
      return api('User').get({ action: 'current' }).then(resp => {
        vm.current_user = resp.data;
        return vm.me;
      });
    },
    login(username, password) {
      const vm = this.$root;
      if(vm.config.action_login) {
        return vm.config.action_login.apply(vm, [username, password]);
      }
      return api('User').save(
        { action: 'login' },
        { username, password }
      ).then(resp => {
        vm.current_user = resp.data;
        if (!vm.me.is_staff) {
          vm.notify('用户不具备管理员权限');
        } else {
          vm.$router.push({ name: 'main' });
        }
        return vm.me;
      });
    },
    change_password(password_old, password_new) {
      const vm = this.$root;
      if(vm.config.action_change_password) {
        return vm.config.action_change_password.apply(vm, [password_old, password_new]);
      }
      return api('User').save(
        { action: 'change_password' },
        { password_old, password_new }
      ).then(resp => {
        return vm.me;
      });
    },
    logout() {
      const vm = this.$root;
      // 可以从 config 函数钩出这个处理方法
      if (typeof(vm.config.action_logout) === 'function') {
        return vm.config.action_logout.apply(vm, []);
      }
      return api('User').get({ action: 'logout' }).then(() => {
        vm.current_user = null;
        vm.$router.push({ name: 'passport_login' });
      });
    },
    updateModel(model, id, field, value, notify = '操作成功', callback = null) {
      const vm = this;
      return api(model).patch({ id }, { [field]: value }).then(resp => {
        const item = resp.data;
        if (notify) vm.$message.success(notify);
        if (callback) callback(item);
      });
    },
    deleteModel(model, id, confirm = '确认删除此对象？', notify = '操作成功', callback = null) {
      const vm = this;
      const promise = confirm ? this.confirm(confirm) : Promise.resolve();
      return promise.then(() => {
        api(model).delete({ id }).then(() => {
          if (notify) vm.$message.success(notify);
          if (callback) callback();
        });
      });
    },
    // /**
    //  * 这个方法会默认将当前 vm 的 this.filter 数据（对象）作为路由的 query
    //  * 进行重定向。
    //  */
    // query() {
    //   // 为了让输出的 url 更简洁，默认选项不显示出来
    //   const vm = this;
    //   const filter = {};
    //   if (!vm.filter) return;
    //   Object.keys(vm.filter).forEach(key => {
    //     if (vm.filter[key]) filter[key] = vm.filter[key];
    //   });
    //   vm.$router.replace({ query: filter });
    // },
    /**
     * 返回区划号码的一个前缀
     * @param district
     * @param length
     */
    areaPrefix(district, length = 6) {
      return Number((`${district.toString().substr(0, length)}000000`).substr(0, 6));
    },
    getDistrict(adcode = 86) {
      return this.$root.areaData[adcode] || [];
    },
    getDistrictFullNameByCode(zipCode) {
      const vm = this;
      return zipCode ?
        `${vm.getDistrictNameByCode(vm.areaPrefix(zipCode, 2))} ` +
        `${vm.getDistrictNameByCode(vm.areaPrefix(zipCode, 4))} ` +
        `${vm.getDistrictNameByCode(zipCode)}` : '';
    },
    getDistrictNameByCode(adcode) {
      const data = this.$root.areaData;
      const parentCode = this.getDistrictParentCode(adcode);
      return parentCode && data[parentCode][adcode];
    },
    getDistrictParentCode(adcode) {
      if (adcode % 10000 === 0) return 86;
      if (adcode % 100 === 0) return adcode - adcode % 10000;
      return adcode - adcode % 100;
    },
    getUrlFromRoute(route, absolute = true) {
      const vm = this;
      // let path = vm.$router.stringifyPath(route);
      let path = vm.$router.resolve(route).href;
      if (vm.$router.mode === 'hash') {
        if (vm.$router.history.hashbang) {
          path = `!${path}`;
        }
        if (path[0] !== '#') path = `#${path}`;
      }
      if (absolute) {
        // finally we add the absolute prefix before that
        if (path[0] === '#') {
          // hash mode join
          path = `${location.origin}${location.pathname}${location.query || ''}${path}`;
        } else if (path[0] === '/') {
          // absolute path
          path = `${location.origin}${path}`;
        } else {
          // relative path
          path = `${location.origin}${location.pathname.replace(/\/[^/]+$/, '/')}${path}`;
        }
      }
      return path;
    },
    // Naming utils
    trim(str) {
      return str.replace(/^\s+|\s+$/g, '');
    },
    toCamel(str) {
      return str.replace(
        /([-_][a-z])/g,
        $1 => $1.toUpperCase().substr(1)
      ).replace(/^[a-z]/);
    },
    toDash(str) {
      return str.replace(
        /([A-Z])/g,
        $1 => `-${$1.toLowerCase()}`
      ).replace(/^-/, '');
    },
    toUnderscore(str) {
      return str.replace(
        /([A-Z])/g,
        $1 => `_${$1.toLowerCase()}`
      ).replace(/^_/, '');
    },
    // View utils
    getColValue(col, item) {
      // console.log(
      //   'getColValue',
      //   JSON.parse(JSON.stringify(col)),
      //   JSON.parse(JSON.stringify(item)),
      // );
      let value = item;
      try {
        if (col.key) {
          const colKey = this.evaluate(col.key, item);
          value = this.getProperty(item, colKey);
        }
        if (col.filter) {
          value = col.filter(value, item);
        }
        if (col.mapper) {
          const colMapper = this.evaluate(col.mapper, item);
          value = ((value in colMapper) ? colMapper[value] :
              colMapper.__else__) || null;
        }
      } catch (e) {
        console.warn(e);
      }
      return value;
    },
    getProperty(item, keyStr) {
      // 缺省 keyStr 的时候直接返回 item
      if (!keyStr) return item;
      // 执行 keyStr 级联求值
      let value = item;
      if (typeof (keyStr || '') !== 'string') {
        console.warn('getProperty 属性的 key 取值不规范');
        console.log('keyStr:', keyStr);
        console.log('item:', item);
      }
      keyStr.split('.').forEach(key => {
        try {
          value = value && value[key] || null;
        } catch (e) {
          console.error('getProperty 求值错误', e);
        }
      });
      return value;
    },
    evaluate(self, item, keyStr) {
      if (keyStr && typeof keyStr !== 'string') {
        console.warn('evaluate 指定的 field 无效，应为一个字符串');
        return this.evaluate(self, '', item);
      }
      const obj = keyStr ? this.getProperty(self, keyStr) : self;
      return obj instanceof Function ? obj(item) : obj;
    },
    setQueryKey(key, value) {
      const vm = this;
      vm.$router.replace({
        query: Object.assign(vm.$route.query, { [key]: value }),
      });
      vm.reload();
    },
    removeQueryKey(key) {
      const vm = this;
      const query = { ...vm.$route.query };
      delete query[key];
      vm.$router.replace({ query });
      vm.reload();
    },
  },
};
<commit_msg>添加了快速读取字典功能<commit_after>// Mixins

import areaData from 'china-area-data';
import Loading from 'vue-spinner/src/ScaleLoader.vue';
import dateformat from 'dateformat';

import * as common from './components/_common';
import * as controls from './components/_control';
import * as modules from './components/_modules';
import api from './resource/api';

import choices from '../config/choices';
import config from '../config/config';

export default {
  mounted() {
    // Auto reload
    if (this.reload) {
      // console.log('mounted Reload', this.$route.name);
      this.reload();
    }
  },
  components: { Loading, ...common, ...controls, ...modules },
  computed: {
    choices() {
      return choices;
    },
    areaData() {
      return config.area_data || areaData;
    },
    me() {
      return this.$root.current_user;
    },
    modelUnderscore() {
      return this.model.replace(/([A-Z])/g, $1 => `_${$1.toLowerCase()}`).substr(1);
    },
    config() {
      return config;
    },
  },
  filters: {
    currency(value, note = '￥') {
      return `${note}${Number(value).toFixed(2)}`;
    },
    date(value, fmt = 'yyyy-mm-dd HH:MM:ss') {
      try {
        let val = value;
        if (/^\d\d\d\d-\d\d-\d\d \d\d:\d\d(:\d\d)?$/.test(val)) {
          // http://stackoverflow.com/q/13363673/2544762
          const date = new Date(value.replace(' ', 'T'));
          // timezone convert
          val = new Date(
            date.getUTCFullYear(),
            date.getUTCMonth(),
            date.getUTCDate(),
            date.getUTCHours(),
            date.getUTCMinutes(),
            date.getUTCSeconds(),
          );
        }
        return dateformat(val, fmt);
      } catch (e) {
        return value;
      }
    },
  },
  methods: {
    api(model = this.model, api_root = this.api_root || config.api_root) {
      return api(model, api_root);
    },
    authenticate(reload = false) {
      const vm = this.$root;
      // 可以从 config 函数钩出这个处理方法
      if (typeof(vm.config.action_authenticate) === 'function') {
        return vm.config.action_authenticate.apply(vm, [reload]);
      }
      if (vm.me && !reload) return Promise.resolve(vm.me);
      // debugger; // eslint-disable-line
      return api('User').get({ action: 'current' }).then(resp => {
        vm.current_user = resp.data;
        return vm.me;
      });
    },
    login(username, password) {
      const vm = this.$root;
      if (vm.config.action_login) {
        return vm.config.action_login.apply(vm, [username, password]);
      }
      return api('User').save(
        { action: 'login' },
        { username, password }
      ).then(resp => {
        vm.current_user = resp.data;
        if (!vm.me.is_staff) {
          vm.notify('用户不具备管理员权限');
        } else {
          vm.$router.push({ name: 'main' });
        }
        return vm.me;
      });
    },
    change_password(password_old, password_new) {
      const vm = this.$root;
      if (vm.config.action_change_password) {
        return vm.config.action_change_password.apply(vm, [password_old, password_new]);
      }
      return api('User').save(
        { action: 'change_password' },
        { password_old, password_new }
      ).then(resp => {
        return vm.me;
      });
    },
    logout() {
      const vm = this.$root;
      // 可以从 config 函数钩出这个处理方法
      if (typeof(vm.config.action_logout) === 'function') {
        return vm.config.action_logout.apply(vm, []);
      }
      return api('User').get({ action: 'logout' }).then(() => {
        vm.current_user = null;
        vm.$router.push({ name: 'passport_login' });
      });
    },
    updateModel(model, id, field, value, notify = '操作成功', callback = null) {
      const vm = this;
      return api(model).patch({ id }, { [field]: value }).then(resp => {
        const item = resp.data;
        if (notify) vm.$message.success(notify);
        if (callback) callback(item);
      });
    },
    deleteModel(model, id, confirm = '确认删除此对象？', notify = '操作成功', callback = null) {
      const vm = this;
      const promise = confirm ? this.confirm(confirm) : Promise.resolve();
      return promise.then(() => {
        api(model).delete({ id }).then(() => {
          if (notify) vm.$message.success(notify);
          if (callback) callback();
        });
      });
    },
    // /**
    //  * 这个方法会默认将当前 vm 的 this.filter 数据（对象）作为路由的 query
    //  * 进行重定向。
    //  */
    // query() {
    //   // 为了让输出的 url 更简洁，默认选项不显示出来
    //   const vm = this;
    //   const filter = {};
    //   if (!vm.filter) return;
    //   Object.keys(vm.filter).forEach(key => {
    //     if (vm.filter[key]) filter[key] = vm.filter[key];
    //   });
    //   vm.$router.replace({ query: filter });
    // },
    /**
     * 返回区划号码的一个前缀
     * @param district
     * @param length
     */
    areaPrefix(district, length = 6) {
      return Number((`${district.toString().substr(0, length)}000000`).substr(0, 6));
    },
    getDistrict(adcode = 86) {
      return this.$root.areaData[adcode] || [];
    },
    getDistrictFullNameByCode(zipCode) {
      const vm = this;
      return zipCode ?
        `${vm.getDistrictNameByCode(vm.areaPrefix(zipCode, 2))} ` +
        `${vm.getDistrictNameByCode(vm.areaPrefix(zipCode, 4))} ` +
        `${vm.getDistrictNameByCode(zipCode)}` : '';
    },
    getDistrictNameByCode(adcode) {
      const data = this.$root.areaData;
      const parentCode = this.getDistrictParentCode(adcode);
      return parentCode && data[parentCode][adcode];
    },
    getDistrictParentCode(adcode) {
      if (adcode % 10000 === 0) return 86;
      if (adcode % 100 === 0) return adcode - adcode % 10000;
      return adcode - adcode % 100;
    },
    getUrlFromRoute(route, absolute = true) {
      const vm = this;
      // let path = vm.$router.stringifyPath(route);
      let path = vm.$router.resolve(route).href;
      if (vm.$router.mode === 'hash') {
        if (vm.$router.history.hashbang) {
          path = `!${path}`;
        }
        if (path[0] !== '#') path = `#${path}`;
      }
      if (absolute) {
        // finally we add the absolute prefix before that
        if (path[0] === '#') {
          // hash mode join
          path = `${location.origin}${location.pathname}${location.query || ''}${path}`;
        } else if (path[0] === '/') {
          // absolute path
          path = `${location.origin}${path}`;
        } else {
          // relative path
          path = `${location.origin}${location.pathname.replace(/\/[^/]+$/, '/')}${path}`;
        }
      }
      return path;
    },
    // Naming utils
    trim(str) {
      return str.replace(/^\s+|\s+$/g, '');
    },
    toCamel(str) {
      return str.replace(
        /([-_][a-z])/g,
        $1 => $1.toUpperCase().substr(1)
      ).replace(/^[a-z]/);
    },
    toDash(str) {
      return str.replace(
        /([A-Z])/g,
        $1 => `-${$1.toLowerCase()}`
      ).replace(/^-/, '');
    },
    toUnderscore(str) {
      return str.replace(
        /([A-Z])/g,
        $1 => `_${$1.toLowerCase()}`
      ).replace(/^_/, '');
    },
    getChoiceText(choice, value, fieldText='text', fieldValue='value') {
      let result = null;
      choice.some(opt => {
        if (opt[fieldValue] === value) {
          result = opt[fieldText];
          return true;
        }
        return false;
      });
      return result;
    },
    // View utils
    getColValue(col, item) {
      // console.log(
      //   'getColValue',
      //   JSON.parse(JSON.stringify(col)),
      //   JSON.parse(JSON.stringify(item)),
      // );
      let value = item;
      try {
        if (col.key) {
          const colKey = this.evaluate(col.key, item);
          value = this.getProperty(item, colKey);
        }
        if (col.filter) {
          value = col.filter(value, item);
        }
        if (col.mapper) {
          const colMapper = this.evaluate(col.mapper, item);
          value = ((value in colMapper) ? colMapper[value] :
              colMapper.__else__) || null;
        }
      } catch (e) {
        console.warn(e);
      }
      return value;
    },
    getProperty(item, keyStr) {
      // 缺省 keyStr 的时候直接返回 item
      if (!keyStr) return item;
      // 执行 keyStr 级联求值
      let value = item;
      if (typeof (keyStr || '') !== 'string') {
        console.warn('getProperty 属性的 key 取值不规范');
        console.log('keyStr:', keyStr);
        console.log('item:', item);
      }
      keyStr.split('.').forEach(key => {
        try {
          value = value && value[key] || null;
        } catch (e) {
          console.error('getProperty 求值错误', e);
        }
      });
      return value;
    },
    evaluate(self, item, keyStr) {
      if (keyStr && typeof keyStr !== 'string') {
        console.warn('evaluate 指定的 field 无效，应为一个字符串');
        return this.evaluate(self, '', item);
      }
      const obj = keyStr ? this.getProperty(self, keyStr) : self;
      return obj instanceof Function ? obj(item) : obj;
    },
    setQueryKey(key, value) {
      const vm = this;
      vm.$router.replace({
        query: Object.assign(vm.$route.query, { [key]: value }),
      });
      vm.reload();
    },
    removeQueryKey(key) {
      const vm = this;
      const query = { ...vm.$route.query };
      delete query[key];
      vm.$router.replace({ query });
      vm.reload();
    },
  },
};
<|endoftext|>


<commit_before>function getProcessGraphWidgetConfig(widgetId, bagName) {
  display('widgetdata' + widgetId, true);
  display('widgetdatawait' + widgetId, false);
  var extraAttr;
  var extraAttrForm = document.getElementById("widgetselect" + widgetId);
  if(extraAttrForm != null) {
	  extraAttr = extraAttrForm.value;
  }
  var pValue = document.getElementById("pValue" + widgetId);
  if(pValue != null) {
    extraAttr = pValue.value;
  }
  AjaxServices.getProcessGraphWidget(widgetId,bagName,extraAttr,handleGraphWidget);
}

function handleGraphWidget(widget) {
  Element.hide($('widgetdatanoresults' + widget.configId));
  if(widget.hasResults) {
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);

    Element.update($(widgetdataname),widget.html);
    Element.hide($(widgetdatawait));
    Element.show($(widgetdataname));
  } else {
    Element.hide($('widgetdatawait' + widget.configId));
    Element.hide($('widgetdata' + widget.configId));
    Element.show($('widgetdatanoresults' + widget.configId));
    //toggleWidget('widgetcontainer' + widget.configId, 'togglelink' + widget.configId);
  }
  calcNotAnalysed(widget);
}

function getProcessHTMLWidgetConfig(widgetId, bagName) {
	AjaxServices.getProcessHTMLWidget(widgetId, bagName, handleHTMLWidget);
}

function handleHTMLWidget(widget) {
	var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);
    var widgetdatacontent = document.getElementById('widgetdatacontent' + widget.configId);
    Element.hide($(widgetdatawait));
    Element.hide($(widgetdataname));
    Element.show($(widgetdatacontent));
}

function getProcessTableWidgetConfig(widgetId, bagName) {
  AjaxServices.getProcessTableWidget(widgetId,bagName,handleTableWidget);
}

function handleTableWidget(widget) {
  Element.hide($('widgetdatanoresults' + widget.configId));

  if(widget.hasResults) {
    removeChildren($("tablewidget"+widget.configId+"head"));
    removeChildren($("tablewidget"+widget.configId+"body"));
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);

    var row = document.createElement("tr");

    // checkbox
    var checkboxCell = document.createElement("th");
    var formName = "widgetaction" + widget.configId;
    var checky = "<input type=\"checkbox\" name=\"select_all\" id=\"selected_all" + widget.configId + "\"";
          checky += " onclick=\"toggleAllChecks('" + formName + "','" + widget.configId + "')\">";
    checkboxCell.innerHTML = checky;
    row.appendChild(checkboxCell);

      // column names
    for(var i = 0; i < widget.columns.length ; i++){
      var cell = document.createElement("th");
      cell.innerHTML = widget.columns[i];
      row.appendChild(cell);
    }

    $("tablewidget"+widget.configId+"head").appendChild(row);

  var bagContent;
  if(widget.title == "Protein Interactions") {
     bagContent = widget.elementInList;
   }

  for(var i = 0; i < widget.flattenedResults.length ; i++){
    row = document.createElement("tr");
      var columns = widget.flattenedResults[i];
      for(var j = 0; j < columns.length ; j++){
      var cell = document.createElement("td");
         if(columns[j]!=null) {
             if(columns[j][1] != null) {
               var link = document.createElement("a");
               link.setAttribute("href",columns[j][1]);
               link.innerHTML = columns[j][0];
               cell.appendChild(link);
             } else {
              cell.innerHTML = columns[j][0];
             }
         }
         row.appendChild(cell);
    }
      $("tablewidget"+widget.configId+"body").appendChild(row);
    }
    Element.hide($(widgetdatawait));
     Element.show($(widgetdataname));
  } else {
    Element.hide($('widgetdatawait' + widget.configId));
    Element.hide($('widgetdata' + widget.configId));
    Element.show($('widgetdatanoresults' + widget.configId));
    //toggleWidget('widgetcontainer' + widget.configId, 'togglelink' + widget.configId);
  }
  calcNotAnalysed(widget);
}

function getProcessGridWidgetConfig(widgetId, bagName) {
  var widgetdataname = document.getElementById('widgetdata' + widgetId);
  var widgetdatawait = document.getElementById('widgetdatawait' + widgetId);

  Element.hide($(widgetdataname));
  Element.show($(widgetdatawait));

  var externalLink;
  if($("externalLink" + widgetId)!=null) {
    externalLink = $("externalLink" + widgetId).value;
  }

  var externalLinkLabel;
  if($("externalLinkLabel" + widgetId)!=null) {
    externalLinkLabel = $("externalLinkLabel" + widgetId).value;
  }

  var highlight;
  if($("highlight" + widgetId)!=null) {
    highlight = $("highlight" + widgetId).value;
  }

  var numberOpt;
  if($("numberOpt" + widgetId)!=null) {
    numberOpt = $("numberOpt" + widgetId).value;
  }

  var pValue;
  if($("pValue" + widgetId)!=null) {
    pValue = $("pValue" + widgetId).value;
  }
  AjaxServices.getProcessGridWidget(widgetId,bagName,highlight,pValue,numberOpt,externalLink,externalLinkLabel,handleGridWidget);
}

function getProcessEnrichmentWidgetConfig(widgetId, bagName) {
  var widgetdataname = document.getElementById('widgetdata' + widgetId);
  var widgetdatawait = document.getElementById('widgetdatawait' + widgetId);

  Element.hide($(widgetdataname));
  Element.show($(widgetdatawait));
  var errorCorrection;
  if($("errorCorrection" + widgetId)!=null) {
    errorCorrection = $("errorCorrection" + widgetId).value;
  }
  var max;
  if($("max" + widgetId)!=null) {
    max = $("max" + widgetId).value;
  }
  var extraAttr;
  if($("widgetselect" + widgetId)!=null) {
    extraAttr = $("widgetselect" + widgetId).value;
  }
  var externalLink;
  if($("externalLink" + widgetId)!=null) {
    externalLink = $("externalLink" + widgetId).value;
  }

  var externalLinkLabel;
  if($("externalLinkLabel" + widgetId)!=null) {
    externalLinkLabel = $("externalLinkLabel" + widgetId).value;
  }
  AjaxServices.getProcessEnrichmentWidget(widgetId,bagName,errorCorrection,max,extraAttr,externalLink,externalLinkLabel,handleTableWidget);
}

function removeChildren(node) {
  while(node.childNodes.length > 0) {
    node.removeChild(node.childNodes[0]);
  }
}

function checkSelected(formName) {
  var elts = Form.getElements(formName);
  for(var i=0;i<elts.length;i++) {
    if( $(elts[i]).name=='selected' && $(elts[i]).checked ) {
     return true;
    }
  }
  alert("Please select some items")
  return false;
}

function submitWidgetForm(widgetId,type,extra) {
  if(type == 'displayAll' || checkSelected('widgetaction'+widgetId)) {
    $('action'+widgetId).value=type;
    $('export' + widgetId).value=extra;
    $('widgetaction' + widgetId).submit();
  }
}

function displayNotAnalysed(widgetId,type,extra) {
    $('action'+widgetId).value='notAnalysed';
    $('widgetaction' + widgetId).submit();
}

function calcNotAnalysed(widget) {
        var isMSIE = /*@cc_on!@*/false;
        if (!isMSIE) {
            //document.getElementById('widgetnotanalysed' + widget.configId).innerHTML=widget.notAnalysed;
            $('widgetnotanalysed' + widget.configId).update(widget.notAnalysed);
        }
}

function toggleAllChecks(formName, widgetId) {
  var checked = document.getElementById('selected_all' + widgetId).checked;
  var elts = Form.getElements(formName);
  for(var i=0;i<elts.length;i++) {
    if( $(elts[i]).name=='selected') {
        $(elts[i]).checked=checked;
    }
  }
}
<commit_msg>remove unused method.  use common method in imutils instead of Prototype's Element.show and Element.hide.  Refs #2244.<commit_after>function getProcessGraphWidgetConfig(widgetId, bagName) {
  display('widgetdata' + widgetId, true);
  display('widgetdatawait' + widgetId, false);
  var extraAttr;
  var extraAttrForm = document.getElementById("widgetselect" + widgetId);
  if(extraAttrForm != null) {
	  extraAttr = extraAttrForm.value;
  }
  var pValue = document.getElementById("pValue" + widgetId);
  if(pValue != null) {
    extraAttr = pValue.value;
  }
  AjaxServices.getProcessGraphWidget(widgetId,bagName,extraAttr,handleGraphWidget);
}

function handleGraphWidget(widget) {
  display('widgetdatanoresults' + widget.configId, false);
  if(widget.hasResults) {
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    widgetdataname.innerHTML = widget.html;
    display('widgetdatawait' + widget.configId, false);
    widgetdataname.style.display = 'block';
  } else {
    display('widgetdatawait' + widget.configId, false);
    display('widgetdata' + widget.configId, false);
    display('widgetdatanoresults' + widget.configId, true);
  }
  calcNotAnalysed(widget);
}

function getProcessHTMLWidgetConfig(widgetId, bagName) {
	AjaxServices.getProcessHTMLWidget(widgetId, bagName, handleHTMLWidget);
}

function handleHTMLWidget(widget) {
	var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);
    var widgetdatacontent = document.getElementById('widgetdatacontent' + widget.configId);
    Element.hide($(widgetdatawait));
    Element.hide($(widgetdataname));
    Element.show($(widgetdatacontent));
}

function getProcessTableWidgetConfig(widgetId, bagName) {
  AjaxServices.getProcessTableWidget(widgetId,bagName,handleTableWidget);
}

function handleTableWidget(widget) {
  display('widgetdatanoresults' + widget.configId, false);

  if(widget.hasResults) {
    removeChildren($("tablewidget"+widget.configId+"head"));
    removeChildren($("tablewidget"+widget.configId+"body"));
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);

    var row = document.createElement("tr");

    // checkbox
    var checkboxCell = document.createElement("th");
    var formName = "widgetaction" + widget.configId;
    var checky = "<input type=\"checkbox\" name=\"select_all\" id=\"selected_all" + widget.configId + "\"";
          checky += " onclick=\"toggleAllChecks('" + formName + "','" + widget.configId + "')\">";
    checkboxCell.innerHTML = checky;
    row.appendChild(checkboxCell);

      // column names
    for(var i = 0; i < widget.columns.length ; i++){
      var cell = document.createElement("th");
      cell.innerHTML = widget.columns[i];
      row.appendChild(cell);
    }

    $("tablewidget"+widget.configId+"head").appendChild(row);

  var bagContent;
  if(widget.title == "Protein Interactions") {
     bagContent = widget.elementInList;
   }

  for(var i = 0; i < widget.flattenedResults.length ; i++){
    row = document.createElement("tr");
      var columns = widget.flattenedResults[i];
      for(var j = 0; j < columns.length ; j++){
      var cell = document.createElement("td");
         if(columns[j]!=null) {
             if(columns[j][1] != null) {
               var link = document.createElement("a");
               link.setAttribute("href",columns[j][1]);
               link.innerHTML = columns[j][0];
               cell.appendChild(link);
             } else {
              cell.innerHTML = columns[j][0];
             }
         }
         row.appendChild(cell);
    }
      $("tablewidget"+widget.configId+"body").appendChild(row);
    }
    Element.hide($(widgetdatawait));
     Element.show($(widgetdataname));
  } else {
    display('widgetdatawait' + widget.configId, false);
    display('widgetdata' + widget.configId, false);
    display('widgetdatanoresults' + widget.configId, true);
  }
  calcNotAnalysed(widget);
}

function getProcessEnrichmentWidgetConfig(widgetId, bagName) {
  display('widgetdata' + widgetId, false);
  display('widgetdatawait' + widgetId, true);
  var errorCorrection;
  if($("errorCorrection" + widgetId)!=null) {
    errorCorrection = $("errorCorrection" + widgetId).value;
  }
  var max;
  if($("max" + widgetId)!=null) {
    max = $("max" + widgetId).value;
  }
  var extraAttr;
  if($("widgetselect" + widgetId)!=null) {
    extraAttr = $("widgetselect" + widgetId).value;
  }
  var externalLink;
  if($("externalLink" + widgetId)!=null) {
    externalLink = $("externalLink" + widgetId).value;
  }

  var externalLinkLabel;
  if($("externalLinkLabel" + widgetId)!=null) {
    externalLinkLabel = $("externalLinkLabel" + widgetId).value;
  }
  AjaxServices.getProcessEnrichmentWidget(widgetId,bagName,errorCorrection,max,extraAttr,externalLink,externalLinkLabel,handleTableWidget);
}

function removeChildren(node) {
  while(node.childNodes.length > 0) {
    node.removeChild(node.childNodes[0]);
  }
}

function checkSelected(formName) {
  var elts = Form.getElements(formName);
  for(var i=0;i<elts.length;i++) {
    if( $(elts[i]).name=='selected' && $(elts[i]).checked ) {
     return true;
    }
  }
  alert("Please select some items")
  return false;
}

function submitWidgetForm(widgetId,type,extra) {
  if(type == 'displayAll' || checkSelected('widgetaction'+widgetId)) {
    $('action'+widgetId).value=type;
    $('export' + widgetId).value=extra;
    $('widgetaction' + widgetId).submit();
  }
}

function displayNotAnalysed(widgetId,type,extra) {
    $('action'+widgetId).value='notAnalysed';
    $('widgetaction' + widgetId).submit();
}

function calcNotAnalysed(widget) {
        var isMSIE = /*@cc_on!@*/false;
        if (!isMSIE) {
            document.getElementById('widgetnotanalysed' + widget.configId).innerHTML=widget.notAnalysed;
            //$('widgetnotanalysed' + widget.configId).update(widget.notAnalysed);
        }
}

function toggleAllChecks(formName, widgetId) {
  var checked = document.getElementById('selected_all' + widgetId).checked;
  var elts = Form.getElements(formName);
  for(var i=0;i<elts.length;i++) {
    if( $(elts[i]).name=='selected') {
        $(elts[i]).checked=checked;
    }
  }
}
<|endoftext|>


<commit_before>(function () {
	'use strict';
	/**
	 * @ngdoc service
	 * @name passmanApp.TagService
	 * @description
	 * # TagService
	 * Service in the passmanApp.
	 */
	angular.module('passmanApp')
		.service('TagService', ['$filter', function ($filter) {
			var _tags = [];
			return {
				getTags: function () {
					return _tags;
				},
				searchTag: function (string) {
					return $filter('filter')(_tags, {text: string});
				},
				addTags: function (tags) {
					for (var i = 0; i < tags.length; i++) {
						if ($filter('filter')(_tags, {text: tags[i].text}).length === 0) {
							_tags.push(tags[i]);
						}
					}
				},
				removeTag: function (tag) {

				}
			};
		}]);
}());<commit_msg>Fix for ng-dupes<commit_after>(function () {
	'use strict';
	/**
	 * @ngdoc service
	 * @name passmanApp.TagService
	 * @description
	 * # TagService
	 * Service in the passmanApp.
	 */
	angular.module('passmanApp')
		.service('TagService', ['$filter', function ($filter) {
			var _tags = [];
			return {
				getTags: function () {
					return _tags;
				},
				searchTag: function (string) {
					return $filter('filter')(_tags, {text: string});
				},
				addTags: function (tags) {
					for (var i = 0; i < tags.length; i++) {
						if (tags[i].text) {
							if ($filter('filter')(_tags, {text: tags[i].text}).length === 0) {
								_tags.push(tags[i]);
							}
						}
					}
				},
				removeTag: function (tag) {

				}
			};
		}]);
}());<|endoftext|>


<commit_before>
var fs = require('fs');
var exec = require ('child_process').exec;
var async = require ("async");
var app_path, ssh_file, local, email;
var i = 0;
var prompt = require ("prompt");
var config = {};

async.waterfall ([

    function (done){
        // Installs the whole setup
        console.log ("\n\nWELCOME TO THE NODE-AWS-DEPLOY INSTALLER");
        console.log ("This installs your application onto AWS and allows automatic deployment just by pushing to your remote git repository." +
            " Just answer a few questions and everything will be setup");
        prompt.start ();
        done ();
    },

    function (done){
        console.log (++i + ") Is this a 'remote' install? (If this is on a remote server the answer is y)");
        prompt.get (['(y/n)'], function (err, results){
            var answer = (results['(y/n)'] === 'y');
            local = !answer;
            config.sudo = (local) ? "" : "sudo";
            done ();
        });
    },

    function (done){
        console.log (++i + ") Enter your desired application's full path. (no file names. Example  '/home/ec2-user//MyCoolApplication')");
        prompt.get (['folder'], function (err, results){
            var answer = results['folder'];
            config.applicationDirectory = answer;
            try{
                fs.mkdir (answer, function (err){
                    app_path = answer;
                    done ();
                });
            }
            catch (err){
                done ();
            }
        });
    },

    function (done){
        console.log (++i + ") Enter your application's name");
        prompt.get (['name'], function (err, results){
            config.applicationName = results['name'];
            done ();
        });
    },
    function (done){
        console.log (++i + ") Enter your application's entry point (defaults to 'start.js')");
        prompt.get (['entry point'], function(err, results) {
            config.appEntry = results['entry point'];
            done ();
        });
    },
    function (done){
        if (local){
            console.log ("Please take a second ensure you are set up to clone your repository. This might require you to create an ssh key pair or simply use credentials.");
            console.log ("When you have your repository cloned press <enter> to continue.");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Enter your email address to seed the ssh key");
            prompt.get (['email'], function(err, results) {
                email = results['email'];
                done ();
            });
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            // go get the ssh key or create one if it doesn't exist
            try { ssh_file = fs.readFileSync ("/root/.ssh/id_rsa.pub");}
            catch (err) {ssh_file = null; console.log (err);}
            if (!ssh_file){
                console.log ("/tssh key not generated, generating a new one.");
console.log ('ssh-keygen -t rsa -C "' + email + '"');
                var child = exec ('echo HELLO', function (err, std, ster){
console.log ("debug here: err:%j, std:%j, ster:%j", err, std, ster);
                    if (err){done (err);}
                    else{
                        ssh_file = fs.readFileSync ("/home/ec2-user/.ssh/id_rsa.pub");
                        done ();
                    }
                });
            }
            else{
                console.log ("/tssh key already generated!");
                done ();
            }
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            console.log(++i + ") Please take a second to copy the ssh key from this server, listed below, and paste into your git repository service (such as github). This will authorize this server AMI to " +
                "clone your repository and perform git pulls. Press <enter> when done.");
            console.log ("\n" + ssh_file + "\n");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Now that your Git repository has been configured, enter the ssh url for remote access so this server can clone it:");
            prompt.get (['Git repository URL'], function (err, results){
                var git_url = results['Git repository URL'];
                if (git_url){
                    console.log ("  Cloning your repository...");
                    var child = exec ('cd ' + config.applicationDirectory + ' ; cd .. ; ' + config.sudo + ' git clone ' + git_url, function (err, std, ster){
                        if (err){
                            done (err);
                        }
                        else{
                            console.log (std);
                            done ();
                        }
                    });
                }
                else{
                    done ();
                }
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Enter the pull information, what triggers it how its configured, etc...");
            console.log ("\t pullPort: <set this to the port for a pull requests> - defaults to 8000");
            console.log ("\t pullKey: <path to a ssh key file for the HTTPS Server>");
            console.log ("\t pullCert: <path to a ssh cert file for the HTTPS Server>");
            console.log ("\t pullCa: <array of paths to the certificate authority files> (optional)");
            console.log ("\t pullPassphrase: <string - phrase that the certificate was generated with> (optional)");
            console.log ("\t pullSecret: <secret phrase that this server uses to identify as a valid pull request> (optional))");
            console.log ("\t pullBranch: <the branch that this server should pull from on pull requests> (defaults to master))");
            prompt.get (["pullPort", "pullKey", "pullCert", "pullCa", "pullPassphrase", "pullSecret", "pullBranch"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    },
    function (done) {
        if (!local){
            console.log (++i + ") Enter AWS SDK Information so that this server can talk to others on a pull request");
            console.log ("\t accessKeyId: <AWS API Access key 'XXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t secretAccessKey: <AWS Secret Access key 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t region: <aws region that the servers are located in. EX 'us-east-1'>");
            prompt.get (["accessKeyId", "secretAccessKey", "region"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    }

], function (err){
    if (!err){
        var data = JSON.stringify (config);
        fs.writeFileSync ("app-config.json", data);
        console.log ("Success installed: " + config.applicationName + ". The Configuration has been written out to app-config.json");
        console.log ("To Launch the application type 'sudo start node-aws-deploy'");
        process.exit (0);
    }
    else{
        console.log ("There were errors. Errors:" + err);
        process.exit (1);
    }
});

<commit_msg>Initial<commit_after>
var fs = require('fs');
var exec = require ('child_process').exec;
var async = require ("async");
var app_path, ssh_file, local, email;
var i = 0;
var prompt = require ("prompt");
var config = {};

async.waterfall ([

    function (done){
        // Installs the whole setup
        console.log ("\n\nWELCOME TO THE NODE-AWS-DEPLOY INSTALLER");
        console.log ("This installs your application onto AWS and allows automatic deployment just by pushing to your remote git repository." +
            " Just answer a few questions and everything will be setup");
        prompt.start ();
        done ();
    },

    function (done){
        console.log (++i + ") Is this a 'remote' install? (If this is on a remote server the answer is y)");
        prompt.get (['(y/n)'], function (err, results){
            var answer = (results['(y/n)'] === 'y');
            local = !answer;
            config.sudo = (local) ? "" : "sudo";
            done ();
        });
    },

    function (done){
        if (local){
            console.log (++i + ") Enter your desired application's full path. (no file names. Example  '/User/me/MyCoolApplication')");
            prompt.get (['folder'], function (err, results){
                config.applicationDirectory = results['folder'];
                done ();
            });
        }
        else{
            done ();
        }
    },

    function (done){
        console.log (++i + ") Enter your application's name");
        prompt.get (['name'], function (err, results){
            config.applicationName = results['name'];
            done ();
        });
    },
    function (done){
        console.log (++i + ") Enter your application's entry point (defaults to 'start.js')");
        prompt.get (['entry point'], function(err, results) {
            config.appEntry = results['entry point'];
            done ();
        });
    },
    function (done){
        if (local){
            console.log ("Please take a second ensure you are set up to clone your repository. This might require you to create an ssh key pair or simply use credentials.");
            console.log ("When you have your repository cloned press <enter> to continue.");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            // go get the ssh key
            try { ssh_file = fs.readFileSync ("/root/.ssh/id_rsa.pub");}
            catch (err) {ssh_file = null;}
            if (!ssh_file){
                done ("/tssh key not generated, please exit generate one, and re-run");
            }
            else{
                done ();
            }
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            console.log(++i + ") Please take a second to copy the ssh key from this server, listed below, and paste into your git repository service (such as github). This will authorize this server AMI to " +
                "clone your repository and perform git pulls. Press <enter> when done.");
            console.log ("\n" + ssh_file + "\n");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Now that your Git repository has been configured, enter the ssh url for remote access so this server can clone it:");
            prompt.get (['Git repository URL'], function (err, results){
                var git_url = results['Git repository URL'];
                if (git_url){
                    console.log ("  Cloning your repository...");
                    var child = exec ('cd ' + config.applicationDirectory + ' ; cd .. ; ' + config.sudo + ' git clone ' + git_url, function (err, std, ster){
                        if (err){
                            done (err);
                        }
                        else{
                            console.log (std);
                            var dir = std.split ("Cloning into ");
                            dir = dir && dir[1] && dir[1].replace ("'", "").replace ("...", "");
                            if (dir){
                                config.applicationDirectory = '/home/ec2-user/' + dir;
                            }
                            done ();
                        }
                    });
                }
                else{
                    done ();
                }
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Enter the pull information, what triggers it how its configured, etc...");
            console.log ("\t pullPort: <set this to the port for a pull requests> - defaults to 8000");
            console.log ("\t pullKey: <path to a ssh key file for the HTTPS Server>");
            console.log ("\t pullCert: <path to a ssh cert file for the HTTPS Server>");
            console.log ("\t pullCa: <array of paths to the certificate authority files> (optional)");
            console.log ("\t pullPassphrase: <string - phrase that the certificate was generated with> (optional)");
            console.log ("\t pullSecret: <secret phrase that this server uses to identify as a valid pull request> (optional))");
            console.log ("\t pullBranch: <the branch that this server should pull from on pull requests> (defaults to master))");
            prompt.get (["pullPort", "pullKey", "pullCert", "pullCa", "pullPassphrase", "pullSecret", "pullBranch"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    },
    function (done) {
        if (!local){
            console.log (++i + ") Enter AWS SDK Information so that this server can talk to others on a pull request");
            console.log ("\t accessKeyId: <AWS API Access key 'XXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t secretAccessKey: <AWS Secret Access key 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t region: <aws region that the servers are located in. EX 'us-east-1'>");
            prompt.get (["accessKeyId", "secretAccessKey", "region"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    }

], function (err){
    if (!err){
        var data = JSON.stringify (config);
        fs.writeFileSync ("app-config.json", data);
        console.log ("Success installed: " + config.applicationName + ". The Configuration has been written out to app-config.json");
        console.log ("To Launch the application type 'sudo start node-aws-deploy'");
        process.exit (0);
    }
    else{
        console.log ("There were errors. Errors:" + err);
        process.exit (1);
    }
});

<|endoftext|>