text:
/**
 * Shim layer, polyfill, for requestAnimationFrame with setTimeout fallback.
 * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
 */
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          window.oRequestAnimationFrame      ||
          window.msRequestAnimationFrame     ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

/**
 * Shim layer, polyfill, for cancelAnimationFrame with setTimeout fallback.
 */
window.cancelRequestAnimFrame = (function(){
  return  window.cancelRequestAnimationFrame ||
          window.webkitCancelRequestAnimationFrame ||
          window.mozCancelRequestAnimationFrame    ||
          window.oCancelRequestAnimationFrame      ||
          window.msCancelRequestAnimationFrame     ||
          window.clearTimeout;
})();

//****************
// Configurations
//****************
var config = {
  canW: 500,
  canH: 400,
  vehiclesR: ['../img/game/lorry_green.png',
    '../img/game/bus_yellow.png',
    '../img/game/sportscar_red.png',
    '../img/game/pickup_blue.png',
    '../img/game/dumpster_brown.png'],
  vehiclesL: ['../img/game/lorry_green_l.png',
    '../img/game/bus_yellow_l.png',
    '../img/game/sportscar_red_l.png',
    '../img/game/pickup_blue_l.png',
    '../img/game/dumpster_brown_l.png']
};

//***********************
// Game loop-module
//***********************
var Game = (function(conf) {
  var running = true,
    lastFrame,
    ctx,
    screen,
    now,
    timeDiff;

  //*** Init game ***
  var init = function(context) {
    ctx = context;
  };

  //*** Game loop ***
  var gameLoop = function(){
    now = Date.now();

    lastFrame = lastFrame || now;

    // Time difference since last call. This can vary and
    // you need to adjust for it, else the speed of the game
    // will vary as well. You want the speed of the game to be
    // consistent.
    timeDiff = now - lastFrame;
    lastFrame = now;
    if (running) {
      requestAnimFrame(gameLoop);
      ctx.clearRect(0, 0, config.canW, config.canH);
//      ctx.fillRect(0, 0, config.canW, config.canH); // Provar olika sätt att snabba upp
      screen.update(timeDiff);
      screen.draw();
    }
  };

  var start = function() {
    running = true;
    lastFrame = Date.now();
    requestAnimFrame(gameLoop);
  };

  var stop = function() {
    running = false;
  };

  var setScreen = function(scr) {
    screen = scr;
  };

  // Draws the screen only once
  var singleFrame = function() {
    ctx.clearRect(0, 0, config.canW, config.canH);
    screen.draw();
  };

  // The public interface that is returned
  return {
    'init': init,
    'startLoop': start,
    'stopLoop': stop,
    'setScreen': setScreen,
    'singleFrame': singleFrame
  };
})();

//*******************
// Game sequence/logic object, decides which screens to create and display
// based on different game events, controls the game loop.
//*******************
var GameSeq = (function() {
  var gameLoop,
    status,
    level,
    scrFactory,
    highScore,
    player,
    ctx,
    initSpec;

    // Init function
    var init = function(spec) {
      level = spec.level || 1;
      gameLoop = spec.gameLoop;
      scrFactory = spec.scrFactory;
      ctx = spec.ctx;
      initSpec = spec;

      // Creates a player, the same Player-obj is used throughout
      // the game.
      player = new Player({
        'ctx': ctx,
        'x': config.canW / 2, 'y': config.canH * 0.9,
        'type': 'player',   // Känns lite onödigt
        'img': '../img/game/tomato.png',
        'keyCheck': keyMem.isDown
      });

      // Register the GameSeq-obj as listener on player events
      player.registerListener(listener);
    };

    // Event handler.
    // Here you specify the game sequence, what happens when a player
    // has completed a level for example.
    var listener = function(event) {

      // Handling game events
      switch(event) {

        case 'welcome': // Start/Restart the game
          gameLoop.setScreen(screenFactory(ctx, 'welcome', player));
          gameLoop.singleFrame();
          break;

        case 'start': // Start a level
          // Create a screen with objects and start the game loop
          gameLoop.setScreen(screenFactory(ctx, 'level' + level, player));
          gameLoop.startLoop();
          break;

        case 'finish': // The player has finished a level
          gameLoop.stopLoop();
          level++;
          if (level <= 2) {  // There are only two levels in this version
            console.log('level' + level);
            setTimeout(function() {
                gameLoop.setScreen(screenFactory(ctx, 'nextLevel', player));
                gameLoop.singleFrame();
                setTimeout(function() {
                  player.resetPos();
                  listener('start');
                }, 3000);
            }, 1000);
          } else {
              // The player has completed the game
              gameLoop.setScreen(screenFactory(ctx, 'completed', player));
              resetGame();
              setTimeout(function() {
                listener('welcome');
              }, 4000);
          }
          break;

        case 'dead': // The player is dead
          gameLoop.stopLoop();
          gameLoop.setScreen(screenFactory(ctx, 'end', player));
          gameLoop.singleFrame();
          resetGame();
          setTimeout(function() {
                listener('welcome');
          }, 4000);
          break;
      }
    };

    var keyListener = function(event) {
      // Start the game with the space bar
      if (event.keyCode === 32) listener('start');
    };

    var resetGame = function() {
      player.fullReset();
      level = initSpec.level || 1; // Duplicering!!!
    };

    return {
      'init': init,
      'listener': listener,
      'keyListener': keyListener
    };

})();

//*******************
// A game object constructor.
// All visible part in a screen is a game object, for example:
// start and finish areas, cars, players, ...
//*******************
var GameObj = function(spec) {

  this.ctx = spec.ctx;
  this.position = {
      x: spec.x || 0,
      y: spec.y || 0
    };
  this.width = spec.width || 10;
  this.height = spec.height || 10;
  this.pattern = spec.pattern || null;
  this.type = spec.type || 'background'; // Type needed for rules
  this.keyCheck = spec.keyCheck;

  if (this.pattern !== null) { // Inte så snyggt!!!
    this.img = new Image();
    this.img.src = this.pattern;
    var that = this;
    this.img.onload = function() {
      that.canvasPat = that.ctx.createPattern(that.img, 'repeat');
    };
  }

  if (spec.background) {
    this.ctx.fillStyle = spec.background;
  }
};

GameObj.prototype.update = function() { };
GameObj.prototype.draw = function() {

  this.ctx.save();

  // If a pattern is specified, fill the game object's area with it
  if (this.pattern && this.img.complete) {
    this.ctx.fillStyle = this.canvasPat;
  }

//    this.ctx.rect(this.position.x, this.position.y, this.width, this.height); // När jag bytte detta mot fillRect försvann prestandaprob.
//    this.ctx.fill();

  this.ctx.fillRect(this.position.x, this.position.y, this.width, this.height);

  this.ctx.restore();
};

GameObj.prototype.position = function() {
      return this.position;
};
GameObj.prototype.width = function() {
      return this.width;
};
GameObj.prototype.height = function() {
    return this.height;
};

// Check if two objects touch
// Code adapted from this place: http://blog.sklambert.com/html5-canvas-game-2d-collision-detection/
GameObj.prototype.isTouching = function(gameObj) {

  var x1 = this.position.x,
    y1 = this.position.y,
    w1 = this.width,
    h1 = this.height,
    x2 = gameObj.position.x,
    y2 = gameObj.position.y,
    w2 = gameObj.width,
    h2 = gameObj.height;

  if (x1 < x2 + w2  && x1 + w1  > x2 &&
    y1 < y2 + h2 && y1 + h1 > y2) {
    return true; // The objects are touching
  }
  return false;
};

//*****************
// Making a vehicle-constructor using Crockfords
// functional inheritance pattern. A vehicle is based
// on a GameObj.
//*****************
var makeVehicle = function(spec) {
  var obj,
    speed = spec.speed || 0;

    spec.type = 'vehicle';

    // A vehicle inherits GameObj
    obj = new GameObj(spec);

    // Handling the image representing the vehicle
    if (spec.img !== undefined) {
      obj.img = new Image();
      obj.img.src = spec.img;

      obj.img.onload = function() {
        // Sets the objects width and height equal to the image's
        obj.width = obj.img.width;
        obj.height = obj.img.height;

        // Adjust the position of the vehicle so that all vehicles
        // in a lane drives att the same height.
        obj.position.y += spec.laneHeight - obj.height;
      };
    }

    // Overrides the update method in GameObj
    obj.update = function(timeDiff) {

      this.position.x += speed * (timeDiff/1000); // speed in pixels per second

      // When the vehicle moves outside of a canvas border,
      // set the vehicles position so that it reappears on the
      // facing side.
      if (this.position.x > config.canW) { // TODO: Behöver göra liten justering här för hur långa obj är
        this.position.x = -this.width;
      }
      if (this.position.x + this.width < 0) {
        this.position.x = config.canW;
      }
    };

    // Overrides the draw method in GameObj
    obj.draw = function() {
      if(this.img.complete) { // First check if the image has been loaded
        this.ctx.drawImage(this.img, Math.floor(this.position.x), Math.floor(this.position.y)); // Math.floor for canvas optimization
      }
    };

    return obj;
};

//*****************
// Making a player constructor object using
// "classical" inheritance. A player inherits
// the GameObj object.
//*****************
var Player = function(spec) {
  GameObj.call(this, spec); //GameObj-constructor adding properties to the new obj ie. "this"
  this.startPos = {x: spec.x, y: spec.y};
  this.startLifes = spec.lifes || 3;
  this.lifes = this.startLifes;
  this.score = 0;
  this.listeners = []; // Array with listeners on Player events

  // Handling the image
  if (spec.img !== undefined) { //Duplicering av kod!!!
    this.img = new Image();
    this.img.src = spec.img;

    var that = this;
    this.img.onload = function() {
      // Sets the objects width and height equal to the image's
      that.width = that.img.width;
      that.height = that.img.height;

      // Adjusts the start position of the player based
      // on the size of the image representing the player
      that.position.x = that.startPos.x -= that.width / 2;
      that.position.y = that.startPos.y -= that.height / 2;
    };
  }
};

Player.prototype = Object.create(GameObj.prototype); // Inherits GameObj
Player.prototype.constructor = Player; // Fixing constructor property that was overwritten in the step above
Player.prototype.update = function(timeDiff) {

  var movement = 60 * (timeDiff/1000); // Moves at 60 pixels per second

  if (this.keyCheck(38)) this.position.y -= movement; //Up
  if (this.keyCheck(40)) this.position.y += movement; //Down
  if (this.keyCheck(37)) this.position.x -= movement; //Left
  if (this.keyCheck(39)) this.position.x += movement; //Right
};

// Called when a player touch another object,
// then generates different events based on
// what the player touched.
Player.prototype.touch = function(obj) {

  //(Move these rules to a frog class???)

  // Event: Player has hit a vehicle
  if (obj.type === 'vehicle') {

    //Play sound effect
    document.getElementById('splash').play();

    // Count down lifes
    this.lifes--;
    console.log('Liv kvar:' + this.lifes);

    // Check lifes left
    if (this.lifes < 0) {

      // Inform listeners that the player is dead
      this.listeners.forEach(function(listener) {
        listener('dead');
      });
    } else {
      // Reset player to start position
      this.resetPos();
    }
  }

  // Event: Player has reached the finish
  if (obj.type === 'finish') {

    // Inform listeners that the player has reached the finish
    this.listeners.forEach(function(listener) {
      listener('finish');
    });
  }
};

Player.prototype.resetPos = function() {
  this.position.x = this.startPos.x;
  this.position.y = this.startPos.y;
};

