text:
/*
 * Enemy Class
 * Created by *Game Company Name*
 * Programmed by: Micah Hawman
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace orion
{
    /*
     * This class will create enemies for the play to kill for a score, the enemies
     * values tie into the main game as well as eventually tie into other aspects
     * such as high score and difficulty
     */
    public class Enemy : GameComponent
    {
        public Vector2 enemyPosition = new Vector2(100, 100); // Enemy Position on screen
        public Vector2 firePosition = new Vector2(0, 0); // enemy shot position on screen
        public List<EnemyFire> theEnemyFire = new List<EnemyFire>(); // list of enemy fire
        public Game1 game; // create an instance of Game
        public bool checkAttack = false; // see if enemy has been hit
        public bool Visible; // see if the enemy is vissible
        public bool enemyDeath = false; // see if the enemy is dead
        protected int randomDirection; // random number to pick directon
        protected int directionTickCount; // counter to check if it's time to change direction
        protected int directionTimer = 1500; // timer for how ofter direction changes.
        public int shotTimer = 1550; // timer for how ofter enemy fires.
        protected int gameTimer = 0; // counter to see if it's time to fire
        protected Rectangle enemyRectangle; // rectangle around the enemy for collision detection
        protected Random random; // the random number generator
        protected Rectangle screenBounds; // the rectangle around the screen
        public int enemyHealth = 20; // enemies health
        public int damage = 10;
        public bool set = false;

        // width and height of sprite in texture
        private int eShipWidth = 128;
        private int eShipHeight = 128;

        Texture2D enemyShipTexture; // texture of the enemy

        ContentManager fireContentManager;

        // Movement algorithm variables
        public bool leftSideStrike = false;
        private bool leftSideUp = false;
        private bool leftSideDown = true;
        public bool rightSideStrike = false;
        private bool rightSideUp = false;
        private bool rightSideDown = true;
        public bool topDown = false;
        public bool topDownLongLeft = false;
        private bool topDownLongRight = false;
        public bool topDownShortLeft = false;
        private bool topDownShortRight = false;
        public int speed = 0;

        // powerup variables
        public Vector2 powerUpPosition; // position of the power up on the screen
        public bool powerVisible; // see if the powerup is visible
        public Rectangle powerUpRectangle; // rectangle around the powerup for collision detection
        public int powerSelector; // find out what type of powerup to drop
        public bool dropPowerUp; // see if we drop the powerup
        public int dropChance = 6; // a value to check against to see if we in fact drop it
        public int dropRandom; // random number created to check against drop chance.

        // width and height of sprite in texture
        public int PUWidth = 64;
        public int PUHeight = 64;

        public Texture2D powerUpTexture; // texture of the powerup
        ContentManager powerUpContentManager;

        public Enemy(Game game)
            : base(game)
        {
            this.game = (Game1)game; // Set Game to current game;
            enemyPosition = new Vector2(); // reset the vector

            // place rectangles on the screen
            enemyRectangle = new Rectangle(0, 0, eShipWidth, eShipHeight);
            powerUpRectangle = new Rectangle(0, 0, PUWidth, PUHeight);
#if XBOX360
            //on the 360, we need to be carefule about the TV's "safe" area.
            screenBounds = new Rectangle(
                    (int)(Game.Window.ClientBounds.Width * 0.03f),
                    (int)(Game.Window.ClientBounds.Height * 0.03f),
                    Game.Window.ClientBounds.Width -
                    (int)(Game.Window.ClientBounds.Width * 0.03f),
                    Game.Window.ClientBounds.Height -
                    (int)(Game.Window.ClientBounds.Height * 0.03f));
#else
            screenBounds = new Rectangle(0, 0,
                Game.Window.ClientBounds.Width,
                Game.Window.ClientBounds.Height);
#endif

            random = new Random(this.GetHashCode()); // create a random hash to generate random numbers from
        }

        public void LoadContent(ContentManager theContentManager)
        {
            // load the content managers and set them to the current content manager
            fireContentManager = theContentManager;
            powerUpContentManager = theContentManager;

            // load the textures based off of a random number value from Game1 class
            enemyShipTexture = theContentManager.Load<Texture2D>(game.enemyLoad);
            powerUpTexture = theContentManager.Load<Texture2D>(game.powerUpLoad);

            foreach (EnemyFire enemyShot in theEnemyFire)
            {
                enemyShot.LoadContent(theContentManager); // load texture for each shot
            }
        }

        public override void Update(GameTime gameTime)
        {

            if (leftSideStrike == false && rightSideStrike == false && topDown == false)
            {
                enemyPosition.Y += speed;
            }
            if (leftSideStrike == true)
            {
                enemyPosition.X += speed;
                if (directionTickCount >= directionTimer)
                {
                    if (leftSideDown == true)
                    {
                        leftSideUp = true;
                        leftSideDown = false;
                        directionTickCount = 0;
                    }
                    else
                    {
                        leftSideDown = true;
                        leftSideUp = false;
                        directionTickCount = 0;
                    }
                }
                else
                {
                    directionTickCount += gameTime.ElapsedGameTime.Milliseconds;
                }

                if (leftSideDown == true)
                {
                    enemyPosition.Y += speed;
                }
                if (leftSideUp == true)
                {
                    enemyPosition.Y -= speed;
                }

            }
            if (rightSideStrike == true)
            {
                enemyPosition.X -= speed;

                if (directionTickCount >= directionTimer)
                {
                    if (rightSideDown == true)
                    {
                        rightSideUp = true;
                        rightSideDown = false;
                        directionTickCount = 0;
                    }
                    else
                    {
                        rightSideDown = true;
                        rightSideUp = false;
                        directionTickCount = 0;
                    }
                }
                else
                {
                    directionTickCount += gameTime.ElapsedGameTime.Milliseconds;
                }

                if (rightSideDown == true)
                {
                    enemyPosition.Y += speed;
                }
                if (rightSideUp == true)
                {
                    enemyPosition.Y -= speed;
                }
            }
            if (topDown == true && (topDownLongLeft == true || topDownLongRight == true))
            {
                enemyPosition.Y += speed;
                if (directionTickCount >= directionTimer)
                {
                    if (topDownLongLeft == true)
                    {
                        topDownLongLeft = false;
                        topDownLongRight = true;
                        directionTickCount = 0;
                    }
                    else
                    {
                        topDownLongRight = false;
                        topDownLongLeft = true;
                        directionTickCount = 0;
                    }
                }
                else
                {
                    directionTickCount += gameTime.ElapsedGameTime.Milliseconds;
                }
            }
            if (topDownLongLeft == true)
            {
                enemyPosition.X -= speed;
            }
            if (topDownLongRight == true)
            {
                enemyPosition.X += speed;
            }

            if (topDown == true && (topDownShortLeft == true || topDownShortRight == true))
            {
                enemyPosition.Y += speed;
                if (directionTickCount >= directionTimer)
                {
                    if (topDownShortLeft == true)
                    {
                        topDownShortLeft = false;
                        topDownShortRight = true;
                        directionTickCount = 0;
                    }
                    else
                    {
                        topDownShortRight = false;
                        topDownShortLeft = true;
                        directionTickCount = 0;
                    }
                }
                else
                {
                    directionTickCount += gameTime.ElapsedGameTime.Milliseconds;
                }
            }
            if (topDownShortLeft == true)
            {
                enemyPosition.X -= speed;
            }
            if (topDownShortRight == true)
            {
                enemyPosition.X += speed;
            }

            // update every shot on the screen currently
            foreach (EnemyFire enemyShot in theEnemyFire)
            {
                enemyShot.Update(gameTime);
            }

            if (game.gameIsOver == true)
            {
                for (int i = theEnemyFire.Count - 1; i >= 0; i--)
                {
                    EnemyFire shot = theEnemyFire[i];
                    shot.Update(gameTime);
                    theEnemyFire[i] = shot; // you need this is Shot is a value type
                    theEnemyFire.Remove(shot);
                }
            }

            // if the shot is outside the screen view, we remove it
            for (int i = theEnemyFire.Count - 1; i >= 0; i--)
            {
                EnemyFire shot = theEnemyFire[i];
                shot.Update(gameTime);
                theEnemyFire[i] = shot; // you need this is Shot is a value type

                if ((shot.enemyFirePosition.Y >= Game.Window.ClientBounds.Height) ||
                (shot.enemyFirePosition.Y >= Game.Window.ClientBounds.Width) || (shot.enemyFirePosition.Y < 4))
                {
                    theEnemyFire.Remove(shot);
                }
            }

            // see if the shot hit the player
            DoCollisionLogic(gameTime);

            // see if it's time for a new shot to happen
            if (gameTimer >= shotTimer)
            {
                gameTimer = 0; // reset timer
                Shoot(); // call the shoot method
            }

            else
            {
                gameTimer += gameTime.ElapsedGameTime.Milliseconds;
            }

            // see if the player has hit the enemy, if it has deduct life.
            if (checkAttack == true)
            {
                enemyHealth -= damage;
                if (enemyHealth < 0)
                {
                    game.addExplosion(new Vectors(enemyPosition.X, enemyPosition.Y));
                    enemyDeath = true;
                    checkAttack = false;
                }
                else checkAttack = false;
            }

        }

        public void Draw(SpriteBatch theSpriteBatch)
        {
            theSpriteBatch.Draw(enemyShipTexture, enemyPosition, enemyRectangle, Color.White); // draw the enemy

            foreach (EnemyFire enemyShot in theEnemyFire)
            {
                enemyShot.Draw(theSpriteBatch); // draw each shot
            }
        }

        // This will find out the current location of the enemy and return it's rectangle around the enemy
        public Rectangle GetBounds()
        {
            return new Rectangle((int)enemyPosition.X, (int)enemyPosition.Y,
                eShipWidth, eShipHeight);
        }

        // Enemy will shoot at the player and add it into the current list of shots.
        public void Shoot()
        {
            bool createNew = true;
            firePosition = new Vector2(enemyPosition.X + 55, enemyPosition.Y + 125);

            foreach (EnemyFire enemyShot in theEnemyFire)
            {
                if (enemyShot.Visible == false)
                {
                    createNew = false;
                    break;
                }
            }

            if (createNew == true)
            {
                EnemyFire enemyShot = new EnemyFire(game);
                enemyShot.LoadContent(fireContentManager);
                enemyShot.Fire(firePosition);
                theEnemyFire.Add(enemyShot);
            }
        }

        // will check for the players rectangle and see if shot's position collides with said rectangle.
        // If it colides the player will loose health and the shot will be removed from the list of shots.
        private void DoCollisionLogic(GameTime gameTime)
        {
            bool hasCollision = false;
            Rectangle playerRectangle = game.thePlayer.GetBounds();

            for (int i = theEnemyFire.Count - 1; i >= 0; i--)
            {
                EnemyFire shot = theEnemyFire[i];
                shot.Update(gameTime);
                theEnemyFire[i] = shot; // you need this is Shot is a value type
                hasCollision = shot.CheckCollision(playerRectangle);
                if (hasCollision)
                {
                    game.thePlayerHealth.checkAttack = true;
                    game.thePlayerHealth.rumble = true;
                    //game.thePlayerHealth.theFlash = true;
                    theEnemyFire.Remove(shot);
                }
            }
        }

        /*
         * In this function we have the enemy decide via random number if it will drop a powerup
         * if it does drop a power up it will randomly select a powerup it can drop.
         * It will then create the enemy with those parameters and add them to the list,
         * in a random spot inside of the viewing area.
         */
        // we will have them appear in formations in later code.
        public void Create()
        {
            Visible = true;
            bool validChoice = false;
            int dropMissile;
            game.enemytype = 1 + random.Next(3);
            powerSelector = 1 + random.Next(6);
            dropRandom = 1 + random.Next(6);

            if (dropRandom > (dropChance - 2)) // we'll drop a random powerup
            {
                dropPowerUp = true;
                powerVisible = true;
            }
            else // we don't drop a powerup
            {
                dropPowerUp = false;
            }

            while (validChoice == false)
            {
                if (dropPowerUp == true)
                {
                    switch (powerSelector)
                    {
                        case 1: // shield power
                            {
                                if (game.DropHeal == true)
                                {
                                    game.powerUpLoad = "ShieldPlus";
                                    powerSelector = 1;
                                    game.DropHeal = false;
                                    validChoice = true;
                                    break;
                                }
                                else
                                {

                                    game.powerUpLoad = "ShieldPlus";
                                    validChoice = true;
                                    break;
                                }
                            }
                        case 2: // rapid fire
                            {
                                if (game.DropHeal == true)
                                {
                                    game.powerUpLoad = "ShieldPlus";
                                    powerSelector = 1;
                                    game.DropHeal = false;
                                    validChoice = true;
                                    break;
                                }
                                else
                                {
                                    if (game.thePlayer.initialGun == true && game.thePlayer.gunSelector >= 1
                                        && game.thePlayer.rapidGun == false)
                                    {
                                        game.powerUpLoad = "RapidPU";
                                        validChoice = true;
                                        break;
                                    }
                                    else
                                    {
                                        powerSelector = 1 + random.Next(6);
                                        break;
                                    }
                                }
                            }
                        case 3: // spread shot
                            {
                                if (game.DropHeal == true)
                                {
                                    game.powerUpLoad = "ShieldPlus";
                                    powerSelector = 1;
                                    game.DropHeal = false;
                                    validChoice = true;
                                    break;
                                }
                                else
                                {
                                    if (game.thePlayer.rapidGun == true && game.thePlayer.gunSelector == 2
                                        && game.thePlayer.gunSelector != 3 && game.thePlayer.spreadGun == false)
                                    {
                                        game.powerUpLoad = "SpreadShot";
                                        validChoice = true;
                                        break;
                                    }
                                    else
                                    {
                                        powerSelector = 1 + random.Next(6);
                                        break;
                                    }
                                }
                            }
                        case 4: // missiles
                            {
                                if (game.DropHeal == true)
                                {
                                    game.powerUpLoad = "ShieldPlus";
                                    powerSelector = 1;
                                    game.DropHeal = false;
                                    validChoice = true;
                                    break;
                                }
                                else
                                {
                                    if (game.thePlayer.spreadGun == true && game.thePlayer.missiles == false)
                                    {
                                        dropMissile = 1 + random.Next(7);
                                        if (dropMissile >= 6)
                                        {
                                            game.powerUpLoad = "Rockets";
                                            validChoice = true;
                                            break;
                                        }
                                        else
                                        {
                                            powerSelector = 1 + random.Next(6);
                                            break;
                                        }
                                    }
                                    else if (game.thePlayer.missiles == true)
                                    {
                                        game.powerUpLoad = "ShieldPlus";
                                        powerSelector = 1;
                                        break;
                                    }
                                    else
                                    {
                                        powerSelector = 1 + random.Next(6);
                                        break;
                                    }
                                }
                            }
                        case 5: // Extra Life
                            {
                                if (game.DropHeal == true)
                                {
                                    game.powerUpLoad = "ShieldPlus";
                                    powerSelector = 1;
                                    game.DropHeal = false;
                                    validChoice = true;
                                    break;
                                }
                                else
                                {
                                    if (game.DropLife == true)
                                    {
                                        if (game.playerLives < 8)
                                        {
                                            game.DropLife = false ;
                                            game.powerUpLoad = "ExtraLife";
                                            validChoice = true;
                                            break;
                                        }
                                        else
                                        {
                                            game.powerUpLoad = "ShieldPlus";
                                            powerSelector = 1;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        game.powerUpLoad = "ShieldPlus";
                                        powerSelector = 1;
                                        break;
                                    }
                                }
                            }
                        case 6: // Bomb
                            {
                                if (game.DropHeal == true)
                                {
                                    game.powerUpLoad = "ShieldPlus";
                                    powerSelector = 1;
                                    game.DropHeal = false;
                                    validChoice = true;
                                    break;
                                }
                                else
                                {
                                    if (game.thePlayer.nuke <= 3)
                                    {
                                        game.powerUpLoad = "Nuke";
                                        validChoice = true;
                                        break;
                                    }
                                    else
                                    {
                                        powerSelector = 1 + random.Next(6);
                                        break;
                                    }

                                }
                            }
                    }
                }

                else
                {
                    validChoice = true;
                }
            }

            switch (game.enemytype)
            {
                case 1:
                    {
                        game.enemyLoad = "Enemy";
                        break;
                    }
                case 2:
                    {
                        game.enemyLoad = "Enemy1";
                        break;
                    }
                case 3: // supply ship
                    {
                        game.enemyLoad = "Enemy2";

                        break;
                    }
            }
        }
    }
}


