text:
package org.bitcoins.testkitcore.gen.p2p

import org.bitcoins.core.number.{UInt32, UInt64}
import org.bitcoins.core.p2p._
import org.bitcoins.core.protocol.CompactSizeUInt
import org.bitcoins.core.wallet.fee.{
  SatoshisPerByte,
  SatoshisPerKW,
  SatoshisPerKiloByte,
  SatoshisPerVirtualByte
}
import org.bitcoins.testkitcore.gen._
import org.bitcoins.testkitcore.gen.p2p.P2PGenerator._
import org.scalacheck.Gen
import scodec.bits.ByteVector

object ControlMessageGenerator {

  /** Generates a valid P2P control message */
  def controlMessage: Gen[ControlPayload] =
    Gen.oneOf(
      addrMessage,
      filterAddMessage,
      filterLoadMessage,
      feeFilterMessage,
      pingMessage,
      pongMessage,
      rejectMessage,
      versionMessage
    )

  def feeFilterMessage: Gen[FeeFilterMessage] = {
    for {
      fee <- Gen.oneOf(FeeUnitGen.satsPerByte, FeeUnitGen.satsPerKiloByte)
    } yield fee match {
      case fee: SatoshisPerByte     => FeeFilterMessage(fee)
      case fee: SatoshisPerKiloByte => FeeFilterMessage(fee)
      case SatoshisPerVirtualByte(_) | SatoshisPerKW(_) =>
        throw new RuntimeException(s"We cannot end up here")
    }
  }

  /** Generates a random [[org.bitcoins.core.p2p.VersionMessage VersionMessage]]
    *
    * @see [[https://bitcoin.org/en/developer-reference#version]]
    */
  def versionMessage: Gen[VersionMessage] =
    for {
      version <- protocolVersion
      identifier <- serviceIdentifier
      timestamp <- NumberGenerator.int64s
      addressReceiveServices <- serviceIdentifier
      addressReceiveIpAddress <- inetAddress
      addressReceivePort <- portNumber
      addressTransServices <- serviceIdentifier
      addressTransIpAddress <- inetAddress
      addressTransPort <- portNumber
      nonce <- NumberGenerator.uInt64s
      userAgent <- StringGenerators.genString
      startHeight <- NumberGenerator.int32s
      relay = scala.util.Random.nextInt() % 2 == 0
    } yield VersionMessage(
      version,
      identifier,
      timestamp,
      addressReceiveServices,
      addressReceiveIpAddress,
      addressReceivePort,
      addressTransServices,
      addressTransIpAddress,
      addressTransPort,
      nonce,
      userAgent,
      startHeight,
      relay
    )

  /** Generates a [[org.bitcoins.core.p2p.PingMessage]]
    *
    * @see [[https://bitcoin.org/en/developer-reference#ping]]
    */
  def pingMessage: Gen[PingMessage] =
    for {
      uInt64 <- NumberGenerator.uInt64s
    } yield PingMessage(uInt64)

  /** Generates a [[org.bitcoins.core.p2p.PongMessage]]
    *
    * @see [[https://bitcoin.org/en/developer-reference#pong]]
    */
  def pongMessage: Gen[PongMessage] =
    for {
      uInt64 <- NumberGenerator.uInt64s
    } yield PongMessage(uInt64)

  def addrMessage: Gen[AddrMessage] = {
    for {
      addresses <- Gen.listOf(P2PGenerator.networkIpAddress)
    } yield AddrMessage(addresses)
  }

  /** Generates a random [[org.bitcoins.core.p2p.ProtocolVersion]]
    *
    * @see [[https://bitcoin.org/en/developer-reference#protocol-versions]]
    */
  def protocolVersion: Gen[ProtocolVersion] =
    for {
      randomNum <- Gen.choose(0, ProtocolVersion.versions.length - 1)
    } yield ProtocolVersion.versions(randomNum)

  /** Generates a [[org.bitcoins.core.p2p.ServiceIdentifier]]
    *
    * @see [[https://bitcoin.org/en/developer-reference#version]]
    */
  def serviceIdentifier: Gen[ServiceIdentifier] =
    for {
      //service identifiers can only be NodeNetwork or UnnamedService
      randomNum <- Gen.choose(0, 1)
    } yield ServiceIdentifier(randomNum)

  def portNumber: Gen[Int] = Gen.choose(0, 65535)

  /** Creates a [[org.bitcoins.core.p2p.FilterLoadMessage]]
    *
    * @see [[https://bitcoin.org/en/developer-reference#filterload]]
    */
  def filterLoadMessage: Gen[FilterLoadMessage] =
    for {
      filter <- NumberGenerator.bytes
      hashFuncs <- Gen.choose(0, 50)
      tweak <- NumberGenerator.uInt32s
      flags <- BloomFilterGenerator.bloomFlag
    } yield FilterLoadMessage(ByteVector(filter),
                              UInt32(hashFuncs),
                              tweak,
                              flags)

  /** Creates a [[org.bitcoins.core.p2p.FilterAddMessage]]
    *
    * @see [[https://bitcoin.org/en/developer-reference#filteradd]]
    */
  def filterAddMessage: Gen[FilterAddMessage] =
    for {
      element <- CryptoGenerators.doubleSha256Digest
      elementSize = CompactSizeUInt(UInt64(element.bytes.size))
    } yield FilterAddMessage(elementSize, element.bytes)

  /** Creates a [[org.bitcoins.core.p2p.RejectMessage]]
    *
    * @see [[https://bitcoin.org/en/developer-reference#reject]]
    */
  def rejectMessage: Gen[RejectMessage] =
    for {
      message <- StringGenerators.genString
      code <- StringGenerators.strChar
      reason <- StringGenerators.genString
      extra <- CryptoGenerators.doubleSha256Digest
    } yield RejectMessage(message, code, reason, extra.bytes)
}


text:
package org.elasticsearch.common.inject.assistedinject;

import org.elasticsearch.common.inject.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Models a method or constructor parameter.
 *
 * @author jmourits@google.com (Jerome Mourits)
 * @author jessewilson@google.com (Jesse Wilson)
 */
class Parameter {

    private final Type type;
    private final boolean isAssisted;
    private final Annotation bindingAnnotation;
    private final boolean isProvider;

    public Parameter(Type type, Annotation[] annotations) {
        this.type = type;
        this.bindingAnnotation = getBindingAnnotation(annotations);
        this.isAssisted = hasAssistedAnnotation(annotations);
        this.isProvider = isProvider(type);
    }

    public boolean isProvidedByFactory() {
        return isAssisted;
    }

    public Type getType() {
        return type;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        if (isAssisted) {
            result.append("@Assisted");
            result.append(" ");
        }
        if (bindingAnnotation != null) {
            result.append(bindingAnnotation.toString());
            result.append(" ");
        }
        result.append(type.toString());
        return result.toString();
    }

