text:
package com.intellij.psi.codeStyle.arrangement;

import com.intellij.application.options.CodeStyle;
import com.intellij.lang.Language;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.editor.FoldRegion;
import com.intellij.openapi.editor.FoldingModel;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.codeStyle.arrangement.engine.ArrangementEngine;
import com.intellij.psi.codeStyle.arrangement.group.ArrangementGroupingRule;
import com.intellij.psi.codeStyle.arrangement.match.ArrangementSectionRule;
import com.intellij.psi.codeStyle.arrangement.match.StdArrangementEntryMatcher;
import com.intellij.psi.codeStyle.arrangement.match.StdArrangementMatchRule;
import com.intellij.psi.codeStyle.arrangement.model.ArrangementAtomMatchCondition;
import com.intellij.psi.codeStyle.arrangement.model.ArrangementMatchCondition;
import com.intellij.psi.codeStyle.arrangement.std.*;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Order.KEEP;

/**
 * @author Denis Zhdanov
 * @since 20.07.2012
 */
public abstract class AbstractRearrangerTest extends LightPlatformCodeInsightFixtureTestCase {
  private static final RichTextHandler[] RICH_TEXT_HANDLERS = {new RangeHandler(), new FoldingHandler()};
  private static final Pattern ATTRIBUTE_PATTERN = Pattern.compile("([^\\s]+)=([^\\s]+)");

  protected FileType fileType;
  protected Language language;

  @NotNull
  protected CommonCodeStyleSettings getCommonSettings() {
    return CodeStyle.getSettings(myFixture.getProject()).getCommonSettings(language);
  }

  protected static ArrangementSectionRule section(@NotNull StdArrangementMatchRule... rules) {
    return section(null, null, rules);
  }

  protected static ArrangementSectionRule section(@Nullable String start, @Nullable String end, @NotNull StdArrangementMatchRule... rules) {
    return ArrangementSectionRule.create(start, end, rules);
  }

  protected static StdArrangementRuleAliasToken alias(@NotNull String id, @NotNull StdArrangementMatchRule... rules) {
    return new StdArrangementRuleAliasToken(id, id, ContainerUtil.newArrayList(rules));
  }

  @NotNull
  protected static ArrangementGroupingRule group(@NotNull ArrangementSettingsToken type) {
    return group(type, KEEP);
  }

  @NotNull
  protected static ArrangementGroupingRule group(@NotNull ArrangementSettingsToken type, @NotNull ArrangementSettingsToken order) {
    return new ArrangementGroupingRule(type, order);
  }

  @NotNull
  protected static StdArrangementMatchRule rule(@NotNull ArrangementSettingsToken token) {
    return new StdArrangementMatchRule(new StdArrangementEntryMatcher(atom(token)));
  }

  @NotNull
  protected static StdArrangementMatchRule nameRule(@NotNull String nameFilter, @NotNull ArrangementSettingsToken... tokens) {
    if (tokens.length == 0) {
      return new StdArrangementMatchRule(new StdArrangementEntryMatcher(atom(nameFilter)));
    }
    else {
      ArrangementAtomMatchCondition[] conditions = new ArrangementAtomMatchCondition[tokens.length + 1];
      conditions[0] = atom(nameFilter);
      for (int i = 0; i < tokens.length; i++) conditions[i + 1] = atom(tokens[i]);
      ArrangementMatchCondition compositeCondition = ArrangementUtil.combine(conditions);
      return new StdArrangementMatchRule(new StdArrangementEntryMatcher(compositeCondition));
    }
  }

  @NotNull
  protected static StdArrangementMatchRule rule(@NotNull ArrangementSettingsToken... conditions) {
    return rule(ContainerUtil.map(conditions, it -> atom(it)));
  }

  @NotNull
  protected static StdArrangementMatchRule rule(@NotNull List<ArrangementAtomMatchCondition> conditions) {
    return rule(conditions.toArray(new ArrangementAtomMatchCondition[0]));
  }

  @NotNull
  protected static StdArrangementMatchRule rule(@NotNull ArrangementAtomMatchCondition... conditions) {
    ArrangementMatchCondition compositeCondition = ArrangementUtil.combine(conditions);
    return new StdArrangementMatchRule(new StdArrangementEntryMatcher(compositeCondition));
  }

  @NotNull
  protected static StdArrangementMatchRule ruleWithOrder(@NotNull ArrangementSettingsToken orderType, @NotNull StdArrangementMatchRule rule) {
    return new StdArrangementMatchRule(rule.getMatcher(), orderType);
  }

  @NotNull
  protected static ArrangementAtomMatchCondition atom(@NotNull ArrangementSettingsToken token) {
    return new ArrangementAtomMatchCondition(token);
  }

  protected static ArrangementAtomMatchCondition atom(@NotNull ArrangementSettingsToken token, boolean included) {
    return new ArrangementAtomMatchCondition(token, included);
  }

  @NotNull
  protected static ArrangementAtomMatchCondition atom(@NotNull String nameFilter) {
    return new ArrangementAtomMatchCondition(StdArrangementTokens.Regexp.NAME, nameFilter);
  }

  protected void doTest(@NotNull Map<String, ?> args) {
    String text = (String)args.get("initial");
    String expected = (String)args.get("expected");
    @SuppressWarnings("unchecked") List<TextRange> ranges = (List<TextRange>)args.get("ranges");

    Info info = parse(text);
    if (!isEmpty(ranges) && !isEmpty(info.ranges)) {
      fail("Duplicate ranges set: explicit: " + ranges + ", " + "derived: " + info.ranges + ", text:\n" + text);
    }
    if (isEmpty(info.ranges)) {
      info.ranges = !isEmpty(ranges) ? ranges : Collections.singletonList(TextRange.from(0, text.length()));
    }

    myFixture.configureByText(fileType, info.text);

    final FoldingModel foldingModel = myFixture.getEditor().getFoldingModel();
    for (final FoldingInfo foldingInfo : info.foldings) {
      foldingModel.runBatchFoldingOperation(() -> {
        FoldRegion region = foldingModel.addFoldRegion(foldingInfo.start, foldingInfo.end, foldingInfo.placeholder);
        if (region != null) region.setExpanded(false);
      });
    }

    @SuppressWarnings("unchecked") List<ArrangementGroupingRule> groupingRules = (List<ArrangementGroupingRule>)args.get("groups");
    if (groupingRules == null) groupingRules = Collections.emptyList();

    List<?> rules = (List<?>)args.get("rules");
    List<ArrangementSectionRule> sectionRules = getSectionRules(rules);

    @SuppressWarnings("unchecked")
    List<StdArrangementRuleAliasToken> aliases = (List<StdArrangementRuleAliasToken>)args.get("aliases");
    CommonCodeStyleSettings settings = CodeStyle.getSettings(myFixture.getProject()).getCommonSettings(language);
    final StdArrangementSettings arrangementSettings =
      aliases == null ?
      new StdArrangementSettings(groupingRules, sectionRules) :
      new StdArrangementExtendableSettings(groupingRules, sectionRules, aliases);
    settings.setArrangementSettings(arrangementSettings);
    ArrangementEngine engine = ServiceManager.getService(myFixture.getProject(), ArrangementEngine.class);
    CommandProcessor.getInstance().executeCommand(getProject(), ()-> engine.arrange(myFixture.getEditor(), myFixture.getFile(), info.ranges), null, null);

    // Check expectation.
    Info after = parse(expected);
    assertEquals(after.text, myFixture.getEditor().getDocument().getText());
    for (FoldingInfo it : after.foldings) {
      FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(it.start);
      assertNotNull("Expected to find fold region at offset " + it.start, foldRegion);
      assertEquals(it.end, foldRegion.getEndOffset());
    }
  }

  protected List<ArrangementSectionRule> getSectionRules(List<?> rules) {
    List<ArrangementSectionRule> sectionRules = Collections.emptyList();
    if (rules != null) sectionRules = ContainerUtil.map(rules, (Function<Object, ArrangementSectionRule>)o -> o instanceof ArrangementSectionRule ? (ArrangementSectionRule)o : ArrangementSectionRule.create((StdArrangementMatchRule)o));
    return sectionRules;
  }

  private static boolean isEmpty(Collection<?> collection) {
    return collection == null || collection.isEmpty();
  }

  @NotNull
  private static Info parse(@NotNull String text) {
    Info result = new Info();
    StringBuilder buffer = new StringBuilder(text);

    int offset = 0;
    while (offset < buffer.length()) {
      RichTextHandler handler = null;
      int richTextMarkStart = -1;
      for (RichTextHandler h : RICH_TEXT_HANDLERS) {
        int i = buffer.indexOf("<" + h.getMarker(), offset);
        if (i >= 0 && (handler == null || i < richTextMarkStart)) {
          richTextMarkStart = i;
          handler = h;
        }
      }
      if (handler == null) break;

      String marker = handler.getMarker();
      int attrStart = richTextMarkStart + marker.length() + 1;
      int openingTagEnd = buffer.indexOf(">", richTextMarkStart);
      int openTagLength = openingTagEnd - richTextMarkStart + 1;
      Map<String, String> attributes = parseAttributes(buffer.substring(attrStart, openingTagEnd));

      String closingTag = "</" + marker + ">";
      int closingTagStart = buffer.indexOf(closingTag);
      assert closingTagStart > 0;

      handler.handle(result, attributes, richTextMarkStart, closingTagStart - openTagLength);
      buffer.delete(closingTagStart, closingTagStart + closingTag.length());
      buffer.delete(richTextMarkStart, openingTagEnd + 1);
      offset = closingTagStart - openTagLength;
    }

    result.text = buffer.toString();
    return result;
  }

  @NotNull
  private static Map<String, String> parseAttributes(@NotNull String text) {
    if (text.isEmpty()) return Collections.emptyMap();
    Matcher matcher = ATTRIBUTE_PATTERN.matcher(text);
    Map<String, String> result = ContainerUtil.newLinkedHashMap();
    while (matcher.find()) result.put(matcher.group(1), matcher.group(2));
    return result;
  }
}


text:
package be.fror.password.rule;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import be.fror.common.function.MoreCollectors;
import be.fror.common.function.Suppliers;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Chars;

import java.util.Arrays;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Supplier;

import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.NotThreadSafe;
import javax.annotation.concurrent.ThreadSafe;

/**
 *
 * @author Olivier Grégoire <fror@users.noreply.github.com>
 */
@ThreadSafe
@Immutable
public final class Ruler {

  /**
   * Factory method to easily create a new <tt>Ruler</tt> with all the rules given as parameter.
   *
   * @param rules the rules to create the ruler with.
   * @return a new <tt>Ruler</tt> using each <tt>Rule</tt> of <tt>rules</tt>.
   */
  public static Ruler createFromRules(Iterable<Rule> rules) {
    return new Builder().addRules(rules).build();
  }

  @VisibleForTesting
  final ImmutableSet<Rule> rules;

  private final Supplier<Generator> generator;

  @VisibleForTesting
  Ruler(Builder builder) {
    this.rules = builder.rules.build();
    this.generator = Suppliers.memoize(this::createGenerator);
  }