text:
<?php
/**
 * SortKey
 *
 * PHP version 5
 *
 * @category Class
 * @package  Swagger\Client
 * @author   http://github.com/swagger-api/swagger-codegen
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link     https://github.com/swagger-api/swagger-codegen
 */
/**
 *  Copyright 2015 SmartBear Software
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace Aspose\Cells\Models;

use \ArrayAccess;
/**
 * SortKey Class Doc Comment
 *
 * @category    Class
 * @description
 * @package     Swagger\Client
 * @author      http://github.com/swagger-api/swagger-codegen
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class SortKey implements ArrayAccess
{
    /**
      * Array of property to type mappings. Used for (de)serialization
      * @var string[]
      */
    static $swaggerTypes = array(
        'key' => 'int',
        'sort_order' => 'string',
        'custom_list' => 'string'
    );

    /**
      * Array of attributes where the key is the local name, and the value is the original name
      * @var string[]
      */
    static $attributeMap = array(
        'key' => 'Key',
        'sort_order' => 'SortOrder',
        'custom_list' => 'CustomList'
    );

    /**
      * Array of attributes to setter functions (for deserialization of responses)
      * @var string[]
      */
    static $setters = array(
        'key' => 'setKey',
        'sort_order' => 'setSortOrder',
        'custom_list' => 'setCustomList'
    );

    /**
      * Array of attributes to getter functions (for serialization of requests)
      * @var string[]
      */
    static $getters = array(
        'key' => 'getKey',
        'sort_order' => 'getSortOrder',
        'custom_list' => 'getCustomList'
    );

    /**
      * $key
      * @var int
      */
    protected $key;

    /**
      * $sort_order
      * @var string
      */
    protected $sort_order;

    /**
      * $custom_list
      * @var string
      */
    protected $custom_list;

    /**
     * Constructor
     * @param mixed[] $data Associated array of property value initalizing the model
     */
    public function __construct(array $data = null)
    {
        if ($data != null) {
            $this->key = $data["key"];
            $this->sort_order = $data["sort_order"];
            $this->custom_list = $data["custom_list"];
        }
    }

    /**
     * Gets key
     * @return int
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * Sets key
     * @param int $key
     * @return $this
     */
    public function setKey($key)
    {

        $this->key = $key;
        return $this;
    }

    /**
     * Gets sort_order
     * @return string
     */
    public function getSortOrder()
    {
        return $this->sort_order;
    }

    /**
     * Sets sort_order
     * @param string $sort_order
     * @return $this
     */
    public function setSortOrder($sort_order)
    {

        $this->sort_order = $sort_order;
        return $this;
    }

    /**
     * Gets custom_list
     * @return string
     */
    public function getCustomList()
    {
        return $this->custom_list;
    }

    /**
     * Sets custom_list
     * @param string $custom_list
     * @return $this
     */
    public function setCustomList($custom_list)
    {

        $this->custom_list = $custom_list;
        return $this;
    }

    /**
     * Returns true if offset exists. False otherwise.
     * @param  integer $offset Offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->$offset);
    }

    /**
     * Gets offset.
     * @param  integer $offset Offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return $this->$offset;
    }

    /**
     * Sets value based on offset.
     * @param  integer $offset Offset
     * @param  mixed   $value  Value to be set
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        $this->$offset = $value;
    }

    /**
     * Unsets offset.
     * @param  integer $offset Offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->$offset);
    }

    /**
     * Gets the string presentation of the object
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) {
            return json_encode(get_object_vars($this), JSON_PRETTY_PRINT);
        } else {
            return json_encode(get_object_vars($this));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface ThModel : JSONModel
{

}

//接收到的Json,或者其他类型字符串
@prop_strong(NSString<Ignore>* , strData);

@prop_strong(id<Ignore>  , data);

@prop_strong(NSDictionary<Ignore> *  , dicdata);

@prop_strong(NSNumber<Ignore>  * , intChanged);
@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="css/myapp.css">


text:
package com.knowledgecode.cordova.websocket;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.eclipse.jetty.websocket.WebSocket.Connection;
import org.json.JSONArray;

import com.knowledgecode.cordova.websocket.TaskRunner.Task;

import android.util.Base64;
import android.util.SparseArray;

/**
 * Send text/binary data.
 */