    private boolean hasAssistedAnnotation(Annotation[] annotations) {
        for (Annotation annotation : annotations) {
            if (annotation.annotationType().equals(Assisted.class)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns the Guice {@link Key} for this parameter.
     */
    public Object getValue(Injector injector) {
        return isProvider
                ? injector.getProvider(getBindingForType(getProvidedType(type)))
                : injector.getInstance(getPrimaryBindingKey());
    }

    public boolean isBound(Injector injector) {
        return isBound(injector, getPrimaryBindingKey())
                || isBound(injector, fixAnnotations(getPrimaryBindingKey()));
    }

    private boolean isBound(Injector injector, Key<?> key) {
        // This method is particularly lame - we really need an API that can test
        // for any binding, implicit or explicit
        try {
            return injector.getBinding(key) != null;
        } catch (ConfigurationException e) {
            return false;
        }
    }

    /**
     * Replace annotation instances with annotation types, this is only
     * appropriate for testing if a key is bound and not for injecting.
     * <p/>
     * See Guice bug 125,
     * http://code.google.com/p/google-guice/issues/detail?id=125
     */
    public Key<?> fixAnnotations(Key<?> key) {
        return key.getAnnotation() == null
                ? key
                : Key.get(key.getTypeLiteral(), key.getAnnotation().annotationType());
    }

    Key<?> getPrimaryBindingKey() {
        return isProvider
                ? getBindingForType(getProvidedType(type))
                : getBindingForType(type);
    }

    private Type getProvidedType(Type type) {
        return ((ParameterizedType) type).getActualTypeArguments()[0];
    }

    private boolean isProvider(Type type) {
        return type instanceof ParameterizedType
                && ((ParameterizedType) type).getRawType() == Provider.class;
    }

    private Key<?> getBindingForType(Type type) {
        return bindingAnnotation != null
                ? Key.get(type, bindingAnnotation)
                : Key.get(type);
    }

    /**
     * Returns the unique binding annotation from the specified list, or
     * {@code null} if there are none.
     *
     * @throws IllegalStateException if multiple binding annotations exist.
     */
    private Annotation getBindingAnnotation(Annotation[] annotations) {
        Annotation bindingAnnotation = null;
        for (Annotation a : annotations) {
            if (a.annotationType().getAnnotation(BindingAnnotation.class) != null) {
                if (bindingAnnotation != null) {
                    throw new IllegalArgumentException("Parameter has multiple binding annotations: " + bindingAnnotation + " and " + a);
                }
                bindingAnnotation = a;
            }
        }
        return bindingAnnotation;
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Roled
  class Panel::BusynessesController < Panel::BaseController
    before_action :set_busyness, only: [:show, :edit, :update, :move_higher, :move_lower]

    def index
      @busynesses = Busyness.with_attached_logo.order(position: :asc).page(params[:page])
    end

    def sync
      Busyness.sync
    end

    def show
    end

    def edit
    end

    def update
      @busyness.assign_attributes(busyness_params)

      unless @busyness.save
        render :edit, locals: { model: @busyness }, status: :unprocessable_entity
      end
    end

    def move_higher
      @busyness.move_higher
    end

    def move_lower
      @busyness.move_lower
    end

    private
    def busyness_params
      params.fetch(:busyness, {}).permit(
        :name,
        :logo
      )
    end

    def set_busyness
      @busyness = Busyness.find(params[:id])
    end

  end
end


text:
<?php

class Webshopapps_Wsacommon_Helper_Shipping extends Mage_Core_Helper_Abstract
{
	public static function getVirtualItemTotals($item, &$weight, &$qty, &$price, $useParent=true,$ignoreFreeItems=true, &$itemGroup=array(),
			$useDiscountValue=false, $cartFreeShipping=false, $useBase=false, $useTax = false, $includeVirtual = false) {

		$addressWeight=0;
		$addressQty=0;
		$freeMethodWeight=0;
		$itemGroup[]=$item;
		$applyShipping= Mage::getModel('catalog/product')->load($item->getProduct()->getId())->getApplyShipping();
		$downloadShipping = Mage::helper('wsacommon')->isModuleEnabled('Webshopapps_Downloadshipping');
		$hasCustomOptions = 0;
		if($downloadShipping) {
			$hasCustomOptions = Mage::helper('downloadshipping')->hasCustomOptions($item);
		}

		if(!$downloadShipping && $item->getProduct()->isVirtual() && !$includeVirtual){

			return false;
		}

		if ($ignoreFreeItems && $item->getFreeShipping()) {
			return false;
		}

		/*
		 * Children weight we calculate for parent
		*/
		if ($item->getParentItem() && ( ($item->getParentItem()->getProduct()->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE && $useParent)
				|| $item->getParentItem()->getProduct()->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE  )) {
			return false;
		}

		if (!$useParent && $item->getHasChildren() && $item->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE ) {
			return false;
		}

		if ($item->getHasChildren() && $item->isShipSeparately()) {

			foreach ($item->getChildren() as $child) {
				$itemGroup[]=$item;
				if($downloadShipping){
					if ($child->getProduct()->isVirtual() && !$applyShipping || !$hasCustomOptions) {
						continue;
					}
				}

				$addressQty += $item->getQty()*$child->getQty();

				if (!$item->getProduct()->getWeightType()) {
					$itemWeight = $child->getWeight();
					$itemQty    = $child->getTotalQty();
					$rowWeight  = $itemWeight*$itemQty;
					if ($cartFreeShipping || $child->getFreeShipping()===true) {
						$rowWeight = 0;
					} elseif (is_numeric($child->getFreeShipping())) {
						$freeQty = $child->getFreeShipping();
						if ($itemQty>$freeQty) {
							$rowWeight = $itemWeight*($itemQty-$freeQty);
						} else {
							$rowWeight = 0;
						}
					}
					$freeMethodWeight += $rowWeight;
				}
			}
			if ($item->getProduct()->getWeightType()) {
				$itemWeight = $item->getWeight();
				$rowWeight  = $itemWeight*$item->getQty();
				$addressWeight+= $rowWeight;
				if ($cartFreeShipping || $item->getFreeShipping()===true) {
					$rowWeight = 0;
				} elseif (is_numeric($item->getFreeShipping())) {
					$freeQty = $item->getFreeShipping();
					if ($item->getQty()>$freeQty) {
						$rowWeight = $itemWeight*($item->getQty()-$freeQty);
					} else {
						$rowWeight = 0;
					}
				}
				$freeMethodWeight+= $rowWeight;
			}
		} else {
			if ($downloadShipping || $includeVirtual){

				if(!$item->getProduct()->isVirtual() || $item->getProduct()->isVirtual() && $applyShipping || $hasCustomOptions || $includeVirtual){

					$addressQty += $item->getQty();
				}
				else{return false;
				}
			}
			$itemWeight = $item->getWeight();
			$rowWeight  = $itemWeight*$item->getQty();
			$addressWeight+= $rowWeight;
			if ($cartFreeShipping || $item->getFreeShipping()===true) {
				$rowWeight = 0;
			} elseif (is_numeric($item->getFreeShipping())) {
				$freeQty = $item->getFreeShipping();
				if ($item->getQty()>$freeQty) {
					$rowWeight = $itemWeight*($item->getQty()-$freeQty);
				} else {
					$rowWeight = 0;
				}
			}
			$freeMethodWeight+= $rowWeight;
		}

		if (!$useParent && $item->getParentItem() && $item->getParentItem()->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE ) {
			$weight=$addressWeight*$item->getParentItem()->getQty();
			$qty=$addressQty*$item->getParentItem()->getQty();
			$parentProduct = $item->getParentItem()->getProduct();
			!$useBase ? $finalPrice = $item->getRowTotal() : $finalPrice = $item->getBaseRowTotal();
			$useTax && $useBase ? $finalPrice += $item->getBaseTaxAmount() : false;
			$useTax && !$useBase ? $finalPrice += $item->getTaxAmount() : false;

			if ($parentProduct->getPriceType() == Mage_Bundle_Model_Product_Price::PRICE_TYPE_FIXED) {
				if ($parentProduct->hasCustomOptions()) {
					$customOption = $parentProduct->getCustomOption('bundle_option_ids');
					$customOption = $parentProduct->getCustomOption('bundle_selection_ids');
					$selectionIds = unserialize($customOption->getValue());
					$selections = $parentProduct->getTypeInstance(true)->getSelectionsByIds($selectionIds, $parentProduct);
 					if (method_exists($selections,'addTierPriceData')) {
						$selections->addTierPriceData();
					}
					foreach ($selections->getItems() as $selection) {
						if ($selection->getProductId()== $item->getProductId()) {
							$finalPrice = $item->getParentItem()->getProduct()->getPriceModel()->getChildFinalPrice(
									$parentProduct, $item->getParentItem()->getQty(),
									$selection, $qty, $item->getQty());
							//Price from here is always base. Convert to store to stay consistent unless flag $useBase is set.
							!$useBase ? $finalPrice = Mage::helper('directory')->currencyConvert($finalPrice,
									Mage::app()->getStore()->getBaseCurrencyCode(), Mage::app()->getStore()->getCurrentCurrencyCode()) : '';
						}
					}
				}
			}
			$price=$finalPrice;
		} else {
			$weight=$addressWeight;
 			$qty=$addressQty;
 			!$useBase ? $price = $item->getRowTotal() : $price = $item->getBaseRowTotal();
 			$useTax && !$useBase ? $price += ($item->getRowTotalInclTax() - $item->getRowTotal()) : false;
 			$useTax && $useBase ? $price += ($item->getBaseRowTotalInclTax() - $item->getBaseRowTotal()) : false;
		}

		if ($useDiscountValue){
			!$useBase ? $price-=$item->getDiscountAmount() : $price-=$item->getBaseDiscountAmount();;
		}

		return true;
   	}

   	/**
   	 * PHP - Doesnt support function overloading. Bring on a real language!
   	 * Enter description here ...
   	 * @param unknown_type $item
   	 * @param unknown_type $weight
   	 * @param unknown_type $qty
   	 * @param unknown_type $price
   	 * @param unknown_type $useParent
   	 * @param unknown_type $ignoreFreeItems
   	 * @param unknown_type $itemGroup
   	 * @param unknown_type $useDiscountValue
   	 */
   	public static function getItemTotals($item, &$weight, &$qty, &$price, $useParent=true,$ignoreFreeItems=true,
 			&$itemGroup=array(),$useDiscountValue=false, $cartFreeShipping = false,$useBase = false, $useTax = false) {

 		$freeMethodWeight =0;
 		return self::getItemInclFreeTotals($item, $weight, $qty, $price, $freeMethodWeight, $useParent,$ignoreFreeItems,
 			$itemGroup,$useDiscountValue,$cartFreeShipping, $useBase, $useTax);
 	}

 	/**
 	 * Freemethod weight now returned
 	 * Enter description here ...
 	 * @param unknown_type $item
 	 * @param unknown_type $weight
 	 * @param unknown_type $qty
 	 * @param unknown_type $price
 	 * @param unknown_type $freeMethodWeight
 	 * @param unknown_type $useParent
 	 * @param unknown_type $ignoreFreeItems
 	 * @param unknown_type $itemGroup
 	 * @param unknown_type $useDiscountValue
 	 */
 	public static function getItemInclFreeTotals($item, &$weight, &$qty, &$price, &$freeMethodWeight, $useParent=true,$ignoreFreeItems=true,
 			&$itemGroup=array(),$useDiscountValue=false, $cartFreeShipping = false, $useBase = false, $useTax = false, &$basePriceInclTax = 0) {

 		$addressWeight=0;
 		$addressQty=0;
 		$freeMethodWeight=0;
 		$itemGroup[]=$item;

 		if (!is_object($item))
 		{
 			Mage::helper('wsacommon/log')->postCritical('wsacommon','Fatal Error','Item/Product is Malformed');
 			return false;
 		}

 		/**
 		 * Skip if this item is virtual
 		 **/

 		if ($item->getProduct()->isVirtual()) {
 			return false;
 		}

 		if ($ignoreFreeItems && ($item->getFreeShipping() || $cartFreeShipping)) {
 			return false;
 		}

 		/**
 		 * Children weight we calculate for parent
 		 */

 		if ($item->getParentItem() && ( ($item->getParentItem()->getProduct()->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE && $useParent)
 				|| $item->getParentItem()->getProduct()->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE  )) {
 			return false;
 		}

 		if (!$useParent && $item->getHasChildren() && $item->getProduct()->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE ) {
            if ($item->getProduct()->getPriceType() == Mage_Bundle_Model_Product_Price::PRICE_TYPE_FIXED) {
                //Add on the fixed initial parent price. Children are calculated separately.
                $basePrice = $item->getProduct()->getPrice();
                $storePrice = Mage::helper('directory')->currencyConvert($basePrice,
                    Mage::app()->getStore()->getBaseCurrencyCode(), Mage::app()->getStore()->getCurrentCurrencyCode());

                !$useBase ? $price = $storePrice : $price = $basePrice;

                $calculator = Mage::helper('tax')->getCalculator();
                $taxRequest = $calculator->getRateOriginRequest();
                $taxRequest->setProductClassId($item->getProduct()->getTaxClassId());
                $taxPercentage = $calculator->getRate($taxRequest);

                $taxAmount = round(($taxPercentage/100) * $price, 2);
                $storeTaxAmount = round(Mage::helper('directory')->currencyConvert($taxAmount,
                    Mage::app()->getStore()->getBaseCurrencyCode(), Mage::app()->getStore()->getCurrentCurrencyCode()), 2);

                $useTax && !$useBase ? $price += $storeTaxAmount : false;
                $useTax && $useBase ? $price += $taxAmount : false;

                if($item->getProduct()->getWeightType()){
                    $itemWeight = $item->getProduct()->getWeight();
                    $rowWeight  = $itemWeight*$item->getQty();

                    if ($cartFreeShipping || $item->getFreeShipping()===true) {
                        $rowWeight = 0;
                    } elseif (is_numeric($item->getFreeShipping())) {
                        $freeQty = $item->getFreeShipping();
                        if ($item->getQty()>$freeQty) {
                            $rowWeight = $itemWeight*($item->getQty()-$freeQty);
                        } else {
                            $rowWeight = 0;
                        }
                    }
                    $weight = $rowWeight;
                    $freeMethodWeight+= $rowWeight;
                }

                return true; //return - the weight & qty is worked out from the child items. Children may have additional fixed price to add on.
             } else {
                return false;
             }
        }

 		if ($item->getHasChildren() && $item->isShipSeparately()) {
 			foreach ($item->getChildren() as $child) {
 				$itemGroup[]=$item;
 				if ($child->getProduct()->isVirtual()) {
 					continue;
 				}
 				$addressQty += $item->getQty()*$child->getQty();

 				if (!$item->getProduct()->getWeightType()) {
 					$itemWeight = $child->getWeight();
 					$itemQty    = $child->getTotalQty();
 					$rowWeight  = $itemWeight*$itemQty;
 					if ($cartFreeShipping || $child->getFreeShipping()===true) {
 						$rowWeight = 0;
 					} elseif (is_numeric($child->getFreeShipping())) {
 						$freeQty = $child->getFreeShipping();
 						if ($itemQty>$freeQty) {
 							$rowWeight = $itemWeight*($itemQty-$freeQty);
 						} else {
 							$rowWeight = 0;
 						}
 					}
 					$freeMethodWeight += $rowWeight;
 				}
 			}
 			if ($item->getProduct()->getWeightType()) {
 				$itemWeight = $item->getWeight();
 				$rowWeight  = $itemWeight*$item->getQty();
 				$addressWeight+= $rowWeight;
 				if ($cartFreeShipping || $item->getFreeShipping()===true) {
 					$rowWeight = 0;
 				} elseif (is_numeric($item->getFreeShipping())) {
 					$freeQty = $item->getFreeShipping();
 					if ($item->getQty()>$freeQty) {
 						$rowWeight = $itemWeight*($item->getQty()-$freeQty);
 					} else {
 						$rowWeight = 0;
 					}
 				}
 				$freeMethodWeight+= $rowWeight;
 			}
 		} else {
            if (!$item->getProduct()->isVirtual()) {
                $addressQty += $item->getQty();
            }

            if($item->getParentItem() && $item->getParentItem()->getProduct()->getWeightType()){
                $itemWeight = 0;
                $rowWeight = 0;
                $addressWeight += 0; //Added in parent logic above
            } else {
                $itemWeight = $item->getWeight();
                $rowWeight  = $itemWeight*$item->getQty();
                $addressWeight+= $rowWeight;
            }
 			if ($cartFreeShipping || $item->getFreeShipping()===true) {
 				$rowWeight = 0;
 			} elseif (is_numeric($item->getFreeShipping())) {
 				$freeQty = $item->getFreeShipping();
 				if ($item->getQty()>$freeQty) {
 					$rowWeight = $itemWeight*($item->getQty()-$freeQty);
 				} else {
 					$rowWeight = 0;
 				}
 			}
 			$freeMethodWeight+= $rowWeight;
 		}

 		if (!$useParent && $item->getParentItem() && $item->getParentItem()->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE ) {
 			$weight=$addressWeight*$item->getParentItem()->getQty();
 			$qty=$addressQty*$item->getParentItem()->getQty();
 			$parentProduct = $item->getParentItem()->getProduct();
 			!$useBase ? $finalPrice = $item->getRowTotal() : $finalPrice = $item->getBaseRowTotal();
 			$useTax && $useBase ? $finalPrice += $item->getBaseTaxAmount() : false;
 			$useTax && !$useBase ? $finalPrice += $item->getTaxAmount() : false;
 			if ($parentProduct->getPriceType() == Mage_Bundle_Model_Product_Price::PRICE_TYPE_FIXED) {
 				if ($parentProduct->hasCustomOptions()) {
 					$customOption = $parentProduct->getCustomOption('bundle_option_ids');
 					$customOption = $parentProduct->getCustomOption('bundle_selection_ids');
 					$selectionIds = unserialize($customOption->getValue());
 					$selections = $parentProduct->getTypeInstance(true)->getSelectionsByIds($selectionIds, $parentProduct);
 					if (method_exists($selections,'addTierPriceData')) {
 						$selections->addTierPriceData();
					}
 					foreach ($selections->getItems() as $selection) {
 						if ($selection->getProductId()== $item->getProductId()) {
                             $finalPrice = $item->getParentItem()->getProduct()->getPriceModel()->getChildFinalPrice(
 									$parentProduct, $item->getParentItem()->getQty(),
 									$selection, $qty, $item->getQty());
                             //Price from here is always base. Convert to store to stay consistent unless flag $useBase is set.
                             !$useBase ? $finalPrice = Mage::helper('directory')->currencyConvert($finalPrice,
                                 Mage::app()->getStore()->getBaseCurrencyCode(), Mage::app()->getStore()->getCurrentCurrencyCode()) : '';

                             if($useTax) {
                                 $calculator = Mage::helper('tax')->getCalculator();
                                 $taxRequest = $calculator->getRateOriginRequest();
                                 $taxRequest->setProductClassId($parentProduct->getTaxClassId());
                                 $taxPercentage = $calculator->getRate($taxRequest);

                                 $taxAmount = round(($taxPercentage/100) * $finalPrice,2);
                                 $storeTaxAmount = round(Mage::helper('directory')->currencyConvert($taxAmount,
                                     Mage::app()->getStore()->getBaseCurrencyCode(), Mage::app()->getStore()->getCurrentCurrencyCode()),2);

                                 $finalPrice += $useBase ? $taxAmount : $storeTaxAmount;
                             }
                         }
 					}
 				}
 			}
 			$price=$finalPrice;
 		}   else {
 			$weight=$addressWeight;
 			$qty=$addressQty;
 			!$useBase ? $price = $item->getRowTotal() : $price = $item->getBaseRowTotal();
 			$useTax && !$useBase ? $price += ($item->getRowTotalInclTax() - $item->getRowTotal()) : false;
 			$useTax && $useBase ? $price += ($item->getBaseRowTotalInclTax() - $item->getBaseRowTotal()) : false;
 		}

 		if ($useDiscountValue){
 			!$useBase ? $price-=$item->getDiscountAmount() : $price-=$item->getBaseDiscountAmount();;
 		}

        $basePriceInclTax += $item->getBaseRowTotalInclTax();  //TODO: Need to cover all scenarios

 		return true;
 	}

   	public static function updateStatus($session,$numRows) {
   		if ($numRows<1) {
			$session->addError(Mage::helper('adminhtml')->__($numRows.' rows have been imported. See wiki article for help'))  ;
        } else {
        	$session->addSuccess(Mage::helper('adminhtml')->__($numRows.' rows have been imported.'));
        }
   	}

   	public static function hasFreightCarrierEnabled() {
   		if(Mage::helper('wsacommon')->isModuleEnabled('Webshopapps_Yrcfreight','carriers/yrcfreight/active') ||
   			Mage::helper('wsacommon')->isModuleEnabled('Webshopapps_Wsaupsfreight','carriers/wsaupsfreight/active') ||
   			Mage::helper('wsacommon')->isModuleEnabled('Webshopapps_Rlfreight','carriers/rlfreight/active')  ) {
   			return true;
   		}
   		return false;
   	}

   	/**
   	 *
   	 * Retrieves enabled freight carriers. Currently only returns one
   	 */
  	public static function getFreightCarriers() {
   		if(Mage::helper('wsacommon')->isModuleEnabled('Webshopapps_Yrcfreight','carriers/yrcfreight/active')) {
   			return 'yrcfreight';
   		}

   		if (Mage::helper('wsacommon')->isModuleEnabled('Webshopapps_Wsaupsfreight','carriers/wsaupsfreight/active') ) {
   			return 'wsaupsfreight';
   		}

  	   	if (Mage::helper('wsacommon')->isModuleEnabled('Webshopapps_Rlfreight','carriers/rlfreight/active') ) {
   			return 'rlfreight';
   		}
   		return '';
   	}

   	/**
   	 *
   	 * Method to save a backup copy of the CSV file to the file system.
   	 * @param String $file - CSV file to be saved.
   	 * @param String $fileName - What to call the file including extension.
     * @param string $websiteId - The website Id to be added to the file name.
   	 */
   	public function saveCSV($file, $fileName, $websiteId=NULL, $extension=NULL) {

   		$dir = Mage::getBaseDir('var').'/export/';

		$fileName = 'WSA_' . $extension . '_'; // Add unique WSA marker for csv exporting and removed filename.

    	$timestamp = md5(microtime());
        if (!is_null($websiteId)) {
            $fileName = $fileName . 'WebsiteId=' . $websiteId . '_' . $timestamp . '.csv';
        } else {
            $fileName = $fileName . $timestamp . '.csv';
        }

   		try {
   			if(!is_dir($dir)) {
   				if(!mkdir($dir)){
   					Mage::helper('wsacommon/log')->postMajor("WSA Helper","IO Error","Error Creating Backup CSV File Directory");
   				}
   			}
   			if (!ctype_digit(file_put_contents($dir.$fileName, $file))) {
   				Mage::helper('wsacommon/log')->postMajor("WSA Helper","IO Error","Error Creating Backup CSV File");
   			}
   		} catch (Exception $e) {
   			Mage::helper('wsacommon/log')->postMajor("Helper","Error Saving CSV File Backup",$e->getMessage());
   		}

   	}

	public static function getProduct($item,$useParent=true) {
		$product = null;

		if ($item->getParentItem()!=null &&  $useParent ) {
   			$product=$item->getParentItem()->getProduct();
   		} else if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE && !$useParent ) {
   			if ($item->getHasChildren()) {
                   foreach ($item->getChildren() as $child) {
                   	$product=Mage::getModel('catalog/product')->load($child->getProductId());
   					break;
                   }
   			}
   		} else {
			$product = Mage::getModel('catalog/product')->load($item->getProductId());
   		}

   		return $product;
	}

}


text:
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :content
      t.string :commentable_type
      t.integer :commentable_id
      t.integer :owner_id
      t.timestamps
    end
    add_index :comments, :commentable_id
    add_index :comments, :owner_id
  end
end


text:
from ..utils import ApiUtil
from ..utils import StringUtil
from ..utils.ApiUtil import Url

def get_permission_list(code, token, role_id):
    if StringUtil.isEmpty(code):
        return None

    if StringUtil.isEmpty(token):
        return None

    if StringUtil.isEmpty(role_id):
        return None
    url = Url.permissionList(role_id, Url.url)
    data = {'auth_token': token}
    list = ApiUtil.requestGet(url, code, data)

    return list


text:
import re
from math import sqrt, sin, cos, log, tan, acos, asin, atan, e, pi
from operator import add, sub, div, mul, pow
from numbers import NumberService

class MathService(object):

    __constants__ = {
        'e': e,
        'E': e,
        'EE': e,
        'pi': pi,
        'pie': pi
    }

    __unaryOperators__ = {
        'log': log,
        'sine': sin,
        'sin': sin,
        'cosine': cos,
        'cos': cos,
        'tan': tan,
        'tangent': tan,
        'arcsine': asin,
        'arcsin': asin,
        'asin': asin,
        'arccosine': acos,
        'arccos': acos,
        'acos': acos,
        'arctanget': atan,
        'arctan': atan,
        'atan': atan,
        'sqrt': sqrt
    }

    __binaryOperators__ = {
        'plus': add,
        'add': add,
        'sum': add,
        'minus': sub,
        'sub': sub,
        'subtract': sub,
        'less': sub,
        'over': div,
        'divide': div,
        'times': mul,
        'multiply': mul,
        'to': pow
    }

    @staticmethod
    def _applyBinary(a, b, op):
        a = float(a)
        b = float(b)
        return op(a, b)

    @staticmethod
    def _applyUnary(a, op):
        a = float(a)
        return op(a)

    @staticmethod
    def _preprocess(input):
        """Revise wording to match canonical and expected forms."""
        input = re.sub(r'(\b)a(\b)', r'\g<1>one\g<2>', input)
        input = re.sub(r'to the (.*) power', r'to \g<1>', input)
        input = re.sub(r'to the (.*?)(\b)', r'to \g<1>\g<2>', input)
        input = re.sub(r'log of', r'log', input)
        input = re.sub(r'(square )?root( of)?', r'sqrt', input)
        input = re.sub(r'squared', r'to two', input)
        input = re.sub(r'cubed', r'to three', input)
        input = re.sub(r'divided?( by)?', r'divide', input)
        input = re.sub(r'(\b)over(\b)', r'\g<1>divide\g<2>', input)
        input = re.sub(r'(\b)EE(\b)', r'\g<1>e\g<2>', input)
        input = re.sub(r'(\b)E(\b)', r'\g<1>e\g<2>', input)
        input = re.sub(r'(\b)pie(\b)', r'\g<1>pi\g<2>', input)
        input = re.sub(r'(\b)PI(\b)', r'\g<1>pi\g<2>', input)

        def findImplicitMultiplications(input):
            """Replace omitted 'times' references."""

            def findConstantMultiplications(input):
                split = input.split(' ')
                revision = ""

                converter = NumberService()
                for i, w in enumerate(split):
                    if i > 0 and w in MathService.__constants__:
                        if converter.isValid(split[i - 1]):
                            revision += " times"
                    if not revision:
                        revision = w
                    else:
                        revision += " " + w

                return revision

            def findUnaryMultiplications(input):
                split = input.split(' ')
                revision = ""

                for i, w in enumerate(split):
                    if i > 0 and w in MathService.__unaryOperators__:
                        last_op = split[i - 1]

                        binary = last_op in MathService.__binaryOperators__
                        unary = last_op in MathService.__unaryOperators__

                        if last_op and not (binary or unary):
                            revision += " times"
                    if not revision:
                        revision = w
                    else:
                        revision += " " + w

                return revision

            return findUnaryMultiplications(findConstantMultiplications(input))

        return findImplicitMultiplications(input)

    @staticmethod
    def _calculate(numbers, symbols):
        """Calculates a final value given a set of numbers and symbols."""
        if len(numbers) is 1:
            return numbers[0]

        precedence = [[pow], [mul, div], [add, sub]]

        # Find most important operation
        for op_group in precedence:
            for i, op in enumerate(symbols):
                if op in op_group:
                    # Apply operation
                    a = numbers[i]
                    b = numbers[i + 1]
                    result = MathService._applyBinary(a, b, op)
                    new_numbers = numbers[:i] + [result] + numbers[i + 2:]
                    new_symbols = symbols[:i] + symbols[i + 1:]

                    return MathService._calculate(new_numbers, new_symbols)

    def parseEquation(self, input):
        """Solves the equation specified by the input string.

        Args:
            input (str): An equation, specified in words, containing some
                combination of numbers, binary, and unary operations.

        Returns:
            The floating-point result of carrying out the computation.
        """
        input = MathService._preprocess(input)
        split = input.split(' ')

        # Recursive call on unary operators
        for i, w in enumerate(split):
            if w in self.__unaryOperators__:
                op = self.__unaryOperators__[w]

                # Split equation into halves
                eq1 = ' '.join(split[:i])
                eq2 = ' '.join(split[i + 1:])

                # Calculate second half
                result = MathService._applyUnary(self.parseEquation(eq2), op)

                return self.parseEquation(eq1 + " " + str(result))

        def extractNumbersAndSymbols(input):
            numbers = []
            symbols = []

            # Divide into values (numbers), operators (symbols)
            next_number = ""
            for w in input.split(' '):
                if w in self.__binaryOperators__:
                    symbols.append(self.__binaryOperators__[w])

                    if next_number:
                        numbers.append(next_number)
                        next_number = ""

                else:
                    if next_number:
                        next_number += " "
                    next_number += w

            if next_number:
                numbers.append(next_number)

            # Cast numbers from words to integers
            def convert(n):
                if n in self.__constants__:
                    return self.__constants__[n]

                converter = NumberService()
                return converter.parse(n)

            numbers = [convert(n) for n in numbers]

            return numbers, symbols

        numbers, symbols = extractNumbersAndSymbols(input)

        return MathService._calculate(numbers, symbols)

def parseEquation(self, input):
    """Solves the equation specified by the input string. This is a convenience
    method which would only be used if you'd rather not initialize a
    NumberService object.

    Args:
        input (str): An equation, specified in words, containing some
            combination of numbers, binary, and unary operations.

    Returns:
        The floating-point result of carrying out the computation.
    """

    service = NumberService()
    return service.parseEquation(input)


text:
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
function getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_nodeattributenodevalue";
   }

var docsLoaded = -1000000;
var builder = null;

//
//   This function is called by the testing framework before
//      running the test suite.
//
//   If there are no configuration exceptions, asynchronous
//        document loading is started.  Otherwise, the status
//        is set to complete and the exception is immediately
//        raised when entering the body of the test.
//
function setUpPage() {
   setUpPageStatus = 'running';
   try {
     //
     //   creates test document builder, may throw exception
     //
     builder = createConfiguredBuilder();

      docsLoaded = 0;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      docsLoaded += preload(docRef, "doc", "hc_staff");

       if (docsLoaded == 1) {
          setUpPageStatus = 'complete';
       }
    } catch(ex) {
        catchInitializationError(builder, ex);
        setUpPageStatus = 'complete';
    }
}

//
//   This method is called on the completion of
//      each asychronous load started in setUpTests.
//
//   When every synchronous loaded document has completed,
//      the page status is changed which allows the
//      body of the test to be executed.
function loadComplete() {
    if (++docsLoaded == 1) {
        setUpPageStatus = 'complete';
    }
}

/**
*

    The string returned by the "getNodeValue()" method for an
    Attribute Node is the value of the Attribute.

    Retrieve the Attribute named "title" from the last
    child of the first "p" and check the string returned
    by the "getNodeValue()" method.   It should be equal to
    "Yes".

* @author Curt Arnold
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-F68D080
*/
function hc_nodeattributenodevalue() {
   var success;
    if(checkInitialization(builder, "hc_nodeattributenodevalue") != null) return;
    var doc;
      var elementList;
      var testAddr;
      var addrAttr;
      var attrValue;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      doc = load(docRef, "doc", "hc_staff");
      elementList = doc.getElementsByTagName("acronym");
      testAddr = elementList.item(0);
      addrAttr = testAddr.getAttributeNode("title");
      attrValue = addrAttr.nodeValue;

      assertEquals("nodeValue","Yes",attrValue);

}

function runTest() {
   hc_nodeattributenodevalue();
}


text:
package biz.jovido.seed;

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

import java.util.UUID;

/**
 * @author Stephan Grundner
 */
@NoRepositoryBean
public interface UniqueRepository<T extends Unique> extends JpaRepository<T, Long> {

    T findByUuid(UUID uuid);
}


text:
layout: post
title: "2014-11-20-Download-Stock-Data-1"
description: ""
category: R
tags: [knitr,lubridate,stringr,plyr,dplyr]
---
This article illustrates how to download stock price data files from Google, save it into a local drive and merge them into a single data frame. This script is slightly modified from a script which downloads RStudio package download log data. The original source can be found [here](https://github.com/hadley/cran-logs-dplyr/blob/master/1-download.r).

First of all, the following three packages are used.

{% highlight r %}
library(knitr)
library(lubridate)
library(stringr)
library(plyr)
library(dplyr)
{% endhighlight %}

The script begins with creating a folder to save data files.

{% highlight r %}
# create data folder
dataDir <- paste0("data","_","2014-11-20-Download-Stock-Data-1")
if(file.exists(dataDir)) {
      unlink(dataDir, recursive = TRUE)
      dir.create(dataDir)
} else {
      dir.create(dataDir)
}
{% endhighlight %}

After creating urls and file paths, files are downloaded using `Map` function - it is a warpper of `mapply`. Note that, in case the function breaks by an error (eg when a file doesn't exist), `download.file` is wrapped by another function that includes an error handler (`tryCatch`).

{% highlight r %}
# assumes codes are known beforehand
codes <- c("MSFT", "TCHC") # codes <- c("MSFT", "1234") for testing
urls <- paste0("http://www.google.com/finance/historical?q=NASDAQ:",
               codes,"&output=csv")
paths <- paste0(dataDir,"/",codes,".csv") # back slash on windows (\\)

# simple error handling in case file doesn't exists
downloadFile <- function(url, path, ...) {
      # remove file if exists already
      if(file.exists(path)) file.remove(path)
      # download file
      tryCatch(
            download.file(url, path, ...), error = function(c) {
                  # remove file if error
                  if(file.exists(path)) file.remove(path)
                  # create error message
                  c$message <- paste(substr(path, 1, 4),"failed")
                  message(c$message)
            }
      )
}
# wrapper of mapply
Map(downloadFile, urls, paths)
{% endhighlight %}

Finally files are read back using `llply` and they are combined using `rbind_all`. Note that, as the merged data has multiple stocks' records, `Code` column is created.

{% highlight r %}
# read all csv files and merge
files <- dir(dataDir, full.name = TRUE)
dataList <- llply(files, function(file){
      data <- read.csv(file, stringsAsFactors = FALSE)
      # get code from file path
      pattern <- "/[A-Z][A-Z][A-Z][A-Z]"
      code <- substr(str_extract(file, pattern), 2, nchar(str_extract(file, pattern)))
      # first column's name is funny
      names(data) <- c("Date","Open","High","Low","Close","Volume")
      data$Date <- dmy(data$Date)
      data$Open <- as.numeric(data$Open)
      data$High <- as.numeric(data$High)
      data$Low <- as.numeric(data$Low)
      data$Close <- as.numeric(data$Close)
      data$Volume <- as.integer(data$Volume)
      data$Code <- code
      data
}, .progress = "text")

data <- rbind_all(dataList)
{% endhighlight %}

Some of the values are shown below.

|Date       |  Open|  High|   Low| Close|   Volume|Code |
|:----------|-----:|-----:|-----:|-----:|--------:|:----|
|2014-11-26 | 47.49| 47.99| 47.28| 47.75| 27164877|MSFT |
|2014-11-25 | 47.66| 47.97| 47.45| 47.47| 28007993|MSFT |
|2014-11-24 | 47.99| 48.00| 47.39| 47.59| 35434245|MSFT |
|2014-11-21 | 49.02| 49.05| 47.57| 47.98| 42884795|MSFT |
|2014-11-20 | 48.00| 48.70| 47.87| 48.70| 21510587|MSFT |
|2014-11-19 | 48.66| 48.75| 47.93| 48.22| 26177450|MSFT |

This way wouldn't be efficient compared to the way where files are read directly without being saved into a local drive. This option may be useful, however, if files are large and the API server breaks connection abrubtly.

I hope this article is useful and I'm going to write an article to show the second way.


text:
package io.aos.crypto.spl10;

import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

/**
 * SSL Client with client-side authentication.
 */
public class SSLClientWithClientAuthTrustExample
    extends SSLClientExample
{
    /**
     * Create an SSL context with both identity and trust store
     */
    static SSLContext createSSLContext()
        throws Exception
    {
        // set up a key manager for our local credentials
		KeyManagerFactory mgrFact = KeyManagerFactory.getInstance("SunX509");
		KeyStore clientStore = KeyStore.getInstance("PKCS12");

		clientStore.load(new FileInputStream("client.p12"), Utils.CLIENT_PASSWORD);

		mgrFact.init(clientStore, Utils.CLIENT_PASSWORD);

		// set up a trust manager so we can recognize the server
		TrustManagerFactory trustFact = TrustManagerFactory.getInstance("SunX509");
		KeyStore            trustStore = KeyStore.getInstance("JKS");

		trustStore.load(new FileInputStream("trustStore.jks"), Utils.TRUST_STORE_PASSWORD);

		trustFact.init(trustStore);

		// create a context and set up a socket factory
		SSLContext sslContext = SSLContext.getInstance("TLS");

		sslContext.init(mgrFact.getKeyManagers(), trustFact.getTrustManagers(), null);

		return sslContext;
    }

    public static void main(
        String[] args)
        throws Exception
    {
        SSLContext       sslContext = createSSLContext();
		SSLSocketFactory fact = sslContext.getSocketFactory();
        SSLSocket        cSock = (SSLSocket)fact.createSocket(Utils.HOST, Utils.PORT_NO);

        doProtocol(cSock);
    }
}


text:
<component name="InspectionProjectProfileManager">
  <profile version="1.0">
    <option name="myName" value="Project Default" />
    <inspection_tool class="MoreThanThreeArgumentsInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SingletonFactoryPatternViolationInspection" enabled="false" level="WARNING" enabled_by_default="false" />
  </profile>
</component>


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**allow_3rd_party_billing** | **bool** | True if this method allows the customer to use their own shipper account number | [optional]
**comment** | **string** | Comment to display to the customer about this method | [optional]
**cost** | [**\ultracart\v2\models\Currency**](Currency.md) |  | [optional]
**cost_before_discount** | [**\ultracart\v2\models\Currency**](Currency.md) |  | [optional]
**default_method** | **bool** | True if this is the default method | [optional]
**discount** | [**\ultracart\v2\models\Currency**](Currency.md) |  | [optional]
**discounted** | **bool** | True if this method is discounted because of a coupon | [optional]
**display_name** | **string** | The name to display to the customer | [optional]
**estimated_delivery** | **string** | Date of the estimated delivery (or range) | [optional]
**lift_gate_option** | **bool** | True if a lift gate option for this method should be offered to the customer | [optional]
**name** | **string** | Shipping method name | [optional]
**pickup** | **bool** | True if this shipping method requires customers to physically pickup product themselves | [optional]
**tax** | [**\ultracart\v2\models\Currency**](Currency.md) |  | [optional]
**total_tax** | [**\ultracart\v2\models\Currency**](Currency.md) |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
layout: compress
---
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% if page.title %}{{ page.title }} - {{ site.title }}{% else %}{{ site.title }}{% endif %}</title>
  <link href="https://fonts.googleapis.com/css?family=Lato:900|Work+Sans" rel="stylesheet">
  <link rel="stylesheet" href="{{site.baseurl}}/css/main.css">
  <link rel="stylesheet" href="https://cdn.plyr.io/2.0.13/plyr.css">
  <link rel="stylesheet" href="{{site.baseurl}}/css/mycss.css">
  {% seo %}

 {% if page.plotgen %}

 {% endif %}

  {{ content }}

        Info

{% include analytics.html %}


text:
#pragma once
#include <aws/dms/DatabaseMigrationService_EXPORTS.h>
#include <aws/dms/DatabaseMigrationServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace DatabaseMigrationService
{
namespace Model
{

  /**
   *

   */
  class AWS_DATABASEMIGRATIONSERVICE_API StopReplicationTaskRequest : public DatabaseMigrationServiceRequest
  {
  public:
    StopReplicationTaskRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The Amazon Resource Number(ARN) of the replication task to be stopped.

     */
    inline const Aws::String& GetReplicationTaskArn() const{ return m_replicationTaskArn; }

    /**
     *
The Amazon Resource Number(ARN) of the replication task to be stopped.

     */
    inline void SetReplicationTaskArn(const Aws::String& value) { m_replicationTaskArnHasBeenSet = true; m_replicationTaskArn = value; }

    /**
     *
The Amazon Resource Number(ARN) of the replication task to be stopped.

     */
    inline void SetReplicationTaskArn(Aws::String&& value) { m_replicationTaskArnHasBeenSet = true; m_replicationTaskArn = value; }

    /**
     *
The Amazon Resource Number(ARN) of the replication task to be stopped.

     */
    inline void SetReplicationTaskArn(const char* value) { m_replicationTaskArnHasBeenSet = true; m_replicationTaskArn.assign(value); }

    /**
     *
The Amazon Resource Number(ARN) of the replication task to be stopped.

     */
    inline StopReplicationTaskRequest& WithReplicationTaskArn(const Aws::String& value) { SetReplicationTaskArn(value); return *this;}

    /**
     *
The Amazon Resource Number(ARN) of the replication task to be stopped.

     */
    inline StopReplicationTaskRequest& WithReplicationTaskArn(Aws::String&& value) { SetReplicationTaskArn(value); return *this;}

    /**
     *
The Amazon Resource Number(ARN) of the replication task to be stopped.

     */
    inline StopReplicationTaskRequest& WithReplicationTaskArn(const char* value) { SetReplicationTaskArn(value); return *this;}

  private:
    Aws::String m_replicationTaskArn;
    bool m_replicationTaskArnHasBeenSet;
  };

} // namespace Model
} // namespace DatabaseMigrationService
} // namespace Aws


text:
package s3manager_test

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"sort"
	"strings"
	"sync"
	"testing"

	"github.com/dragonfax/aws-sdk-go/aws"
	"github.com/dragonfax/aws-sdk-go/aws/awserr"
	"github.com/dragonfax/aws-sdk-go/aws/awsutil"
	"github.com/dragonfax/aws-sdk-go/aws/request"
	"github.com/dragonfax/aws-sdk-go/internal/test/unit"
	"github.com/dragonfax/aws-sdk-go/service/s3"
	"github.com/dragonfax/aws-sdk-go/service/s3/s3manager"
	"github.com/stretchr/testify/assert"
)

var _ = unit.Imported
var buf12MB = make([]byte, 1024*1024*12)
var buf2MB = make([]byte, 1024*1024*2)

var emptyList = []string{}

func val(i interface{}, s string) interface{} {
	return awsutil.ValuesAtPath(i, s)[0]
}

func contains(src []string, s string) bool {
	for _, v := range src {
		if s == v {
			return true
		}
	}
	return false
}

func loggingSvc(ignoreOps []string) (*s3.S3, *[]string, *[]interface{}) {
	var m sync.Mutex
	partNum := 0
	names := []string{}
	params := []interface{}{}
	svc := s3.New(nil)
	svc.Handlers.Unmarshal.Clear()
	svc.Handlers.UnmarshalMeta.Clear()
	svc.Handlers.UnmarshalError.Clear()
	svc.Handlers.Send.Clear()
	svc.Handlers.Send.PushBack(func(r *request.Request) {
		m.Lock()
		defer m.Unlock()

		if !contains(ignoreOps, r.Operation.Name) {
			names = append(names, r.Operation.Name)
			params = append(params, r.Params)
		}

		r.HTTPResponse = &http.Response{
			StatusCode: 200,
			Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
		}

		switch data := r.Data.(type) {
		case *s3.CreateMultipartUploadOutput:
			data.UploadId = aws.String("UPLOAD-ID")
		case *s3.UploadPartOutput:
			partNum++
			data.ETag = aws.String(fmt.Sprintf("ETAG%d", partNum))
		case *s3.CompleteMultipartUploadOutput:
			data.Location = aws.String("https://location")
		}
	})

	return svc, &names, &params
}

func buflen(i interface{}) int {
	r := i.(io.Reader)
	b, _ := ioutil.ReadAll(r)
	return len(b)
}

func TestUploadOrderMulti(t *testing.T) {
	s, ops, args := loggingSvc(emptyList)
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s})
	resp, err := mgr.Upload(&s3manager.UploadInput{
		Bucket:               aws.String("Bucket"),
		Key:                  aws.String("Key"),
		Body:                 bytes.NewReader(buf12MB),
		ServerSideEncryption: aws.String("AES256"),
		ContentType:          aws.String("content/type"),
	})