  /**
   * Validates the password according to the defined rules and aggregates their result in a
   * <tt>{@link RuleResult}</tt>.
   *
   * @param password the password to validatePassword
   * @return the result of the validation
   */
  public RuleResult validatePassword(final String password) {
    checkNotNull(password, "password must not be null");
    final Password pwd = new Password(password);
    final RuleResult.FailedResult failedResult = RuleResult.failed();
    boolean failed = false;
    for (Rule rule : this.rules) {
      final RuleResult result = rule.validate(pwd);
      if (!result.isValid()) {
        failed = true;
        failedResult.addFailures(result.getFailures());
      }
    }
    if (failed) {
      return failedResult;
    } else {
      return RuleResult.ok();
    }
  }

  /**
   * Generates a password of length <tt>length</tt> using <tt>random</tt>.
   *
   * @param length the length of the password to generate
   * @param random the random number generator to use to generate the password
   * @return A password valid according the provided character rules.
   * @throws IllegalArgumentException if <tt>length <= 0</tt>
   * @throws IllegalStateException if no <tt>CharacterRule</tt> were provided when creating this
   * ruler.
   */
  public String generatePassword(final int length, final Random random) {
    final Generator gen = this.generator.get();
    checkArgument(length >= gen.minLength, "length (%s) must be greater than %s given the CharacterRules provided", length, gen.minLength);
    checkNotNull(random, "random must not be null");
    return gen.generate(length, random);
  }

  private Generator createGenerator() {
    final ImmutableSet<CharacterRule> charRules = rules.stream()
        .filter(e -> e instanceof CharacterRule)
        .map(e -> (CharacterRule) e)
        .collect(MoreCollectors.toImmutableSet());
    checkState(!charRules.isEmpty(), "No CharacterRule were added to this Ruler");
    Set<Character> uniqueChars = new TreeSet<>();
    int minLen = 0;
    for (CharacterRule rule : charRules) {
      for (char c : rule.getValidCharacters().toCharArray()) {
        uniqueChars.add(c);
      }
      minLen += rule.getNumberOfCharacters();
    }
    return new Generator(charRules, Chars.toArray(uniqueChars), minLen);
  }

  class Generator {

    final ImmutableSet<CharacterRule> rules;
    final char[] allChars;
    final int minLength;

    Generator(ImmutableSet<CharacterRule> rules, char[] allChars, int minLength) {
      this.rules = rules;
      this.allChars = allChars;
      this.minLength = minLength;
    }

    String generate(int length, Random random) {
      final char[] password = new char[length];
      int offset = 0;

      // Add mandatory characters
      for (CharacterRule rule : rules) {
        final String source = rule.getValidCharacters();
        for (int i = 0, l = rule.getNumberOfCharacters(); i < l; i++) {
          password[offset++] = source.charAt(random.nextInt(source.length()));
        }
      }

      // Add to match length
      while (offset < length) {
        password[offset++] = allChars[random.nextInt(allChars.length)];
      }

      // Shuffle the charaters // What? No Arrays.shuffle??
      for (int i = password.length - 1; i > 0; i--) {
        final int pos = random.nextInt(i + 1);
        final char swap = password[pos];
        password[pos] = password[i];
        password[i] = swap;
      }

      return new String(password);
    }
  }

  /**
   * The builder class for Ruler.
   *
   *

   * The rules of the <tt>Ruler</tt> are ordered in the order they were added in this Builder.
   *
   *

   * The methods are chained, meaning that it is possible to create a
   * <tt>Ruler</tt> like this:
   *
   *

   * Ruler ruler = new Ruler.Builder()
   *   .addRule(firstRule)
   *   .addRule(secondRule)
   *   .build();
   *

   */
  @NotThreadSafe
  public static class Builder {

    private boolean nonEmpty = false;
    private final ImmutableSet.Builder<Rule> rules = ImmutableSet.builder();

    /**
     * Instantiates a new <tt>Rule</tt> builder.
     */
    public Builder() {
    }

    /**
     * Adds a rule to the <tt>Ruler</tt> being built.
     *
     *

     * If two identical rules are added, only the first is retained and the other one is silently
     * not added.
     *
     * @param rule the <tt>Rule</tt> to add.
     * @return <tt>this</tt>
     */
    public Builder addRule(Rule rule) {
      this.rules.add(rule);
      this.nonEmpty = true;
      return this;
    }

    /**
     * Adds rules to the <tt>Ruler</tt> being built.
     *
     *

     * If two identical rules are added, only the first is retained and the other one is silently
     * not added.
     *
     * @param rules the <tt>Rule</tt> to add.
     * @return <tt>this</tt>
     */
    public Builder addRules(Iterable<Rule> rules) {
      boolean nonEmptyRules = rules.iterator().hasNext();
      this.rules.addAll(rules);
      this.nonEmpty |= nonEmptyRules;
      return this;
    }