class SendingTask implements Task {

    private final SparseArray<Connection> _map;

    /**
     * Constructor
     *
     * @param map
     */
    public SendingTask(SparseArray<Connection> map) {
        _map = map;
    }

    @Override
    public void execute(String rawArgs, CallbackContext ctx) {
        try {
            String args = new JSONArray(rawArgs).getString(0);
            Connection conn = _map.get(Integer.parseInt(args.substring(0, 8), 16));

            if (conn != null) {
                if (args.charAt(8) == '1') {
                    byte[] binary = Base64.decode(args.substring(args.indexOf(',') + 1), Base64.NO_WRAP);
                    conn.sendMessage(binary, 0, binary.length);
                } else {
                    conn.sendMessage(args.substring(9));
                }
            } else {
            }
        } catch (Exception e) {
            if (!ctx.isFinished()) {
                PluginResult result = new PluginResult(Status.ERROR);
                result.setKeepCallback(true);
                ctx.sendPluginResult(result);
            }
        }
    }
}


text:
'use strict';

var path = process.cwd();
var Poll = require('../models/polls.js');
var Choice = require('../models/choices.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	function add_choices(id, options){
		options.forEach(function(option){
			Choice.find({"poll_id": id, "poll_option": option}, function(err, opt){
				if (err){
					throw err;
				}
				if (opt.length == 0 && option !== ""){
					var newChoice = new Choice();
					newChoice.poll_id = id;
					newChoice.poll_option = option;
					newChoice.votes = 0;
					newChoice.save();
				}
			});
		});
	}

	app.route('/')
		.get(function (req, res) {
			res.sendFile(path + '/public/index.html');

		});

	app.route('/login')
		.get(function (req, res) {
			/*res.sendFile(path + '/public/login.html');*/
			res.redirect("/auth/twitter");
		});

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/');
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

	app.route('/error')
		.get(function(req, res){
			res.sendFile(path + '/public/error.html');
		});

	app.route('/profile/info')
		.get(isLoggedIn, function(req, res){
			Poll.find({"user_id": req.user._id}, function(err, polls){
				var obj = {
					"twitter_id": req.user.twitter.id,
					"username": req.user.username,
					"polls": polls.length > 0? polls.map(function(poll){
						return {"_id": poll._id, "poll_name": poll.poll_name, "date_last": poll.date_last.toDateString()};
					}):[]
				};
			res.json(obj);
		})});

	app.get('/auth', function(req, res){
		if (req.user !== undefined){
			res.json({"authenticated": true, "username": req.user.username});
		}
		else{
			res.json({"authenticated": false, "username": ""});
		}
	});

	app.get('/auth/twitter',
		passport.authenticate('twitter'));

	app.get('/auth/twitter/callback',
		passport.authenticate('twitter', {failureRedirect: '/login'}),
		function(req, res){
			res.redirect('/');
		});

	app.get('/polls', function(req, res){
		Poll.find(function(err, poll){
			if (err){
				throw err;
			}
			var polls = poll.map(function(poll){
				return {"_id": poll._id, "poll_name": poll.poll_name, "date_last": poll.date_last.toDateString()};
			});
			res.json(polls);
		});
	});

	app.route('/polls/add')
		.get(isLoggedIn, function(req, res){
			res.sendFile(path + '/public/polls/new_poll.html');
		});

	app.get('/polls/add/new', function(req, res){

		var poll_name = req.query.poll_name;

		Poll.find({"poll_name": poll_name}, function(err, poll){
			if (err){
				throw err;
			}
			if (poll.length > 0){
				res.send("Poll already exists");
			}
			else{
				var newPoll = new Poll();
				newPoll.poll_name = req.query.poll_name;
				newPoll.user_id = req.user._id;
				newPoll.save();

				add_choices(newPoll._id, req.query.option);
				res.redirect('/polls/' + newPoll._id);
			}
		});
	});

	app.get('/polls/result/:id', function(req, res){

		Poll.findById(req.params.id, function(err, poll){
			if (err){
				throw err;
			}

			var name = poll.poll_name;

			Choice.find({"poll_id": req.params.id}, function(err, choice){
				if (err){
					throw err;
				}
				var choices = choice.map(function(obj){
					return {"option": obj.poll_option, "vote": obj.votes, "id": obj._id, "poll_id": obj.poll_id};
				});

				var poll_info = {"name": name, choices};
				res.json(poll_info);
			});
		});
	});

	app.get("/polls/delete/:id", function(req, res){
		if (req.user != undefined){
			Poll.find({"_id": req.params.id}, function(err, poll){
				if (err){
					throw err;
				}
				Choice.find({"poll_id": req.params.id}).remove(function(err){
					if (err){
						throw err;
					}
					if (poll[0].user_id == req.user._id){
						poll[0].remove(function(err){
							if (err){
								throw err;
							}
							res.redirect('/');
						});
					}
					else{
						res.send("You don't have the authorization to delete the poll");
					}
				});
			});
		}
		else{
			res.send("You don't have the authorization to delete the poll");
		}
	});

	app.get('/polls/options/add/:id', function(req, res){
		add_choices(req.params.id, req.query.option);
		res.redirect('/polls/' + req.params.id);
	});

	app.get('/polls/:id/vote/', function(req, res){
		var poll_id = req.params.id;

		if (req.query.opts != "new_option"){
			Poll.findById(poll_id, function(err, poll){
				if (err){
					throw err;
				}
				var d = new Date();
				poll.date_last = d;
				poll.save();
				Choice.findOne({"poll_id": poll_id, "_id": req.query.opts}, function(err, option){
					if (err){
						throw err;
					}
					option.votes++;
					option.save(function(err){
						if (err){
							throw err;
						}
						res.redirect('/polls/' + req.params.id + "/results");
					});
				});
			});
		}
		else{
			add_choices(poll_id, [req.query.option_name]);
			Poll.findById(poll_id, function(err, poll){
				if (err){
					throw err;
				}
				var d = new Date();
				poll.date_last = d;
				poll.save();
				Choice.findOne({"poll_id": poll_id, "poll_option": req.query.option_name}, function(err, option){
					if (err){
						throw err;
					}
					option.votes++;
					option.save(function(err){
						if (err){
							throw err;
						}
						res.redirect('/polls/' + req.params.id + "/results");
					});
				});
			});
		}
	});

	app.get('/polls/:id/results', function(req, res){
		res.sendFile(path + "/public/polls/results.html");
	});

	app.get('/polls/:id', function(req, res){
		Poll.findById(req.params.id, function(err, poll){
			if (err){
				throw err;
			}

			if (poll != null || poll != undefined){
				res.sendFile(path + '/public/polls/view.html');
			}
			else{
				res.redirect('/error');
			}
		});
	});
};


text:
/* Less prepare example */
.clearfix {
  content: " ";
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
}
#header {
  margin: 0;
  height: 10px;
}
#header .logo {
  width: 50px;
}
#header .nav span {
  width: 12px;
}
#content {
  margin: auto;
  width: 800px;
}
#content button {
  font-size: 0.9px;
  font-weight: bold;
  width: 12px;
}
#content .float-container {
  content: " ";
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
}
#content .float-container .left {
  float: left;
}