	assert.NoError(t, err)
	assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "UploadPart", "CompleteMultipartUpload"}, *ops)
	assert.Equal(t, "https://location", resp.Location)
	assert.Equal(t, "UPLOAD-ID", resp.UploadID)

	// Validate input values

	// UploadPart
	assert.Equal(t, "UPLOAD-ID", val((*args)[1], "UploadId"))
	assert.Equal(t, "UPLOAD-ID", val((*args)[2], "UploadId"))
	assert.Equal(t, "UPLOAD-ID", val((*args)[3], "UploadId"))

	// CompleteMultipartUpload
	assert.Equal(t, "UPLOAD-ID", val((*args)[4], "UploadId"))
	assert.Equal(t, int64(1), val((*args)[4], "MultipartUpload.Parts[0].PartNumber"))
	assert.Equal(t, int64(2), val((*args)[4], "MultipartUpload.Parts[1].PartNumber"))
	assert.Equal(t, int64(3), val((*args)[4], "MultipartUpload.Parts[2].PartNumber"))
	assert.Regexp(t, `^ETAG\d+$`, val((*args)[4], "MultipartUpload.Parts[0].ETag"))
	assert.Regexp(t, `^ETAG\d+$`, val((*args)[4], "MultipartUpload.Parts[1].ETag"))
	assert.Regexp(t, `^ETAG\d+$`, val((*args)[4], "MultipartUpload.Parts[2].ETag"))

	// Custom headers
	assert.Equal(t, "AES256", val((*args)[0], "ServerSideEncryption"))
	assert.Equal(t, "content/type", val((*args)[0], "ContentType"))
}