    /**
     * Creates a new <tt>Ruler</tt> with all the rules that were add to
     * <tt>this</tt>.
     *
     * @return a new ruler containing the rules
     * @throws IllegalStateException if no rule were added to <tt>this</tt>.
     */
    public Ruler build() {
      checkState(this.nonEmpty, "No rules were added to this builder");
      return new Ruler(this);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace backend\controllers;

use Yii;
use backend\models\ClubBooking;
use backend\models\ClubBookingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;

/**
 * ClubBookingController implements the CRUD actions for ClubBooking model.
 */
class ClubBookingController extends Controller
{
    public function behaviors()
    {
        return [
             'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                         'actions' => [],
                        'allow' => true,
                        'roles' => ['@'],

                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all ClubBooking models.
     * @return mixed
     */
    public function actionIndex()
    {
        $userinfo=  \yii::$app->user->identity;

        $searchModel = new ClubBookingSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $userinfo=  Yii::$app->user->identity;
        $clubName=  \backend\models\Club::findOne($userinfo['club_id']);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'clubName'=>$clubName

        ]);
    }

    /**
     * Displays a single ClubBooking model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $paymentModelObj=new \backend\models\BookingPaymentHistory();
        $paymentModel=$paymentModelObj->getPaymentHistory($id);
       // var_dump($paymentModel);die;
        return $this->render('view', [
            'model' => $this->findModel($id),
            'paymentModel'=>$paymentModel
        ]);
    }

    /**
     * Creates a new ClubBooking model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ClubBooking();

        $userinfo=Yii::$app->user->identity;
        $utilsObj=new \common\models\Utils();
        $model->pa_pnr=$utilsObj->randomString();
        $model->booked_type=1;
        $model->user_id=$userinfo['id'];
        $model->created_at=date("Y-m-d H:i:s");
        $model->updated_at=date("Y-m-d H:i:s");
        $model->in_confirm=0;
        $model->price_of_girl=0;
        $model->price_of_couple=0;
        $model->price_of_stage=0;
        $model->no_of_boys=0;
        $model->no_of_girls=0;
        if($userinfo['role_id']==5)
        {
           $model->club_id=$userinfo['club_id'];
           $clubDetails=  \backend\models\Club::findOne($userinfo['club_id']);
           $model->commission=$clubDetails->commission;
           $model->commission_rate=$clubDetails->commission_rate;
           $model->tax_rate=$clubDetails->tax_rate;
           $model->convenience_fee=$clubDetails->convenience_fee;

        }

        $bookingnameModelObj=new \backend\models\ClubBookingNames();
        $paymentModelObj=new \backend\models\BookingPaymentHistory();

        if($model->load(Yii::$app->request->post()) ) {

          // var_dump($model->booking_category);die;
             $session = Yii::$app->session;

             $arr_booking_data['c_id']=$userinfo['club_id'];
             $arr_booking_data['txt_datepicker']=$model->booking_date;
             $arr_booking_data['b_type']=  strtolower($model->booking_category);
             $arr_booking_data['popup_drop_boys']=$model->no_of_boys;
             $arr_booking_data['popup_drop_girls']=$model->no_of_girls;

             //var_dump($arr_booking_data);die;
             $session['booking_data']=$arr_booking_data;

            if (isset($arr_booking_data['c_id']))
            {
                $c_id = $arr_booking_data['c_id'];
                $obj_club = new \backend\models\Club();
                $obj_club_info = \backend\models\Club::findOne($c_id);
                //echo $obj_club->getCurentClubAvailableCapacity($c_id);
                //print_r($arr_booking_data);
                //die;
                if ($obj_club->getCurentClubAvailableCapacity($c_id,$arr_booking_data['txt_datepicker']) > 0)
                    return $this->render('confirm', array('obj_club_info' => $obj_club_info,'session'=>$session));
                else
                    return $this->render('confirm', array('obj_club_info' => $obj_club_info, 'is_full' => 1,'session'=>$session));
            }

            $model->save();
            return $this->redirect(['index', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'bookingnameModelObj'=>$bookingnameModelObj,
                'paymentModelObj'=>$paymentModelObj
            ]);
        }
    }

    /**
     * Updates an existing ClubBooking model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ClubBooking model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ClubBooking model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ClubBooking the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ClubBooking::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

     public function actionGetratebydate()
    {
		$connection = \Yii::$app->db;
		$return_array = array();
		$currdate = isset($_REQUEST['currdate']) ? $_REQUEST['currdate'] : '';
		$c_id = isset($_REQUEST['c_id']) ? $_REQUEST['c_id'] : '';
		if($currdate !='' && $c_id !='')
		{
			$currdate = date("Y-m-d", strtotime($currdate));

			$model = $connection->createCommand('select
			CASE
				WHEN b.rate_date IS Not NULL THEN b.boy_rate
			ELSE
				c.booking_rate_boy
			END as boy,
			CASE
				WHEN b.rate_date IS Not NULL THEN b.girl_rate
			ELSE
				c.booking_rate_ladies
			END as girl,
			CASE
				WHEN b.rate_date IS Not NULL THEN b.couple_rate
			ELSE
				c.booking_rate_couple
			END as couple
			from club c
			left join booking_rate_asdate b on b.club_id = c.id and b.rate_date = "'.$currdate.'"
			where c.id = '.$c_id.' limit 0,1
			');

			$arr_result = $model->queryAll();
			$arr_city = array();
			$return_array = $arr_result[0];
                        echo $return_array['boy']."##".$return_array['girl']."##".$return_array['couple'] ;
			//echo json_encode($return_array);
			die;
		}
		else
		{
			$model = $connection->createCommand('select
			c.booking_rate_boy as boy,c.booking_rate_ladies as girl, c.booking_rate_couple as couple
			from club c
			where c.id = '.$c_id.' limit 0,1
			');

			$arr_result = $model->queryAll();
			$arr_city = array();
			$return_array = $arr_result[0];
                        echo $return_array['boy']."##".$return_array['girl']."##".$return_array['couple'] ;
			//echo json_encode($return_array);
			die;
		}
    }
    public function actionProcessorder()
    {

        $session = Yii::$app->session;
    	$arr_booking_data = $session['booking_data'];
       // var_dump($arr_booking_data);die;
		$connection = \Yii::$app->db;

		if(isset($arr_booking_data['c_id'])) {
			$c_id = $arr_booking_data['c_id'];
			$obj_club = new \backend\models\Club();
			$obj_club_info = \backend\models\Club::findOne($c_id);
			$arr_return = array();
			if($obj_club->getCurentClubAvailableCapacity($c_id,$arr_booking_data['txt_datepicker']) == 0 ) {
				$arr_return['status'] = false;
				echo json_encode($arr_return);
				die;
			}
			else
			{
				$model = new \backend\models\ClubBooking();

				$model->club_id = $c_id;

				$utilsModel=new \common\models\Utils();
				$pnr  = $utilsModel->randomString(10);

				$model->pa_pnr = $pnr;
				if(isset($session['is_guest'])) {
					$b_type = 1;
					$model->booked_type = $b_type;
					$model->user_id = $session['user_id'];
				}
				else {
					$b_type = 0;
					$model->booked_type = $b_type;
					$model->user_id = Yii::$app->user->id;
				}

				$price_model = $connection->createCommand('select
				CASE
					WHEN b.rate_date IS Not NULL THEN b.boy_rate
				ELSE
					c.booking_rate_boy
				END as boy,
				CASE
					WHEN b.rate_date IS Not NULL THEN b.girl_rate
				ELSE
					c.booking_rate_ladies
				END as girl,
				CASE
					WHEN b.rate_date IS Not NULL THEN b.couple_rate
				ELSE
					c.booking_rate_couple
				END as couple
				from club c
				left join booking_rate_asdate b on b.club_id = c.id and b.rate_date = "'.date("Y-m-d H:i:s",strtotime($arr_booking_data['txt_datepicker'])).'"
				where c.id = '.$c_id.' limit 0,1
				');
				$price_result = $price_model->queryAll();
				$price_array = $price_result[0];

				$model->price_of_girl = $price_array['girl'];
				$model->price_of_stage = $price_array['boy'];
				$model->price_of_couple = $price_array['couple'];

				$model->booking_category = ucfirst($arr_booking_data['b_type']);
				if(strtolower($arr_booking_data['b_type']) == 'group')
				{
					$model->no_of_girls = $arr_booking_data['popup_drop_girls'];
					$model->no_of_boys = $arr_booking_data['popup_drop_boys'];
				}else if(strtolower($arr_booking_data['b_type']) == 'girl')
                                {
                                    $model->no_of_girls = 1;
                                }else if(strtolower($arr_booking_data['b_type']) == 'boy')
                                {
                                    $model->no_of_boys = 1;
                                }else if(strtolower($arr_booking_data['b_type']) == 'couple')
                                {
                                    $model->no_of_boys = 1;
                                    $model->no_of_girls =1;
                                }

				$club_chagres = 0;
                                if($arr_booking_data['b_type'] == 'boy')
					$club_chagres = $price_array['boy'];
				if($arr_booking_data['b_type'] == 'girl')
					$club_chagres = $price_array['girl'];
				if($arr_booking_data['b_type'] == 'couple')
					$club_chagres = $price_array['couple'];
				if($arr_booking_data['b_type'] == 'group')
				{
					if($arr_booking_data['popup_drop_boys'] < $arr_booking_data['popup_drop_girls']) {
						$only_girls = $arr_booking_data['popup_drop_girls'] - $arr_booking_data['popup_drop_boys'];
						$couple = $arr_booking_data['popup_drop_boys'];
						$couples_rates = $price_array['couple'] * $couple;
						$club_chagres = $only_girls * $price_array['girl'];
						$club_chagres = $club_chagres + $couples_rates;
					}
					else {
						$only_boys = $arr_booking_data['popup_drop_boys'] - $arr_booking_data['popup_drop_girls'];
						$couple = $arr_booking_data['popup_drop_girls'];
						$couples_rates = $price_array['couple'] * $couple;
						$club_chagres = $only_boys * $price_array['boy'];
						$club_chagres = $club_chagres + $couples_rates;
					}
				}
				$convienice_charges = $obj_club_info->convenience_fee;
				$tax_charges = ($club_chagres * $obj_club_info->tax_rate) / 100;
				$gross_total = $club_chagres + $tax_charges + $convienice_charges;
				$model->tax_rate = $tax_charges ;
				$commission_rate = 0;
				$model->commission_rate = 0;
				$commission = 'Percentage';
				$model->commission = $commission;

				$model->convenience_fee = $convienice_charges;

				$model->total_price = $gross_total;
				$model->booking_date = date("Y-m-d H:i:s",strtotime($arr_booking_data['txt_datepicker']));
				$in_confirm = 0;
				//$model->in_confirm = 0;
				$model->created_at = date("Y-m-d H:i:s");
                                //var_dump($_REQUEST);die;
                                $param=Yii::$app->request->post();
				if($model->save()){
					$order_id = $model->id;

					$p=0;
					foreach ($param['booking_person'] as $name) {

						$modelClubBookingNames = new \backend\models\ClubBookingNames();

						if(isset($param['booking_person_mobile'][$p])) {
							$phone	= $param['booking_person_mobile'][$p];
							$modelClubBookingNames->mobile_no = $phone;
						}
                                                if(isset($param['booking_person_email'][$p])) {
							$email	= $param['booking_person_email'][$p];
							$modelClubBookingNames->email = $email;
						}

						$modelClubBookingNames->club_booking_id = $order_id;
						$modelClubBookingNames->booking_name = $name;

						$modelClubBookingNames->created_at = date("Y-m-d H:i:s");
						if($modelClubBookingNames->save())
							$p++;
					}

					$modelBookingPaymentHistory = new \backend\models\BookingPaymentHistory();
					$raw_request ="processorder";//rand(1,100000);
					$modelBookingPaymentHistory->booking_id = $order_id;

					$modelBookingPaymentHistory->amount = $gross_total;

					$modelBookingPaymentHistory->raw_request = $raw_request;

					if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
						$ip = $_SERVER['HTTP_CLIENT_IP'];
					} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
						$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
					} else {
						$ip = $_SERVER['REMOTE_ADDR'];
					}

					$modelBookingPaymentHistory->customer_ip = $ip;
					$modelBookingPaymentHistory->created_at = date("Y-m-d H:i:s");

					if($modelBookingPaymentHistory->save())
					{

						$bookingCapacityAsdateModels = \backend\models\BookingCapacityAsdate::find()->asArray()->where(['club_id'=>$c_id,'capacity_active_date'=>date("Y-m-d",strtotime($arr_booking_data['txt_datepicker']))])->all();

						if(count($bookingCapacityAsdateModels) == 0) {
							$query_bookingCapacityAsdateModels = $connection->createCommand("insert into booking_capacity_asdate (`id`,`club_id`,`booking_capacity`,`capacity_active_date`,`created_at`,`no_of_booking`) values ('NULL',".$c_id.",".$obj_club_info->booking_capacity.",'".date("Y-m-d",strtotime($arr_booking_data['txt_datepicker']))."','".date("Y-m-d")."',1);");
							$query_bookingCapacityAsdateModels->execute();
						}
						else
						{
							$query_bookingCapacityAsdateModels = $connection->createCommand("update booking_capacity_asdate set `no_of_booking` = `no_of_booking` +1 where club_id = ".$c_id." and capacity_active_date= '".date("Y-m-d",strtotime($arr_booking_data['txt_datepicker']))."'");
							$query_bookingCapacityAsdateModels->execute();
						}

						$arr_return['status'] = true;
						$arr_return['pnr'] = $pnr;
						//Site order process and dorward to payment
						//if(Yii::$app->params['is_local']) {
							 $arr_return['b_id'] = $order_id;
							 echo json_encode($arr_return);
							die;
						/*}
                                                else {
							$api = new \frontend\models\Instamojo('971542dda81fa94a308b13a07465194e', '20587eb9956553694f7159b29fd7b728');
				            try {
		                    	$response = $api->linkCreate(array(
		                        'title'=>'Party Animals',
		                        'description'=>'Party Animals Ticket Booking',
		                        'base_price'=>$gross_total,
		                        'cover_image'=>'/path/to/photo.jpg',
		                        'redirect_url' => 'http://partyanimals.in/beta/backend/web/index.php?r=club-booking/thankyou&b_id='.$order_id
		                        ));

		                    	$arr_return['url'] = $response["url"];
								echo json_encode($arr_return);
								die;

			                }
			                catch (Exception $e) {
			                    print('Error: ' . $e->getMessage());
			                }
			        	}*/
                                        }else{
                                            var_dump($modelBookingPaymentHistory->errors);die;
                                        }

				}
				else {
					print_r($model);
					echo "Order not created";
					die;
				}
				//echo "prashant";
			}

			die;
		}
		else
		{
			$this->redirect("index.php");
		}
	}

    public function actionThankyou() {

        $subject="Confirm Booking";
        $session = Yii::$app->session;
        $arr_booking_data = $session['booking_data'];
        $userinfo=\Yii::$app->user->identity;
        $booking_id=  \Yii::$app->request->get('b_id');
        //var_dump(Yii::$app->request->post());die;
        if(isset($arr_booking_data['phone']))
        {
        $param['mobile_no']=$arr_booking_data['phone'];
        }else if(isset($userinfo['id']))
        {
        	$profile=\backend\models\Profile::find()->where(['user_id'=>$userinfo['id']])->one();
        	$param['mobile_no']=$profile->phone_no;
        }

        $param['subject']=$subject;
        if(isset($arr_booking_data['email']))
        {
            $param['email']=$arr_booking_data['email'];

        }else if(isset($userinfo['id']))
        {
               $useridentity=  \Yii::$app->user->identity;
        	$param['email']=  $useridentity['email'];
        }
        $clubObj=  \backend\models\Club::findOne( $arr_booking_data['c_id']);
        $clubbooking=  ClubBooking::find()->select('pa_pnr')->where(["id"=>$booking_id])->asArray()->one();
        $param['club_name']= $clubObj->name ;
        $param['booking_date']=$arr_booking_data['txt_datepicker'];
        $param['booking_type']=$arr_booking_data['b_type'];
        //$pnr=  Yii::$app->request->get('pnr');
        $param['pnr']=$clubbooking['pa_pnr'];
        $view="orderconfirm";
        $utilsobj=new \common\models\Utils;
        //get booking user details
        //echo $booking_id;die;
        $bookingnames=  \backend\models\ClubBookingNames::find()->where(["club_booking_id"=>$booking_id])->asArray()->all();
       // var_dump($bookingnames);die;
        foreach($bookingnames as $bname)
        {
            $sendparam=array('user_name'=>$bname['booking_name'],'mobile_no'=>$bname['mobile_no'],'email'=>$bname['email'],'club_name'=>$param['club_name'],'booking_date'=>$param['booking_date'],'pnr'=>$param['pnr'],'booking_type'=>$param['booking_type']);
            if($bname['email']!="" &&  $bname['email']!=NULL)
            {
                $mailsend=$utilsobj->sendMessage($bname['email'], $param['subject'], $view, $sendparam);
            }
            $view="sms/orderconfirm";
            if($bname['mobile_no']!="" &&  $bname['mobile_no']!=NULL)
            {
                $sendsms=$utilsobj->sendSMS($bname['mobile_no'], $param['subject'], $view, $sendparam);
            }
        }

        return $this->render('thankyou',['param'=>$param]);
    }

}