text:
package com.prado.cerveja.repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;

import com.prado.cerveja.model.Estado;

public interface Estados extends JpaRepository<Estado, Long> {

	Optional<Estado> findByNomeIgnoreCase(String nome);

}


text:
var uuid = require('node-uuid'),
    Session = require('./session.js'),
    Script = require('../script.js'),
    memcached = require('memcached');

function SessionProvider(options) {

   options = options || { };
   options.host = options.host || '127.0.0.1';
   options.port = options.port || 11211;
   options.expiry = options.expiry || 900;

   this._memcached_client = new memcached(options.host + ':' + options.port);
   this._expiry = options.expiry;
}

require('util').inherits(SessionProvider, require('events').EventEmitter);

SessionProvider.COOKIE_REGEX = /sessionId=([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/;

SessionProvider.SYNC_REGEX = /session\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\//;

SessionProvider._mount_path = null;

SessionProvider.prototype.register = function(dommr, mount_path) {

   this._mount_path = mount_path;

   dommr.on('template:scripts:pre', this._attach_client_session.bind(this));

   dommr.register_intercept(SessionProvider.SYNC_REGEX, this._put_in_session.bind(this));
   dommr.register_pre_exec(this._attach_session.bind(this));
   dommr.register_post_exec(this._detach_session.bind(this));

};

/**
 * Deals with a request coming in from a client using window.session to change a session item
 *
 * @param match the match returned by the RegExp SessionProvider.SYNC_REGEX
 * @param {HttpRequest} request the request made by the client
 * @param {HttpResponse} response the response back to the client
 */
SessionProvider.prototype._put_in_session = function(match, request, response) {

   var id = match[1],
       payload;

   if (request.body) this._set_key_val(id, request.body, function() { response.end(); });
   else {
      request.on('data', function(data) { console.log('data in'); payload = (payload) ? payload + data : data; });
      request.on('end', (function() {
         payload && this._set_key_val(id, JSON.parse(payload.toString('utf8')), function() { response.end(); });
      }).bind(this));
   }

};

SessionProvider.prototype._set_key_val = function(id, key_val, callback) {
   var session = new Session(id, this._memcached_client, this._expiry);

   console.log('setting', key_val, id);

   session.set(key_val.key, key_val.value);
   session.save(callback);
};

/**
 * Attaches the client session code to the template and ensure it will only
 * run in the client
 *
 * @param {Template} template the dommr tempplate to add the session code to.
 */
SessionProvider.prototype._attach_client_session = function(template) {
   template.add_script(new Script(null, __dirname + '/client-session.js', Script.CLIENT, Script.JAVASCRIPT));
};

/**
 * Attaches the window.session object to the request's window object
 *
 * @param d_request the request object including window/httprequest/httpresponse
 */
SessionProvider.prototype._attach_session = function(d_request, done) {

   var id = d_request.session_id = this._get_id(d_request),
       session = d_request.window.session = new Session(id, this._memcached_client, this._expiry);

   console.log('[' + d_request.id + '] Part of session ' + id);

   session.load(function() { done(); });

};

SessionProvider.prototype._detach_session = function(d_request, done) {

   console.log('detaching session');

   var session = d_request.window.session,
       document = d_request.window.document,
       tag = document.createElement('script'),
       first_script_tag = document.getElementsByTagName('script')[0],
       data;

   tag.type = 'text/javascript';
   tag.charset = 'utf-8';

   data = { __id: d_request.session_id,
            __endpoint: this._mount_path + '/session/' + d_request.session_id + '/',
            __payload: session.all() };

   tag.appendChild(document.createTextNode('window.session = ' + JSON.stringify(data) + ';'));

   first_script_tag.parentNode.insertBefore(tag, first_script_tag);

   console.log('saving');
   session.save(function() { console.log('calling done');done(); });

};

SessionProvider.prototype._get_id = function(d_request) {

   var cookies = d_request.http_request.headers.cookie,
       cookie_match = SessionProvider.COOKIE_REGEX.exec(cookies),
       id;

   if (cookie_match) id = cookie_match[1];
   else {
      id = uuid();

      d_request.http_response.setHeader('Set-Cookie', 'sessionId=' + id + ';path=/; HttpOnly');
   }

   return id;

};

module.exports = SessionProvider;


text:
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var utils = require('primereact/utils');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}

function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}

function _setPrototypeOf(o, p) {
  _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };

  return _setPrototypeOf(o, p);
}

function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      writable: true,
      configurable: true
    }
  });
  if (superClass) _setPrototypeOf(subClass, superClass);
}

function _typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    _typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}

function _possibleConstructorReturn(self, call) {
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
    return call;
  }

  return _assertThisInitialized(self);
}

function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return _getPrototypeOf(o);
}

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

var propTypes = {exports: {}};

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';

var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var ReactPropTypesSecret = ReactPropTypesSecret_1;

function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;

var factoryWithThrowingShims = function() {
  function shim(props, propName, componentName, location, propFullName, secret) {
    if (secret === ReactPropTypesSecret) {
      // It is still safe when called from React.
      return;
    }
    var err = new Error(
      'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
      'Use PropTypes.checkPropTypes() to call them. ' +
      'Read more at http://fb.me/use-check-prop-types'
    );
    err.name = 'Invariant Violation';
    throw err;
  }  shim.isRequired = shim;
  function getShim() {
    return shim;
  }  // Important!
  // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
  var ReactPropTypes = {
    array: shim,
    bool: shim,
    func: shim,
    number: shim,
    object: shim,
    string: shim,
    symbol: shim,

    any: shim,
    arrayOf: getShim,
    element: shim,
    elementType: shim,
    instanceOf: getShim,
    node: shim,
    objectOf: getShim,
    oneOf: getShim,
    oneOfType: getShim,
    shape: getShim,
    exact: getShim,

    checkPropTypes: emptyFunctionWithReset,
    resetWarningCache: emptyFunction
  };

  ReactPropTypes.PropTypes = ReactPropTypes;

  return ReactPropTypes;
};

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

{
  // By explicitly using `prop-types` you are opting into new production behavior.
  // http://fb.me/prop-types-in-prod
  propTypes.exports = factoryWithThrowingShims();
}