func TestUploadOrderMultiDifferentPartSize(t *testing.T) {
	s, ops, args := loggingSvc(emptyList)
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{
		S3:          s,
		PartSize:    1024 * 1024 * 7,
		Concurrency: 1,
	})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(buf12MB),
	})

	assert.NoError(t, err)
	assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "CompleteMultipartUpload"}, *ops)

	// Part lengths
	assert.Equal(t, 1024*1024*7, buflen(val((*args)[1], "Body")))
	assert.Equal(t, 1024*1024*5, buflen(val((*args)[2], "Body")))
}

func TestUploadIncreasePartSize(t *testing.T) {
	s3manager.MaxUploadParts = 2
	defer func() { s3manager.MaxUploadParts = 10000 }()

	s, ops, args := loggingSvc(emptyList)
	opts := &s3manager.UploadOptions{S3: s, Concurrency: 1}
	mgr := s3manager.NewUploader(opts)
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(buf12MB),
	})

	assert.NoError(t, err)
	assert.Equal(t, int64(0), opts.PartSize) // don't modify orig options
	assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "CompleteMultipartUpload"}, *ops)

	// Part lengths
	assert.Equal(t, 1024*1024*6, buflen(val((*args)[1], "Body")))
	assert.Equal(t, 1024*1024*6, buflen(val((*args)[2], "Body")))
}