Player.prototype.fullReset = function() {
  this.resetPos();
  this.lifes = this.startLifes;
  this.score = 0;
};

Player.prototype.registerListener = function(listener) { // Kanske lyfta upp på GameObj nivå?
  this.listeners.push(listener);
};

// Overrides the draw method in GameObj - Gör om, flytta till GameObj?! Nu duplicering av kod!!!
Player.prototype.draw = function() {
  if(this.img.complete) {
    this.ctx.drawImage(this.img, Math.floor(this.position.x), Math.floor(this.position.y));
  }
};

//*******************
// A panel constructor function that inherits from GameObj
//*******************

var Panel = function(spec) {
  GameObj.call(this, spec);
  this.headline = spec.headline || '';
  this.sub = spec.sub || '';
  this.bg = spec.background;
};

Panel.prototype = Object.create(GameObj.prototype); // Inherits GameObj
Panel.prototype.constructor = Panel;

Panel.prototype.draw = function() { // TODO: Gör om det mesta här och flytta ut värden

  this.ctx.save();
  this.ctx.fillStyle = 'green';
  this.ctx.fillRect(0, 0, config.canW, config.canH);
  this.ctx.fillStyle = 'red';
  this.ctx.font = 'bold 50px sans-serif';
  this.ctx.shadowOffsetX = 2;
  this.ctx.shadowOffsetY = 2;
  this.ctx.shadowColor = "yellow";
  this.ctx.fillText(this.headline, 150, 150);
  this.ctx.restore();
  this.ctx.save();
  this.ctx.font = 'bold 20px sans-serif';
  this.ctx.fillStyle = 'yellow';
  this.ctx.fillText(this.sub, 30, 200);
  this.ctx.restore();
};

//*******************
// A Simple factory that creates screens. There are different
// screens for: start, level1, end, ....
// A screen dictates how the game looks and which objects it
// contains.
//*******************
var screenFactory = function(ctx, type, player) {
  var objects = [];

  switch (type) {

    // Welcome screen
    case 'welcome':
      objects.push(new Panel({
        'ctx': ctx,
        'x': 0, 'y': 0,
        'width': config.canW,
        'height': config.canH,
        'type': 'panel',
        'headline': 'Ketchup',
        'sub': 'Starta med mellanslag, styr med piltangenterna',
        'background': 'green',
        'keyCheck': keyMem.isDown // Behövs den verkligen här?
      }));
      break;

    // Main game screens
    case 'level2':
      var speedFactor = 1.4; // Increase the speed in level 2
    case 'level1':
      // Creates the start area
      objects.push(new GameObj({
        'ctx': ctx,
        'x': 0, 'y': config.canH * 0.8,
        'width': config.canW,
        'height': config.canH * 0.2,
        'type': 'start',
        'pattern': '../img/game/floor/grass/grass_flowers_yellow1.png',
        'keyCheck': keyMem.isDown // Behövs den verkligen här?
      }));

      // Creates the road
      objects.push(new GameObj({
        'ctx': ctx,
        'x': 0, 'y':config.canH * 0.2,
        'width': config.canW,
        'height': config.canH * 0.6,
        'background': 'black'
      }));

/*
      // Curbs
      objects.push(new GameObj({
        'ctx': ctx,
        'x': 0, 'y': config.canH * 0.75,
        'width': config.canW,
        'height': config.canH * 0.05,
        'type': 'curb',
        'pattern': '../img/game/floor/rect_gray0.png',
        'keyCheck': keyMem.isDown // Behövs den verkligen här?
      }));
*/
      // Creates the finishing area
      objects.push(new GameObj({
        'ctx': ctx,
        'x': 0, 'y': 0,
        'width': config.canW,
        'height': config.canH * 0.2,
        'type': 'finish',
        'pattern': '../img/game/floor/grass/grass_flowers_yellow1.png',
        'keyCheck': keyMem.isDown
      }));

/*
      // Creates a info panel for score, lifes, ...
      objects.push(new GameObj({
        'ctx': ctx,
        'x': 0, 'y': 0,
        'width': config.canW/5,
        'height': 50,
        'type': 'panel',
      }));
*/
      // Creates the cars
      var laneY = config.canH * 0.2,
        laneNo = 4,
        laneHeight = config.canH * 0.55 / laneNo,
        cars = 3,
        distance = config.canW / cars,
        speeds = [60, -60, 45, -30]; // In pixels per second

      for (var i = 0 ; i < laneNo ; i++) {
        for (var j = 0 ; j < cars ; j++) {
          objects.push(makeVehicle({
            'ctx': ctx,
//            'x': distance * j - (distance * 0.7 * Math.random()),
            'x': distance * j + (distance * 0.7 * Math.random()),
            'y': laneY,
            'speed': speeds[i] * (speedFactor || 1),
            'img': speeds[i] > 0 ? config.vehiclesR[Kajja.random(0, config.vehiclesR.length - 1)] :
              config.vehiclesL[Kajja.random(0, config.vehiclesL.length - 1)],
            'laneHeight': laneHeight,
            'keyCheck': keyMem.isDown
          }));
        }
        laneY += laneHeight;
      }

      // Adds the player object (which is not connected to a specific screen
      // like other objects are).
      objects.push(player);
      break;

    // Screen when the player moves to a new level
    case 'nextLevel':
      objects.push(new Panel({
        'ctx': ctx,
        'x': 0, 'y': 250,
        'width': config.canW,
        'height': 50,
        'type': 'panel',
        'sub': 'Bra jobbat, nu blir det lite svårare',
        'keyCheck': keyMem.isDown // Behövs den verkligen här?
    }));
    break;

    // Screen when the player has no lifes left
    case 'end':
      objects.push(new Panel({
        'ctx': ctx,
        'x': 0, 'y': 250,
        'width': config.canW,
        'height': 50,
        'type': 'panel',
        'sub': '   Tyvärr, inga liv kvar. Spelet är slut!',
        'keyCheck': keyMem.isDown // Behövs den verkligen här?
      }));
      break;

    // Screen when the player has completed the whole game
    case 'completed':
      objects.push(new Panel({
        'ctx': ctx,
        'x': 0, 'y': 250,
        'width': config.canW,
        'height': 50,
        'type': 'panel',
        'sub': 'Grattis!!! Du klarade hela spelet!',
        'keyCheck': keyMem.isDown // Behövs den verkligen här?
      }));
      break;
  }
  return new Screen(objects, player);
};

//*********************
// A Screen constructor function
// A screen is an object that contains a collection of game objects
// which it manages, ie. execute command on the collection.
// (Interface for screens: update(), draw())
//*********************
var Screen = function(objects, player) {
  this.objects = objects;
  this.player = player;
};

Screen.prototype.update = function(timeDiff) {

  var that = this;

  // Update all objects
  this.objects.forEach(function(obj) {
      obj.update(timeDiff);
  });

  // Check if the player is touching any other object
  this.objects.forEach(function(obj) {
    if (obj.type !== 'player' && obj.isTouching(that.player)) {
      that.player.touch(obj);
    }
  });
};

Screen.prototype.draw = function() {

  // Draw all objects
  this.objects.forEach(function(obj) {
    obj.draw();
  });
};

//(Man kanske kan optimera ngt genom att skapa de vanligaste screens från början?)

//********************
// A log object that holds information on which keys that are pressed down,
// to avoid choppy movement of the player since the key-events happens at
// some interval when a key is pressed down, not synced with redraws.
// Created as a module. A global singleton object (so there can be "hidden" references in code).
// Idea from here (although a different implementation):
// http://nokarma.org/2011/02/27/javascript-game-development-keyboard-input/index.html
//********************
var keyMem = (function() {

  var keysDown = [];

  var listenerDown = function(event) {
    keysDown[event.keyCode] = true;
    return false;
  };

  var listenerUp = function(event) {
    delete keysDown[event.keyCode];
    return false;
  };

  var isDown = function(key) {
    return keysDown[key] ? true : false;
  };

  return {
    'listenerDown': listenerDown,
    'listenerUp': listenerUp,
    'isDown': isDown
  };
})();

//********************
// Starts the game when the document is ready
//********************
$(document).ready(function(){
  'use strict';

  // Setting the canvas dimensions
  var canvas = document.getElementById('game'),
    context = canvas.getContext('2d');
  canvas.width = config.canW;
  canvas.height = config.canH;

  // Handling key events
  $(document).on('keydown', keyMem.listenerDown);
  $(document).on('keyup', keyMem.listenerUp);

  // Init the gameLoop
  Game.init(context);

  // Init the GameSeq object
  GameSeq.init({
      gameLoop: Game,
      scrFctory: screenFactory,
      ctx: context
  });

  // Register listeners for start and pause events
  $(document).on('keydown', GameSeq.keyListener);

  // Start the game by triggering a 'welcome' event
  GameSeq.listener('welcome');

});


text:
(function(){
  			'use strict';
})();
var request = require('request');
promise = require('bluebird');
_ = require('lodash');
geocode = require('geocoder');
promise.promisifyAll(request);