var PropTypes = propTypes.exports;

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var VirtualScroller = /*#__PURE__*/function (_Component) {
  _inherits(VirtualScroller, _Component);

  var _super = _createSuper(VirtualScroller);

  function VirtualScroller(props) {
    var _this;

    _classCallCheck(this, VirtualScroller);

    _this = _super.call(this, props);

    var isBoth = _this.isBoth();

    _this.state = {
      first: isBoth ? {
        rows: 0,
        cols: 0
      } : 0,
      last: isBoth ? {
        rows: 0,
        cols: 0
      } : 0,
      numItemsInViewport: isBoth ? {
        rows: 0,
        cols: 0
      } : 0,
      numToleratedItems: props.numToleratedItems,
      loading: false
    };
    _this.onScroll = _this.onScroll.bind(_assertThisInitialized(_this));
    _this.lastScrollPos = isBoth ? {
      top: 0,
      left: 0
    } : 0;
    return _this;
  }

  _createClass(VirtualScroller, [{
    key: "scrollTo",
    value: function scrollTo(options) {
      this.element && this.element.scrollTo(options);
    }
  }, {
    key: "scrollToIndex",
    value: function scrollToIndex(index) {
      var _this2 = this;

      var behavior = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'auto';
      var isBoth = this.isBoth();
      var isHorizontal = this.isHorizontal();
      var first = this.state.first;
      var itemSize = this.props.itemSize;
      var contentPadding = this.getContentPadding();

      var calculateFirst = function calculateFirst() {
        var _index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

        return _index <= _this2.state.numToleratedItems ? 0 : _index;
      };

      var calculateCoord = function calculateCoord(_first, _size, _padding) {
        return _first * _size + _padding;
      };

      var scrollTo = function scrollTo() {
        var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
        var top = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
        return _this2.scrollTo({
          left: left,
          top: top,
          behavior: behavior
        });
      };

      if (isBoth) {
        var newFirst = {
          rows: calculateFirst(index[0]),
          cols: calculateFirst(index[1])
        };
        (newFirst.rows !== first.rows || newFirst.cols !== first.cols) && scrollTo(calculateCoord(newFirst.cols, itemSize[1], contentPadding.left), calculateCoord(newFirst.rows, itemSize[0], contentPadding.top));
      } else {
        var _newFirst = calculateFirst(index);

        if (_newFirst !== first) {
          isHorizontal ? scrollTo(calculateCoord(_newFirst, itemSize, contentPadding.left), 0) : scrollTo(0, calculateCoord(_newFirst, itemSize, contentPadding.top));
        }
      }
    }
  }, {
    key: "scrollInView",
    value: function scrollInView(index, to) {
      var _this3 = this;

      var behavior = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'auto';

      if (to) {
        var isBoth = this.isBoth();
        var isHorizontal = this.isHorizontal();

        var _this$getRenderedRang = this.getRenderedRange(),
            first = _this$getRenderedRang.first,
            viewport = _this$getRenderedRang.viewport;

        var itemSize = this.props.itemSize;

        var scrollTo = function scrollTo() {
          var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
          var top = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
          return _this3.scrollTo({
            left: left,
            top: top,
            behavior: behavior
          });
        };

        var isToStart = to === 'to-start';
        var isToEnd = to === 'to-end';

        if (isToStart) {
          if (isBoth) {
            if (viewport.first.rows - first.rows > index[0]) {
              scrollTo(viewport.first.cols * itemSize, (viewport.first.rows - 1) * itemSize);
            } else if (viewport.first.cols - first.cols > index[1]) {
              scrollTo((viewport.first.cols - 1) * itemSize, viewport.first.rows * itemSize);
            }
          } else {
            if (viewport.first - first > index) {
              var pos = (viewport.first - 1) * itemSize;
              isHorizontal ? scrollTo(pos, 0) : scrollTo(0, pos);
            }
          }
        } else if (isToEnd) {
          if (isBoth) {
            if (viewport.last.rows - first.rows <= index[0] + 1) {
              scrollTo(viewport.first.cols * itemSize, (viewport.first.rows + 1) * itemSize);
            } else if (viewport.last.cols - first.cols <= index[1] + 1) {
              scrollTo((viewport.first.cols + 1) * itemSize, viewport.first.rows * itemSize);
            }
          } else {
            if (viewport.last - first <= index + 1) {
              var _pos2 = (viewport.first + 1) * itemSize;

              isHorizontal ? scrollTo(_pos2, 0) : scrollTo(0, _pos2);
            }
          }
        }
      } else {
        this.scrollToIndex(index, behavior);
      }
    }
  }, {
    key: "getRenderedRange",
    value: function getRenderedRange() {
      var isBoth = this.isBoth();
      var isHorizontal = this.isHorizontal();
      var _this$state = this.state,
          first = _this$state.first,
          last = _this$state.last,
          numItemsInViewport = _this$state.numItemsInViewport;
      var itemSize = this.props.itemSize;

      var calculateFirstInViewport = function calculateFirstInViewport(_pos, _size) {
        return Math.floor(_pos / (_size || _pos));
      };

      var firstInViewport = first;
      var lastInViewport = 0;

      if (this.element) {
        var scrollTop = this.element.scrollTop;
        var scrollLeft = this.element.scrollLeft;

        if (isBoth) {
          firstInViewport = {
            rows: calculateFirstInViewport(scrollTop, itemSize[0]),
            cols: calculateFirstInViewport(scrollLeft, itemSize[1])
          };
          lastInViewport = {
            rows: firstInViewport.rows + numItemsInViewport.rows,
            cols: firstInViewport.cols + numItemsInViewport.cols
          };
        } else {
          var scrollPos = isHorizontal ? scrollLeft : scrollTop;
          firstInViewport = calculateFirstInViewport(scrollPos, itemSize);
          lastInViewport = firstInViewport + numItemsInViewport;
        }
      }

      return {
        first: first,
        last: last,
        viewport: {
          first: firstInViewport,
          last: lastInViewport
        }
      };
    }
  }, {
    key: "isHorizontal",
    value: function isHorizontal() {
      return this.props.orientation === 'horizontal';
    }
  }, {
    key: "isBoth",
    value: function isBoth() {
      return this.props.orientation === 'both';
    }
  }, {
    key: "calculateOptions",
    value: function calculateOptions() {
      var _this4 = this;

      var isBoth = this.isBoth();
      var isHorizontal = this.isHorizontal();
      var first = this.state.first;
      var itemSize = this.props.itemSize;
      var contentPadding = this.getContentPadding();
      var contentWidth = this.element ? this.element.offsetWidth - contentPadding.left : 0;
      var contentHeight = this.element ? this.element.offsetHeight - contentPadding.top : 0;

      var calculateNumItemsInViewport = function calculateNumItemsInViewport(_contentSize, _itemSize) {
        return Math.ceil(_contentSize / (_itemSize || _contentSize));
      };

      var numItemsInViewport = isBoth ? {
        rows: calculateNumItemsInViewport(contentHeight, itemSize[0]),
        cols: calculateNumItemsInViewport(contentWidth, itemSize[1])
      } : calculateNumItemsInViewport(isHorizontal ? contentWidth : contentHeight, itemSize);
      var numToleratedItems = this.state.numToleratedItems || Math.ceil((isBoth ? numItemsInViewport.rows : numItemsInViewport) / 2);

      var calculateLast = function calculateLast(_first, _num, _isCols) {
        return _this4.getLast(_first + _num + (_first < numToleratedItems ? 2 : 3) * numToleratedItems, _isCols);
      };

      var last = isBoth ? {
        rows: calculateLast(first.rows, numItemsInViewport.rows),
        cols: calculateLast(first.cols, numItemsInViewport.cols, true)
      } : calculateLast(first, numItemsInViewport);
      var state = {
        numItemsInViewport: numItemsInViewport,
        last: last,
        numToleratedItems: numToleratedItems
      };

      if (this.props.showLoader) {
        state['loaderArr'] = Array.from({
          length: isBoth ? numItemsInViewport.rows : numItemsInViewport
        });
      }

      this.setState(state, function () {
        if (_this4.props.lazy) {
          _this4.props.onLazyLoad && _this4.props.onLazyLoad({
            first: _this4.state.first,
            last: _this4.state.last
          });
        }
      });
    }
  }, {
    key: "getLast",
    value: function getLast(last, isCols) {
      return this.props.items ? Math.min(isCols ? this.props.items[0].length : this.props.items.length, last) : 0;
    }
  }, {
    key: "getContentPadding",
    value: function getContentPadding() {
      if (this.content) {
        var style = getComputedStyle(this.content);
        var left = parseInt(style.paddingLeft, 10);
        var right = parseInt(style.paddingRight, 10);
        var top = parseInt(style.paddingTop, 10);
        var bottom = parseInt(style.paddingBottom, 10);
        return {
          left: left,
          right: right,
          top: top,
          bottom: bottom,
          x: left + right,
          y: top + bottom
        };
      }

      return {
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        x: 0,
        y: 0
      };
    }
  }, {
    key: "setSize",
    value: function setSize() {
      var _this5 = this;

      if (this.element) {
        var isBoth = this.isBoth();
        var isHorizontal = this.isHorizontal();
        var parentElement = this.element.parentElement;
        var width = this.props.scrollWidth || "".concat(this.element.offsetWidth || parentElement.offsetWidth, "px");
        var height = this.props.scrollHeight || "".concat(this.element.offsetHeight || parentElement.offsetHeight, "px");

        var setProp = function setProp(_name, _value) {
          return _this5.element.style[_name] = _value;
        };

        if (isBoth) {
          setProp('height', height);
          setProp('width', width);
        } else {
          isHorizontal ? setProp('width', width) : setProp('height', height);
        }
      }
    }
  }, {
    key: "setSpacerSize",
    value: function setSpacerSize() {
      var _this6 = this;

      var items = this.props.items;

      if (this.spacer && items) {
        var isBoth = this.isBoth();
        var isHorizontal = this.isHorizontal();
        var itemSize = this.props.itemSize;
        var contentPadding = this.getContentPadding();

        var setProp = function setProp(_name, _value, _size) {
          var _padding = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;

          return _this6.spacer.style[_name] = (_value || []).length * _size + _padding + 'px';
        };

        if (isBoth) {
          setProp('height', items[0], itemSize[0], contentPadding.y);
          setProp('width', items[1], itemSize[1], contentPadding.x);
        } else {
          isHorizontal ? setProp('width', items, itemSize, contentPadding.x) : setProp('height', items, itemSize, contentPadding.y);
        }
      }
    }
  }, {
    key: "setContentPosition",
    value: function setContentPosition(pos) {
      var _this7 = this;

      if (this.content) {
        var isBoth = this.isBoth();
        var isHorizontal = this.isHorizontal();
        var first = pos ? pos.first : this.state.first;
        var itemSize = this.props.itemSize;

        var calculateTranslateVal = function calculateTranslateVal(_first, _size) {
          return _first * _size;
        };

        var setTransform = function setTransform() {
          var _x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

          var _y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

          return _this7.content.style.transform = "translate3d(".concat(_x, "px, ").concat(_y, "px, 0)");
        };

        if (isBoth) {
          setTransform(calculateTranslateVal(first.cols, itemSize[1]), calculateTranslateVal(first.rows, itemSize[0]));
        } else {
          var translateVal = calculateTranslateVal(first, itemSize);
          isHorizontal ? setTransform(translateVal, 0) : setTransform(0, translateVal);
        }
      }
    }
  }, {
    key: "onScrollPositionChange",
    value: function onScrollPositionChange(event) {
      var _this8 = this;

      var target = event.target;
      var isBoth = this.isBoth();
      var isHorizontal = this.isHorizontal();
      var _this$state2 = this.state,
          first = _this$state2.first,
          last = _this$state2.last,
          numItemsInViewport = _this$state2.numItemsInViewport,
          numToleratedItems = _this$state2.numToleratedItems;
      var itemSize = this.props.itemSize;
      var contentPadding = this.getContentPadding();

      var calculateScrollPos = function calculateScrollPos(_pos, _padding) {
        return _pos ? _pos > _padding ? _pos - _padding : _pos : 0;
      };

      var calculateCurrentIndex = function calculateCurrentIndex(_pos, _size) {
        return Math.floor(_pos / (_size || _pos));
      };

      var calculateTriggerIndex = function calculateTriggerIndex(_currentIndex, _first, _last, _num, _isScrollDownOrRight) {
        return _currentIndex <= numToleratedItems ? numToleratedItems : _isScrollDownOrRight ? _last - _num - numToleratedItems : _first + numToleratedItems - 1;
      };

      var calculateFirst = function calculateFirst(_currentIndex, _triggerIndex, _first, _last, _num, _isScrollDownOrRight) {
        if (_currentIndex <= numToleratedItems) return 0;else return _isScrollDownOrRight ? _currentIndex < _triggerIndex ? _first : _currentIndex - numToleratedItems : _currentIndex > _triggerIndex ? _first : _currentIndex - 2 * numToleratedItems;
      };

      var calculateLast = function calculateLast(_currentIndex, _first, _last, _num, _isCols) {
        var lastValue = _first + _num + 2 * numToleratedItems;

        if (_currentIndex >= numToleratedItems) {
          lastValue += numToleratedItems + 1;
        }

        return _this8.getLast(lastValue, _isCols);
      };

      var scrollTop = calculateScrollPos(target.scrollTop, contentPadding.top);
      var scrollLeft = calculateScrollPos(target.scrollLeft, contentPadding.left);
      var newFirst = 0;
      var newLast = last;
      var isRangeChanged = false;

      if (isBoth) {
        var isScrollDown = this.lastScrollPos.top <= scrollTop;
        var isScrollRight = this.lastScrollPos.left <= scrollLeft;
        var currentIndex = {
          rows: calculateCurrentIndex(scrollTop, itemSize[0]),
          cols: calculateCurrentIndex(scrollLeft, itemSize[1])
        };
        var triggerIndex = {
          rows: calculateTriggerIndex(currentIndex.rows, first.rows, last.rows, numItemsInViewport.rows, isScrollDown),
          cols: calculateTriggerIndex(currentIndex.cols, first.cols, last.cols, numItemsInViewport.cols, isScrollRight)
        };
        newFirst = {
          rows: calculateFirst(currentIndex.rows, triggerIndex.rows, first.rows, last.rows, numItemsInViewport.rows, isScrollDown),
          cols: calculateFirst(currentIndex.cols, triggerIndex.cols, first.cols, last.cols, numItemsInViewport.cols, isScrollRight)
        };
        newLast = {
          rows: calculateLast(currentIndex.rows, newFirst.rows, last.rows, numItemsInViewport.rows),
          cols: calculateLast(currentIndex.cols, newFirst.cols, last.cols, numItemsInViewport.cols, true)
        };
        isRangeChanged = newFirst.rows !== first.rows || newFirst.cols !== first.cols || newLast.rows !== last.rows || newLast.cols !== last.cols;
        this.lastScrollPos = {
          top: scrollTop,
          left: scrollLeft
        };
      } else {
        var scrollPos = isHorizontal ? scrollLeft : scrollTop;
        var isScrollDownOrRight = this.lastScrollPos <= scrollPos;

        var _currentIndex2 = calculateCurrentIndex(scrollPos, itemSize);

        var _triggerIndex2 = calculateTriggerIndex(_currentIndex2, first, last, numItemsInViewport, isScrollDownOrRight);

        newFirst = calculateFirst(_currentIndex2, _triggerIndex2, first, last, numItemsInViewport, isScrollDownOrRight);
        newLast = calculateLast(_currentIndex2, newFirst, last, numItemsInViewport);
        isRangeChanged = newFirst !== first || newLast !== last;
        this.lastScrollPos = scrollPos;
      }

      return {
        first: newFirst,
        last: newLast,
        isRangeChanged: isRangeChanged
      };
    }
  }, {
    key: "onScrollChange",
    value: function onScrollChange(event) {
      var _this9 = this;

      var _this$onScrollPositio = this.onScrollPositionChange(event),
          first = _this$onScrollPositio.first,
          last = _this$onScrollPositio.last,
          isRangeChanged = _this$onScrollPositio.isRangeChanged;

      if (isRangeChanged) {
        var newState = {
          first: first,
          last: last
        };
        this.setContentPosition(newState);

        if (this.props.lazy) {
          this.props.onLazyLoad && this.props.onLazyLoad(newState);
        }

        this.setState(newState, function () {
          _this9.props.onScrollIndexChange && _this9.props.onScrollIndexChange(newState);
        });
      }
    }
  }, {
    key: "onScroll",
    value: function onScroll(event) {
      var _this10 = this;

      this.props.onScroll && this.props.onScroll(event);

      if (this.props.delay) {
        if (this.scrollTimeout) {
          clearTimeout(this.scrollTimeout);
        }

        if (!this.state.loading && this.props.showLoader) {
          var _this$onScrollPositio2 = this.onScrollPositionChange(event),
              changed = _this$onScrollPositio2.isRangeChanged;

          changed && this.setState({
            loading: true
          });
        }

        this.scrollTimeout = setTimeout(function () {
          _this10.onScrollChange(event);

          if (_this10.state.loading && _this10.props.showLoader && !_this10.props.lazy) {
            _this10.setState({
              loading: false
            });
          }
        }, this.props.delay);
      } else {
        this.onScrollChange(event);
      }
    }
  }, {
    key: "getOptions",
    value: function getOptions(index, count) {
      return {
        index: index,
        count: count,
        first: index === 0,
        last: index === count - 1,
        even: index % 2 === 0,
        odd: index % 2 !== 0,
        props: this.props
      };
    }
  }, {
    key: "init",
    value: function init() {
      this.setSize();
      this.calculateOptions();
      this.setSpacerSize();
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.init();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      if (prevProps.itemSize !== this.props.itemSize || !prevProps.items || prevProps.items.length !== (this.props.items || []).length) {
        this.init();
      }

      if (this.props.lazy && prevProps.loading !== this.props.loading && this.state.loading !== this.props.loading) {
        this.setState({
          loading: this.props.loading
        });
      }

      if (prevProps.orientation !== this.props.orientation) {
        this.lastScrollPos = this.isBoth() ? {
          top: 0,
          left: 0
        } : 0;
      }
    }
  }, {
    key: "renderItem",
    value: function renderItem(item, index, count, passedItem) {
      var options = this.getOptions(index, count);
      var content = utils.ObjectUtils.getJSXElement(this.props.itemTemplate, passedItem || item, options);
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, {
        key: index
      }, content);
    }
  }, {
    key: "renderItems",
    value: function renderItems() {
      var _this11 = this;

      var items = this.props.items;

      if (items && !this.state.loading) {
        var isBoth = this.isBoth();
        var _this$state3 = this.state,
            first = _this$state3.first,
            last = _this$state3.last;
        var count = items.length;

        if (isBoth) {
          return items.slice(first.rows, last.rows).map(function (item, i) {
            var items = item.slice(first.cols, last.cols);
            var index = first.rows + i;
            return _this11.renderItem(item, index, count, items);
          });
        } else {
          return items.slice(first, last).map(function (item, i) {
            var index = first + i;
            return _this11.renderItem(item, index, count);
          });
        }
      }

      return null;
    }
  }, {
    key: "renderLoaderItem",
    value: function renderLoaderItem(index, count, extOptions) {
      var options = _objectSpread(_objectSpread({}, this.getOptions(index, count)), extOptions || {});

      var content = utils.ObjectUtils.getJSXElement(this.props.loadingTemplate, options);
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, {
        key: index
      }, content);
    }
  }, {
    key: "renderLoader",
    value: function renderLoader() {
      var _this12 = this;

      if (this.state.loading) {
        var className = utils.classNames('p-virtualscroller-loader', {
          'p-component-overlay': !this.props.loadingTemplate
        });
        var content = /*#__PURE__*/React__default['default'].createElement("i", {
          className: "p-virtualscroller-loading-icon pi pi-spinner pi-spin"
        });

        if (this.props.loadingTemplate) {
          var isBoth = this.isBoth();
          var numItemsInViewport = this.state.numItemsInViewport;
          var length = isBoth ? numItemsInViewport.rows : numItemsInViewport;
          content = this.state.loaderArr.map(function (_, index) {
            return _this12.renderLoaderItem(index, length, isBoth && {
              numCols: numItemsInViewport.cols
            });
          });
        }

        return /*#__PURE__*/React__default['default'].createElement("div", {
          className: className
        }, content);
      }

      return null;
    }
  }, {
    key: "renderContent",
    value: function renderContent() {
      var _this13 = this;

      var items = this.renderItems();
      var content = /*#__PURE__*/React__default['default'].createElement("div", {
        className: "p-virtualscroller-content",
        ref: function ref(el) {
          return _this13.content = el;
        }
      }, items);

      if (this.props.contentTemplate) {
        var _this$state4 = this.state,
            loading = _this$state4.loading,
            first = _this$state4.first,
            last = _this$state4.last;
        var defaultOptions = {
          className: 'p-virtualscroller-content',
          ref: function ref(el) {
            return _this13.content = el;
          },
          children: items,
          element: content,
          props: this.props,
          loading: loading,
          first: first,
          last: last
        };
        return utils.ObjectUtils.getJSXElement(this.props.contentTemplate, defaultOptions);
      }

      return content;
    }
  }, {
    key: "render",
    value: function render() {
      var _this14 = this;

      var isBoth = this.isBoth();
      var isHorizontal = this.isHorizontal();
      var className = utils.classNames('p-virtualscroller', {
        'p-both-scroll': isBoth,
        'p-horizontal-scroll': isHorizontal
      }, this.props.className);
      var loader = this.renderLoader();
      var content = this.renderContent();
      return /*#__PURE__*/React__default['default'].createElement("div", {
        ref: function ref(el) {
          return _this14.element = el;
        },
        className: className,
        style: this.props.style,
        onScroll: this.onScroll
      }, content, /*#__PURE__*/React__default['default'].createElement("div", {
        ref: function ref(el) {
          return _this14.spacer = el;
        },
        className: "p-virtualscroller-spacer"
      }), loader);
    }
  }]);

  return VirtualScroller;
}(React.Component);