func TestUploadFailIfPartSizeTooSmall(t *testing.T) {
	opts := &s3manager.UploadOptions{PartSize: 5}
	mgr := s3manager.NewUploader(opts)
	resp, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(buf12MB),
	})

	assert.Nil(t, resp)
	assert.NotNil(t, err)

	aerr := err.(awserr.Error)
	assert.Equal(t, "ConfigError", aerr.Code())
	assert.Contains(t, aerr.Message(), "part size must be at least")
}

func TestUploadOrderSingle(t *testing.T) {
	s, ops, args := loggingSvc(emptyList)
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s})
	resp, err := mgr.Upload(&s3manager.UploadInput{
		Bucket:               aws.String("Bucket"),
		Key:                  aws.String("Key"),
		Body:                 bytes.NewReader(buf2MB),
		ServerSideEncryption: aws.String("AES256"),
		ContentType:          aws.String("content/type"),
	})

	assert.NoError(t, err)
	assert.Equal(t, []string{"PutObject"}, *ops)
	assert.NotEqual(t, "", resp.Location)
	assert.Equal(t, "", resp.UploadID)
	assert.Equal(t, "AES256", val((*args)[0], "ServerSideEncryption"))
	assert.Equal(t, "content/type", val((*args)[0], "ContentType"))
}