text:
/*
 * Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.EC2.Model
{
    /// <summary>
    /// Describes a conversion task.
    /// </summary>
    public partial class ConversionTask
    {
        private string _conversionTaskId;
        private string _expirationTime;
        private ImportInstanceTaskDetails _importInstance;
        private ImportVolumeTaskDetails _importVolume;
        private ConversionTaskState _state;
        private string _statusMessage;
        private List<Tag> _tags = new List<Tag>();

        /// <summary>
        /// Gets and sets the property ConversionTaskId.
        /// <para>
        /// The ID of the conversion task.
        /// </para>
        /// </summary>
        public string ConversionTaskId
        {
            get { return this._conversionTaskId; }
            set { this._conversionTaskId = value; }
        }

        // Check to see if ConversionTaskId property is set
        internal bool IsSetConversionTaskId()
        {
            return this._conversionTaskId != null;
        }

        /// <summary>
        /// Gets and sets the property ExpirationTime.
        /// <para>
        /// The time when the task expires. If the upload isn't complete before the expiration
        /// time, we automatically cancel the task.
        /// </para>
        /// </summary>
        public string ExpirationTime
        {
            get { return this._expirationTime; }
            set { this._expirationTime = value; }
        }

        // Check to see if ExpirationTime property is set
        internal bool IsSetExpirationTime()
        {
            return this._expirationTime != null;
        }

        /// <summary>
        /// Gets and sets the property ImportInstance.
        /// <para>
        /// If the task is for importing an instance, this contains information about the import
        /// instance task.
        /// </para>
        /// </summary>
        public ImportInstanceTaskDetails ImportInstance
        {
            get { return this._importInstance; }
            set { this._importInstance = value; }
        }

        // Check to see if ImportInstance property is set
        internal bool IsSetImportInstance()
        {
            return this._importInstance != null;
        }

        /// <summary>
        /// Gets and sets the property ImportVolume.
        /// <para>
        /// If the task is for importing a volume, this contains information about the import
        /// volume task.
        /// </para>
        /// </summary>
        public ImportVolumeTaskDetails ImportVolume
        {
            get { return this._importVolume; }
            set { this._importVolume = value; }
        }

        // Check to see if ImportVolume property is set
        internal bool IsSetImportVolume()
        {
            return this._importVolume != null;
        }

        /// <summary>
        /// Gets and sets the property State.
        /// <para>
        /// The state of the conversion task.
        /// </para>
        /// </summary>
        public ConversionTaskState State
        {
            get { return this._state; }
            set { this._state = value; }
        }

        // Check to see if State property is set
        internal bool IsSetState()
        {
            return this._state != null;
        }

        /// <summary>
        /// Gets and sets the property StatusMessage.
        /// <para>
        /// The status message related to the conversion task.
        /// </para>
        /// </summary>
        public string StatusMessage
        {
            get { return this._statusMessage; }
            set { this._statusMessage = value; }
        }

        // Check to see if StatusMessage property is set
        internal bool IsSetStatusMessage()
        {
            return this._statusMessage != null;
        }

        /// <summary>
        /// Gets and sets the property Tags.
        /// </summary>
        public List<Tag> Tags
        {
            get { return this._tags; }
            set { this._tags = value; }
        }

        // Check to see if Tags property is set
        internal bool IsSetTags()
        {
            return this._tags != null && this._tags.Count > 0;
        }

    }
}


text:
window.t = {};

//Titles
window.t['html_title_planets'] 		= "GLORIA All Sky Drawing: Planets";
window.t['html_title_meteors'] 		= "GLORIA All Sky Drawing: Meteors";
window.t['content_title'] 			= "Tracking Objects on the Night Sky";

//Information Window (Planets)
window.t['about_planets_title'] 	= "About this tool.";
window.t['about_planets_p1'] 		= "Use the slider to move between the images.";
window.t['about_planets_p2'] 		= "Double-click to mark an object, click-and-drag to move an existing mark.";
window.t['about_planets_p3'] 		= "Stars and planets move in different ways across the sky.";
//Information Window (Meteors
window.t['about_meteors_title'] 	= "About this tool.";
window.t['about_meteors_p1'] 		= "Use the slider to move between the images.";
window.t['about_meteors_p2'] 		= "Click and drag to mark streaks and lines on the image.";
window.t['about_meteors_p3'] 		= "Watch the lines build up to show the sourc eof the meteor shower.";

//Footer
window.t['component_name'] 			= "All-Sky Camera Component";
window.t['download']				= "Download";
window.t['image_source'] 			= "Image source";
window.t['bootes'] 					= "BOOTES/CASANDRA-1 (Mars)";
window.t['bayfordbury'] 			= "Bayfordbury All-Sky Camera (Jupiter)";


text:
{% extends "base.html" %}
{% load helpful_tags verbatim %}

  {% block nav %}

New Search

  {% if request.PERMISSIONS.add_allowed_tags %}

Manage Tags

  {% endif %}

Get Raw SQL for ActionKit Mailings

Get AKIDs for Actionkit Includes/Excludes

  {% endblock %}

  {% block content %}

Found: {{ num_users }} people

  Searched for people who match::

{{ human_query }}

{% replace_value of "count_submit" with "" in request.GET as search_params %}
View full results

{% endblock %}


text:
#pragma warning(disable:4355)

#include <iostream>
#include <Hydrax.h>

namespace Hydrax
{

  Hydrax::Hydrax(Ogre::SceneManager *sm, Ogre::Viewport *v)
  {
    // Initialisation
    mSceneManager = sm;
    mViewportList.insert(v);

    mCreated = false;
    mVisible = true;
    mPolygonMode = Ogre::PM_SOLID;
    mPosition = Ogre::Vector3(0, 0, 0);
    mPlanesError = 0;
    mFullReflectionDistance = 99999997952.0;
    mGlobalTransparency = 0.05;
    mWaterColor = Ogre::Vector3(0, 0.1, 0.172);
    mNormalDistortion = 0.09;
    mSunPosition = Ogre::Vector3(5000, 3000, 1);
    mSunStrength = 1.75;
    mSunArea = 150;
    mSunColor = Ogre::Vector3(1, 0.75, 0.25);
    mFoamMaxDistance = 75000000.0;
    mFoamScale = 0.0075;
    mFoamStart = 0;
    mFoamTransparency = 1;
    mDepthLimit = 0;
    mDistLimit = 0;
    mSmoothPower = 30.0f;
    mCausticsScale = 10.0f;
    mCausticsPower = 1.0f;
    mCausticsEnd = 0.55f;
    mGodRaysExposure = Ogre::Vector3(0.76, 2.46, 2.29);
    mGodRaysIntensity = 0.015;
    mUnderwaterCameraSwitchDelta = 1.25f;
    mCurrentFrameUnderwater = false;
    mMesh = new Mesh(this);
    mMaterialManager = new MaterialManager(this);
    mRttManager = new RttManager(this);
    mTextureManager = new TextureManager(this);
    mGodRaysManager = new GodRaysManager(this);
    mDecalsManager = new DecalsManager(this);
    mGPUNormalMapManager = new GPUNormalMapManager(this);
    mCfgFileManager = new CfgFileManager(this);
    mModule = 0;
    mComponents = HYDRAX_COMPONENTS_NONE;
    mTimeMultiplier = 1.0f;
    mTimeSinceLastFrame = 0.0f;
    rttVisibilityMask = 0xFFFFFFFF;
	mCamera = v->getCamera(); //mSceneManager->createCamera(Ogre::String("Hydrax/Camera"));

   /* Ogre::Camera* cam = v->getCamera();
    if (cam)
    {
      mCamera->setPosition(cam->getDerivedPosition());
      mCamera->setOrientation(cam->getDerivedOrientation());
      mCamera->setProjectionType(cam->getProjectionType());
      mCamera->setAspectRatio(cam->getAspectRatio());
      mCamera->setNearClipDistance(cam->getNearClipDistance());
      mCamera->setFarClipDistance(cam->getFarClipDistance());
      mCamera->setUseRenderingDistance(cam->getUseRenderingDistance());
      mCamera->setFOVy(cam->getFOVy());
      mCamera->setFocalLength(cam->getFocalLength());
    }*/

    mDeviceLost = false;
	mRttManager->setAutoUpdate(false);
    HydraxLOG("Hydrax created.");
  }

  Hydrax::~Hydrax()
  {
    remove();

    if (mModule)
      delete mModule;

    delete mTextureManager;
    delete mMaterialManager;
    delete mGPUNormalMapManager;
    delete mDecalsManager;
    delete mGodRaysManager;
    delete mRttManager;
    delete mCfgFileManager;
    delete mMesh;
    mSceneManager->destroyCamera(mCamera->getName());

    HydraxLOG("Hydrax object removed.");
  }

  void Hydrax::create()
  {
    if (!mModule)
    {
      HydraxLOG("Module isn't set, skipping...");
      return;
    }

    if (mCreated)
    {
      HydraxLOG("Hydrax is alredy created, skipping...");
      return;
    }

    HydraxLOG("Creating module...");
    mModule->create();
    if (mModule->getNormalMode() == MaterialManager::NM_RTT)
    {
      if (!mModule->getNoise()->createGPUNormalMapResources(mGPUNormalMapManager))
      {
        HydraxLOG(mModule->getNoise()->getName() + " doesn't support GPU Normal map generation.");
      }
    }
    else
    {
      if (mModule->getNoise()->areGPUNormalMapResourcesCreated())
      {
        mModule->getNoise()->removeGPUNormalMapResources(mGPUNormalMapManager);
      }
    }
    HydraxLOG("Module created.");

    HydraxLOG("Initializating RTT Manager...");
    mRttManager->initialize(RttManager::RTT_REFLECTION);
    mRttManager->initialize(RttManager::RTT_REFRACTION);
    if (isComponent(HYDRAX_COMPONENT_DEPTH))
    {
      mRttManager->initialize(RttManager::RTT_DEPTH);
    }
    HydraxLOG("RTT manager initialized.");

    HydraxLOG("Registring device restored listener...");
    mDeviceListener.mHydrax = this;
    Ogre::Root::getSingleton().getRenderSystem()->addListener(&mDeviceListener);
    HydraxLOG("Device restored listener registred.");

    HydraxLOG("Creating materials...");
    mMaterialManager->createMaterials(mComponents, mModule->getNormalMode());
    mMesh->setMaterialName(mMaterialManager->getMaterial(MaterialManager::MAT_WATER)->getName());
    HydraxLOG("Materials created.");

    if (isComponent(HYDRAX_COMPONENT_UNDERWATER_GODRAYS))
    {
      HydraxLOG("Creating god rays...");
      mGodRaysManager->create(mComponents);
      HydraxLOG("God rays created.");
    }

    HydraxLOG("Creating water mesh...");
    mMesh->setOptions(mModule->getMeshOptions());
    mMesh->create();
    HydraxLOG("Water mesh created.");

    mCreated = true;

    // Hide if !mVisible
    _checkVisible();

    // Registering listeners
    ViewportList::iterator iViewportSearched = mViewportList.begin();
    while (iViewportSearched != mViewportList.end())
    {
	  mMaterialManager->addCompositor((*iViewportSearched));
      (*iViewportSearched)->getTarget()->insertListener(this, 0);
      iViewportSearched++;
    }

  }

  void Hydrax::remove()
  {
    if (!mCreated)
    {
      return;
    }

    ViewportList::iterator iViewportSearched = mViewportList.begin();
    while (iViewportSearched != mViewportList.end())
    {
      (*iViewportSearched)->getTarget()->removeListener(this);
      iViewportSearched++;
    }

    Ogre::Root::getSingleton().getRenderSystem()->removeListener(&mDeviceListener);
    mMesh->remove();
    mDecalsManager->removeAll();
    mMaterialManager->removeMaterials();
    mRttManager->removeAll();
    mGodRaysManager->remove();
    mModule->remove();
    mTextureManager->remove();
    mCreated = false;
  }

  void Hydrax::setVisible(const bool& Visible)
  {
    mVisible = Visible;
    _checkVisible();
  }

  void Hydrax::_checkVisible()
  {
    if (!mCreated)
    {
      return;
    }

    if (!mVisible)
    {
      // Stop RTTs:
      mRttManager->removeAll();

      // Hide hydrax mesh
      mMesh->getSceneNode()->setVisible(false);

      // Stop compositor (MaterialManager::setCompositorEnable(...) checks if underwater compositor exists)
      mMaterialManager->setCompositorEnable(MaterialManager::COMP_UNDERWATER, false);
    }
    else
    {
      // Start reflection and refraction RTTs:
      mRttManager->initialize(RttManager::RTT_REFLECTION);
      mRttManager->initialize(RttManager::RTT_REFRACTION);

      // Start depth rtt if needed:
      if (isComponent(HYDRAX_COMPONENT_DEPTH))
      {
        mRttManager->initialize(RttManager::RTT_DEPTH);
      }

      // Start GPU normals rtt if needed:
      if (mModule->getNormalMode() == MaterialManager::NM_RTT)
      {
        mGPUNormalMapManager->create();
      }

      // Set over-water material and check for underwater:
      Ogre::MaterialPtr mat = mMaterialManager->getMaterial(MaterialManager::MAT_WATER);
      if (!mat.isNull())
        mMesh->setMaterialName(mat->getName());

      mMaterialManager->reload(MaterialManager::MAT_WATER);

      ViewportList::iterator iViewportSearched = mViewportList.begin();
      while (iViewportSearched != mViewportList.end())
      {
        Ogre::Camera* cam = (*iViewportSearched)->getCamera();
        if (cam)
          _checkUnderwater(cam, 0);

        iViewportSearched++;
      }
      mMesh->getSceneNode()->setVisible(true);
    }
  }

  void Hydrax::registerViewport(Ogre::Viewport* viewport)
  {
    ViewportList::iterator iViewportSearched = mViewportList.find(viewport);
    if (iViewportSearched == mViewportList.end())
    {
      mViewportList.insert(viewport);

      if (mCreated)
      {
       /* Ogre::Camera* cam = viewport->getCamera();
        if (cam)
        {
          mCamera->setPosition(cam->getDerivedPosition());
          mCamera->setOrientation(cam->getDerivedOrientation());
          mCamera->setProjectionType(cam->getProjectionType());
          mCamera->setAspectRatio(cam->getAspectRatio());
          mCamera->setNearClipDistance(cam->getNearClipDistance());
          mCamera->setFarClipDistance(cam->getFarClipDistance());
          mCamera->setUseRenderingDistance(cam->getUseRenderingDistance());
          mCamera->setFOVy(cam->getFOVy());
          mCamera->setFocalLength(cam->getFocalLength());*/

          mMaterialManager->addCompositor(viewport);
          viewport->getTarget()->insertListener(this, 0);

        /*  _checkUnderwater(cam, 0);
        }*/
      }
    }
  }

  void Hydrax::unregisterViewport(Ogre::Viewport* viewport)
  {
    ViewportList::iterator iViewportSearched = mViewportList.find(viewport);
    if (iViewportSearched != mViewportList.end())
    {
      if (mCreated)
      {
        viewport->getTarget()->removeListener(this);
        mMaterialManager->removeCompositor(viewport);;
      }
      mViewportList.erase(iViewportSearched);
    }
  }

  void Hydrax::DeviceListener::eventOccurred(const Ogre::String& eventName, const Ogre::NameValuePairList *parameters)
  {
    // If needed...
    if (eventName == "DeviceLost")
    {
      mHydrax->mDeviceLost = true;
    }
    else if (eventName == "DeviceRestored")
    {
      mHydrax->mDeviceLost = false;
    }
  }

  void Hydrax::setPolygonMode(const Ogre::PolygonMode& PM)
  {
    if (!mCreated)
    {
      return;
    }

    mMaterialManager->getMaterial(MaterialManager::MAT_WATER)->getTechnique(0)->getPass(0)->setPolygonMode(PM);
    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mMaterialManager->getMaterial(MaterialManager::MAT_UNDERWATER)->getTechnique(0)->getPass(0)->setPolygonMode(PM);
    }
    mPolygonMode = PM;
  }

  void Hydrax::setComponents(const HydraxComponent &Components)
  {
    mComponents = Components;

    //adjust components dependencies
    if (isComponent(HYDRAX_COMPONENT_SMOOTH) && !isComponent(HYDRAX_COMPONENT_DEPTH))
      mComponents = static_cast<HydraxComponent>(mComponents & ~(HYDRAX_COMPONENT_SMOOTH));

    if (isComponent(HYDRAX_COMPONENT_CAUSTICS) && !isComponent(HYDRAX_COMPONENT_DEPTH))
      mComponents = static_cast<HydraxComponent>(mComponents & ~(HYDRAX_COMPONENT_CAUSTICS));

    if (isComponent(HYDRAX_COMPONENT_UNDERWATER_GODRAYS) && (!isComponent(HYDRAX_COMPONENT_DEPTH) || !isComponent(HYDRAX_COMPONENT_SUN) || !isComponent(HYDRAX_COMPONENT_UNDERWATER)))
      mComponents = static_cast<HydraxComponent>(mComponents & ~(HYDRAX_COMPONENT_UNDERWATER_GODRAYS));

    if (isComponent(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS) && !isComponent(HYDRAX_COMPONENT_UNDERWATER))
      mComponents = static_cast<HydraxComponent>(mComponents & ~(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS));

    // do not continue if not enable
    if (!mCreated || !mModule)
      return;

    //reset Material
    mDecalsManager->removeAll();
    mMaterialManager->removeMaterials();
    mRttManager->removeAll();
    mTextureManager->remove();
    mGPUNormalMapManager->remove();

    if (!isComponent(HYDRAX_COMPONENT_UNDERWATER))
      mCurrentFrameUnderwater = false;

    if (isComponent(HYDRAX_COMPONENT_UNDERWATER_GODRAYS))
    {
      mGodRaysManager->create(mComponents);
    }
    else
    {
      mGodRaysManager->remove();
    }

    //add base RTT
    mRttManager->initialize(RttManager::RTT_REFLECTION);
    mRttManager->initialize(RttManager::RTT_REFRACTION);

    // Check for Rtt's
    /*if (isComponent(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS))
    {
        mRttManager->initialize(RttManager::RTT_REFLECTION);
    }*/

    if (isComponent(HYDRAX_COMPONENT_DEPTH))
    {
      mRttManager->initialize(RttManager::RTT_DEPTH);

      if (isComponent(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS) && mCurrentFrameUnderwater)
      {
        mRttManager->initialize(RttManager::RTT_DEPTH_REFLECTION);
      }
    }

    if (!isComponent(HYDRAX_COMPONENT_UNDERWATER) && mCurrentFrameUnderwater)
    {
      mRttManager->getTexture(RttManager::RTT_REFRACTION)->getBuffer()->getRenderTarget()->getViewport(0)->setSkiesEnabled(false);
      mRttManager->getTexture(RttManager::RTT_REFLECTION)->getBuffer()->getRenderTarget()->getViewport(0)->setSkiesEnabled(true);
    }

    mMesh->setMaterialName("BaseWhiteNoLighting");
    mMaterialManager->createMaterials(mComponents, mModule->getNormalMode());

    Ogre::MaterialPtr mat = mMaterialManager->getMaterial(mCurrentFrameUnderwater ? MaterialManager::MAT_UNDERWATER : MaterialManager::MAT_WATER);
    if (!mat.isNull())
      mMesh->setMaterialName(mat->getName());

    if (mCurrentFrameUnderwater)
      mMaterialManager->setCompositorEnable(MaterialManager::COMP_UNDERWATER, true);
  }

  void Hydrax::setModule(Module::Module* Module, const bool& DeleteOldModule)
  {
    if (mModule)
    {
      if (mModule->getNormalMode() != Module->getNormalMode())
      {
        mMaterialManager->createMaterials(mComponents, Module->getNormalMode());
        mMesh->setMaterialName(mMaterialManager->getMaterial(MaterialManager::MAT_WATER)->getName());
      }

      if (mModule->getNormalMode() == MaterialManager::NM_RTT && mModule->isCreated() && mModule->getNoise()->areGPUNormalMapResourcesCreated())
      {
        mModule->getNoise()->removeGPUNormalMapResources(mGPUNormalMapManager);
      }

      if (DeleteOldModule)
      {
        delete mModule;
      }
      else
      {
        mModule->remove();
      }

      // Due to modules can change -internally- scene nodes position,
      // just reset them to the original position.
      setPosition(mPosition);
    }

    mModule = Module;
    if (mCreated)
    {
      if (!mModule->isCreated())
      {
        mModule->create();
        if (mModule->getNormalMode() == MaterialManager::NM_RTT)
        {
          if (!mModule->getNoise()->createGPUNormalMapResources(mGPUNormalMapManager))
          {
            HydraxLOG(mModule->getNoise()->getName() + " doesn't support GPU Normal map generation.");
          }
        }
      }
      else
      {
        if (mModule->getNormalMode() == MaterialManager::NM_RTT)
        {
          if (!mModule->getNoise()->areGPUNormalMapResourcesCreated())
          {
            if (!mModule->getNoise()->createGPUNormalMapResources(mGPUNormalMapManager))
            {
              HydraxLOG(mModule->getNoise()->getName() + " doesn't support GPU Normal map generation.");
            }
          }
        }
        else
        {
          if (mModule->getNoise()->areGPUNormalMapResourcesCreated())
          {
            mModule->getNoise()->removeGPUNormalMapResources(mGPUNormalMapManager);
          }
        }
      }

      HydraxLOG("Updating water mesh...");
      Ogre::String MaterialNameTmp = mMesh->getMaterialName();

      HydraxLOG("Deleting water mesh...");
      mMesh->remove();
      HydraxLOG("Water mesh deleted.");

      HydraxLOG("Creating water mesh...");
      mMesh->setOptions(mModule->getMeshOptions());
      mMesh->setMaterialName(MaterialNameTmp);
      mMesh->create();
      setPosition(mPosition);
      HydraxLOG("Water mesh created.");

      HydraxLOG("Module set.");
    }
  }

  bool Hydrax::isComponent(const HydraxComponent &Component)
  {
    if (mComponents & Component)
    {
      return true;
    }

    if (Component == HYDRAX_COMPONENTS_NONE && mComponents == HYDRAX_COMPONENTS_NONE)
    {
      return true;
    }

    if (Component == HYDRAX_COMPONENTS_ALL && mComponents == HYDRAX_COMPONENTS_ALL)
    {
      return true;
    }

    return false;
  }

  void Hydrax::_checkUnderwater(const Ogre::Camera* cam, const Ogre::Real& timeSinceLastFrame)
  {
    if (!isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mCurrentFrameUnderwater = false;
      return;
    }

    // If the camera is under the current water x/z position
    if (getHeigth(cam->getDerivedPosition()) > cam->getDerivedPosition().y - mUnderwaterCameraSwitchDelta)
    {
      mCurrentFrameUnderwater = true;

      Ogre::MaterialPtr mat = mMaterialManager->getMaterial(MaterialManager::MAT_UNDERWATER);
      if (!mat.isNull() && mMesh->getMaterialName() != mat->getName())
      {
        mRttManager->getTexture(RttManager::RTT_REFRACTION)->getBuffer()->getRenderTarget()->getViewport(0)->setSkiesEnabled(true);
        if (isComponent(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS))
        {
          mRttManager->getTexture(RttManager::RTT_REFLECTION)->getBuffer()->getRenderTarget()->getViewport(0)->setSkiesEnabled(false);
          if (isComponent(HYDRAX_COMPONENT_DEPTH))
          {
            mRttManager->initialize(RttManager::RTT_DEPTH_REFLECTION);
          }
        }
        else
        {
          mRttManager->remove(RttManager::RTT_REFLECTION);
        }

        if (isComponent(HYDRAX_COMPONENT_DEPTH) && isComponent(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS))
        {
          mRttManager->initialize(RttManager::RTT_DEPTH_REFLECTION);
        }

        mMaterialManager->reload(MaterialManager::MAT_UNDERWATER);
        mMaterialManager->setCompositorEnable(MaterialManager::COMP_UNDERWATER, true);
        mMesh->setMaterialName(mat->getName());
      }

      // Update god rays
      if (isComponent(HYDRAX_COMPONENT_UNDERWATER_GODRAYS))
      {
        mGodRaysManager->update(timeSinceLastFrame);
      }
    }
    else
    {
      mCurrentFrameUnderwater = false;

      Ogre::MaterialPtr mat = mMaterialManager->getMaterial(MaterialManager::MAT_WATER);
      if (!mat.isNull() && mMesh->getMaterialName() != mat->getName())
      {
        // We asume that RefractionRtt/ReflectionRtt are initialized
        mRttManager->getTexture(RttManager::RTT_REFRACTION)->getBuffer()->getRenderTarget()->getViewport(0)->setSkiesEnabled(false);
        if (!isComponent(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS))
        {
          mRttManager->initialize(RttManager::RTT_REFLECTION);
          mMaterialManager->reload(MaterialManager::MAT_WATER);
        }

        mRttManager->getTexture(RttManager::RTT_REFLECTION)->getBuffer()->getRenderTarget()->getViewport(0)->setSkiesEnabled(true);
        if (isComponent(HYDRAX_COMPONENT_DEPTH) && isComponent(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS))
        {
          mRttManager->remove(RttManager::RTT_DEPTH_REFLECTION);
        }

        mMaterialManager->setCompositorEnable(MaterialManager::COMP_UNDERWATER, false);
        mMesh->setMaterialName(mat->getName());
      }
    }
  }

  void Hydrax::setPosition(const Ogre::Vector3 &Position)
  {
    mPosition = Position;

    // For world-space -> object-space conversion
    setSunPosition(mSunPosition);

    if (!mCreated)
      return;

    if (isComponent(HYDRAX_COMPONENT_DEPTH))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_VERTEX, MaterialManager::MAT_DEPTH, "uPlaneYPos", Position.y);
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_VERTEX, MaterialManager::MAT_DEPTH_TRANS, "uPlaneYPos", Position.y);
    }

    mMesh->getSceneNode()->setPosition(Position.x - mMesh->getSize().Width / 2, Position.y, Position.z - mMesh->getSize().Height / 2);
    mRttManager->getPlanesSceneNode()->setPosition(Position);
  }

  void Hydrax::rotate(const Ogre::Quaternion &q)
  {
    if (!mCreated)
    {
      HydraxLOG("Hydrax::rotate(...) must be called after Hydrax::create(), skipping...");
      return;
    }

    mMesh->getSceneNode()->rotate(q);
    mRttManager->getPlanesSceneNode()->rotate(q);

    // For world-space -> object-space conversion
    setSunPosition(mSunPosition);
  }

  void Hydrax::setPlanesError(const Ogre::Real &PlanesError)
  {
    mPlanesError = PlanesError;
  }

  void Hydrax::_setStrength(const Ogre::Real &Strength)
  {
    if (isComponent(HYDRAX_COMPONENT_FOAM))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uFoamRange", Strength);
    }

    mDecalsManager->_setWaterStrength(Strength);
  }

  void Hydrax::setFullReflectionDistance(const Ogre::Real &FullReflectionDistance)
  {
    mFullReflectionDistance = FullReflectionDistance;

    if (!mCreated)
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uFullReflectionDistance", FullReflectionDistance);
    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER, "uFullReflectionDistance", FullReflectionDistance);
    }
  }

  void Hydrax::setGlobalTransparency(const Ogre::Real &GlobalTransparency)
  {
    mGlobalTransparency = GlobalTransparency;

    if (!mCreated)
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uGlobalTransparency", GlobalTransparency);
    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER, "uGlobalTransparency", GlobalTransparency);
    }
  }

  void Hydrax::setWaterColor(const Ogre::Vector3 &WaterColor)
  {
    mWaterColor = WaterColor;

    if (!mCreated)
      return;

    Ogre::TexturePtr tex;
    Ogre::ColourValue WC = Ogre::ColourValue(WaterColor.x, WaterColor.y, WaterColor.z);
    if (isComponent(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS) || !_isCurrentFrameUnderwater())
    {
      tex = mRttManager->getTexture(RttManager::RTT_REFLECTION);
      if (!tex.isNull())
      {
        tex->getBuffer()->getRenderTarget()->getViewport(0)->setBackgroundColour(WC);
        tex.setNull();
      }
    }
    tex = mRttManager->getTexture(RttManager::RTT_REFRACTION);
    if (!tex.isNull())
    {
      tex->getBuffer()->getRenderTarget()->getViewport(0)->setBackgroundColour(WC);
      tex.setNull();
    }

    if (isComponent(HYDRAX_COMPONENT_DEPTH))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uWaterColor", WaterColor);
    }

    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER, "uWaterColor", WaterColor);

      //mMaterialManager->getCompositor(MaterialManager::COMP_UNDERWATER)->
      //	getTechnique(0)->getTargetPass(0)->getPass(0)->setClearColour(WC);

      /* Active creation/destruction
      if (getHeigth(mCamera->getDerivedPosition()) > mCamera->getDerivedPosition().y-1.25f)
      {
        if (mMaterialManager->isCompositorEnable(MaterialManager::COMP_UNDERWATER))
        {
          mMaterialManager->setCompositorEnable(MaterialManager::COMP_UNDERWATER, false);
          mMaterialManager->setCompositorEnable(MaterialManager::COMP_UNDERWATER, true);
        }
      }
      */
    }
  }

  void Hydrax::setNormalDistortion(const Ogre::Real &NormalDistortion)
  {
    mNormalDistortion = NormalDistortion;

    if (!mCreated)
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uNormalDistortion", NormalDistortion);
    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER, "uNormalDistortion", NormalDistortion);
    }
  }

  void Hydrax::setSunPosition(const Ogre::Vector3 &SunPosition)
  {
    mSunPosition = SunPosition;

    if (!isComponent(HYDRAX_COMPONENT_SUN) || !isCreated())
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uSunPosition", mMesh->getObjectSpacePosition(SunPosition));
    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER, "uSunPosition", mMesh->getObjectSpacePosition(SunPosition));
    }
  }

  void Hydrax::setSunStrength(const Ogre::Real &SunStrength)
  {
    mSunStrength = SunStrength;

    if (!isComponent(HYDRAX_COMPONENT_SUN))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uSunStrength", SunStrength);
    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER, "uSunStrength", SunStrength);
    }
  }

  void Hydrax::setSunArea(const Ogre::Real &SunArea)
  {
    mSunArea = SunArea;

    if (!isComponent(HYDRAX_COMPONENT_SUN))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uSunArea", SunArea);
    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER, "uSunArea", SunArea);
    }
  }

  void Hydrax::setSunColor(const Ogre::Vector3 &SunColor)
  {
    mSunColor = SunColor;

    if (!isComponent(HYDRAX_COMPONENT_SUN))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uSunColor", SunColor);
    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER, "uSunColor", SunColor);
    }
  }

  void Hydrax::setFoamMaxDistance(const Ogre::Real &FoamMaxDistance)
  {
    mFoamMaxDistance = FoamMaxDistance;

    if (!isComponent(HYDRAX_COMPONENT_FOAM))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uFoamMaxDistance", FoamMaxDistance);
  }

  void Hydrax::setFoamScale(const Ogre::Real &FoamScale)
  {
    mFoamScale = FoamScale;

    if (!isComponent(HYDRAX_COMPONENT_FOAM))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uFoamScale", FoamScale);
  }

  void Hydrax::setFoamStart(const Ogre::Real &FoamStart)
  {
    mFoamStart = FoamStart;

    if (!isComponent(HYDRAX_COMPONENT_FOAM))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uFoamStart", FoamStart);
  }

  void Hydrax::setFoamTransparency(const Ogre::Real &FoamTransparency)
  {
    mFoamTransparency = FoamTransparency;

    if (!isComponent(HYDRAX_COMPONENT_FOAM))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uFoamTransparency", FoamTransparency);
  }

  void Hydrax::setDepthLimit(const Ogre::Real &DepthLimit)
  {
    mDepthLimit = DepthLimit;
    if (mDepthLimit <= 0)
    {
      mDepthLimit = 1;
    }

    if (!isComponent(HYDRAX_COMPONENT_DEPTH))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_DEPTH, "uDepthLimit", 1 / mDepthLimit);
    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_DEPTH_TRANS, "uDepthLimit", 1 / mDepthLimit);
  }

  void Hydrax::setDistLimit(const Ogre::Real &DistLimit)
  {
    mDistLimit = DistLimit;
    if (mDistLimit <= 0)
    {
      mDistLimit = 1;
    }

    if (!isComponent(HYDRAX_COMPONENT_DEPTH))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_DEPTH, "uDistLimit", 1 / mDistLimit);
    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_DEPTH_TRANS, "uDistLimit", 1 / mDistLimit);
  }

  void Hydrax::setSmoothPower(const Ogre::Real &SmoothPower)
  {
    mSmoothPower = SmoothPower;

    if (!isComponent(HYDRAX_COMPONENT_SMOOTH))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uSmoothPower", SmoothPower);
  }

  void Hydrax::setCausticsScale(const Ogre::Real &CausticsScale)
  {
    mCausticsScale = CausticsScale;

    if (!isComponent(HYDRAX_COMPONENT_CAUSTICS))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_DEPTH, "uCausticsScale", CausticsScale);
    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_DEPTH_TRANS, "uCausticsScale", CausticsScale);
  }

  void Hydrax::setCausticsPower(const Ogre::Real &CausticsPower)
  {
    mCausticsPower = CausticsPower;

    if (!isComponent(HYDRAX_COMPONENT_CAUSTICS))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_WATER, "uCausticsPower", CausticsPower);

    if (isComponent(HYDRAX_COMPONENT_UNDERWATER))
    {
      if (isComponent(HYDRAX_COMPONENT_UNDERWATER_REFLECTIONS))
      {
        mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER, "uCausticsPower", CausticsPower);
      }

      mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_UNDERWATER_COMPOSITOR, "uCausticsPower", CausticsPower);
    }
  }

  void Hydrax::setCausticsEnd(const Ogre::Real &CausticsEnd)
  {
    mCausticsEnd = CausticsEnd;

    if (!isComponent(HYDRAX_COMPONENT_CAUSTICS))
      return;

    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_DEPTH, "uCausticsEnd", 1.0f - CausticsEnd);
    mMaterialManager->setGpuProgramParameter(MaterialManager::GPUP_FRAGMENT, MaterialManager::MAT_DEPTH_TRANS, "uCausticsEnd", 1.0f - CausticsEnd);
  }

  void Hydrax::update(const Ogre::Real& timeSinceLastFrame)
  {
    mTimeSinceLastFrame = timeSinceLastFrame;
  }

  void Hydrax::preRenderTargetUpdate(const Ogre::RenderTargetEvent& evt)
  {
    if (mCreated && mModule && mVisible)
    {
      //get the first camera
      Ogre::Camera* cam = evt.source->getViewport(0)->getCamera();
      if (!cam)
        return;

      //mCamera->synchroniseBaseSettingsWith(cam);
      //mCamera->setPosition(cam->getDerivedPosition());
      //mCamera->setOrientation(cam->getDerivedOrientation());

      // Update Hydrax
      mModule->update(mTimeSinceLastFrame * mTimeMultiplier, cam);
      mDecalsManager->update(cam);

      _checkUnderwater(cam, mTimeSinceLastFrame * mTimeMultiplier);
      mTimeSinceLastFrame = 0;

      if (!mRttManager->isAutoUpdated())
      {
        mRttManager->updateAll();
      }
    }
  }

  void Hydrax::setTimeMultiplier(const Ogre::Real& timeMultiplier)
  {
    mTimeMultiplier = timeMultiplier;
  }

  const Ogre::Real& Hydrax::getTimeMultiplier() const
  {
    return mTimeMultiplier;
  }

  void Hydrax::setRttVisibilityMask(const Ogre::uint32& visibilityMask)
  {
    rttVisibilityMask = visibilityMask;
  }

  const Ogre::uint32 Hydrax::getRttVisibilityMask() const
  {
    return rttVisibilityMask;
  }
}