_defineProperty(VirtualScroller, "defaultProps", {
  id: null,
  style: null,
  className: null,
  items: null,
  itemSize: 0,
  scrollHeight: null,
  scrollWidth: null,
  orientation: 'vertical',
  numToleratedItems: null,
  delay: 0,
  lazy: false,
  showLoader: false,
  loadingTemplate: null,
  itemTemplate: null,
  contentTemplate: null,
  onScroll: null,
  onScrollIndexChange: null,
  onLazyLoad: null
});

_defineProperty(VirtualScroller, "propTypes", {
  id: PropTypes.string,
  style: PropTypes.object,
  className: PropTypes.string,
  items: PropTypes.any,
  itemSize: PropTypes.oneOfType([PropTypes.number, PropTypes.array]).isRequired,
  scrollHeight: PropTypes.string,
  scrollWidth: PropTypes.string,
  orientation: PropTypes.string,
  numToleratedItems: PropTypes.number,
  delay: PropTypes.number,
  lazy: PropTypes.bool,
  showLoader: PropTypes.bool,
  loadingTemplate: PropTypes.any,
  itemTemplate: PropTypes.any,
  contentTemplate: PropTypes.any,
  onScroll: PropTypes.func,
  onScrollIndexChange: PropTypes.func,
  onLazyLoad: PropTypes.func
});