func TestUploadOrderSingleFailure(t *testing.T) {
	s, ops, _ := loggingSvc(emptyList)
	s.Handlers.Send.PushBack(func(r *request.Request) {
		r.HTTPResponse.StatusCode = 400
	})
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s})
	resp, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(buf2MB),
	})

	assert.Error(t, err)
	assert.Equal(t, []string{"PutObject"}, *ops)
	assert.Nil(t, resp)
}

func TestUploadOrderZero(t *testing.T) {
	s, ops, args := loggingSvc(emptyList)
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s})
	resp, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(make([]byte, 0)),
	})

	assert.NoError(t, err)
	assert.Equal(t, []string{"PutObject"}, *ops)
	assert.NotEqual(t, "", resp.Location)
	assert.Equal(t, "", resp.UploadID)
	assert.Equal(t, 0, buflen(val((*args)[0], "Body")))
}

func TestUploadOrderMultiFailure(t *testing.T) {
	s, ops, _ := loggingSvc(emptyList)
	s.Handlers.Send.PushBack(func(r *request.Request) {
		switch t := r.Data.(type) {
		case *s3.UploadPartOutput:
			if *t.ETag == "ETAG2" {
				r.HTTPResponse.StatusCode = 400
			}
		}
	})

	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(buf12MB),
	})

	assert.Error(t, err)
	assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "AbortMultipartUpload"}, *ops)
}