text:
package bigbank;

import java.util.HashMap;
import java.util.Map;

public class BankDaoStub implements BankDao {
	private long id = 0;
	private final Map<Long, Account> accounts = new HashMap<>();

	public void createOrUpdateAccount(Account account) {
		if (account.getId() == -1) {
			id++;
			account.setId(id);
		}
		accounts.put(account.getId(), account);
		System.out.println("SAVE: " + account);
	}

	public Account[] findAccounts() {
		Account[] accounts = this.accounts.values().toArray(new Account[] {});
		System.out.println("Returning " + accounts.length + " account(s):");
		for (Account account : accounts) {
			System.out.println(" > " + account);
		}
		return accounts;
	}

	public Account readAccount(Long id) {
		return accounts.get(id);
	}

}


text:
Chef Provisioning was officially end-of-life on August 31, 2019 and is no longer included with Chef DK. The Chef Provisioning source code and drivers have been moved into the chef-boneyard organization. If you are a current user of Chef Provisioning, please contact your Chef Customer Success Manager or Account Representative to review your options.

# Chef Provisioning AWS
[![Build Status](https://travis-ci.org/chef/chef-provisioning-aws.svg?branch=master)](https://travis-ci.org/chef/chef-provisioning-aws)[![Gem Version](https://badge.fury.io/rb/chef-provisioning-aws.svg)](https://badge.fury.io/rb/chef-provisioning-aws)

This README is a work in progress.  Feel free to open PRs expanding it!

# Prerequisites

## Credentials

There are 3 ways you can provide your AWS Credentials.  We will look for credentials in the order from below and use the first one found.  This precedence order is taken from http://docs.aws.amazon.com/sdkforruby/api/index.html#Configuration:

1. Through the environment variables `ENV["AWS_ACCESS_KEY_ID"]`, `ENV["AWS_SECRET_ACCESS_KEY"]` and optionally `ENV["AWS_SESSION_TOKEN"]`
2. The shared credentials ini file.  The default location is `~/.aws/credentials` but you can overwrite this by specifying `ENV["AWS_CONFIG_FILE"]`.  You can specify
multiple profiles in this file and select one with the `ENV["AWS_DEFAULT_PROFILE"]`
environment variable or via the driver url.  For example, a driver url of `aws:staging:us-east-1` would use the profile `staging`.  If you do not specify a profile then the `default` one is used.  Read
[this](http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs) for more information about profiles.
3. From an instance profile when running on EC2.  This accesses the local
metadata service to discover the local instance's IAM instance profile.

## Configurable Options

### aws_retry_limit

When using `machine_batch` with a large number of machines it is possible to overwhelm the AWS SDK until it starts returning `AWS::EC2::Errors::RequestLimitExceeded`.  You can configure the AWS SDK to retry these errors automatically by specifying

```ruby
chef_provisioning({:aws_retry_limit => 10})
```

in your client.rb for the provisioning workstation.  The default `:aws_retry_limit` is 5.

### image_max_wait_time and machine_max_wait_time

By default, the time we will wait for a `machine` to become ready or for the transport to become ready is 120 seconds (each).
For a `machine_image` we wait 300 seconds for the AMI to be created.  These timeouts can be configured with

```ruby
chef_provisioning({:image_max_wait_time => 600, :machine_max_wait_time => 240})
```

in your client.rb for the provisioning workstation.

# Resources

TODO: List out weird/unique things about resources here.  We don't need to document every resource
because users can look at the resource model.

## aws_key_pair

You can specify an existing key pair to upload by specifying the following:

```ruby
aws_key_pair 'my-aws-key' do
  private_key_path "~boiardi/.ssh/my-aws-key.pem"
  public_key_path "~boiardi/.ssh/my-aws-key.pub"
  allow_overwrite false # Set to true if you want to regenerate this each chef run
end
```

## aws_launch_configuration

In the AWS SDK V1, you must specify `key_pair` instead of `key_name` when specifying the key name to use for machines in the auto scaling group.  This is fixed in V2 and uses `key_name` like machines do.

```ruby
aws_launch_configuration 'example-windows-launch-configuration' do
  image 'example-windows-image'
  instance_type 't2.medium'
  options security_groups: 'example-windows-sg',
    key_pair: 'my-key-name',
    ebs_optimized: false,
    detailed_instance_monitoring: false,
    iam_instance_profile: 'example-windows-role',
    user_data: <<-EOF
<powershell>
# custom powershell code goes here, executed at instance creation time
</powershell>
  EOF
end
```

## aws_vpc

If you specify `internet_gateway true` the VPC will create and manage its own internet gateway.
Specifying `internet_gateway false` will delete that managed internet gateway.

Specifying `main_routes` without `main_route_table` will update the 'default' route table
that is created when AWS creates the VPC.

Specifying `main_route_table` without specifying `main_routes` will update the main route
association to point to the provided route table.

If you specify both `main_routes` and `main_route_table` we will update the `main_route_table`
to have the specified `main_routes`.  IE, running

```ruby
aws_route_table 'ref-main-route-table' do
  vpc 'ref-vpc'
  routes '0.0.0.0/0' => :internet_gateway
end

aws_vpc 'ref-vpc' do
  main_route_table 'ref-main-route-table'
  main_routes '0.0.0.0/1' => :internet_gateway
end

aws_vpc 'ref-vpc' do
  main_routes '0.0.0.0/2' => :internet_gateway
end
```

will cause resource flapping.  The `ref-main-route-table` resource will set the routes to `/0`
and then the vpc will set the routes to `/1`.  Then because `ref-main-route-table` is set
to the main route for `ref-vpc` the third resource will set the routes to `/2`.

The takeaway from this is that you should either specify `main_routes` on your VPC and only
manage the routes through that, OR only specify `main_route_table` and manage the routes
through the `aws_route_table` resource.

### Purging

If you specify `action :purge` on the VPC it will attempt to delete ALL resources contained in this
VPC before deleting the actual VPC.

A potential danger of this is that it does not delete the data bag entries for tracked AWS objects.
If you `:purge` a VPC and it has `aws_route_table[ref-route]` in it, the data bag entry for
`ref-route` is not automatically destroyed.  Purge is most useful for testing to ensure no objects
are left that AWS can charge for.

# Machine Options

You can pass machine options that will be used by `machine`, `machine_batch` and `machine_image` to
configure the machine.

These options are an extension of the [base options](https://github.com/chef/chef-provisioning#machine-options).  Please see that for a list of the `machine_options` shared between drivers.

The full syntax available in the `bootstrap_options` hash is the hash expected by the AWS  [`create_instances`](http://docs.aws.amazon.com/sdkforruby/api/Aws/EC2/Resource.html#create_instances-instance_method) method.  The options seen below in the example are the default options.

```ruby
with_machine_options({
  # See https://github.com/chef/chef-provisioning#machine-options for options shared between drivers
  bootstrap_options: {
    # http://docs.aws.amazon.com/sdkforruby/api/Aws/EC2/Resource.html#create_instances-instance_method
    # lists the available options.  The below options are the default
    image_id: "ami-5915e11d", # default for us-west-1
    instance_type: "t2.micro",
    key_name: "chef_default", # If not specified, this will be used and generated
    key_path: "~/.chef/keys/chef_default", # only necessary if storing keys some other location
    user_data: "...", # Only defaulted on Windows instances to start winrm
  },
  use_private_ip_for_ssh: false, # DEPRECATED, use `transport_address_location`
  transport_address_location: :public_ip, # `:public_ip` (default), `:private_ip` or `:dns`.  Defines how SSH or WinRM should find an address to communicate with the instance.
  is_windows: true, # false by default
  winrm_username: "Administrator",
  winrm_password: "password", # Override if you have specified your own password and are not fetching the password from AWS
})
```

This options hash can be supplied to either `with_machine_options` at the recipe level or directly into the `machine_options`
attribute.

# Load Balancer Options

You can configure the ELB options by setting `with_load_balancer_options` or specifying them on each `load_balancer` resource.

```ruby
machine 'test1'
m2 = machine 'test2'
load_balancer "my_elb" do
  machines ['test1', m2]
  load_balancer_options({
    subnets: subnets,
    security_groups: [load_balancer_sg],
    listeners: [
      {
          instance_port: 8080,
          protocol: 'HTTP',
          instance_protocol: 'HTTP',
          port: 80
      },
      {
          instance_port: 8080,
          protocol: 'HTTPS',
          instance_protocol: 'HTTP',
          port: 443,
          ssl_certificate_id: "arn:aws:iam::360965486607:server-certificate/cloudfront/foreflight-2015-07-09"
      }
    ],
    health_check: {
      healthy_threshold: 2,
      unhealthy_threshold: 4,
      interval: 12,
      timeout: 5,
      target: 'HTTPS:443/_status'
    }
  })
```

The available parameters for `load_balancer_options` can be viewed in the [aws docs](http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/ELB/Client.html#create_load_balancer-instance_method).

If you wish to enable sticky sessions, pass a `sticky_sessions` key to the
`load_balancer_options` and specify a cookie name and the ports that should be
sticky. In the above example, it would look like this:

```ruby
machine 'test1'
m2 = machine 'test2'
load_balancer "my_elb" do
  machines ['test1', m2]
  load_balancer_options({
    subnets: subnets,
    security_groups: [load_balancer_sg],
    listeners: [
      {
          instance_port: 8080,
          protocol: 'HTTP',
          instance_protocol: 'HTTP',
          port: 80
      },
      {
          instance_port: 8080,
          protocol: 'HTTPS',
          instance_protocol: 'HTTP',
          port: 443,
          ssl_certificate_id: "arn:aws:iam::360965486607:server-certificate/cloudfront/foreflight-2015-07-09"
      }
    ],
    sticky_sessions: {
      cookie_name: 'my-app-cookie',
      ports: [80, 443]
    }
  })
```

NOTES:

1. You can specify either `ssl_certificate_id` or `server_certificate` in a listener but the value to both parameters should be the ARN of an existing IAM::ServerCertificate object.

2. The `sticky_sessions` option currently only supports Application-Controlled
   Session Stickiness.

# RDS Instance Options

### Additional Options

RDS instances have many options. Some of them live as first class attributes. Any valid RDS option that is not a first class attribute can still be set via a hash in `additional_options`.
*If you set an attribute and also specify it in `additional_options`, the resource will chose the attribute and not what is specified in `additional_options`.*

To illustrate, note that the following example defines `multi_az` as both an attribute and in the `additional_options` hash:

```
aws_rds_instance "test-rds-instance2" do
  engine "postgres"
  publicly_accessible false
  db_instance_class "db.t1.micro"
  master_username "thechief"
  master_user_password "securesecure"
  multi_az false
  additional_options(multi_az: true)
end
```

The above would result in a new `aws_rds_instance` with `multi_az` being `false`.

Additional values for `additional_options` can view viewed in the [aws docs](http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/RDS/Client.html#create_db_instance-instance_method).

### Specifying a DB Subnet Group for your RDS Instance

See [this example](docs/examples/aws_rds_subnet_group.rb) for how to set up a DB Subnet Group and pass it to your RDS Instance.

# Specifying a Chef Server

See [Pointing Boxes at Chef Servers](https://github.com/chef/chef-provisioning/blob/master/README.md#pointing-boxes-at-chef-servers)

# Tagging Resources

## For Recipe authors

All resources (incuding base resources like `machine`) that are taggable support an `aws_tags` attribute which accepts a single layer hash.  To set just the key of an AWS tag specify the value as nil.  EG, `aws_tags {my_tag_key: nil}`.  Some AWS objects cannot accept nil values and will automatically convert it to an empty string.

Some AWS objects (may EC2) view the `Name` tag as unique - it shows up in a `Name` column in the AWS console.  By default we specify the `Name` tag as the resource name.  This can be overridden by specifying `aws_tags {Name: 'some other name'}`.

You can remove all the tags _except_ the `Name` tag by specifying `aws_tags({})`.

Tag keys and values can be specified as symbols or strings but will be converted to strings before sending to AWS.

Examples:

```ruby
aws_ebs_volume 'ref-volume' do
  aws_tags company: 'my_company', 'key_as_string' => :value_as_symbol
end

aws_vpc 'ref-vpc' do
  aws_tags 'Name' => 'custom-vpc-name'
end
```

## For Resource Authors

To enable tagging support you must make specific changes to the Resource and Attribute.  For the Resource it needs to include the `attribute aws_tags`.  This should be done by `include Chef::Provisioning::AWSDriver::AWSTaggable` on the Resource.

The `AWSProvider` class will automatically try to call `converge_tags` when running the `action_create` method.  You should instantiate an instance of the `AWSTagger` and provide it a strategy depending on the client used to perform the tagging.  For example, an RDS Provider should define

```ruby
def aws_tagger
  @aws_tagger ||= begin
    rds_strategy = Chef::Provisioning::AWSDriver::TaggingStrategy::RDS.new(
      new_resource.driver.rds,
      construct_arn(new_resource),
      new_resource.aws_tags
    )
    Chef::Provisioning::AWSDriver::AWSTagger.new(rds_strategy, action_handler)
  end
end
def converge_tags
  aws_tagger.converge_tags
end
```

The `aws_tagger` method is used by the tests to assert that the object tags are correct.  These methods can be encapsulated in an module for DRY purposes, as the EC2 strategy shows.

Finally, you should add 3 standard tests for taggable objects - 1) Tags can be created on a new object, 2) Tags can be updated on an existing object with tags and 3) Tags can be cleared by setting `aws_tags({})`.  Copy the tests from an existing spec file and modify them to support your resource.  TODO make a module that copies these tests for us.  Right now it is complicated by the fact that some resources have required attributes that others don't.

# Looking up AWS objects

## \#aws\_object

All chef-provisioning-aws resources have a `aws_object` method that will return the AWS object.  The base
resources `machine`, `machine_image` and `load_balancer` are monkeypatched to also include the `aws_object`
method and should respond to it like all other resources.

The AWS object won't exist until the resource converges, however.  An example of how to do this looks like:

```ruby
my_vpc = aws_vpc 'my_vpc' do
  cidr_block '10.0.0.0/24'
  main_routes '0.0.0.0/0' => :internet_gateway
  internet_gateway true
end

my_sg = aws_security_group 'my_sg' do
  vpc lazy { my_vpc.aws_object.id }
  inbound_rules '0.0.0.0/0' => [ 22, 80 ]
end

my_subnet = aws_subnet 'my_subnet' do
  vpc lazy { my_vpc.aws_object.id }
  cidr_block '10.0.0.0/24'
  availability_zone 'eu-west-1a'
  map_public_ip_on_launch true
end

machine 'my_machine' do
  machine_options(
    lazy do
      {
        bootstrap_options: {
          subnet_id: my_subnet.aws_object.id,
          security_group_ids: [my_sg.aws_object.id]
        }
      }
    end
  )
end
```

Note the use of the `lazy` attribute modifier.  This is necessary because when the resources are compiled
the aws_objects do not exist yet, so we must wait to reference them until the converge phase.

## \#lookup\_options

You have access to the aws object when necessary, but often it isn't needed.  The above example is better
written as:

```ruby
aws_vpc 'my_vpc' do
  cidr_block '10.0.0.0/24'
  main_routes '0.0.0.0/0' => :internet_gateway
  internet_gateway true
end

aws_security_group 'my_sg' do
  vpc 'my_vpc'
  inbound_rules '0.0.0.0/0' => [ 22, 80 ]
end

aws_subnet 'my_subnet' do
  vpc 'my_vpc'
  cidr_block '10.0.0.0/24'
  availability_zone 'eu-west-1a'
  map_public_ip_on_launch true
end

machine 'my_machine' do
  machine_options(
    bootstrap_options: {
      subnet_id: 'my_subnet',
      security_group_ids: ['my_sg']
    }
  )
end
```

When specifying `bootstrap_options` and any attributes which reference another aws resource, we
perform [lookup_options](https://github.com/chef/chef-provisioning-aws/blob/master/lib/chef/provisioning/aws_driver/aws_resource.rb#L63-L91).
This tries to turn elements with names like `vpc`, `security_group_ids`, `machines`, `launch_configurations`,
`load_balancers`, etc. to the correct AWS object.

# How to update Security Groups for EC2-VPC instances
The behavior of the `machine` resource is that once a machine has been allocated,
the `bootstrap_options` can not be modified. This currently reflects AWS's
restrictions on EC2-Classic instances, but AWS *does* allow users to modify the
security groups associated with EC2-VPC instances. This is because the security
groups for EC2-VPC instances are _actually_ associated with that instance's
Network Interface. This means that if you wish to modify the security groups
associated with an EC2-VPC instance, you'll want to use the `aws_network_interface`
resource.

The first step is to find the Network Interface ID (`eni-XXXXXXX`) associated
with your machine. You can do this by inspecting the instance details in the AWS
Console or by using the AWS CLI. If you want to use the AWS CLI, you can use
this command replacing `MACHINE_NAME` with the name of the `machine` resource
you wish to update.

```shell
aws ec2 describe-instances --filter "Name=tag:Name,Values=MACHINE_NAME" | grep NetworkInterfaceId
```

Once you have the Network Interface ID, in a chef-provisioning recipe you can
specify the following resource:

```ruby
require 'chef/provisioning/aws_driver'
with_driver 'aws' # specify the profile / region as appropriate

aws_network_interface 'eni-XXXXXXXX' do
  security_groups ['sg-XXXXXXXX', 'sg-YYYYYYYY']
end
```

This resource can be in the same chef-provisioning recipe as the corresponding
machine resource, or it can be in a different one.

# Running Integration Tests

To run the integration tests execute `bundle exec rspec`.  If you have not set it up,
you should see an error message about a missing environment variable `AWS_TEST_DRIVER`.  You can add
this as a normal environment variable or set it for a single run with `AWS_TEST_DRIVER=aws::eu-west-1
bundle exec rspec`.  The format should match what `with_driver` expects.

You will also need to have configured your `~/.aws/config` or environment variables with your
AWS credentials.

This creates real objects within AWS.  The tests make their best effort to delete these objects
after each test finishes but errors can happen which prevent this.  Be aware that this may charge
you!

If you find the tests leaving behind resources during normal conditions (IE, not when there is an
unexpected exception) please file a bug.  Most objects can be cleaned up by deleting the `test_vpc`
from within the AWS browser console.