exports.VirtualScroller = VirtualScroller;


text:
<?xml version="1.0" encoding="utf-8"?>

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/apptheme_accent">
</ripple>


text:
1. Features
    - EventEmitter-ify interface
    - Image upload for avatars
2. Testing
    - Test the IncomingStream
    - Testing library


text:
To run the setup file to configure Enzyme and the Adapter (as shown in the [Installation docs](https://airbnb.io/enzyme/docs/installation/)) with Jest, set `setupFilesAfterEnv` (previously `setupTestFrameworkScriptFile`) in your config file (check [Jest's documentation](http://jestjs.io/docs/en/configuration) for the possible locations of that config file) to literally the string `<rootDir>` and the path to your setup file.

```json
{
  "jest": {
    "setupFilesAfterEnv": ["<rootDir>src/setupTests.js"]
  }
}
```

## Jest version 15 and up

Starting with version 15, Jest [no longer mocks modules by default](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html). Because of this, you no longer have to add _any_ special configuration for Jest to use it with enzyme.

Install Jest, and its Babel integrations, as recommended in the [Jest docs](https://facebook.github.io/jest/docs/en/getting-started.html). Install enzyme. Then, simply require/import React, enzyme functions, and your module at the top of a test file.

```js
import React from 'react';
import { shallow, mount, render } from 'enzyme';

import Foo from '../Foo';
```

You do **not** need to include Jest's own renderer, unless you want to use it _only_ for Jest snapshot testing.

## Example Project for Jest version 15+

- [Example test for Jest 15+](https://github.com/vjwilson/enzyme-example-jest)

## Jest prior to version 15

If you are using Jest 0.9 – 14.0 with enzyme and using Jest's automocking feature, you will need to mark react and enzyme to be unmocked in your `package.json`:

`package.json`:
```json
{
  "jest": {
    "unmockedModulePathPatterns": [
      "node_modules/react/",
      "node_modules/enzyme/"
    ]
  }
}
```

If you are using a previous version of Jest together with npm3, you may need to unmock [more modules](https://github.com/airbnb/enzyme/blob/78febd90fe2fb184771b8b0356b0fcffbdad386e/docs/guides/jest.md).


text:
include Chef::Mixin::Pacemaker::RunnableResource
include Chef::Mixin::Pacemaker::StandardCIBObject

action :create do
  standard_create_action
end

action :delete do
  delete_runnable_resource
end

action :start do
  start_runnable_resource
end

action :stop do
  stop_runnable_resource
end

def cib_object_class
  ::Pacemaker::Resource::MasterSlave
end

def load_current_resource
  standard_load_current_resource
end

def init_current_resource
  name = @new_resource.name
  @current_resource = Chef::Resource::PacemakerMs.new(name)
  @current_cib_object.copy_attrs_to_chef_resource(@current_resource, :rsc)
end

def create_resource(name)
  standard_create_resource
end

def maybe_modify_resource(name)
  Chef::Log.info "Checking existing #{@current_cib_object} for modifications"

  desired_clone = cib_object_class.from_chef_resource(new_resource)
  if desired_clone.definition_string != @current_cib_object.definition_string
    Chef::Log.debug "changed from [#{@current_cib_object.definition_string}] to [#{desired_clone.definition_string}]"
    cmd = desired_clone.reconfigure_command
    execute cmd do
      action :nothing
    end.run_action(:run)
    new_resource.updated_by_last_action(true)
  end
end


text:
using System.Xml;
using FuncPatterns.ChainOfResponsibility;

namespace FuncPatterns.Tests.ShapeReader
{
    sealed class CircleReader : MonadicLink<XmlReader, string>
    {
        protected internal override bool IsApplicableFor(XmlReader input) => input.Name == "Circle";

        protected internal override string Resolve(XmlReader input) => input.GetAttribute("radius");
    }
}


text:
var path = require('path');
var nconf = require('nconf');
var openweatherwrap = require('../main.js');

// configure config order
nconf.argv().env().file({
    file: path.join(__dirname,'../config.json')
});

exports['findWeatherInStationsByCoords'] = function (test) {
    openweatherwrap.findWeatherInStations({'lat':55, 'lon':73, 'cnt':10}, function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['findWeatherInStationsByBoundingBox'] = function (test) {
    openweatherwrap.findWeatherInStations({'bbox':'12, 32, 15, 37, 10', 'cluster':'yes', 'lang':'en'}, function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['findWeatherInStationsByBoundingRadius'] = function (test) {
    openweatherwrap.findWeatherInStations({'lat':55, 'lon':73, 'radius':10, 'cluster':'no', 'lang':'de'}, function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['findWeatherInCitiesByCoords'] = function (test) {
    openweatherwrap.findWeatherInCities({'lat':55, 'lon':73, 'cnt':10}, function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['findWeatherInCitiesByBoundingBox'] = function (test) {
    openweatherwrap.findWeatherInCities({'bbox':'12, 32, 15, 37, 10', 'cluster':'yes', 'lang':'en'}, function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['findWeatherInCitiesByBoundingRadius'] = function (test) {
    openweatherwrap.findWeatherInCities({'lat':55, 'lon':73, 'radius':10, 'cluster':'no', 'lang':'de'}, function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['findWeatherInCitiesByName'] = function (test) {
    openweatherwrap.findWeatherInCitiesByName({'q':'london', 'units':'imperial'}, function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['findWeatherInCitiesByFuzzyName'] = function (test) {
    openweatherwrap.findWeatherInCitiesByName({'q':'Maloyarolslav', 'type':'like', 'units':'metric'}, function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['findWeatherInCitiesByNameAndCountryCode'] = function (test) {
    openweatherwrap.findWeatherInCitiesByName({'q':'london,Uk'}, function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['getCurrentWeatherByCityId'] = function (test) {
    openweatherwrap.getCurrentWeatherByCityId('2935022', {'lan':'de'},  function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['getForecastByCityId'] = function (test) {
    openweatherwrap.getForecastByCityId('2935022', {'lan':'de'},  function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}

exports['getForecastByCityName'] = function (test) {
    openweatherwrap.getForecastByCityName({'1':'london', 'mode':'daily_compact'},  function(error, response) {
        test.ok((response !== false));
        test.done();
    });
}


text:
package com.tirthal.learning.helloworld.greeting;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Demo client application consuming greeting service - with and without Spring.
 *
 * @author tirthalp
 *
 */
public class App {

	private static final Logger log = LoggerFactory.getLogger(App.class);

	@SuppressWarnings("resource")
	public static void main(String[] args) {

		/**
		 * ================ OPTION 1 - Without using Spring DI (Dependency Injection) =====================
		 *
		 * Implementation class of GreetingService is tightly coupled in the calling client
		 */
		GreetingService greeting = new GreetingServiceImpl();

		Message msg1 = new Message("Simple Demo", "This is not Spring Hello World demo");
		greeting.sayHello(msg1);

		log.debug("----------------");

		/**
		 * ================ OPTION 2 - Using Spring DI (Dependency Injection) =====================
		 */

		// ----------> Step 1 - Get Spring Application Context by loading "helloworld-app-container.xml" file located in the classpath
		/**
		 * Ideally we should place "helloworld-app-container.xml" file in resources folder and in that case it can be accessed like,
		 * ApplicationContext appContext = new ClassPathXmlApplicationContext("helloworld-app-container.xml");
		 */
		ApplicationContext appContext = new ClassPathXmlApplicationContext("com/tirthal/learning/helloworld/greeting/app-container.xml");

		log.debug("------------------");

		// ----------> Step 2 - Get a bean instances using Spring DI and execute service method = loosely coupled design

		// Values assigned to message can be controlled in xml file without changing code here
		Message msg2 = appContext.getBean("message", Message.class);

		// GreetingService implementation class can be changed in xml file without impacting below client code
		GreetingService greeting1 = (GreetingService) appContext.getBean("greetingService");
		greeting1.sayHello(msg2);

		/**
		 * -------------- Let's try Spring bean scope - singleton vs. prototype
		 */
		GreetingService greeting2 = (GreetingService) appContext.getBean("greetingService");
		GreetingService greeting3 = (GreetingService) appContext.getBean("greetingService");
		if(greeting2 == greeting3) {
			log.debug(greeting2 + " and " + greeting3 + " are the same bean instances"); // singleton scope
		} else {
			log.debug(greeting2 + " and " + greeting3 + " are the different bean instances");
		}

		GreetingService greeting4 = (GreetingService) appContext.getBean("greetingServicePrototype");
		GreetingService greeting5 = (GreetingService) appContext.getBean("greetingServicePrototype");
		if(greeting4 == greeting5) {
			log.debug(greeting4 + " and " + greeting5 + " are the same bean instances");
		} else {
			log.debug(greeting4 + " and " + greeting5 + " are the different bean instances"); // prototype scope
		}
	}

}


text:
#ifdef FCM_ALIGNMENT
    #pragma pack(push, FCMAlign, FCM_ALIGNMENT)
#endif


text:
package com.phloc.commons.name;

import java.util.Locale;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import com.phloc.commons.compare.AbstractCollationComparator;
import com.phloc.commons.compare.ESortOrder;

/**
 * This is a collation {@link java.util.Comparator} for objects that implement
 * the {@link IHasDisplayText} interface.
 *
 * @author Philip Helger
 * @param <DATATYPE>
 *        The type of elements to be compared.
 */
public final class ComparatorHasDisplayText <DATATYPE extends IHasDisplayText> extends
                                                                               AbstractCollationComparator <DATATYPE>
{
  private final Locale m_aContentLocale;

  /**
   * Constructor.
   *
   * @param aSortLocale
   *        The locale to be used for sorting. May be null.
   * @param aContentLocale
   *        The locale to be used to retrieve the display text of an object. May
   *        not be null.
   */
  public ComparatorHasDisplayText (@Nullable final Locale aSortLocale, @Nonnull final Locale aContentLocale)
  {
    this (aSortLocale, aContentLocale, ESortOrder.DEFAULT);
  }

  /**
   * Constructor.
   *
   * @param aSortLocale
   *        The locale to be used for sorting. May be null.
   * @param aContentLocale
   *        The locale to be used to retrieve the display text of an object. May
   *        not be null.
   * @param eSortOrder
   *        The sort order to be used. May not be null.
   */
  public ComparatorHasDisplayText (@Nullable final Locale aSortLocale,
                                   @Nonnull final Locale aContentLocale,
                                   @Nonnull final ESortOrder eSortOrder)
  {
    super (aSortLocale, eSortOrder);
    if (aContentLocale == null)
      throw new NullPointerException ("contentLocale");
    m_aContentLocale = aContentLocale;
  }

  @Override
  protected String asString (final DATATYPE aObject)
  {
    return aObject.getDisplayText (m_aContentLocale);
  }
}


text:
namespace cpp3ds
{
////////////////////////////////////////////////////////////
SoundBuffer::SoundBuffer() :
m_duration()
{
}

////////////////////////////////////////////////////////////
SoundBuffer::SoundBuffer(const SoundBuffer& copy) :
m_samples (copy.m_samples),
m_duration(copy.m_duration),
m_sounds  () // don't copy the attached sounds
{
    // Update the internal buffer with the new samples
    update(copy.getChannelCount(), copy.getSampleRate());
}

////////////////////////////////////////////////////////////
SoundBuffer::~SoundBuffer()
{
    // To prevent the iterator from becoming invalid, move the entire buffer to another
    // container. Otherwise calling resetBuffer would result in detachSound being
    // called which removes the sound from the internal list.
    SoundList sounds;
    sounds.swap(m_sounds);

    // Detach the buffer from the sounds that use it (to avoid OpenAL errors)
    for (SoundList::const_iterator it = sounds.begin(); it != sounds.end(); ++it)
        (*it)->resetBuffer();
}

////////////////////////////////////////////////////////////
bool SoundBuffer::loadFromFile(const std::string& filename)
{
    InputSoundFile file;
    if (file.openFromFile(filename))
        return initialize(file);
    else
        return false;
}

////////////////////////////////////////////////////////////
bool SoundBuffer::loadFromMemory(const void* data, std::size_t sizeInBytes)
{
    InputSoundFile file;
    if (file.openFromMemory(data, sizeInBytes))
        return initialize(file);
    else
        return false;
}

////////////////////////////////////////////////////////////
bool SoundBuffer::loadFromStream(InputStream& stream)
{
    InputSoundFile file;
    if (file.openFromStream(stream))
        return initialize(file);
    else
        return false;
}

////////////////////////////////////////////////////////////
bool SoundBuffer::loadFromSamples(const Int16* samples, Uint64 sampleCount, unsigned int channelCount, unsigned int sampleRate)
{
	if (samples && sampleCount && channelCount && sampleRate)
	{
        m_samples.resize(sampleCount);
		// Copy the new audio samples
		m_samples.assign(samples, samples + sampleCount);

		// Update the internal buffer with the new samples
		return update(channelCount, sampleRate);
	}
	else
	{
		// Error...
		err() << "Failed to load sound buffer from samples ("
		<< "array: "      << samples      << ", "
		<< "count: "      << sampleCount  << ", "
		<< "channels: "   << channelCount << ", "
		<< "samplerate: " << sampleRate   << ")"
		<< std::endl;

		return false;
	}
}

////////////////////////////////////////////////////////////
bool SoundBuffer::saveToFile(const std::string& filename) const
{
    // Create the sound file in write mode
    OutputSoundFile file;
    if (file.openFromFile(filename, getSampleRate(), getChannelCount()))
    {
        // Write the samples to the opened file
        file.write(&m_samples[0], m_samples.size());

        return true;
    }
    else
    {
        return false;
    }
}

////////////////////////////////////////////////////////////
const Int16* SoundBuffer::getSamples() const
{
    return m_samples.empty() ? NULL : &m_samples[0];
}

////////////////////////////////////////////////////////////
Uint64 SoundBuffer::getSampleCount() const
{
    return m_samples.size();
}

////////////////////////////////////////////////////////////
unsigned int SoundBuffer::getSampleRate() const
{
	return m_sampleRate;
}

////////////////////////////////////////////////////////////
unsigned int SoundBuffer::getChannelCount() const
{
    return m_channelCount;
}

////////////////////////////////////////////////////////////
Time SoundBuffer::getDuration() const
{
    return m_duration;
}

////////////////////////////////////////////////////////////
SoundBuffer& SoundBuffer::operator =(const SoundBuffer& right)
{
    SoundBuffer temp(right);

    std::swap(m_samples,      temp.m_samples);
    std::swap(m_duration,     temp.m_duration);
    std::swap(m_channelCount, temp.m_channelCount);
    std::swap(m_sampleRate,   temp.m_sampleRate);
    std::swap(m_sounds,       temp.m_sounds); // swap sounds too, so that they are detached when temp is destroyed

    return *this;
}

////////////////////////////////////////////////////////////
bool SoundBuffer::initialize(InputSoundFile& file)
{
    // Retrieve the sound parameters
    Uint64       sampleCount  = file.getSampleCount();
    unsigned int channelCount = file.getChannelCount();
    unsigned int sampleRate   = file.getSampleRate();

	// Read the samples from the provided file
	m_samples.resize(static_cast<std::size_t>(sampleCount));
	if (file.read(&m_samples[0], sampleCount) == sampleCount)
	{
		// Update the internal buffer with the new samples
		return update(channelCount, sampleRate);
	}
	else
	{
		return false;
	}
}

////////////////////////////////////////////////////////////
bool SoundBuffer::update(unsigned int channelCount, unsigned int sampleRate)
{
    // Check parameters
    if (!channelCount || !sampleRate || m_samples.empty())
        return false;

    // Check if the format is valid
    if (channelCount > 2){
        err() << "Failed to load sound buffer (unsupported number of channels: " << channelCount << ")" << std::endl;
        return false;
    }

	m_channelCount = channelCount;
	m_sampleRate = sampleRate;

    // First make a copy of the list of sounds so we can reattach later
    SoundList sounds(m_sounds);

    // Detach the buffer from the sounds that use it (to avoid OpenAL errors)
    for (SoundList::const_iterator it = sounds.begin(); it != sounds.end(); ++it)
        (*it)->resetBuffer();

    // Compute the duration
    m_duration = seconds(static_cast<float>(m_samples.size()) / sampleRate / channelCount);

    // Now reattach the buffer to the sounds that use it
    for (SoundList::const_iterator it = sounds.begin(); it != sounds.end(); ++it)
        (*it)->setBuffer(*this);

    return true;
}

////////////////////////////////////////////////////////////
void SoundBuffer::attachSound(Sound* sound) const
{
    m_sounds.insert(sound);
}

////////////////////////////////////////////////////////////
void SoundBuffer::detachSound(Sound* sound) const
{
    m_sounds.erase(sound);
}

} // namespace cpp3ds