func TestUploadOrderMultiFailureOnComplete(t *testing.T) {
	s, ops, _ := loggingSvc(emptyList)
	s.Handlers.Send.PushBack(func(r *request.Request) {
		switch r.Data.(type) {
		case *s3.CompleteMultipartUploadOutput:
			r.HTTPResponse.StatusCode = 400
		}
	})

	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(buf12MB),
	})

	assert.Error(t, err)
	assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart",
		"UploadPart", "CompleteMultipartUpload", "AbortMultipartUpload"}, *ops)
}

func TestUploadOrderMultiFailureOnCreate(t *testing.T) {
	s, ops, _ := loggingSvc(emptyList)
	s.Handlers.Send.PushBack(func(r *request.Request) {
		switch r.Data.(type) {
		case *s3.CreateMultipartUploadOutput:
			r.HTTPResponse.StatusCode = 400
		}
	})

	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(make([]byte, 1024*1024*12)),
	})

	assert.Error(t, err)
	assert.Equal(t, []string{"CreateMultipartUpload"}, *ops)
}

func TestUploadOrderMultiFailureLeaveParts(t *testing.T) {
	s, ops, _ := loggingSvc(emptyList)
	s.Handlers.Send.PushBack(func(r *request.Request) {
		switch data := r.Data.(type) {
		case *s3.UploadPartOutput:
			if *data.ETag == "ETAG2" {
				r.HTTPResponse.StatusCode = 400
			}
		}
	})

	mgr := s3manager.NewUploader(&s3manager.UploadOptions{
		S3:                s,
		Concurrency:       1,
		LeavePartsOnError: true,
	})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(make([]byte, 1024*1024*12)),
	})

	assert.Error(t, err)
	assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart"}, *ops)
}