request.getAsync('https://seeclickfix.com/api/v2/issues?place_url=virginia-beach&state=VA&per_page=10&page=1')
		.spread(function(res,body) { //callback signature is (err, res, body) so we need to use spread instead of then
			var data = JSON.parse(body).issues;
			return data;
		}).then(function(data) {
			var lat = _.pluck(data,'lat');
		    					lng = _.pluck(data,'lng');
		    					lat_lng = {
		    					lat:lat,
		    					lng:lng
		    };
			return lat_lng;
		}).then(function(lat_lng) {
			console.log('these are the lats \n', lat_lng.lat,  '\n these are the longs \n',lat_lng.lng);
		})
		.then(function() {

//how to promisify geocode
			promise.promisifyAll(geocode);

			var getzips = function(lat,lng) {
				return new promise(function(resolve, reject) {
					geocode.reverseGeocodeAsync(lat,lng)
		  .then(function(data) {
		  					var zips = data.results[0].address_components;
		  					var newzips = _.reduce(zips,function(all,item, index) {
			if (item.types[0] == 'postal_code') {
				all.push(item.short_name);
			}
			return all;
		},[]);
		  					resolve(newzips);
		  });
				})
		 .catch(function(err) {
		  					console.log(err);
		  });
			};

			promise.all(lat_lng.lat.map(function(_,index) {
				return getzips(lat_lng.lat[index],lat_lng.lng[index]);
			})
		).then(function(data) {
			var zipcodes = _.uniq(_.flatten(data));
			console.log('\n zipcodes:(uniqued):\n',zipcodes.join(' '));
		});
		});

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/grero/StatUtils.jl.svg?branch=master)](https://travis-ci.org/grero/StatUtils.jl)
[![codecov.io](http://codecov.io/github/grero/StatUtils.jl/coverage.svg?branch=master)](http://codecov.io/github/grero/StatUtils.jl?branch=master)

Various statistics related utilities that I find useful, but couldn't find elsewhere in the Julia eco system (probably because I didn't look hard enough )


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: module RequestHelper</title>

<big><big>RequestHelper</big></big>	index
/home/zhao/CMPUT410W14T07/sys/controller/RequestHelper.py

<big>Modules</big>

<tt>      </tt>

json

	mysql

	sys

<big>Classes</big>

<tt>      </tt>

RequestHelper

class RequestHelper

<tt>   </tt>
Methods defined here:

__init__(self, dbAdapter)

addNewRequest(self, recipientId, senderId)

deleteAllRequestByAid(self, recipient_id)

deleteRequest(self, recipientId, senderId)

getRequestCountByAid(self, recipientId)

getRequestListByAid(self, recipientId)

getSentRequestByAid(self, aid)

<tt>To get list of authors, who is the author followed</tt>

Data and other attributes defined here:

dbAdapter = None


text:
package org.xsaas.xstat.web.action.manage.delete;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xsaas.xstat.web.conf.StatusConstants;

import org.xsaas.xstat.business.IEmployeeInfoService;
import org.xsaas.xstat.business.IOptionInfoService;
import org.xsaas.xstat.po.EmployeeInfo;
import org.xsaas.xstat.po.OptionInfo;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DeleteSelectManageAction extends ActionSupport {

	/**
	 *
	 */
	private static final long serialVersionUID = -6769434775929025493L;
	private static Log logger = LogFactory.getLog(DeleteSelectManageAction.class);

	private IOptionInfoService optionInfoService = null;
	private IEmployeeInfoService employeeInfoService = null;

	private Long optionID = null;

	public String execute()throws Exception{

		try{
			String username = (String)ActionContext.getContext().getSession().get("LOGINUSERNAME");
			String password = (String)ActionContext.getContext().getSession().get("LOGINPASSWORD");
			if(username == null || password == null) {
				return LOGIN;
			}

			if(optionID == null){
				return ERROR;
			}

			OptionInfo info = optionInfoService.getOptionInfo(optionID);
			info.setStatus(StatusConstants.SHANCHU);
			optionInfoService.update(info);
		}catch(Exception e) {
			logger.error(""+e.getMessage(),e.getCause());
		}

		return SUCCESS;
	}

	public void setEmployeeInfoService(IEmployeeInfoService employeeInfoService) {
		this.employeeInfoService = employeeInfoService;
	}

	public Long getOptionID() {
		return optionID;
	}

	public void setOptionID(Long optionID) {
		this.optionID = optionID;
	}

	public void setOptionInfoService(IOptionInfoService optionInfoService) {
		this.optionInfoService = optionInfoService;
	}

}


text:
FROM dawnorigin/openjdk:6-jdk

CMD ["gradle"]

ENV GRADLE_HOME /opt/gradle
ENV GRADLE_VERSION 2.14.1

ARG GRADLE_DOWNLOAD_SHA256=cfc61eda71f2d12a572822644ce13d2919407595c2aec3e3566d2aab6f97ef39
RUN set -o errexit -o nounset \
	&& echo "Downloading Gradle" \
	&& wget --no-verbose --output-document=gradle.zip "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip" \
	\
	&& echo "Checking download hash" \
	&& echo "${GRADLE_DOWNLOAD_SHA256} *gradle.zip" | sha256sum --check - \
	\
	&& echo "Installing Gradle" \
	&& unzip gradle.zip \
	&& rm gradle.zip \
	&& mv "gradle-${GRADLE_VERSION}" "${GRADLE_HOME}/" \
	&& ln --symbolic "${GRADLE_HOME}/bin/gradle" /usr/bin/gradle \
	\
	&& echo "Creating Gradle cache for root" \
	&& mkdir /root/.gradle \
	\
	&& echo "Adding gradle user and group" \
	&& groupadd --system --gid 1000 gradle \
	&& useradd --system --gid gradle --uid 1000 --shell /bin/bash --create-home gradle \
	&& mkdir /home/gradle/.gradle \
	&& chown --recursive gradle:gradle /home/gradle

# Create root .gradle volume
VOLUME "/root/.gradle"

# Create gradle .gradle volume
USER gradle
VOLUME "/home/gradle/.gradle"
WORKDIR /home/gradle

RUN set -o errexit -o nounset \
	&& echo "Testing Gradle installation" \
	&& gradle --version


text:
using EveMarket.Core.Enums;
using EveMarket.Core.Models;
using EveMarket.Core.Models.CrestApi;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using eZet.EveLib.EveCrestModule;
using EveMarket.Core.Models.FlyingCircus;
using EveMarket.Core.Repositories.Eve;
using EveMarket.Core.Services.Interfaces;
using LiteDB;

namespace EveMarket.Core.Services
{
    public class ItemService : IItemService
    {

        private readonly EveDb _eveDb;
        private readonly LiteDatabase _liteDb;

        private static readonly Dictionary<MineralType, ReprocessingType> MineralPrimaryOreMapping
            = new Dictionary<MineralType, ReprocessingType>
        {
            {MineralType.Tritanium, ReprocessingType.Veldspar},
            {MineralType.Pyerite, ReprocessingType.Scordite},
            {MineralType.Mexallon, ReprocessingType.Plagioclase},
            {MineralType.Isogen, ReprocessingType.Kernite},
            {MineralType.Nocxium, ReprocessingType.Pyroxeres},
            {MineralType.Zydrine, ReprocessingType.Bistot},
            {MineralType.Megacyte, ReprocessingType.Arkonor},
            {MineralType.Morphite, ReprocessingType.Mercoxit}
        };

        private static readonly Dictionary<MineralType, int> MineralSortOrder
            = new Dictionary<MineralType, int>
            {
                {MineralType.Tritanium, 8},
                {MineralType.Pyerite, 7},
                {MineralType.Mexallon, 6},
                {MineralType.Isogen, 5},
                {MineralType.Nocxium, 4},
                {MineralType.Zydrine, 2},
                {MineralType.Megacyte, 3},
                {MineralType.Morphite, 1},
            };

        public ItemService(EveDb eveDb, LiteDatabase liteDb)
        {
            _eveDb = eveDb;
            _liteDb = liteDb;
        }

        public List<OreGroup> GetOreGroups(ReprocessingSkills reprocessingSkills)
        {
            var oreCategory = _eveDb.invCategories.Single(c => c.categoryName == "Asteroid" && true == c.published);

            var oreGroups = oreCategory.invGroups.Where(g => g.groupName != "Ice" && true == g.published)
                .Select(g => new OreGroup
                {
                    ReprocessingType = (ReprocessingType)
                                    Enum.Parse(typeof(ReprocessingType), g.groupName.Replace(" ", ""), true),
                    GroupName = g.groupName,
                    Ores = g.invTypes.Where(t => true == t.published && t.portionSize == 1 && t.marketGroupID > 0)
                        .OrderBy(t => t.basePrice)
                        .Select((t, i) =>
                        {
                            var yieldBonus = i*.05;
                            var reprocessingType =
                                (ReprocessingType)
                                    Enum.Parse(typeof(ReprocessingType), g.groupName.Replace(" ", ""), true);
                            return new OreMinerals
                            {
                                Id = t.typeID,
                                Name = t.typeName,
                                ReprocessingType = reprocessingType,
                                ReprocessingRate = reprocessingSkills.CalculateReprocessingRate(reprocessingType),
                                YieldModifier = yieldBonus,
                                Volume = t.volume,
                                Pricing = GetCurrentItemPricing(t.typeID),
                                ReprocessedMinerals = new MineralList
                                {
                                    Tritanium = t[MineralType.Tritanium],
                                    Pyerite = t[MineralType.Pyerite],
                                    Mexallon = t[MineralType.Mexallon],
                                    Isogen = t[MineralType.Isogen],
                                    Nocxium = t[MineralType.Nocxium],
                                    Zydrine = t[MineralType.Zydrine],
                                    Megacyte = t[MineralType.Megacyte],
                                    Morphite = t[MineralType.Morphite],
                                }
                            };
                        }).ToList()
                });

            return oreGroups.ToList();
        }

        public List<Mineral> GetMinerals()
        {
            return _eveDb.invGroups.Where(g => g.groupName == "Mineral")
                .SelectMany(g => g.invTypes)
                .Where(t => true == t.published)
                .ToList()
                .Select(t =>
                {
                    var mineralType = (MineralType) Enum.Parse(typeof(MineralType), t.typeName);

                    return new Mineral
                    {
                        Id = t.typeID,
                        Name = t.typeName,
                        Volume = t.volume,
                        MineralType = mineralType,
                        PrimaryOreReprocessingType = MineralPrimaryOreMapping[mineralType],
                        ReprocessingOrder = MineralSortOrder[mineralType],
                        Pricing = GetCurrentItemPricing(t.typeID)
                    };
                }).ToList();
        }

        public OrderSummary GetCompressedOres(ReprocessingSkills reprocessingSkills, MineralList mineralList)
        {
            var oreGroups = GetOreGroups(reprocessingSkills);
            var minerals = GetMinerals();

            var optimizedOres = OptimizeOres(minerals, oreGroups, mineralList, reprocessingSkills);

            var finalOres = optimizedOres.Where(o => o.Qty > 0).ToList();

            var currentMinerals = new MineralList();
            foreach (var ore in finalOres)
            {
                foreach (MineralType mineral in Enum.GetValues(typeof(MineralType)))
                {
                    currentMinerals[mineral] += ore.GetMineralQty(mineral, reprocessingSkills.CalculateReprocessingRate(ore.ReprocessingType));
                }
            }

            var generatedMinerals = new List<Mineral>();
            foreach (var mineral in minerals)
            {
                mineral.Qty = currentMinerals[mineral.MineralType];
                mineral.DesiredQty = mineralList[mineral.MineralType];

                generatedMinerals.Add(mineral);
            }

            return GetOrderSummary(finalOres, generatedMinerals, mineralList);
        }

        protected List<OreMinerals> OptimizeOres(List<Mineral> minerals, List<OreGroup> oreGroups, MineralList mineralList, ReprocessingSkills reprocessingSkills)
        {
            foreach (var mineral in minerals.OrderBy(o => o.ReprocessingOrder))
            {
                var mineralType = mineral.MineralType;
                var primaryOreGroup = oreGroups.Single(o => o.ReprocessingType == mineral.PrimaryOreReprocessingType);

                var desiredMineralQty = mineralList[mineralType];

                foreach (var ore in oreGroups.SelectMany(o => o.Ores).Where(o => o.Qty > 0))
                {
                    desiredMineralQty -= ore.GetMineralQty(mineralType, ore.ReprocessingRate);
                }

                foreach (var order in primaryOreGroup.OptimizedMarketOrders)
                {
                    if (desiredMineralQty <= 0) break;

                    var oreMineralYield = order.AssociatedOre.ReprocessedMinerals[mineralType]*
                                          order.AssociatedOre.ReprocessingRate;

                    var desiredOrderQty = Math.Ceiling(Math.Min(order.Volume, desiredMineralQty/oreMineralYield));

                    desiredMineralQty -= desiredOrderQty*oreMineralYield;
                    primaryOreGroup.Ores.Single(o => o.Id == order.AssociatedOre.Id).Qty += desiredOrderQty;
                }
            }

            return oreGroups.SelectMany(og => og.Ores.Where(o => o.Qty > 0)).ToList();
        }

        public OrderSummary GetOrderSummary(IEnumerable<MarketItem> items, List<Mineral> minerals, MineralList mineralList)
        {
            var itemList = items.ToList();

            var perfectPurchasePrice = itemList.Sum(o => Math.Round(o.Pricing.CalculateBestTotal((int)Math.Ceiling(o.Qty)), 2));
            var buyAllPurchasePrice = itemList.Sum(o => o.TotalPrice);

            var totalOreVolume = (decimal) itemList.Sum(o => o.Volume*o.Qty);
            var sourceStagingShippingCost = itemList.Sum(o => o.AverageShippingCost*(decimal) o.Qty);

            var mineralBuyAllPurchasePrice = minerals?.Sum(m => m.TotalPrice);
            var totalMineralVolume = minerals?.Sum(m => m.Volume * m.DesiredQty);
            var mineralValueRatio = (buyAllPurchasePrice + sourceStagingShippingCost) / mineralBuyAllPurchasePrice;

            if (minerals != null)
            {
                foreach (var mineral in minerals)
                {
                    if (mineral.Qty == 0) continue;
                    mineral.ComparisonTotal = Math.Round(mineral.TotalPrice * mineralValueRatio.Value, 2);
                    mineral.ComparisonPrice = Math.Round(mineral.ComparisonTotal / (decimal)mineral.DesiredQty, 2);
                }
            }

            return new OrderSummary
            {
                MarketItems = itemList,
                Minerals = minerals,
                MineralValueRatio = mineralValueRatio,
                TotalMineralVolume = totalMineralVolume,
                PurchaseCostBest = perfectPurchasePrice,
                PurchaseCost = buyAllPurchasePrice,
                TotalVolume = totalOreVolume,
                SourceStagingShippingCost = sourceStagingShippingCost,
            };
        }

        public invType GetItem(string itemName)
        {
            return _eveDb.invTypes.SingleOrDefault(i => i.typeName == itemName);
        }

        public invType GetItem(long itemId)
        {
            return _eveDb.invTypes.SingleOrDefault(i => i.typeID == itemId);
        }

        public IEnumerable<Blueprint> GetBlueprints(string name)
        {
            name = name.ToLowerInvariant();
            var matchedTypes = _eveDb.industryActivityProducts.Where(t =>
                true == t.type.published
                && true == t.productType.published
                && t.productType.typeName.ToLower().StartsWith(name)
                && t.productType.invGroup.invCategory.categoryName != "Blueprint")
                .OrderBy(t => t.productType.typeName);

            return matchedTypes.ToList().Select(bp => new Blueprint
            {
                TypeId = bp.productTypeID,
                TypeName = bp.productType.typeName,
            });
        }

        public Blueprint GetBlueprint(int typeId, IndustryActivityType activityType)
        {
            var bp = _eveDb.industryActivityProducts.SingleOrDefault(p => p.productTypeID == typeId && p.activityID == (int)activityType);

            return bp == null
                ? null
                : new Blueprint
                {
                    TypeId = bp.productTypeID,
                    TypeName = bp.productType.typeName,
                    Skills =
                        bp.type.typeSkills.Where(a => a.activityID == (int) IndustryActivityType.Manufacturing)
                            .ToList()
                            .Select(s => new BlueprintSkill
                            {
                                SkillId = s.skillID,
                                SkillName = s.skillType.typeName,
                                MinimumLevel = s.level,
                            }),
                    Materials = GetMaterials(bp.type),
                };
        }

        protected IEnumerable<BlueprintMaterial> GetMaterials(invType type)
        {
            if (type == null)
            {
                return new List<BlueprintMaterial>();
            }

            return type.industryActivityMaterials.Where(am => am.activityID == (int)IndustryActivityType.Manufacturing)
                .ToList()
                .Select(m => new BlueprintMaterial()
                {
                    TypeId = m.materialTypeID,
                    TypeName = m.materialType.typeName,
                    Qty = m.quantity,
                    Volume =m.materialType.volume,
                    Skills = m.type.typeSkills.Where(a => a.activityID == (int)IndustryActivityType.Manufacturing).ToList().Select(s => new BlueprintSkill
                    {
                        SkillId = s.skillID,
                        SkillName = s.skillType.typeName,
                        MinimumLevel = s.level,
                    }),
                    Materials = GetMaterials(m.materialType.activityProducts.Where(p => p.activityID == (int)IndustryActivityType.Manufacturing).Select(p => p.type).SingleOrDefault())
                });
        }

        public IEnumerable<mapSolarSystem> GetSystems(string prefix)
        {
            prefix = prefix.ToLowerInvariant();
            var systems = _eveDb.mapSolarSystems.Where(s => s.solarSystemName.ToLower().StartsWith(prefix));

            return systems.ToList();
        }

        public IEnumerable<staStation> GetStations(int systemId, string prefix)
        {
            prefix = prefix.ToLowerInvariant();
            var stations =
                _eveDb.staStations.Where(s => s.solarSystemID == systemId && s.stationName.ToLower().StartsWith(prefix));

            return stations.ToList();
        }

        public OrderSummary GetItemPricing(List<ItemLookup> itemList, decimal iskPerM3, decimal collateralPct, long stationId)
        {
            var station = _eveDb.staStations.Single(s => s.stationID == stationId);
            var regionId = station.regionID.Value;

            var items = itemList
                .Select(il => _eveDb.invTypes.SingleOrDefault(i => i.typeID == il.TypeId))
                .Where(i => i != null)
                .Select(i => new MarketItem()
                {
                    Id = i.typeID,
                    Name = i.typeName,
                    Volume = i.volume,
                    Pricing = GetCurrentItemPricing(i.typeID, regionId, new List<long> {stationId}),
                    CollateralPct = collateralPct,
                    IskPerM3 = iskPerM3,
                    Qty = itemList.First(il => il.TypeId == i.typeID).Qty,
                });

            return GetOrderSummary(items, null, null);
        }

        public ItemPricing GetCurrentItemPricing(long typeId, long regionId = 10000002, IEnumerable<long> stationIds = null)
        {
            var region = _eveDb.mapRegions.Single(r => r.regionID == regionId);
            var regionStations = region.stations.ToList();
            var stationDict = regionStations.ToDictionary(s => s.stationID, s => s.stationName);

            var sellOrders = _liteDb.GetCollection<RegionMarketOrder>("region-market-orders");

            var regionOrders = sellOrders.FindOne(o => o.TypeId == typeId && o.RegionId == regionId);

            if (regionOrders != null)
            {
                foreach (var marketOrder in regionOrders.MarketOrders)
                {
                    marketOrder.StationName = stationDict[marketOrder.StationId];
                }

                var itemPricing = new ItemPricing
                {
                    RegionId = regionId,
                    LastUpdated = regionOrders.LastUpdated,
                    MarketOrders = regionOrders.MarketOrders,
                    AllowedStationIds = stationIds ?? new List<long> { 60003760 },
                };

                return itemPricing;
            }

            return null;
        }

        public void RefreshMarketOrders(long regionId)
        {
            var crestUrl = $"https://crest-tq.eveonline.com/market/{regionId}/orders/all/?page={{0}}";

            var marketOrders = new List<CrestMarketOrder>();
            var currentPage = 1;

            CrestMarketOrderList result;
            do
            {
                var webRequest = (HttpWebRequest)WebRequest.Create(string.Format(crestUrl, currentPage));
                webRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

                using (var response = webRequest.GetResponse())
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    var content = reader.ReadToEnd();
                    result = JsonConvert.DeserializeObject<CrestMarketOrderList>(content);

                    marketOrders.AddRange(result.Items);
                }
            } while (currentPage++ < result.PageCount);

            var sellOrders = marketOrders.Where(o => !o.Buy)
                .OrderBy(o => o.Price)
                .GroupBy(o => o.Type)
                .Select(o => new RegionMarketOrder
                {
                    TypeId = o.Key,
                    RegionId = regionId,
                    LastUpdated = DateTime.UtcNow,
                    MarketOrders = o.Select(i => new MarketOrder
                    {
                        Price = i.Price,
                        StationId = i.StationId,
                        TypeId = i.Type,
                        Volume = i.Volume,
                    })
                });
            using (var trans = _liteDb.BeginTrans())
            {
                var orders = _liteDb.GetCollection<RegionMarketOrder>("region-market-orders");

                orders.EnsureIndex(i => i.RegionId);
                orders.EnsureIndex(i => i.TypeId);

                orders.Delete(o => o.RegionId == regionId);
                orders.Insert(sellOrders);

                trans.Commit();
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using NGnono.Framework.Logger;
using NGnono.Framework.Models;
using NGnono.Framework.Tools.ImageTools.Configurations;
using NGnono.Framework.Tools.ImageTools.Contract;
using NGnono.Framework.Tools.ImageTools.Core;
using NGnono.Framework.Tools.ImageTools.Models;

namespace NGnono.Framework.Tools.ImageTools.Impl
{
    public class ImageService : IImageService
    {
        private static readonly ILog Log = LoggerManager.Current();

        private static readonly HashSet<string> Pexts = new HashSet<string>(new[] { "bmp", "pcx", "tiff", "gif", "jpeg", "jpg", "tga", "exif", "fpx", "svg", "psd", "cdr", "pcd", "dxf", "ufo", "eps", "png" });

        private ImageSettingConfig _imageSetting;
        private ImageElement _imageElement;
        private string _fileFolder = String.Empty;

        private const string FileTempExt = "_original";

        #region methods

        private FileMessage GetFileName(string key, int fileSize, string clientFilePath, string contentType, out string fileKey, out string fileExt, string[] userFolders)
        {
            Log.Debug(String.Format("Input parameters:\n key:{0}\n fileSize:{1}\n clientFilePath:{2}", key, fileSize, clientFilePath));

            fileKey = string.Empty;
            _imageSetting = (ImageSettingConfig)ConfigurationManager.GetSection("imageSetting");
            _imageElement = _imageSetting.ImageCollection[key];

            _fileFolder = String.IsNullOrEmpty(_imageElement.RootFolder) ? _imageSetting.Folder : _imageElement.RootFolder;

            fileExt = clientFilePath.Substring(clientFilePath.LastIndexOf(".", System.StringComparison.Ordinal) + 1).ToLower();

            if (_imageElement.Suffix.IndexOf(fileExt, System.StringComparison.Ordinal) < 0)
            {
                if (!String.IsNullOrWhiteSpace(contentType))
                {
                    fileExt = ContentType.GetExt(contentType);
                }

                if (_imageElement.Suffix.IndexOf(fileExt, System.StringComparison.Ordinal) < 0)
                {
                    return FileMessage.ExtError;
                }
            }

            if (fileSize > _imageElement.Size * 1024 || fileSize <= 0)
            {
                return FileMessage.SizeError;//ImageMsg.SizeError;
            }

            string tfileFolder;

            if (userFolders == null || userFolders.Length == 0)
            {
                tfileFolder = _imageElement.Folder.Replace("{Year}", DateTime.Now.Year.ToString(CultureInfo.InvariantCulture)).Replace("{Month}", ToLongTime(DateTime.Now.Month)).Replace("{Day}", ToLongTime(DateTime.Now.Day));
            }
            else
            {
                tfileFolder = String.Format(_imageElement.Folder, userFolders);
            }

            _fileFolder = Path.Combine(_fileFolder, tfileFolder);

            if (!Directory.Exists(_fileFolder))
            {
                Directory.CreateDirectory(_fileFolder);
            }

            fileKey = String.Format("{0}{1}", tfileFolder, Guid.NewGuid().ToString());
            //Console.WriteLine(clientFilePath + "验证成功");

            Log.Debug(String.Format("Create file and generate key successful.fileFolder: {0},filekey: {1}", _fileFolder, fileKey));

            return FileMessage.Success;
        }

        #endregion

        #region GetFileName

        public FileMessage GetFileName(string key, int fileSize, string clientFilePath, out string fileKey, out string fileExt)
        {
            return GetFileName(key, fileSize, clientFilePath, null, out  fileKey, out fileExt, new string[0]);
        }

        public FileMessage GetFileName(string key, int fileSize, string clientFilePath, string contentType, out string fileKey,
                                       out string fileExt)
        {
            return GetFileName(key, fileSize, clientFilePath, contentType, out  fileKey, out fileExt, new string[0]);
        }

        public FileMessage GetFileNameByUser(string key, int fileSize, string clientFilePath, string contentType, out string fileKey, out string fileExt, string[] userFolders)
        {
            return GetFileName(key, fileSize, clientFilePath, contentType, out  fileKey, out fileExt, userFolders);
        }

        #endregion

        #region UploadFile

        [Obsolete("此方法已经过期")]
        public void UploadFile(FileUploadMessage request)
        {
            Log.Debug(string.Format("Upload file:\n filename:{0}\n fileext:{1}\n keyname:{2}\n saveorigin:{3}\n converttojpg:{4}\n", request.FileName, request.FileExt, request.KeyName, request.SaveOrigin, request.ConvertToJPG));

            if (request.FileData.CanRead == false)
            {
                Log.Debug(string.Format("\"{0}\"文件不可读", request.FileName));

                request.FileData.Close();
                request.FileData.Dispose();

                return;
            }

            _imageSetting = (ImageSettingConfig)ConfigurationManager.GetSection("imageSetting");
            _imageElement = _imageSetting.ImageCollection[request.KeyName];

            _fileFolder = string.IsNullOrEmpty(_imageElement.RootFolder) ? _imageSetting.Folder : _imageElement.RootFolder;

            var filePath = Path.Combine(_fileFolder, request.FileName + (_imageElement.AsNormalFile ? String.Empty : FileTempExt) + "." + request.FileExt);

            Log.Debug(string.Format("filepath:{0}", filePath));

            var fileInfo = new FileInfo(filePath);

            if (fileInfo.Directory != null && !fileInfo.Directory.Exists)
            {
                Directory.CreateDirectory(fileInfo.Directory.FullName);
            }

            try
            {
                using (var sourceStream = request.FileData)
                {
                    using (var targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {

                        const int bufferLen = 4096;
                        var buffer = new byte[bufferLen];
                        int count = 0;

                        while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                        {
                            targetStream.Write(buffer, 0, count);
                        }

                        targetStream.Close();
                        sourceStream.Close();
                        request.FileData.Close();
                        request.FileData.Dispose();
                    }
                }

                if (Pexts.Contains(request.FileExt, StringComparer.OrdinalIgnoreCase) && !_imageElement.AsNormalFile)
                {

                    foreach (ThumbElement thumb in _imageElement.ThumbCollection)
                    {
                        string thumbPath = filePath.Substring(0, filePath.IndexOf(FileTempExt, System.StringComparison.Ordinal)) + "_" + thumb.Width.ToString(CultureInfo.InvariantCulture) + "x" + thumb.Height.ToString(CultureInfo.InvariantCulture) + ".jpg";
                        try
                        {
                            Thumbnail.Instance.MakeThumbnailPic(filePath, thumbPath, thumb.Width, thumb.Height, thumb.Mode, _imageSetting.ImageQuality);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                else if (Pexts.Contains(request.FileExt, StringComparer.OrdinalIgnoreCase) && request.ConvertToJPG && _imageElement.AsNormalFile)
                {
                    using (var bitmap = Image.FromFile(filePath))
                    {

                        bitmap.Save(filePath.Substring(0, filePath.IndexOf("." + request.FileExt, System.StringComparison.Ordinal)) + ".jpg", ImageFormat.Jpeg);
                    }

                }

                if (!request.SaveOrigin)
                {
                    File.Delete(filePath);
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Format("上传文件\"{0}\"发生错误:{1}", request.FileName, ex.Message));
            }

            Log.Debug(string.Format("Upload file successful.file: {0}, filekey: {1}", request.FileName, request.KeyName));
        }

        #endregion

        #region UploadFileAndReturnInfo

        public ThumbnailInfo UploadFileAndReturnInfo(FileUploadMessage request)
        {
            Log.Debug(string.Format("Upload file:\n filename:{0}\n fileext:{1}\n keyname:{2}", request.FileName, request.FileExt, request.KeyName));

            if (request.FileData.CanRead == false)
            {
                Log.Debug(string.Format("\"{0}\"文件不可读", request.FileName));

                request.FileData.Close();
                request.FileData.Dispose();

                return null;
            }

            _imageSetting = (ImageSettingConfig)ConfigurationManager.GetSection("imageSetting");

            _imageElement = _imageSetting.ImageCollection[request.KeyName];

            _fileFolder = String.IsNullOrEmpty(_imageElement.RootFolder) ? _imageSetting.Folder : _imageElement.RootFolder;

            string filePath = Path.Combine(_fileFolder, request.FileName + (_imageElement.AsNormalFile ? string.Empty : FileTempExt) + "." + request.FileExt);

            var fileInfo = new FileInfo(filePath);

            if (fileInfo.Directory != null && !fileInfo.Directory.Exists)
            {
                Directory.CreateDirectory(fileInfo.Directory.FullName);
            }

            try
            {
                using (var sourceStream = request.FileData)
                {
                    using (var targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {

                        const int bufferLen = 4096;
                        byte[] buffer = new byte[bufferLen];
                        int count = 0;
                        while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                        {
                            targetStream.Write(buffer, 0, count);
                        }

                        targetStream.Close();
                        sourceStream.Close();
                        request.FileData.Close();
                        request.FileData.Dispose();
                    }

                }

                if (Pexts.Contains(request.FileExt, StringComparer.OrdinalIgnoreCase) && !_imageElement.AsNormalFile)
                {
                    ThumbnailInfo thumbnailInfoes = new ThumbnailInfo();
                    thumbnailInfoes.Info = new Dictionary<string, long>();
                    thumbnailInfoes.Sizes = new Dictionary<string, ImageSize>();

                    foreach (ThumbElement thumb in _imageElement.ThumbCollection)
                    {
                        string thumbPath = filePath.Substring(0, filePath.IndexOf(FileTempExt)) + "_" + thumb.Width.ToString() + "x" + thumb.Height.ToString() + ".jpg";
                        try
                        {
                            int realWidth;
                            int realHeight;

                            Log.Debug("thumbPath:" + thumbPath);
                            long size = Thumbnail.Instance.MakeThumbnailPicAndReturnSize(filePath, thumbPath, thumb.Width, thumb.Height, thumb.Mode, _imageSetting.ImageQuality, out realWidth, out realHeight, thumbnailInfoes.ExifInfos);

                            thumbnailInfoes.Info.Add(thumb.Key, size);
                            thumbnailInfoes.Sizes.Add(thumb.Key, new ImageSize(realWidth, realHeight));
                        }
                        catch (Exception ex)
                        {
                            Log.Warn(ex);
                            continue;
                        }
                    }

                    return thumbnailInfoes;
                }

                else if (Pexts.Contains(request.FileExt, StringComparer.OrdinalIgnoreCase) && request.ConvertToJPG && _imageElement.AsNormalFile)
                {
                    using (Image bitmap = Image.FromFile(filePath))
                    {

                        bitmap.Save(filePath.Substring(0, filePath.IndexOf("." + request.FileExt)) + ".jpg", ImageFormat.Jpeg);
                    }

                }

                if (!request.SaveOrigin)
                {
                    File.Delete(filePath);
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Format("上传文件\"{0}\"发生错误:{1}", request.FileName, ex.Message));
            }

            Log.Debug(string.Format("Upload file successful.file: {0}, filekey: {1}", request.FileName, request.KeyName));

            return new ThumbnailInfo();
        }

        #endregion

        #region IsExistingFile

        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="fileName"></param>
        /// <param name="fileExt"></param>
        /// <returns></returns>
        public bool IsExistingFile(string key, string fileName, string fileExt)
        {
            _imageSetting = ConfigurationManager.GetSection("imageSetting") as ImageSettingConfig;

            if (_imageSetting != null)
            {
                _imageElement = _imageSetting.ImageCollection[key];

                _fileFolder = string.IsNullOrEmpty(_imageElement.RootFolder) ? _imageSetting.Folder : _imageElement.RootFolder;

                string filePath = Path.Combine(_fileFolder + _imageElement.Folder.Replace("/", @"\"), fileName + "." + fileExt);
                Log.Debug(string.Format("Is Existing File :\n key:{0}\n fileName:{1}\n fileExt:{2}\n filepath:{3}", key, fileName, fileExt, filePath));

                return File.Exists(filePath);
            }

            return false;
        }

        #endregion

        #region HandleGroupPortrait
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public bool HandleGroupPortrait(string fileName, string url)
        {
            string key = "GroupPortrait";
            string fileExt = "jpg";
            _imageSetting = ConfigurationManager.GetSection("imageSetting") as ImageSettingConfig;

            if (_imageSetting != null)
            {
                _imageElement = _imageSetting.ImageCollection[key];

                _fileFolder = string.IsNullOrEmpty(_imageElement.RootFolder) ? _imageSetting.Folder : _imageElement.RootFolder;

                string filePath = Path.Combine(_fileFolder + _imageElement.Folder.Replace("/", @"\"), fileName + "." + fileExt);

                //log.Error(string.Format("HandleGroupPortrait :\n fileName:{0}\n url:{1}\n filePath:{2}", fileName, url, filePath));

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                FileInfo fileInfo = new FileInfo(filePath);
                if (!fileInfo.Directory.Exists)
                {
                    Directory.CreateDirectory(fileInfo.Directory.FullName);
                }

                try
                {
                    WebResponse response = null;
                    try
                    {
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                        request.Accept = "*/*";
                        response = request.GetResponse();
                        if (response.ContentType.ToLower().StartsWith("image/"))
                        {
                            if (SaveBinaryFile(response, filePath))
                            {
                                return true;
                            }
                        }

                        Log.Error(string.Format("HandleGroupPortrait:从核心服务拷贝图片到文件服务器时出错:fileName:\"{0}\" url:{1} ", fileName, url));
                    }
                    catch (Exception ex)
                    {
                        Log.Error(string.Format("HandleGroupPortrait:从核心服务获取头像时出错:fileName:\"{0}\" url:{1} 错误信息:{2}", fileName, url, ex.Message));
                        return false;
                    }
                    finally
                    {
                        if (response != null) response.Close();
                    }

                    //using (Stream sourceStream = request.FileData)
                    //{
                    //    using (FileStream targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                    //    {
                    //        //从文件流中读取4k
                    //        const int bufferLen = 4096;
                    //        byte[] buffer = new byte[bufferLen];
                    //        int count = 0;

                    //        while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                    //        {
                    //            targetStream.Write(buffer, 0, count);
                    //        }

                    //        targetStream.Close();
                    //        sourceStream.Close();
                    //        request.FileData.Close();
                    //        request.FileData.Dispose();
                    //    }
                    //}
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("HandleGroupPortrait:fileName:\"{0}\" url:{1} 错误信息:{2}", fileName, url, ex.Message));
                }
            }

            Log.Error(string.Format("HandleGroupPortrait :\n fileName:{0}\n url:{1}\n", fileName, url));

            return false;
        }

        #endregion

        #region DeleteFile

        public bool DeleteFile(string key, string[] fileNameList, string[] dateList, string[] userFolders)
        {
            try
            {
                return DeleteFileInternal(key, fileNameList, dateList, userFolders);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message + ex.StackTrace);
            }

            return false;
        }

        public bool DeleteNormalFile(string[] filePaths)
        {
            try
            {
                return DeleteNormalFileInternal(filePaths);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message + ex.StackTrace);
            }

            return false;
        }

        private bool DeleteFileInternal(string key, string[] fileNameList, string[] dateList, string[] userFolders)
        {
            if (string.IsNullOrEmpty(key) || fileNameList == null || fileNameList.Length < 1)
            {
                return true;
            }

            bool isSpecialDate = false;

            if (dateList != null && dateList.Length > 0)
            {
                isSpecialDate = true;

                if (dateList.Length != fileNameList.Length)
                {

                    Log.Error(string.Format("Delete File Error :\n key:{0}\n 指定的flieNameList个数和date个数不符合", key));
                    return false;
                }
            }

            _imageSetting = ConfigurationManager.GetSection("imageSetting") as ImageSettingConfig;

            if (_imageSetting != null)
            {
                _imageElement = _imageSetting.ImageCollection[key];

                string backupRootDirectory = _imageSetting.BackupFolder;

                _fileFolder = string.IsNullOrEmpty(_imageElement.RootFolder) ? _imageSetting.Folder : _imageElement.RootFolder;

                string fileSubFolder = _imageElement.Folder;

                if (userFolders != null && userFolders.Length > 0)
                {
                    fileSubFolder = string.Format(fileSubFolder, userFolders);
                }

                string currentDirectory = string.Empty;

                for (int i = 0; i < fileNameList.Length; i++)
                {
                    if (isSpecialDate && dateList[i].Length != 8)
                    {
                        Log.Error(string.Format("Delete File Error :\n key:{0}\n 指定的日期:{1}不合法", key, dateList[i]));
                        continue;
                    }

                    if (isSpecialDate)
                    {
                        fileSubFolder = fileSubFolder.Replace("{Year}", dateList[i].Substring(0, 4)).Replace("{Month}", ToLongTime(Int32.Parse(dateList[i].Substring(4, 2)))).Replace("{Day}", ToLongTime(Int32.Parse(dateList[i].Substring(6, 2))));
                    }
                    else
                    {
                        fileSubFolder = fileSubFolder.Replace("{Year}", DateTime.Now.Year.ToString()).Replace("{Month}", ToLongTime(DateTime.Now.Month)).Replace("{Day}", ToLongTime(DateTime.Now.Day));
                    }

                    currentDirectory = Path.Combine(_fileFolder, fileSubFolder);

                    string backupDirectory = currentDirectory.Replace(_fileFolder, backupRootDirectory);

                    if (!Directory.Exists(backupDirectory))
                    {
                        Directory.CreateDirectory(backupDirectory);
                    }

                    string searchPattern = string.Format(fileNameList[i] + "*.*");

                    string[] fileNames = Directory.GetFiles(currentDirectory, searchPattern, SearchOption.TopDirectoryOnly);

                    foreach (string name in fileNames)
                    {

                        File.Copy(name, name.Replace(_fileFolder, backupRootDirectory), true);

                        File.Delete(name);
                    }

                    Log.Info(string.Format("Backup File :\n key:{0}\n fileName:{1}\n filepath:{2}", key, fileNameList[i], backupDirectory));

                    Log.Info(string.Format("Delete File :\n key:{0}\n fileName:{1}\n filepath:{2}", key, fileNameList[i], currentDirectory));
                }

                return true;
            }

            return false;
        }

        private bool DeleteNormalFileInternal(string[] filePaths)
        {

            if (filePaths == null || filePaths.Length < 1)
            {
                return false;
            }

            _imageSetting = ConfigurationManager.GetSection("imageSetting") as ImageSettingConfig;

            if (_imageSetting != null)
            {
                foreach (string fileName in filePaths)
                {

                    string key = fileName.Split(new char[] { '/' })[0] + "/";

                    foreach (ImageElement item in _imageSetting.ImageCollection)
                    {
                        if (item.Folder.StartsWith(key))
                        {
                            _imageElement = item;
                        }
                    }

                    if (_imageElement == null)
                    {
                        Log.Error(string.Format("删除文件{0}发生错误,找不到key:{1}的配置节点", fileName, key));
                        return false;
                    }

                    _fileFolder = string.IsNullOrEmpty(_imageElement.RootFolder) ? _imageSetting.Folder : _imageElement.RootFolder;

                    _imageSetting = (ImageSettingConfig)ConfigurationManager.GetSection("imageSetting");
                    string backupRootDirectory = _imageSetting.BackupFolder;

                    string backupDirectory = _fileFolder.Replace(_fileFolder, backupRootDirectory);

                    string backupFullDirectory = backupDirectory;

                    Log.Info(string.Format("backupFullDirectory:{0} fileName:{1},fileFolder:{2}", backupFullDirectory, fileName, _fileFolder));

                    if (fileName.Contains(@"\"))
                    {
                        backupFullDirectory = Path.Combine(backupFullDirectory, fileName.Substring(0, fileName.LastIndexOf(@"\")));
                    }
                    else if (fileName.Contains("/"))
                    {
                        backupFullDirectory = Path.Combine(backupFullDirectory, fileName.Substring(0, fileName.LastIndexOf("/")));
                    }
                    else
                    {
                        backupFullDirectory = Path.Combine(backupFullDirectory, fileName);
                    }

                    if (!Directory.Exists(backupFullDirectory))
                    {
                        Directory.CreateDirectory(backupFullDirectory);
                    }

                    string searchPattern = fileName + "*.*";

                    string[] fileNames = Directory.GetFiles(_fileFolder, searchPattern, SearchOption.TopDirectoryOnly);

                    foreach (string name in fileNames)
                    {

                        File.Copy(name, name.Replace(_fileFolder, backupRootDirectory), true);

                        File.Delete(name);
                    }

                    Log.Info(string.Format("Backup File :\n fileName:{0}\n filepath:{1}", fileName, backupDirectory));

                    Log.Info(string.Format("Delete File :\n fileName:{0}\n filepath:{1}", fileName, _fileFolder));
                }
                return true;
            }
            return false;
        }

        #endregion

        #region Helper

        private static string ToLongTime(int times)
        {
            return times < 10 ? "0" + times.ToString(CultureInfo.InvariantCulture) : times.ToString(CultureInfo.InvariantCulture);
        }

        private static bool SaveBinaryFile(WebResponse response, string path)
        {
            var buffer = new byte[1024];
            //string dir = Path.GetDirectoryName(path);
            //if (!Directory.Exists(dir))
            //    Directory.CreateDirectory(dir);
            //else
            //{
            //    /// 移除过期的头像
            //    string endFile = path.Substring(path.LastIndexOf('_'));
            //    string[] files = Directory.GetFiles(dir, "*" + endFile);
            //    foreach (string file in files)
            //    {
            //        File.Delete(file);
            //    }
            //}

            try
            {
                using (Stream outStream = File.Create(path))
                {
                    using (var inStream = response.GetResponseStream())
                    {

                        int l;
                        do
                        {
                            l = inStream.Read(buffer, 0, buffer.Length);
                            if (l > 0)
                                outStream.Write(buffer, 0, l);
                        }
                        while (l > 0);

                        inStream.Close();
                    }
                    outStream.Close();
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Format("HandleGroupPortrait:保存群组头像 path:\"{0}\" 错误信息:{1}", path, ex.Message));

                return false;
            }

            return true;
        }

        #endregion
    }
}


text:
import { combineReducers } from 'redux'
import data from './dataReducer'
import error from './errorReducer'
import form from './formReducer'
import loading from './loadingReducer'
import note from './noteReducer'
import view from './viewReducer'
import searchTerm from './searchTermReducer'
import searchFilter from './searchFilterReducer'
import token from './tokenReducer'
import prompt from './promptReducer'

const rootReducer = combineReducers({
  data,
  error,
  form,
  loading,
  note,
  searchTerm,
  searchFilter,
  token,
  prompt,
  view
})

export default rootReducer


text:
package alec_wam.CrystalMod.tiles.darkinfection;

import alec_wam.CrystalMod.blocks.connected.ConnectedBlockState;
import alec_wam.CrystalMod.client.model.dynamic.ModelConnectedTexture;
import alec_wam.CrystalMod.util.client.RenderUtil;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.item.ItemStack;

public class ModelDenseDarkness extends ModelConnectedTexture {

	public ModelDenseDarkness(){
		super();
	}
	public ModelDenseDarkness(ItemStack stack){
		super(stack);
	}

	public ModelDenseDarkness(ConnectedBlockState state){
		super(state);
	}

	@Override
	public TextureAtlasSprite getTexture(IBlockState state) {
		//return RenderUtil.getSprite("crystalmod:blocks/crystal_blue_glass_painted");
		return RenderUtil.getSprite("crystalmod:blocks/decorative/dense_darkness");
	}

	@Override
	public TextureAtlasSprite getCenterTexture(IBlockState state) {
		//return RenderUtil.getSprite("crystalmod:blocks/crystal_blue_glass_tinted");
		return RenderUtil.getSprite("crystalmod:blocks/decorative/dense_darkness");
	}

	@Override
	public TextureAtlasSprite getTexture(ItemStack stack) {
		return RenderUtil.getSprite("crystalmod:blocks/decorative/dense_darkness");
	}

	@Override
	public TextureAtlasSprite getCenterTexture(ItemStack stack) {
		return RenderUtil.getSprite("crystalmod:blocks/decorative/dense_darkness");
	}

	@Override
	public ModelConnectedTexture createNewModel(ItemStack stack) {
		return new ModelDenseDarkness(stack);
	}

	@Override
	public ModelConnectedTexture createNewModel(ConnectedBlockState state) {
		return new ModelDenseDarkness(state);
	}

	@Override
	public ModelConnectedTexture createNewModel() {
		return new ModelDenseDarkness();
	}

	@Override
	public boolean renderCenter(){
		return true;
	}

}


text:
require_relative "test_helper"

class UtmParamsTest < Minitest::Test
  def test_default
    message = UtmParamsMailer.welcome.deliver_now
    refute_body "utm", message
    assert_nil ahoy_message.utm_campaign
    assert_nil ahoy_message.utm_medium
    assert_nil ahoy_message.utm_source
  end

  def test_basic
    message = UtmParamsMailer.basic.deliver_now
    assert_body "utm_campaign=basic", message
    assert_body "utm_medium=email", message
    assert_body "utm_source=utm_params_mailer", message
    assert_equal "basic", ahoy_message.utm_campaign
    assert_equal "email", ahoy_message.utm_medium
    assert_equal "utm_params_mailer", ahoy_message.utm_source
  end

  def test_array_params
    message = UtmParamsMailer.array_params.deliver_now
    assert_body "baz%5B%5D=1&baz%5B%5D=2", message
  end

  def test_nested
    message = UtmParamsMailer.nested.deliver_now
    assert_body "utm_medium=email", message
    assert_body '', message
  end

  def test_multiple
    message = UtmParamsMailer.multiple.deliver_now
    assert_body "utm_campaign=second", message
  end

  def test_head_element
    message = UtmParamsMailer.head_element.deliver_now
    assert_body '', message
    assert_body '', message
  end

  def test_doctype
    message = UtmParamsMailer.doctype.deliver_now
    assert_body '<!DOCTYPE html>', message
  end

  def test_body_style
    message = UtmParamsMailer.body_style.deliver_now
    assert_body '', message
  end
end


text:
/*global QUnit,sinon */

jQuery.sap.require("sap.ui.fl.RegistrationDelegator");

(function(RegistrationDelegator) {
	"use strict";

	QUnit.module("sap.ui.fl.RegistrationDelegator", {
		beforeEach: function() {
			this._oSandbox = sinon.sandbox.create();
		},
		afterEach: function() {
			this._oSandbox.restore();
		}
	});

	QUnit.test("Check if all the registration functions were called", function(assert) {
		var registerChangeHandlersStub = sinon.stub(RegistrationDelegator, "registerChangeHandlers");
		var registerLoadComponentEventHandlerStub = sinon.stub(RegistrationDelegator, "registerLoadComponentEventHandler");
		var registerExtensionProviderStub = sinon.stub(RegistrationDelegator, "registerExtensionProvider");
		var registerChangesInComponentStub = sinon.stub(RegistrationDelegator, "registerChangesInComponent");
		var registerXMLPreprocessorStub = sinon.stub(RegistrationDelegator, "registerXMLPreprocessor");
		var registerEventListenerStub = sinon.stub(RegistrationDelegator, "registerEventListener");

		jQuery.sap.require("sap.ui.fl.library");

		sinon.assert.calledOnce(registerChangeHandlersStub, "Change Handlers called.");
		sinon.assert.calledOnce(registerLoadComponentEventHandlerStub, "Load Component Event Handler called.");
		sinon.assert.calledOnce(registerExtensionProviderStub, "Extension provider called.");
		sinon.assert.calledOnce(registerChangesInComponentStub, "Changes in Component called.");
		sinon.assert.calledOnce(registerXMLPreprocessorStub, "XML preprocessor called.");
		sinon.assert.calledOnce(registerEventListenerStub, "Event Listener called.");
	});

}(sap.ui.fl.RegistrationDelegator));


text:
var inspect = require('eyes').inspector();
var awssum = require('awssum');
var amazon = awssum.load('amazon/amazon');
var cloudFrontService = awssum.load('amazon/cloudfront');

var env = process.env;
var accessKeyId = process.env.ACCESS_KEY_ID;
var secretAccessKey = process.env.SECRET_ACCESS_KEY;
var awsAccountId = process.env.AWS_ACCOUNT_ID;

var cloudFront = new cloudFrontService(accessKeyId, secretAccessKey, awsAccountId, amazon.US_EAST_1);

console.log( 'Region :', cloudFront.region() );
console.log( 'EndPoint :',  cloudFront.host() );
console.log( 'AccessKeyId :', cloudFront.accessKeyId() );
// console.log( 'SecretAccessKey :', cloudFront.secretAccessKey() );
console.log( 'AwsAccountId :', cloudFront.awsAccountId() );

cloudFront.ListOais(function(err, data) {
    console.log("\nlisting OAIs - expecting success");
    inspect(err, 'Error');
    inspect(data, 'Data');
});


text:
@interface NSString (Expand)

//判断字符串是否为空
+ (BOOL)isEmptyString:(NSString *)string;

@end


text:
using System;

// ReSharper disable All

#pragma warning disable IDE1006
namespace LmpUpdater.Appveyor.Contracts
{
    public class NuGetFeed
    {
        public string id { get; set; }
        public string name { get; set; }
        public int accountId { get; set; }
        public int projectId { get; set; }
        public bool isPrivateProject { get; set; }
        public bool publishingEnabled { get; set; }
        public string accountTimeZoneId { get; set; }
        public DateTime created { get; set; }
    }
}


text:
angular.module('Mccy.ViewContainersCtrl', [
        'Mccy.services',
        'ui.bootstrap',
        'angular-clipboard'
    ])

    .controller('ViewContainersCtrl', function ($scope, $timeout, $uibModal, Containers, Alerts) {

        $scope.reload = function () {
            reload();
        };

        $scope.$on('reload', function () {
            reload();
        });

        reload();

        $scope.hasConnectInfo = function(c) {
            return !_.isUndefined(c.hostIp);
        };

        $scope.isRunning = function (container) {
            if (container.status && container.status.indexOf('Exited') == 0) {
                return false;
            }
            if (container.running === true) {
                return true;
            }
            // TODO use container details to find out for sure
            return true;
        };

        $scope.stop = function (container) {
            Containers.stop({id: container.id}, {}, function(){
                Alerts.success("Container stopped");
                reload();
            }, Alerts.handleRequestError);
        };

        $scope.start = function (container) {
            Containers.start({id: container.id}, {}, function(){
                Alerts.success("Container started");
                reload();
            }, Alerts.handleRequestError);
        };

        $scope.remove = function (container) {
            $uibModal.open({
                templateUrl: 'ng-bits/confirm-container-remove.html'
            }).result.then(function (answer) {
                if (answer === true) {
                    Containers.remove({id: container.id}, {}, function() {
                        Alerts.success('Server was successfully removed', true);
                    }, Alerts.handleRequestError);
                }
            });
        };

        function fetchContainerDetails(containers) {
            _.each(containers, function (container) {
                Containers.get({id:container.id}, function(details){
                    _.assign(container, details.summary);
                    container.info = details.info;
                }, Alerts.handleRequestError);
            });
        }

        function reload() {
            $scope.containers = Containers.query(function (response) {
                fetchContainerDetails(response);
            }, Alerts.handleRequestError);
        }

    })
;


text:
(function(on_node){
var exports = on_node? module.exports : window['uiaction']={};

// modules
if(on_node) {
//  var primitives  = require('./primitives');
//  var contours    = require('./contours');
//  var planarmap   = require('./planarmap');
//  var constraints = require('./constraints');
//  var numeric_subroutines = require('./numeric_subroutines');
} else {
//  var primitives  = window.primitives;
//  var contours    = window.contours;
//  var planarmap   = window.planarmap;
//  var constraints = window.constraints;
//  var numeric_subroutines = window.numeric_subroutines;
//  if(!primitives || !contours || !planarmap ||
//     !constraints || !numeric_subroutines)
//    throw new Error(
//      "Must have Primitives, Contours, PlanarMap, Constraints, & "+
//      "Numeric Subroutines Modules loaded before UIAction");
}

// IMPORTS

// DECLARATIONS
var UIAction                    = {};
var InstantaneousAction         = Object.create(UIAction);
var OngoingAction               = Object.create(UIAction);

var DeleteAction                = Object.create(InstantaneousAction);
var GrabDragAction              = Object.create(OngoingAction);
var BezierDragAction            = Object.create(OngoingAction);
var InterpretModeAction         = Object.create(InstantaneousAction);
var SelectAction                = Object.create(OngoingAction);
var BezierSelectAction          = Object.create(OngoingAction);
var BezierPointSelectAction     = Object.create(InstantaneousAction);
var AddToMultiSelectAction      = Object.create(InstantaneousAction);
var ClearMultiSelectAction      = Object.create(InstantaneousAction);
var DragBlobWidthAction         = Object.create(OngoingAction);
var DragStrokeWidthAction       = Object.create(OngoingAction);
var DragRectangleHandleAction   = Object.create(OngoingAction);
exports.DeleteAction            = DeleteAction;
exports.GrabDragAction          = GrabDragAction;
exports.BezierDragAction        = BezierDragAction;
exports.InterpretModeAction     = InterpretModeAction;
exports.SelectAction            = SelectAction;
exports.BezierSelectAction      = BezierSelectAction;
exports.BezierPointSelectAction = BezierPointSelectAction;
exports.AddToMultiSelectAction  = AddToMultiSelectAction;
exports.ClearMultiSelectAction  = ClearMultiSelectAction;
exports.DragBlobWidthAction     = DragBlobWidthAction;
exports.DragStrokeWidthAction   = DragStrokeWidthAction;
exports.DragRectangleHandleAction = DragRectangleHandleAction;

UIAction.redo = function() { throw new Error('redo unimplemented'); };
InstantaneousAction.donow = function() {
  throw new Error('donow unimplemented'); };
OngoingAction.dostart = function(params) {
  throw new Error('dostart unimplemented'); };
OngoingAction.docontinue = function(params) {
  throw new Error('dostart unimplemented'); };
OngoingAction.doend = function(params) {
  throw new Error('dostart unimplemented'); };

// UNIVERSAL UNDO
UIAction.saveForUndo = function() {
  this._prev_doc = this.doc.JSONSnapshot();
}
UIAction.undo = function() {
  if(this._prev_doc)
    this.doc.restoreFromJSONSnapshot(this._prev_doc);
  delete this._prev_doc;
}

// IMPLEMENTATIONS
DeleteAction.New = function(doc) {
  var act = Object.create(DeleteAction);
  act.doc = doc;
  return act;
}
DeleteAction.donow = function() {
  // safety guard
  if(!this.doc.select.isBlob() && !this.doc.select.isStroke()) return;

  this.saveForUndo();

  var loops = this.doc.select.getLoops();
  console.log('loops', loops);

  var closed_loops = [];
  var splicing_loops = [];
  for(var k=0; k<loops.length; k++) {
    if(loops[k].length === 1 && loops[k][0].isClosed())
      closed_loops.push(loops[k][0]);
    else
      splicing_loops.push(loops[k]);
  }
  if(splicing_loops.length > 1) {
    throw new Error('CANNOT SUPPORT multiple loops being spliced at once');
  }

  var pmap = this.doc.pmap;
  if(splicing_loops.length === 1) {
    // get gaps
    var loop = splicing_loops[0];
    var gaps = [];
    var lastpt = loop[loop.length-1].end();
    for(var k=0; k<loop.length; k++) {
      gaps.push([loop[k].start(), lastpt]);
      lastpt = loop[k].end();
    }

    pmap = this.doc.analyzer.spliceLoop(gaps);
  }
  for(var k=0; k<closed_loops.length; k++) {
    pmap = pmap.removeContour(closed_loops[k]);
  }
  this.doc.reInit(pmap);

  // Logging
  return 'DELETE';
}

GrabDragAction.New = function(doc, grabpt) {
  var act = Object.create(GrabDragAction);
  act.doc = doc;
  act.grabpt = grabpt;
  return act;
}
GrabDragAction.dostart = function(params) {
  this.saveForUndo();
  // Logging
  this.start_pos = this.grabpt.getxy();
  return 'START_GRAB_DRAG';
}
GrabDragAction.docontinue = function(params) {
  var x = params.x;
  var y = params.y;
  var d_grab = [
    x - this.grabpt.x().get(),
    y - this.grabpt.y().get(),
  ];
  var forces = [];
  if(this.doc.select.isEmpty()) {
    forces.push({ scalar: this.grabpt.x(),  force: d_grab[0] });
    forces.push({ scalar: this.grabpt.y(),  force: d_grab[1] });
  } else {
    this.doc.select.points().forEach(function(pt) {
      forces.push({ scalar: pt.x(), force: d_grab[0] });
      forces.push({ scalar: pt.y(), force: d_grab[1] });
    });
  }
  this.doc.slv.solveForceField(forces);
  //this.doc.slv.debugResponseToForceField(forces);

  // TODO: CAN WE KILL THIS SOMEHOW?
  this.doc.select.repositionSlider(); // safe to call whenever

  //Logging
}
GrabDragAction.doend = function(params) {
  // Logging
  this.end_pos = this.grabpt.getxy();
  return 'END_GRAB_DRAG';
};

BezierDragAction.New = function(doc, grabxy, handle) {
  var act = Object.create(BezierDragAction);
  act.doc = doc;
  act.curr_pos  = grabxy.slice();
  this.handle = handle;
  return act;
}
BezierDragAction.dostart = function(params) {
  this.saveForUndo();
  // Logging
  this.start_pos = this.curr_pos.slice();
  return 'START_GRAB_DRAG';
}
BezierDragAction.docontinue = function(params) {
  var x = params.x;
  var y = params.y;
  var xy = [x,y];
  var dxy = Vec2.sub(xy, this.curr_pos);

  // if this was a drag action on a handle, then
  if(this.handle) {
    // ...
  }
  // otherwise, we're dragging the anchors around
  else {
    this.doc.translateBezierAnchorsBy(dxy);
  }

  this.curr_pos = xy;

  //Logging
}
BezierDragAction.doend = function(params) {
  // Logging
  this.end_pos = this.curr_pos.slice();
  return 'END_GRAB_DRAG';
};

InterpretModeAction.New = function(doc) {
  var act = Object.create(InterpretModeAction);
  act.doc = doc;
  return act;
}
InterpretModeAction.donow = function(params) {
  // don't worry about pushing this on the undo stack
  this.doc.setInterpretationFilter(params.mode);
  var modestr = params.mode;
  if(!modestr) modestr = 'all';
  return 'SET_INTERPRETATION '+modestr.toUpperCase();
}

SelectAction.New = function(doc, bureau) {
  var act = Object.create(SelectAction);
  act.doc = doc;
  act.bureau = bureau;
  return act;
}
// This action doesn't go on the undo stack, because of this null value
SelectAction.undo = null;
SelectAction.dostart = function(select_params) {
  this.doc.openSelectionProposal(select_params);
  // Logging
  return 'START_SELECTION';
}
SelectAction.docontinue = function(select_params) {
  this.doc.updateSelectionProposal(select_params);
  // Logging
}
SelectAction.doend = function() {
  this.doc.closeSelectionProposal();
  if(this.doc.select.isBlob() ||
     this.doc.select.isStroke() ||
     this.doc.select.isRectangle())
  {
    this.doc.select.genSlider(this.doc, this.bureau);
  }
  // Logging
  return 'END_SELECTION';
}

BezierPointSelectAction.New = function(doc, clicked_pt) {
  var act = Object.create(BezierPointSelectAction);
  act.doc = doc;
  act.pt  = clicked_pt;
  return act;
}
// This action doesn't go on the undo stack, because of this null value
BezierPointSelectAction.undo = null;
BezierPointSelectAction.donow = function(params) {
  this.doc.selectSingleBezierPoint(this.pt);
  // Logging
  return 'BEZIER_SINGLE_POINT_SELECT';
}

BezierSelectAction.New = function(doc, clicked_pt, cutoff, bureau) {
  var act = Object.create(BezierSelectAction);
  act.doc         = doc;
  act.clicked_pt  = clicked_pt;
  act.cutoff      = cutoff;
  return act;
}
// This action doesn't go on the undo stack, because of this null value
BezierSelectAction.undo = null;
BezierSelectAction.dostart = function(select_params) {
  this.doc.openBezierProposal(select_params, this.clicked_pt, this.cutoff);
  // Logging
  return 'START_BEZIER_SELECTION';
}
BezierSelectAction.docontinue = function(select_params) {
  this.doc.updateBezierProposal(select_params, this.clicked_pt, this.cutoff);
  // Logging
}
BezierSelectAction.doend = function() {
  this.doc.closeBezierProposal();
  // Logging
  return 'END_BEZIER_SELECTION';
}

AddToMultiSelectAction.New = function(doc) {
  var act = Object.create(AddToMultiSelectAction);
  act.doc = doc;
  return act;
}
AddToMultiSelectAction.undo = null;
AddToMultiSelectAction.donow = function(params) {
  // don't worry about pushing this on the undo stack
  this.doc.addCurrentToMultiSelection();
  return 'ADD_TO_MULTISELECT '+modestr.toUpperCase();
}

ClearMultiSelectAction.New = function(doc) {
  var act = Object.create(ClearMultiSelectAction);
  act.doc = doc;
  return act;
}
ClearMultiSelectAction.undo = null;
ClearMultiSelectAction.donow = function(params) {
  // don't worry about pushing this on the undo stack
  this.doc.clearMultiSelection();
  return 'CLEAR_MULTISELECT '+modestr.toUpperCase();
}

DragBlobWidthAction.New = function(doc, blob) {
  var act = Object.create(DragBlobWidthAction);
  act.doc = doc;
  act.blob = blob;
  return act;
}
DragBlobWidthAction.dostart = function(params) {
  this.saveForUndo();
  this.blob.dragRadius(params.target_radius, this.doc.slv);
  // Logging
  return 'START_DRAG_BLOB_WIDTH';
}
DragBlobWidthAction.docontinue = function(params) {
  this.blob.dragRadius(params.target_radius, this.doc.slv);
}
DragBlobWidthAction.doend = function(params) {
  // Logging
  return 'END_DRAG_BLOB_WIDTH';
}

DragStrokeWidthAction.New = function(doc, stroke) {
  var act = Object.create(DragStrokeWidthAction);
  act.doc = doc;
  act.stroke = stroke;
  return act;
}
DragStrokeWidthAction.dostart = function(params) {
  this.saveForUndo();
  this.stroke.dragWidth(params.target_width, this.doc.slv);
  // Logging
  return 'START_DRAG_STROKE_WIDTH';
}
DragStrokeWidthAction.docontinue = function(params) {
  this.stroke.dragWidth(params.target_width, this.doc.slv);
}
DragStrokeWidthAction.doend = function(params) {
  // Logging
  return 'END_DRAG_STROKE_WIDTH';
}

DragRectangleHandleAction.New = function(doc, rectwidget, side1, side2) {
  var act = Object.create(DragRectangleHandleAction);
  act.doc = doc;
  act.rectwidget = rectwidget;
  act.side1 = side1;
  act.side2 = side2;
  return act;
}
DragRectangleHandleAction.dostart = function(params) {
  this.saveForUndo();

  if(this.side2)
    this.rectwidget.dragCorner(this.side1, this.side2,
                               params.target1, params.target2, this.doc.slv);
  else
    this.rectwidget.dragSide(this.side1, params.target, this.doc.slv);
  this.rectwidget.repositionSlider(); // safe to call whenever
  // Logging

  return 'START_DRAG_STROKE_WIDTH';
}
DragRectangleHandleAction.docontinue = function(params) {
  if(this.side2)
    this.rectwidget.dragCorner(this.side1, this.side2,
                               params.target1, params.target2, this.doc.slv);
  else
    this.rectwidget.dragSide(this.side1, params.target, this.doc.slv);
  this.rectwidget.repositionSlider(); // safe to call whenever
}
DragRectangleHandleAction.doend = function(params) {
  // Logging
  return 'END_DRAG_STROKE_WIDTH';
}

})(typeof window === 'undefined');


text:
#ifndef _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CQSD_RTO
#define _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CQSD_RTO

#include "type_iso.CQSET_RTO.h"

namespace AIMXML
{

namespace iso
{

class CQSD_RTO : public ::AIMXML::iso::CQSET_RTO
{
public:
	AIMXML_EXPORT CQSD_RTO(xercesc::DOMNode* const& init);
	AIMXML_EXPORT CQSD_RTO(CQSD_RTO const& init);
	void operator=(CQSD_RTO const& other) { m_node = other.m_node; }
	static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_iso_altova_CQSD_RTO); }
	MemberElement<iso::CQSET_RTO, _altova_mi_iso_altova_CQSD_RTO_altova_first> first;
	struct first { typedef Iterator<iso::CQSET_RTO> iterator; };
	MemberElement<iso::CQSET_RTO, _altova_mi_iso_altova_CQSD_RTO_altova_second> second;
	struct second { typedef Iterator<iso::CQSET_RTO> iterator; };
	AIMXML_EXPORT void SetXsiType();
};

} // namespace iso

}	// namespace AIMXML

#endif // _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CQSD_RTO


text:
using System;
using System.Collections.Generic;
using System.Text;
using MCSharp.World;
namespace MCSharp
{
    class CmdNewLvl : Command
    {
        // Constructor
        public CmdNewLvl(CommandGroup g, GroupEnum group, string name) : base(g, group, name) { blnConsoleSupported = false; /* By default no console support*/ }

        // Command usage help
        public override void Help(Player p)
        {
            p.SendMessage("/newlvl - creates a new level.");
            p.SendMessage("/newlvl mapname 128 64 128 type");
        }

        // Code to run when used by a player
        public override void Use(Player p, string message)
        {
            if (message != "")
            {
                string[] parameters = message.Split(' '); // Grab the parameters from the player's message
                if (parameters.Length == 5) // make sure there are 5 params
                {
                    switch (parameters[4])
                    {
                        case "flat":
                        case "pixel":
                        case "island":
                        case "mountains":
                        case "ocean":
                        case "forest":

                            break;

                        default:
                            p.SendMessage("Valid types: island, mountains, forest, ocean, flat, pixel"); return;
                    }

                    string name = parameters[0];
                    // create a new level...
                    try
                    {
                        Map lvl = new Map(name,
                                              Convert.ToUInt16(parameters[1]),
                                              Convert.ToUInt16(parameters[2]),
                                              Convert.ToUInt16(parameters[3]),
                                              parameters[4]);
                        lvl.changed = true;
                    }
                    finally
                    {
                        GC.Collect();
                        GC.WaitForPendingFinalizers();

                    }
                    Player.GlobalMessage("Map " + name + " created");
                }
                else
                {
                    p.SendMessage("Not enough parameters! <name> <x> <y> <z> <type>");
                }
            }
            else
            {
                Help(p);
            }
            if (Properties.ValidString(message, " "))
            {

            }
            else
            {
                p.SendMessage("Please use an alphanumerical characters only!");
            }
        }
    }
}


text: PHP library for Dandomain webhooks


text:
require 'spec_helper'

describe CoffeeRandomizerSuperExtreme do
  let(:template_normz) { CoffeeRandomizerSuperExtreme::TemplateNormz}
  let(:testbed) { CoffeeRandomizerSuperExtreme::TestBed}
  let(:generator) { CoffeeRandomizerSuperExtreme::TemplateMaria }

  context :normz do
    it 'should generate a template for 9 participants' do
      tg = template_normz.new(9)
      results = tg.generate
      expect(results).to_not be == false
      expect(tg.check_pairs.uniq.count).to be == 1
    end

    it "should use test bed for generating templates" do
      tb = testbed.new
      tb.start(9..9)
      expect(tb.results).to_not be == false
      expect(tb.results[9][:check_pairs].uniq.count).to be == 1
    end
  end

  context :maria do
    it "generates a template for 9 participants" do
      expect(generator.new(9).generate_groups).to eq true
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monogr. Discom. Bohem. (Prague) 272 (1934)

#### Original name
Peziza albolutea Pers.

### Remarks
null


text:
<?php

// autoload_files.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
    '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
);


text:
package backend

import (
	"fmt"

	"github.com/disintegration/imaging"
	"github.com/pkg/errors"
	"github.com/thoas/picfit/image"
)

// MethodNotImplementedError is an error returned if method is not implemented
var MethodNotImplementedError = errors.New("Not implemented")

// Options is the engine options
type Options struct {
	Color    string
	Degree   int
	Format   imaging.Format
	Height   int
	Images   []image.ImageFile
	Position string
	Quality  int
	Stick    string
	Upscale  bool
	Width    int
}

func (o Options) String() string {
	return fmt.Sprintf("width:%d height:%d quality:%d upscale:%t",
		o.Width, o.Height, o.Quality, o.Upscale)
}

// Engine is an interface to define an image engine
type Backend interface {
	Fit(img *image.ImageFile, options *Options) ([]byte, error)
	Flat(background *image.ImageFile, options *Options) ([]byte, error)
	Flip(img *image.ImageFile, options *Options) ([]byte, error)
	Resize(img *image.ImageFile, options *Options) ([]byte, error)
	Rotate(img *image.ImageFile, options *Options) ([]byte, error)
	String() string
	Thumbnail(img *image.ImageFile, options *Options) ([]byte, error)
}