type failreader struct {
	times     int
	failCount int
}

func (f *failreader) Read(b []byte) (int, error) {
	f.failCount++
	if f.failCount >= f.times {
		return 0, fmt.Errorf("random failure")
	}
	return len(b), nil
}

func TestUploadOrderReadFail1(t *testing.T) {
	s, ops, _ := loggingSvc(emptyList)
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   &failreader{times: 1},
	})

	assert.Equal(t, "ReadRequestBody", err.(awserr.Error).Code())
	assert.EqualError(t, err.(awserr.Error).OrigErr(), "random failure")
	assert.Equal(t, []string{}, *ops)
}

func TestUploadOrderReadFail2(t *testing.T) {
	s, ops, _ := loggingSvc([]string{"UploadPart"})
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   &failreader{times: 2},
	})

	assert.Equal(t, "ReadRequestBody", err.(awserr.Error).Code())
	assert.EqualError(t, err.(awserr.Error).OrigErr(), "random failure")
	assert.Equal(t, []string{"CreateMultipartUpload", "AbortMultipartUpload"}, *ops)
}

type sizedReader struct {
	size int
	cur  int
}

func (s *sizedReader) Read(p []byte) (n int, err error) {
	if s.cur >= s.size {
		return 0, io.EOF
	}

	n = len(p)
	s.cur += len(p)
	if s.cur > s.size {
		n -= s.cur - s.size
	}

	return
}

func TestUploadOrderMultiBufferedReader(t *testing.T) {
	s, ops, args := loggingSvc(emptyList)
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   &sizedReader{size: 1024 * 1024 * 12},
	})

	assert.NoError(t, err)
	assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "UploadPart", "CompleteMultipartUpload"}, *ops)

	// Part lengths
	parts := []int{
		buflen(val((*args)[1], "Body")),
		buflen(val((*args)[2], "Body")),
		buflen(val((*args)[3], "Body")),
	}
	sort.Ints(parts)
	assert.Equal(t, []int{1024 * 1024 * 2, 1024 * 1024 * 5, 1024 * 1024 * 5}, parts)
}

func TestUploadOrderMultiBufferedReaderExceedTotalParts(t *testing.T) {
	s3manager.MaxUploadParts = 2
	defer func() { s3manager.MaxUploadParts = 10000 }()
	s, ops, _ := loggingSvc([]string{"UploadPart"})
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1})
	resp, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   &sizedReader{size: 1024 * 1024 * 12},
	})

	assert.Error(t, err)
	assert.Nil(t, resp)
	assert.Equal(t, []string{"CreateMultipartUpload", "AbortMultipartUpload"}, *ops)

	aerr := err.(awserr.Error)
	assert.Equal(t, "TotalPartsExceeded", aerr.Code())
	assert.Contains(t, aerr.Message(), "exceeded total allowed parts (2)")
}

func TestUploadOrderSingleBufferedReader(t *testing.T) {
	s, ops, _ := loggingSvc(emptyList)
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s})
	resp, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   &sizedReader{size: 1024 * 1024 * 2},
	})

	assert.NoError(t, err)
	assert.Equal(t, []string{"PutObject"}, *ops)
	assert.NotEqual(t, "", resp.Location)
	assert.Equal(t, "", resp.UploadID)
}

func TestUploadZeroLenObject(t *testing.T) {
	requestMade := false
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requestMade = true
		w.WriteHeader(http.StatusOK)
	}))
	svc := s3.New(&aws.Config{
		Endpoint: aws.String(server.URL),
	})
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: svc})
	resp, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   strings.NewReader(""),
	})

	assert.NoError(t, err)
	assert.True(t, requestMade)
	assert.NotEqual(t, "", resp.Location)
	assert.Equal(t, "", resp.UploadID)
}