text:
<?php

/**
 * Product type price model
 *
 * @category    Mage
 * @package     Mage_Catalog
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Catalog_Model_Product_Type_Price
{
    const CACHE_TAG = 'PRODUCT_PRICE';

    static $attributeCache = array();

    /**
     * Default action to get price of product
     *
     * @return decimal
     */
    public function getPrice($product)
    {
        return $product->getData('price');
    }

    /**
     * Get base price with apply Group, Tier, Special prises
     *
     * @param Mage_Catalog_Model_Product $product
     * @param float|null $qty
     *
     * @return float
     */
    public function getBasePrice($product, $qty = null)
    {
        $price = (float)$product->getPrice();
        return min($this->_applyGroupPrice($product, $price), $this->_applyTierPrice($product, $qty, $price),
            $this->_applySpecialPrice($product, $price)
        );
    }

    /**
     * Retrieve product final price
     *
     * @param float|null $qty
     * @param Mage_Catalog_Model_Product $product
     * @return float
     */
    public function getFinalPrice($qty = null, $product)
    {
        if (is_null($qty) && !is_null($product->getCalculatedFinalPrice())) {
            return $product->getCalculatedFinalPrice();
        }

        $finalPrice = $this->getBasePrice($product, $qty);
        $product->setFinalPrice($finalPrice);

        Mage::dispatchEvent('catalog_product_get_final_price', array('product' => $product, 'qty' => $qty));

        $finalPrice = $product->getData('final_price');
        $finalPrice = $this->_applyOptionsPrice($product, $qty, $finalPrice);
        $finalPrice = max(0, $finalPrice);
        $product->setFinalPrice($finalPrice);

        return $finalPrice;
    }

    public function getChildFinalPrice($product, $productQty, $childProduct, $childProductQty)
    {
        return $this->getFinalPrice($childProductQty, $childProduct);
    }

    /**
     * Apply group price for product
     *
     * @param Mage_Catalog_Model_Product $product
     * @param float $finalPrice
     * @return float
     */
    protected function _applyGroupPrice($product, $finalPrice)
    {
        $groupPrice = $product->getGroupPrice();
        if (is_numeric($groupPrice)) {
            $finalPrice = min($finalPrice, $groupPrice);
        }
        return $finalPrice;
    }

    /**
     * Get product group price
     *
     * @param Mage_Catalog_Model_Product $product
     * @return float
     */
    public function getGroupPrice($product)
    {

        $groupPrices = $product->getData('group_price');

        if (is_null($groupPrices)) {
            $attribute = $product->getResource()->getAttribute('group_price');
            if ($attribute) {
                $attribute->getBackend()->afterLoad($product);
                $groupPrices = $product->getData('group_price');
            }
        }

        if (is_null($groupPrices) || !is_array($groupPrices)) {
            return $product->getPrice();
        }

        $customerGroup = $this->_getCustomerGroupId($product);

        $matchedPrice = $product->getPrice();
        foreach ($groupPrices as $groupPrice) {
            if ($groupPrice['cust_group'] == $customerGroup && $groupPrice['website_price'] < $matchedPrice) {
                $matchedPrice = $groupPrice['website_price'];
                break;
            }
        }

        return $matchedPrice;
    }

    /**
     * Apply tier price for product if not return price that was before
     *
     * @param   Mage_Catalog_Model_Product $product
     * @param   float $qty
     * @param   float $finalPrice
     * @return  float
     */
    protected function _applyTierPrice($product, $qty, $finalPrice)
    {
        if (is_null($qty)) {
            return $finalPrice;
        }

        $tierPrice  = $product->getTierPrice($qty);
        if (is_numeric($tierPrice)) {
            $finalPrice = min($finalPrice, $tierPrice);
        }
        return $finalPrice;
    }

    /**
     * Get product tier price by qty
     *
     * @param   float $qty
     * @param   Mage_Catalog_Model_Product $product
     * @return  float
     */
    public function getTierPrice($qty = null, $product)
    {
        $allGroups = Mage_Customer_Model_Group::CUST_GROUP_ALL;
        $prices = $product->getData('tier_price');

        if (is_null($prices)) {
            $attribute = $product->getResource()->getAttribute('tier_price');
            if ($attribute) {
                $attribute->getBackend()->afterLoad($product);
                $prices = $product->getData('tier_price');
            }
        }

        if (is_null($prices) || !is_array($prices)) {
            if (!is_null($qty)) {
                return $product->getPrice();
            }
            return array(array(
                'price'         => $product->getPrice(),
                'website_price' => $product->getPrice(),
                'price_qty'     => 1,
                'cust_group'    => $allGroups,
            ));
        }

        $custGroup = $this->_getCustomerGroupId($product);
        if ($qty) {
            $prevQty = 1;
            $prevPrice = $product->getPrice();
            $prevGroup = $allGroups;

            foreach ($prices as $price) {
                if ($price['cust_group']!=$custGroup && $price['cust_group']!=$allGroups) {
                    // tier not for current customer group nor is for all groups
                    continue;
                }
                if ($qty < $price['price_qty']) {
                    // tier is higher than product qty
                    continue;
                }
                if ($price['price_qty'] < $prevQty) {
                    // higher tier qty already found
                    continue;
                }
                if ($price['price_qty'] == $prevQty && $prevGroup != $allGroups && $price['cust_group'] == $allGroups) {
                    // found tier qty is same as current tier qty but current tier group is ALL_GROUPS
                    continue;
                }
                if ($price['website_price'] < $prevPrice) {
                    $prevPrice  = $price['website_price'];
                    $prevQty    = $price['price_qty'];
                    $prevGroup  = $price['cust_group'];
                }
            }
            return $prevPrice;
        } else {
            $qtyCache = array();
            foreach ($prices as $i => $price) {
                if ($price['cust_group'] != $custGroup && $price['cust_group'] != $allGroups) {
                    unset($prices[$i]);
                } else if (isset($qtyCache[$price['price_qty']])) {
                    $j = $qtyCache[$price['price_qty']];
                    if ($prices[$j]['website_price'] > $price['website_price']) {
                        unset($prices[$j]);
                        $qtyCache[$price['price_qty']] = $i;
                    } else {
                        unset($prices[$i]);
                    }
                } else {
                    $qtyCache[$price['price_qty']] = $i;
                }
            }
        }

        return ($prices) ? $prices : array();
    }

    protected function _getCustomerGroupId($product)
    {
        if ($product->getCustomerGroupId()) {
            return $product->getCustomerGroupId();
        }
        return Mage::getSingleton('customer/session')->getCustomerGroupId();
    }

    /**
     * Apply special price for product if not return price that was before
     *
     * @param   Mage_Catalog_Model_Product $product
     * @param   float $finalPrice
     * @return  float
     */
    protected function _applySpecialPrice($product, $finalPrice)
    {
        return $this->calculateSpecialPrice($finalPrice, $product->getSpecialPrice(), $product->getSpecialFromDate(),
                        $product->getSpecialToDate(), $product->getStore()
        );
    }

    /**
     * Count how many tier prices we have for the product
     *
     * @param   Mage_Catalog_Model_Product $product
     * @return  int
     */
    public function getTierPriceCount($product)
    {
        $price = $product->getTierPrice();
        return count($price);
    }

    /**
     * Get formatted by currency tier price
     *
     * @param   float $qty
     * @param   Mage_Catalog_Model_Product $product
     * @return  array || float
     */
    public function getFormatedTierPrice($qty=null, $product)
    {
        $price = $product->getTierPrice($qty);
        if (is_array($price)) {
            foreach ($price as $index => $value) {
                $price[$index]['formated_price'] = Mage::app()->getStore()->convertPrice(
                        $price[$index]['website_price'], true
                );
            }
        }
        else {
            $price = Mage::app()->getStore()->formatPrice($price);
        }

        return $price;
    }

    /**
     * Get formatted by currency product price
     *
     * @param   Mage_Catalog_Model_Product $product
     * @return  array || float
     */
    public function getFormatedPrice($product)
    {
        return Mage::app()->getStore()->formatPrice($product->getFinalPrice());
    }

    /**
     * Apply options price
     *
     * @param Mage_Catalog_Model_Product $product
     * @param int $qty
     * @param float $finalPrice
     * @return float
     */
    protected function _applyOptionsPrice($product, $qty, $finalPrice)
    {
        if ($optionIds = $product->getCustomOption('option_ids')) {
            $basePrice = $finalPrice;
            foreach (explode(',', $optionIds->getValue()) as $optionId) {
                if ($option = $product->getOptionById($optionId)) {
                    $confItemOption = $product->getCustomOption('option_'.$option->getId());

                    $group = $option->groupFactory($option->getType())
                        ->setOption($option)
                        ->setConfigurationItemOption($confItemOption);
                    $finalPrice += $group->getOptionPrice($confItemOption->getValue(), $basePrice);
                }
            }
        }

        return $finalPrice;
    }

    /**
     * Calculate product price based on special price data and price rules
     *
     * @param   float $basePrice
     * @param   float $specialPrice
     * @param   string $specialPriceFrom
     * @param   string $specialPriceTo
     * @param   float|null|false $rulePrice
     * @param   mixed $wId
     * @param   mixed $gId
     * @param   null|int $productId
     * @return  float
     */
    public static function calculatePrice($basePrice, $specialPrice, $specialPriceFrom, $specialPriceTo,
            $rulePrice = false, $wId = null, $gId = null, $productId = null)
    {
        Varien_Profiler::start('__PRODUCT_CALCULATE_PRICE__');
        if ($wId instanceof Mage_Core_Model_Store) {
            $sId = $wId->getId();
            $wId = $wId->getWebsiteId();
        } else {
            $sId = Mage::app()->getWebsite($wId)->getDefaultGroup()->getDefaultStoreId();
        }

        $finalPrice = $basePrice;
        if ($gId instanceof Mage_Customer_Model_Group) {
            $gId = $gId->getId();
        }

        $finalPrice = self::calculateSpecialPrice($finalPrice, $specialPrice, $specialPriceFrom, $specialPriceTo, $sId);

        if ($rulePrice === false) {
            $storeTimestamp = Mage::app()->getLocale()->storeTimeStamp($sId);
            $rulePrice = Mage::getResourceModel('catalogrule/rule')
                ->getRulePrice($storeTimestamp, $wId, $gId, $productId);
        }

        if ($rulePrice !== null && $rulePrice !== false) {
            $finalPrice = min($finalPrice, $rulePrice);
        }

        $finalPrice = max($finalPrice, 0);
        Varien_Profiler::stop('__PRODUCT_CALCULATE_PRICE__');
        return $finalPrice;
    }

    /**
     * Calculate and apply special price
     *
     * @param float $finalPrice
     * @param float $specialPrice
     * @param string $specialPriceFrom
     * @param string $specialPriceTo
     * @param mixed $store
     * @return float
     */
    public static function calculateSpecialPrice($finalPrice, $specialPrice, $specialPriceFrom, $specialPriceTo,
            $store = null)
    {
        if (!is_null($specialPrice) && $specialPrice != false) {
            if (Mage::app()->getLocale()->isStoreDateInInterval($store, $specialPriceFrom, $specialPriceTo)) {
                $finalPrice     = min($finalPrice, $specialPrice);
            }
        }
        return $finalPrice;
    }

    /**
     * Check is tier price value fixed or percent of original price
     *
     * @return bool
     */
    public function isTierPriceFixed()
    {
        return $this->isGroupPriceFixed();
    }

    /**
     * Check is group price value fixed or percent of original price
     *
     * @return bool
     */
    public function isGroupPriceFixed()
    {
        return true;
    }
}


text:
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Apis.Json;
using Google.Apis.Requests;
using Google.Apis.Util;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace Google.Cloud.BigQuery.V2.Tests
{
    public class RetryHandlerTest
    {

        [Fact]
        public async Task IsRetriableResponse_NonRetriableReason()
        {
            var standardResponse = new StandardResponse<object>
            {
                Error = new RequestError
                {
                    Errors = new[] { new SingleError { Reason = "invalidQuery" } }
                }
            };
            await AssertRetriable(false, standardResponse);
        }

        [Fact]
        public async Task IsRetriableResponse_RetriableReason()
        {
            var standardResponse = new StandardResponse<object>
            {
                Error = new RequestError
                {
                    Errors = new[] { new SingleError { Reason = "backendError" } }
                }
            };
            await AssertRetriable(true, standardResponse);
        }

        [Fact]
        public async Task IsRetriableResponse_NoErrors()
        {
            var standardResponse = new StandardResponse<object>
            {
                Error = new RequestError { Message = "Look ma, no errors collection!" }
            };
            await AssertRetriable(false, standardResponse);
        }

        [Fact]
        public async Task IsRetriableResponse_BadGateway()
        {
            var httpResponse = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.BadGateway,
                Content = new StringContent("No JSON returned")
            };
            var actual = await RetryHandler.IsRetriableResponse(httpResponse);
            Assert.True(actual);
        }

        private async Task AssertRetriable(bool expectedRetriable, StandardResponse<object> standardResponse)
        {
            string json = NewtonsoftJsonSerializer.Instance.Serialize(standardResponse);
            var httpResponse = new HttpResponseMessage { Content = new StringContent(json) };
            var actual = await RetryHandler.IsRetriableResponse(httpResponse);
            Assert.Equal(expectedRetriable, actual);
        }

        [Fact]
        public async Task IsRetriableResponse_UnparseableResponse()
        {
            var response = new HttpResponseMessage();
            response.Content = new StringContent("This isn't JSON");
            Assert.False(await RetryHandler.IsRetriableResponse(response));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package dps

import (
	"bytes"
	"errors"
	"go2o/src/core/domain/interface/enum"
	"go2o/src/core/domain/interface/shopping"
	"go2o/src/core/dto"
)

type shoppingService struct {
	_rep shopping.IShoppingRep
}

func NewShoppingService(r shopping.IShoppingRep) *shoppingService {
	return &shoppingService{
		_rep: r,
	}
}

func (this *shoppingService) BuildOrder(partnerId int, memberId int,
	cartKey string, couponCode string) (map[string]interface{}, error) {
	var sp shopping.IShopping = this._rep.GetShopping(partnerId)
	order, _, err := sp.BuildOrder(memberId, couponCode)
	if err != nil {
		return nil, err
	}

	v := order.GetValue()
	buf := bytes.NewBufferString("")

	for _, v := range order.GetCoupons() {
		buf.WriteString(v.GetDescribe())
		buf.WriteString("\n")
	}

	var data map[string]interface{}
	data = make(map[string]interface{})
	if couponCode != "" {
		if v.CouponFee == 0 {
			data["result"] = v.CouponFee != 0
			data["message"] = "优惠券无效"
		} else {
			// 成功应用优惠券
			data["totalFee"] = v.TotalFee
			data["fee"] = v.Fee
			data["payFee"] = v.PayFee
			data["discountFee"] = v.DiscountFee
			data["couponFee"] = v.CouponFee
			data["couponDescribe"] = buf.String()
		}
	} else {
		// 取消优惠券
		data["totalFee"] = v.TotalFee
		data["fee"] = v.Fee
		data["payFee"] = v.PayFee
		data["discountFee"] = v.DiscountFee
	}
	return data, err
}

func (this *shoppingService) SubmitOrder(partnerId, memberId int, couponCode string, useBalanceDiscount bool) (
	orderNo string, err error) {
	var sp shopping.IShopping = this._rep.GetShopping(partnerId)
	return sp.SubmitOrder(memberId, couponCode, useBalanceDiscount)
}

func (this *shoppingService) SetDeliverShop(partnerId int, orderNo string,
	shopId int) error {
	var sp shopping.IShopping = this._rep.GetShopping(partnerId)
	order, err := sp.GetOrderByNo(orderNo)
	if err == nil {
		err = order.SetShop(shopId)
	}
	err = order.SetShop(shopId)
	if err == nil {
		_, err = order.Save()
	}
	return err
}

func (this *shoppingService) HandleOrder(partnerId int, orderNo string) error {
	var sp shopping.IShopping = this._rep.GetShopping(partnerId)
	order, err := sp.GetOrderByNo(orderNo)
	if err == nil {
		b := order.IsOver()
		if b {
			return errors.New("订单已经完成!")
		}

		status := order.GetValue().Status
		switch status + 1 {
		case enum.ORDER_CONFIRMED:
			err = order.Confirm()
		case enum.ORDER_PROCESSING:
			err = order.Process()
		case enum.ORDER_SENDING:
			err = order.Deliver()
		case enum.ORDER_RECEIVED:
			err = order.SignReceived()
		case enum.ORDER_COMPLETED:
			err = order.Complete()
		}
	}
	return err
}

func (this *shoppingService) GetOrderByNo(partnerId int,
	orderNo string) *shopping.ValueOrder {
	var sp shopping.IShopping = this._rep.GetShopping(partnerId)
	order, err := sp.GetOrderByNo(orderNo)
	if err != nil {
		Context.Log().PrintErr(err)
		return nil
	}
	v := order.GetValue()
	return &v
}

func (this *shoppingService) CancelOrder(partnerId int, orderNo string, reason string) error {
	var sp shopping.IShopping = this._rep.GetShopping(partnerId)
	order, err := sp.GetOrderByNo(orderNo)
	if err == nil {
		err = order.Cancel(reason)
	}
	return err
}

//  获取购物车
func (this *shoppingService) getShoppingCart(partnerId int, buyerId int, cartKey string) shopping.ICart {
	sp := this._rep.GetShopping(partnerId)
	return sp.GetShoppingCart(buyerId, cartKey)
}
func (this *shoppingService) GetShoppingCart(partnerId int, memberId int, cartKey string) *dto.ShoppingCart {
	cart := this.getShoppingCart(partnerId, memberId, cartKey)
	return this.parseDtoCart(cart)
}

func (this *shoppingService) parseDtoCart(c shopping.ICart) *dto.ShoppingCart {
	var cart = new(dto.ShoppingCart)
	v := c.GetValue()
	cart.Id = c.GetDomainId()
	cart.BuyerId = v.BuyerId
	cart.CartKey = v.CartKey
	cart.UpdateTime = v.UpdateTime
	t, f := c.GetFee()
	cart.TotalFee = t
	cart.OrderFee = f
	cart.Summary = c.GetSummary()

	if v.Items != nil {
		if l := len(v.Items); l != 0 {
			cart.Items = make([]*dto.CartItem, l)
			for i, v := range v.Items {
				cart.Items[i] = &dto.CartItem{
					GoodsId:    v.GoodsId,
					GoodsName:  v.Name,
					GoodsNo:    v.GoodsNo,
					SmallTitle: v.SmallTitle,
					GoodsImage: v.Image,
					Num:        v.Num,
					Price:      v.Price,
					SalePrice:  v.SalePrice,
				}
				cart.TotalNum += cart.Items[i].Num
			}
		}
	}

	return cart
}

func (this *shoppingService) AddCartItem(partnerId, memberId int, cartKey string, goodsId, num int) (*dto.CartItem, error) {
	cart := this.getShoppingCart(partnerId, memberId, cartKey)
	item, err := cart.AddItem(goodsId, num)
	if err == nil {
		cart.Save()
		return &dto.CartItem{
			GoodsId:    item.GoodsId,
			GoodsName:  item.Name,
			SmallTitle: item.SmallTitle,
			GoodsImage: item.Image,
			Num:        num,
			Price:      item.Price,
			SalePrice:  item.SalePrice,
		}, nil
	}
	return nil, err
}
func (this *shoppingService) SubCartItem(partnerId, memberId int, cartKey string, goodsId, num int) error {
	cart := this.getShoppingCart(partnerId, memberId, cartKey)
	err := cart.RemoveItem(goodsId, num)
	if err == nil {
		_, err = cart.Save()
	}
	return err
}

// 更新购物车结算
func (this *shoppingService) PrepareSettlePersist(partnerId, memberId, shopId, paymentOpt, deliverOpt, deliverId int) error {
	var cart = this.getShoppingCart(partnerId, memberId, "")
	err := cart.SettlePersist(shopId, paymentOpt, deliverOpt, deliverId)
	if err == nil {
		_, err = cart.Save()
	}
	return err
}

func (this *shoppingService) GetCartSettle(partnerId, memberId int, cartKey string) *dto.SettleMeta {
	var cart = this.getShoppingCart(partnerId, memberId, cartKey)
	shop, deliver, payOpt, dlvOpt := cart.GetSettleData()
	var st *dto.SettleMeta = new(dto.SettleMeta)
	st.PaymentOpt = payOpt
	st.DeliverOpt = dlvOpt
	if shop != nil {
		v := shop.GetValue()

		st.Shop = &dto.SettleShopMeta{
			Id:   v.Id,
			Name: v.Name,
			Tel:  v.Phone,
		}
	}

	if deliver != nil {
		v := deliver.GetValue()
		st.Deliver = &dto.SettleDeliverMeta{
			Id:         v.Id,
			PersonName: v.RealName,
			Phone:      v.Phone,
			Address:    v.Address,
		}
	}

	return st
}

func (this *shoppingService) OrderAutoSetup(partnerId int, f func(error)) {
	sp := this._rep.GetShopping(partnerId)
	sp.OrderAutoSetup(f)
}

// 使用余额为订单付款
func (this *shoppingService) PayForOrderWithBalance(partnerId int, orderNo string) error {
	var sp shopping.IShopping = this._rep.GetShopping(partnerId)
	order, err := sp.GetOrderByNo(orderNo)
	if err == nil {
		err = order.PaymentWithBalance()
	}
	return err
}

// 确认付款
func (this *shoppingService) PayForOrderOnlineTrade(partnerId int, orderNo string, spName string, tradeNo string) error {
	var sp shopping.IShopping = this._rep.GetShopping(partnerId)
	order, err := sp.GetOrderByNo(orderNo)
	if err == nil {
		err = order.PaymentOnlineTrade(spName, tradeNo)
	}
	return err
}

// 确定订单
func (this *shoppingService) ConfirmOrder(partnerId int, orderNo string)error {
	var sp shopping.IShopping = this._rep.GetShopping(partnerId)
	order, err := sp.GetOrderByNo(orderNo)
	if err == nil {
		err = order.Confirm()
	}
	return err
}


text: {-# htermination reads :: String -> [((Ratio Int),String)] #-}


text:
<?php

namespace Buycraft\PocketMine\Util;

use Buycraft\PocketMine\BuycraftPlugin;
use pocketmine\scheduler\AsyncTask;
use pocketmine\Server;

class FinalizeReportTask extends AsyncTask
{
    private $lines;
    private $fn;

    public function __construct($lines)
    {
        //parent::__construct();
        $this->lines = $lines;
        $this->fn = BuycraftPlugin::getInstance()->getDataFolder() . 'report-' . date('Y-m-d-H-i-s') . '.txt';
    }

    /**
     * Actions to execute when run
     *
     * @return void
     */
    public function onRun()
    {
        $ss = ReportUtil::generateServiceStatus();
        $result = implode("\n", array_merge((array)$this->lines, $ss));
        file_put_contents($this->fn, $result);
    }

    public function onCompletion(Server $server)
    {
        BuycraftPlugin::getInstance()->getLogger()->info("Report saved to " .  $this->fn);
    }
}


text:
var locale = {
    placeholder: '请选择时间'
};
export default locale;


text:
package org.springframework.boot.jdbc.init;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.junit.jupiter.api.Test;

import org.springframework.boot.jdbc.DatabaseDriver;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

/**
 * Tests for {@link PlatformPlaceholderDatabaseDriverResolver}
 *
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 */
class PlatformPlaceholderDatabaseDriverResolverTests {

	@Test
	void resolveAllWithPlatformWhenThereAreNoValuesShouldReturnEmptyList() {
		assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll("test")).isEmpty();
	}

	@Test
	void resolveAllWithPlatformWhenValueDoesNotContainPlaceholderShouldReturnValueUnchanged() {
		assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll("test", "schema.sql"))
				.containsExactly("schema.sql");
	}

	@Test
	void resolveAllWithPlatformWhenValuesContainPlaceholdersShouldReturnValuesWithPlaceholdersReplaced() {
		assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll("postgresql", "schema.sql",
				"schema-@@platform@@.sql", "data-@@platform@@.sql")).containsExactly("schema.sql",
						"schema-postgresql.sql", "data-postgresql.sql");
	}

	@Test
	void resolveAllWithDataSourceWhenThereAreNoValuesShouldReturnEmptyList() {
		assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(mock(DataSource.class))).isEmpty();
	}

	@Test
	void resolveAllWithDataSourceWhenValueDoesNotContainPlaceholderShouldReturnValueUnchanged() {
		assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(mock(DataSource.class), "schema.sql"))
				.containsExactly("schema.sql");
	}

	@Test
	void resolveAllWithDataSourceWhenValuesContainPlaceholdersShouldReturnValuesWithPlaceholdersReplaced()
			throws SQLException {
		assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(dataSourceWithProductName("PostgreSQL"),
				"schema.sql", "schema-@@platform@@.sql", "data-@@platform@@.sql")).containsExactly("schema.sql",
						"schema-postgresql.sql", "data-postgresql.sql");
	}

	@Test
	void resolveAllWithDataSourceWhenDriverMappingsAreCustomizedShouldResolvePlaceholderUsingCustomMapping()
			throws SQLException {
		assertThat(new PlatformPlaceholderDatabaseDriverResolver()
				.withDriverPlatform(DatabaseDriver.POSTGRESQL, "postgres")
				.resolveAll(dataSourceWithProductName("PostgreSQL"), "schema-@@platform@@.sql"))
						.containsExactly("schema-postgres.sql");
	}

	@Test
	void resolveAllWithDataSourceWhenValueIsAnEmptyStringShouldReturnValueUnchanged() {
		assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(mock(DataSource.class), ""))
				.containsExactly("");
	}

	@Test
	void resolveAllWithDataSourceWhenDriverIsUnknownShouldThrow() {
		assertThatIllegalStateException().isThrownBy(() -> new PlatformPlaceholderDatabaseDriverResolver()
				.resolveAll(dataSourceWithProductName("CustomDB"), "schema-@@platform@@.sql"));
	}

	@Test
	void resolveAllWithDataSourceWhenPlaceholderIsCustomizedShouldResolvePlaceholders() throws SQLException {
		assertThat(new PlatformPlaceholderDatabaseDriverResolver("##platform##").resolveAll(
				dataSourceWithProductName("PostgreSQL"), "schema-##platform##.sql", "schema-@@platform@@.sql"))
						.containsExactly("schema-postgresql.sql", "schema-@@platform@@.sql");
	}

	private DataSource dataSourceWithProductName(String productName) throws SQLException {
		DataSource dataSource = mock(DataSource.class);
		Connection connection = mock(Connection.class);
		given(dataSource.getConnection()).willReturn(connection);
		DatabaseMetaData metadata = mock(DatabaseMetaData.class);
		given(connection.getMetaData()).willReturn(metadata);
		given(metadata.getDatabaseProductName()).willReturn(productName);
		return dataSource;
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>The Postscript Journal</title>

    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">

    <link rel="stylesheet" href="navbar.css" type="text/css">

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="css/animate.min.css" type="text/css">

    <link rel="stylesheet" href="css/creative.css" type="text/css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                The Postscript Journal

                        About ▾

Overview

Masthead

Online

Print

Submit

Contact

← Back to Issue Three

Issue Three

A letter to the sugar bowl

Talin Tahajian

You look like a kiss: stained, silent, secular, and yet

the sweep of your stomach seems taut, wary

of sugar. Perhaps it is because God's cheekbones

are the color of milk—or so they say. Perhaps

you remember my grandmother from Virginia,

a chalky lady, mouth like a sewing needle. She always

claimed to be royalty, thrice removed; we asked her

which side, she claimed that she couldn't remember.

"Maternal, perhaps." She would be proud to see you

now, I think, a daughter delaying a pearl of neuroglia

in the attic, another daughter wide awake, coffee

brewing, creamer tipping, and you, sugar bowl, waiting

for daybreak.

                        Talin Tahajian is the recipient of the Sixth Annual Helen Creeley Poetry Prize, was a finalist in the Nancy Thorp Poetry Contest, and was awarded several regional keys and a national medal in the 2013 Scholastic Art &amp Writing Awards. She is an executive editor of Polyphony, the creative writing editor of [Slippage] Literary Magazine, and a poetry reader for Postcript. Her work is published in Crashtest and forthcoming from The Winter Tangerine Review, Polyphony, and Postscript. She recently attended the New England Young Writers' Conference at Bread Loaf, the Kenyon Review Young Writers' Workshop, and the UVA Young Writers' Workshop. She will graduate from Belmont High School in 2014.

Copyright © 2012-2015, The Postscript Journal. All rights reserved.


text:
<?php

namespace Phalcon\Test\Unit\Mvc\Model\Transaction;

use Phalcon\Test\Models\Select;
use Phalcon\Test\Module\UnitTest;
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;

class ManagerTest extends UnitTest
{
    /**
     * Tests transaction is removed when rolled back.
     *
     * @author Nochum Sossonko <nsossonko@hotmail.com>
     * @since  2016-04-09
     */
    public function testTransactionRemovedOnRollback()
    {
        $this->specify(
            "Test does not remove transaction when rolled back",
            function () {
                $tm = new Manager;

                $transaction = $tm->get(true);

                $select = new Select();
                $select->setTransaction($transaction);
                $select->create(['name' => 'Crack of Dawn']);

                expect($this->tester->getProtectedProperty($tm, '_number'))->equals(1);
                expect($this->tester->getProtectedProperty($tm, '_transactions'))->count(1);

                try {
                    $transaction->rollback();
                } catch (Failed $e) {
                    // do nothing
                }

                expect($this->tester->getProtectedProperty($tm, '_number'))->equals(0);
                expect($this->tester->getProtectedProperty($tm, '_transactions'))->count(0);
            }
        );
    }

    /**
     * Tests transaction is removed when committed.
     *
     * @author Nochum Sossonko <nsossonko@hotmail.com>
     * @since  2016-04-09
     */
    public function testTransactionRemovedOnCommit()
    {
        $this->specify(
            "Test does not remove transaction when committed",
            function () {
                $tm = new Manager;

                $transaction = $tm->get(true);

                $select = new Select();
                $select->setTransaction($transaction);
                $select->create(['name' => 'Crack of Dawn']);

                expect($this->tester->getProtectedProperty($tm, '_number'))->equals(1);
                expect($this->tester->getProtectedProperty($tm, '_transactions'))->count(1);

                $transaction->commit();

                expect($this->tester->getProtectedProperty($tm, '_number'))->equals(0);
                expect($this->tester->getProtectedProperty($tm, '_transactions'))->count(0);
            }
        );
    }
}


text:
package data;

/**
 * Simple test class with one method returning a String
 *
 * @author Andy Clement
 */
public class Fruity {
	public String getFruit() {
		return "apple";
	}
}


text:
/* global Meteor, Roles */
if (Meteor.roles.createIndex) {
  Meteor.roleAssignment.createIndex({ 'user._id': 1, 'inheritedRoles._id': 1, scope: 1 })
  Meteor.roleAssignment.createIndex({ 'user._id': 1, 'role._id': 1, scope: 1 })
  Meteor.roleAssignment.createIndex({ 'role._id': 1 })
  Meteor.roleAssignment.createIndex({ scope: 1, 'user._id': 1, 'inheritedRoles._id': 1 }) // Adding userId and roleId might speed up other queries depending on the first index
  Meteor.roleAssignment.createIndex({ 'inheritedRoles._id': 1 })

  Meteor.roles.createIndex({ 'children._id': 1 })
} else {
  Meteor.roleAssignment._ensureIndex({ 'user._id': 1, 'inheritedRoles._id': 1, scope: 1 })
  Meteor.roleAssignment._ensureIndex({ 'user._id': 1, 'role._id': 1, scope: 1 })
  Meteor.roleAssignment._ensureIndex({ 'role._id': 1 })
  Meteor.roleAssignment._ensureIndex({ scope: 1, 'user._id': 1, 'inheritedRoles._id': 1 }) // Adding userId and roleId might speed up other queries depending on the first index
  Meteor.roleAssignment._ensureIndex({ 'inheritedRoles._id': 1 })

  Meteor.roles._ensureIndex({ 'children._id': 1 })
}

/*
 * Publish logged-in user's roles so client-side checks can work.
 *
 * Use a named publish function so clients can check `ready()` state.
 */
Meteor.publish('_roles', function () {
  var loggedInUserId = this.userId
  var fields = { roles: 1 }

  if (!loggedInUserId) {
    this.ready()
    return
  }

  return Meteor.users.find(
    { _id: loggedInUserId },
    { fields: fields }
  )
})

Object.assign(Roles, {
  /**
   * @method _isNewRole
   * @param {Object} role `Meteor.roles` document.
   * @return {Boolean} Returns `true` if the `role` is in the new format.
   *                   If it is ambiguous or it is not, returns `false`.
   * @for Roles
   * @private
   * @static
   */
  _isNewRole: function (role) {
    return !('name' in role) && 'children' in role
  },

  /**
   * @method _isOldRole
   * @param {Object} role `Meteor.roles` document.
   * @return {Boolean} Returns `true` if the `role` is in the old format.
   *                   If it is ambiguous or it is not, returns `false`.
   * @for Roles
   * @private
   * @static
   */
  _isOldRole: function (role) {
    return 'name' in role && !('children' in role)
  },

  /**
   * @method _isNewField
   * @param {Array} roles `Meteor.users` document `roles` field.
   * @return {Boolean} Returns `true` if the `roles` field is in the new format.
   *                   If it is ambiguous or it is not, returns `false`.
   * @for Roles
   * @private
   * @static
   */
  _isNewField: function (roles) {
    return Array.isArray(roles) && (typeof roles[0] === 'object')
  },

  /**
   * @method _isOldField
   * @param {Array} roles `Meteor.users` document `roles` field.
   * @return {Boolean} Returns `true` if the `roles` field is in the old format.
   *                   If it is ambiguous or it is not, returns `false`.
   * @for Roles
   * @private
   * @static
   */
  _isOldField: function (roles) {
    return (Array.isArray(roles) && (typeof roles[0] === 'string')) || ((typeof roles === 'object') && !Array.isArray(roles))
  },

  /**
   * @method _convertToNewRole
   * @param {Object} oldRole `Meteor.roles` document.
   * @return {Object} Converted `role` to the new format.
   * @for Roles
   * @private
   * @static
   */
  _convertToNewRole: function (oldRole) {
    if (!(typeof oldRole.name === 'string')) throw new Error("Role name '" + oldRole.name + "' is not a string.")

    return {
      _id: oldRole.name,
      children: []
    }
  },

  /**
   * @method _convertToOldRole
   * @param {Object} newRole `Meteor.roles` document.
   * @return {Object} Converted `role` to the old format.
   * @for Roles
   * @private
   * @static
   */
  _convertToOldRole: function (newRole) {
    if (!(typeof newRole._id === 'string')) throw new Error("Role name '" + newRole._id + "' is not a string.")

    return {
      name: newRole._id
    }
  },

  /**
   * @method _convertToNewField
   * @param {Array} oldRoles `Meteor.users` document `roles` field in the old format.
   * @param {Boolean} convertUnderscoresToDots Should we convert underscores to dots in group names.
   * @return {Array} Converted `roles` to the new format.
   * @for Roles
   * @private
   * @static
   */
  _convertToNewField: function (oldRoles, convertUnderscoresToDots) {
    var roles = []
    if (Array.isArray(oldRoles)) {
      oldRoles.forEach(function (role, index) {
        if (!(typeof role === 'string')) throw new Error("Role '" + role + "' is not a string.")

        roles.push({
          _id: role,
          scope: null,
          assigned: true
        })
      })
    } else if (typeof oldRoles === 'object') {
      Object.entries(oldRoles).forEach(([group, rolesArray]) => {
        if (group === '__global_roles__') {
          group = null
        } else if (convertUnderscoresToDots) {
          // unescape
          group = group.replace(/_/g, '.')
        }

        rolesArray.forEach(function (role) {
          if (!(typeof role === 'string')) throw new Error("Role '" + role + "' is not a string.")

          roles.push({
            _id: role,
            scope: group,
            assigned: true
          })
        })
      })
    }
    return roles
  },

  /**
   * @method _convertToOldField
   * @param {Array} newRoles `Meteor.users` document `roles` field in the new format.
   * @param {Boolean} usingGroups Should we use groups or not.
   * @return {Array} Converted `roles` to the old format.
   * @for Roles
   * @private
   * @static
   */
  _convertToOldField: function (newRoles, usingGroups) {
    var roles

    if (usingGroups) {
      roles = {}
    } else {
      roles = []
    }

    newRoles.forEach(function (userRole) {
      if (!(typeof userRole === 'object')) throw new Error("Role '" + userRole + "' is not an object.")

      // We assume that we are converting back a failed migration, so values can only be
      // what were valid values in 1.0. So no group names starting with $ and no subroles.

      if (userRole.scope) {
        if (!usingGroups) throw new Error("Role '" + userRole._id + "' with scope '" + userRole.scope + "' without enabled groups.")

        // escape
        var scope = userRole.scope.replace(/\./g, '_')

        if (scope[0] === '$') throw new Error("Group name '" + scope + "' start with $.")

        roles[scope] = roles[scope] || []
        roles[scope].push(userRole._id)
      } else {
        if (usingGroups) {
          roles.__global_roles__ = roles.__global_roles__ || []
          roles.__global_roles__.push(userRole._id)
        } else {
          roles.push(userRole._id)
        }
      }
    })
    return roles
  },

  /**
   * @method _defaultUpdateUser
   * @param {Object} user `Meteor.users` document.
   * @param {Array|Object} roles Value to which user's `roles` field should be set.
   * @for Roles
   * @private
   * @static
   */
  _defaultUpdateUser: function (user, roles) {
    Meteor.users.update({
      _id: user._id,
      // making sure nothing changed in meantime
      roles: user.roles
    }, {
      $set: { roles }
    })
  },

  /**
   * @method _defaultUpdateRole
   * @param {Object} oldRole Old `Meteor.roles` document.
   * @param {Object} newRole New `Meteor.roles` document.
   * @for Roles
   * @private
   * @static
   */
  _defaultUpdateRole: function (oldRole, newRole) {
    Meteor.roles.remove(oldRole._id)
    Meteor.roles.insert(newRole)
  },

  /**
   * @method _dropCollectionIndex
   * @param {Object} collection Collection on which to drop the index.
   * @param {String} indexName Name of the index to drop.
   * @for Roles
   * @private
   * @static
   */
  _dropCollectionIndex: function (collection, indexName) {
    try {
      collection._dropIndex(indexName)
    } catch (e) {
      if (e.name !== 'MongoError') throw e
      if (!/index not found/.test(e.err || e.errmsg)) throw e
    }
  },

  /**
   * Migrates `Meteor.users` and `Meteor.roles` to the new format.
   *
   * @method _forwardMigrate
   * @param {Function} updateUser Function which updates the user object. Default `_defaultUpdateUser`.
   * @param {Function} updateRole Function which updates the role object. Default `_defaultUpdateRole`.
   * @param {Boolean} convertUnderscoresToDots Should we convert underscores to dots in group names.
   * @for Roles
   * @private
   * @static
   */
  _forwardMigrate: function (updateUser, updateRole, convertUnderscoresToDots) {
    updateUser = updateUser || Roles._defaultUpdateUser
    updateRole = updateRole || Roles._defaultUpdateRole

    Roles._dropCollectionIndex(Meteor.roles, 'name_1')

    Meteor.roles.find().forEach(function (role, index, cursor) {
      if (!Roles._isNewRole(role)) {
        updateRole(role, Roles._convertToNewRole(role))
      }
    })

    Meteor.users.find().forEach(function (user, index, cursor) {
      if (!Roles._isNewField(user.roles)) {
        updateUser(user, Roles._convertToNewField(user.roles, convertUnderscoresToDots))
      }
    })
  },

  /**
   * Moves the assignments from `Meteor.users` to `Meteor.roleAssignment`.
   *
   * @method _forwardMigrate2
   * @param {Object} userSelector An opportunity to share the work among instances. It's advisable to do the division based on user-id.
   * @for Roles
   * @private
   * @static
   */
  _forwardMigrate2: function (userSelector) {
    userSelector = userSelector || {}
    Object.assign(userSelector, { roles: { $ne: null } })

    Meteor.users.find(userSelector).forEach(function (user, index) {
      user.roles.filter((r) => r.assigned).forEach(r => {
        // Added `ifExists` to make it less error-prone
        Roles._addUserToRole(user._id, r._id, { scope: r.scope, ifExists: true })
      })

      Meteor.users.update({ _id: user._id }, { $unset: { roles: '' } })
    })

    // No need to keep the indexes around
    Roles._dropCollectionIndex(Meteor.users, 'roles._id_1_roles.scope_1')
    Roles._dropCollectionIndex(Meteor.users, 'roles.scope_1')
  },

  /**
   * Migrates `Meteor.users` and `Meteor.roles` to the old format.
   *
   * We assume that we are converting back a failed migration, so values can only be
   * what were valid values in the old format. So no group names starting with `$` and
   * no subroles.
   *
   * @method _backwardMigrate
   * @param {Function} updateUser Function which updates the user object. Default `_defaultUpdateUser`.
   * @param {Function} updateRole Function which updates the role object. Default `_defaultUpdateRole`.
   * @param {Boolean} usingGroups Should we use groups or not.
   * @for Roles
   * @private
   * @static
   */
  _backwardMigrate: function (updateUser, updateRole, usingGroups) {
    updateUser = updateUser || Roles._defaultUpdateUser
    updateRole = updateRole || Roles._defaultUpdateRole

    Roles._dropCollectionIndex(Meteor.users, 'roles._id_1_roles.scope_1')
    Roles._dropCollectionIndex(Meteor.users, 'roles.scope_1')

    Meteor.roles.find().forEach(function (role, index, cursor) {
      if (!Roles._isOldRole(role)) {
        updateRole(role, Roles._convertToOldRole(role))
      }
    })

    Meteor.users.find().forEach(function (user, index, cursor) {
      if (!Roles._isOldField(user.roles)) {
        updateUser(user, Roles._convertToOldField(user.roles, usingGroups))
      }
    })
  },

  /**
   * Moves the assignments from `Meteor.roleAssignment` back to to `Meteor.users`.
   *
   * @method _backwardMigrate2
   * @param {Object} assignmentSelector An opportunity to share the work among instances. It's advisable to do the division based on user-id.
   * @for Roles
   * @private
   * @static
   */
  _backwardMigrate2: function (assignmentSelector) {
    assignmentSelector = assignmentSelector || {}

    if (Meteor.users.createIndex) {
      Meteor.users.createIndex({ 'roles._id': 1, 'roles.scope': 1 })
      Meteor.users.createIndex({ 'roles.scope': 1 })
    } else {
      Meteor.users._ensureIndex({ 'roles._id': 1, 'roles.scope': 1 })
      Meteor.users._ensureIndex({ 'roles.scope': 1 })
    }

    Meteor.roleAssignment.find(assignmentSelector).forEach(r => {
      const roles = Meteor.users.findOne({ _id: r.user._id }).roles || []

      const currentRole = roles.find(oldRole => oldRole._id === r.role._id && oldRole.scope === r.scope)
      if (currentRole) {
        currentRole.assigned = true
      } else {
        roles.push({
          _id: r.role._id,
          scope: r.scope,
          assigned: true
        })

        r.inheritedRoles.forEach(inheritedRole => {
          const currentInheritedRole = roles.find(oldRole => oldRole._id === inheritedRole._id && oldRole.scope === r.scope)

          if (!currentInheritedRole) {
            roles.push({
              _id: inheritedRole._id,
              scope: r.scope,
              assigned: false
            })
          }
        })
      }

      Meteor.users.update({ _id: r.user._id }, { $set: { roles } })
      Meteor.roleAssignment.remove({ _id: r._id })
    })
  }
})


text:
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @license GPL 2+
 */

/**
 * A class to convert page titles on a foreign wiki (ForeignTitle objects) into
 * page titles on the local wiki (Title objects), placing all pages as subpages
 * of a given root page.
 */
class SubpageImportTitleFactory implements ImportTitleFactory {
	/** @var Title */
	protected $rootPage;

	/**
	 * @param Title $rootPage The root page under which all pages should be
	 * created
	 */
	public function __construct( Title $rootPage ) {
		if ( !MWNamespace::hasSubpages( $rootPage->getNamespace() ) ) {
			throw new MWException( "The root page you specified, $rootPage, is in a " .
				"namespace where subpages are not allowed" );
		}
		$this->rootPage = $rootPage;
	}

	/**
	 * Determines which local title best corresponds to the given foreign title.
	 * If such a title can't be found or would be locally invalid, null is
	 * returned.
	 *
	 * @param ForeignTitle $foreignTitle The ForeignTitle to convert
	 * @return Title|null
	 */
	public function createTitleFromForeignTitle( ForeignTitle $foreignTitle ) {
		return Title::newFromText( $this->rootPage->getPrefixedDBkey() . '/' .
			$foreignTitle->getFullText() );
	}
}


text:
package org.apache.beam.runners.spark.metrics;

import org.apache.beam.runners.core.metrics.MetricsContainerStepMap;

/**
 * Sole purpose of this class is to override {@link #toString()} of {@link MetricsContainerStepMap}
 * in order to show meaningful metrics in Spark Web Interface.
 */
public class SparkMetricsContainerStepMap extends MetricsContainerStepMap {

  @Override
  public String toString() {
    return new SparkBeamMetric().renderAll().toString();
  }

  @Override
  public boolean equals(Object o) {
    return super.equals(o);
  }

  @Override
  public int hashCode() {
    return super.hashCode();
  }
}


text:
var loadGruntTasks = require('load-grunt-tasks')

// Module definition
module.exports = function (grunt) {
    'use strict';

    grunt.initConfig({

        tastypie_schema: {

            production: {
                login: {
                    url: 'https://www...',
                    params: {
                        username: '',
                        password: ''
                    }
                },
                options: {
                    keys: ['fields', 'filtering', 'ordering']
                },
                files: {
                    'response.json': 'https://www...'
                }
            }

        }

    });

    // Load all grunt tasks
    loadGruntTasks(grunt);
    grunt.loadTasks('tasks');

    // Register task
    grunt.registerTask('default', ['tastypie_schema']);

};


text:
class Node:
    def __init__(self,value):
        self._value = value
        self._children = []

    def __repr__(self):
        return 'Node({!r})'.format(self._value)

    def add_child(self,node):
        self._children.append(node)

    def __iter__(self):
        return iter(self._children)

    def depth_frist(self):
        yield self
        for c in self:
            yield from c.depth_frist()

if __name__ == '__main__':
    root = Node(0)
    child1 = Node(1)
    child2 = Node(2)
    child3 = Node(3)
    child4 = Node(4)
    child5 = Node(5)
    root.add_child(child1)
    root.add_child(child2)
    child1.add_child(child3)
    child1.add_child(child4)
    child2.add_child(child5)
    testt = root.depth_frist()
#yield from 内部调用了generator
#http://blog.csdn.net/gonux/article/details/42429751
    print(next(testt))
    print(next(testt))
    print(next(testt))
    print(next(testt))


text:
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>
#include <stdint.h>

#include <random>

#include "base/at_exit.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "base/test/task_environment.h"
#include "media/base/decoder_buffer.h"
#include "media/base/media.h"
#include "media/base/media_util.h"
#include "media/filters/vpx_video_decoder.h"

struct Env {
  Env() {
    media::InitializeMediaLibrary();
    base::CommandLine::Init(0, nullptr);
    logging::SetMinLogLevel(logging::LOG_FATAL);
  }

  base::AtExitManager at_exit_manager;
  base::test::SingleThreadTaskEnvironment task_environment;
};

void OnDecodeComplete(base::OnceClosure quit_closure,
                      media::DecoderStatus status) {
  std::move(quit_closure).Run();
}

void OnInitDone(base::OnceClosure quit_closure,
                bool* success_dest,
                media::DecoderStatus status) {
  *success_dest = status.is_ok();
  std::move(quit_closure).Run();
}

void OnOutputComplete(scoped_refptr<media::VideoFrame> frame) {}

// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  // Create Env on the first run of LLVMFuzzerTestOneInput otherwise
  // message_loop will be created before this process forks when used with AFL,
  // causing hangs.
  [[maybe_unused]] static Env* env = new Env();
  std::mt19937_64 rng;

  {  // Seed rng from data.
    std::string str = std::string(reinterpret_cast<const char*>(data), size);
    std::size_t data_hash = std::hash<std::string>()(str);
    rng.seed(data_hash);
  }

  // Compute randomized constants. Put all rng() usages here.
  // Use only values that pass DCHECK in VpxVideoDecoder::ConfigureDecoder().
  media::VideoCodec codec;

  bool has_alpha = false;
  if (rng() & 1) {
    codec = media::VideoCodec::kVP8;
    // non-Alpha VP8 decoding isn't supported by VpxVideoDecoder on Linux.
    has_alpha = true;
  } else {
    codec = media::VideoCodec::kVP9;
    has_alpha = rng() & 1;
  }

  auto profile = static_cast<media::VideoCodecProfile>(
      rng() % media::VIDEO_CODEC_PROFILE_MAX);
  auto color_space =
      media::VideoColorSpace(rng() % 256, rng() % 256, rng() % 256,
                             (rng() & 1) ? gfx::ColorSpace::RangeID::LIMITED
                                         : gfx::ColorSpace::RangeID::FULL);
  auto rotation =
      static_cast<media::VideoRotation>(rng() % media::VIDEO_ROTATION_MAX);
  auto coded_size = gfx::Size(1 + (rng() % 127), 1 + (rng() % 127));
  auto visible_rect = gfx::Rect(coded_size);
  auto natural_size = gfx::Size(1 + (rng() % 127), 1 + (rng() % 127));
  uint8_t reflection = rng() % 4;

  media::VideoDecoderConfig config(
      codec, profile,
      has_alpha ? media::VideoDecoderConfig::AlphaMode::kHasAlpha
                : media::VideoDecoderConfig::AlphaMode::kIsOpaque,
      color_space, media::VideoTransformation(rotation, reflection), coded_size,
      visible_rect, natural_size, media::EmptyExtraData(),
      media::EncryptionScheme::kUnencrypted);

  if (!config.IsValidConfig())
    return 0;

  media::VpxVideoDecoder decoder;

  {
    base::RunLoop run_loop;
    bool success = false;
    decoder.Initialize(
        config, true /* low_delay */, nullptr /* cdm_context */,
        base::BindOnce(&OnInitDone, run_loop.QuitClosure(), &success),
        base::BindRepeating(&OnOutputComplete), base::NullCallback());
    run_loop.Run();
    if (!success)
      return 0;
  }

  {
    base::RunLoop run_loop;
    auto buffer = media::DecoderBuffer::CopyFrom(data, size);
    decoder.Decode(buffer,
                   base::BindOnce(&OnDecodeComplete, run_loop.QuitClosure()));
    run_loop.Run();
  }

  return 0;
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="RDShaderSource" inherits="Reference" version="4.0">
	<brief_description>
	</brief_description>
	<description>
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="get_stage_source" qualifiers="const">
			<return type="String">
			</return>
			<argument index="0" name="stage" type="int" enum="RenderingDevice.ShaderStage">
			</argument>
			<description>
			</description>
		</method>
		<method name="set_stage_source">
			<return type="void">
			</return>
			<argument index="0" name="stage" type="int" enum="RenderingDevice.ShaderStage">
			</argument>
			<argument index="1" name="source" type="String">
			</argument>
			<description>
			</description>
		</method>
	</methods>
	<members>
		<member name="language" type="int" setter="set_language" getter="get_language" enum="RenderingDevice.ShaderLanguage" default="0">
		</member>
		<member name="source_compute" type="String" setter="set_stage_source" getter="get_stage_source" default="""">
		</member>
		<member name="source_fragment" type="String" setter="set_stage_source" getter="get_stage_source" default="""">
		</member>
		<member name="source_tesselation_control" type="String" setter="set_stage_source" getter="get_stage_source" default="""">
		</member>
		<member name="source_tesselation_evaluation" type="String" setter="set_stage_source" getter="get_stage_source" default="""">
		</member>
		<member name="source_vertex" type="String" setter="set_stage_source" getter="get_stage_source" default="""">
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
<?php

namespace Slim\Tests\Http;

use Slim\Http\Headers;
use Slim\Tests\Mocks\MessageStub;

class MessageTest extends \PHPUnit_Framework_TestCase
{
    /*******************************************************************************
     * Protocol
     ******************************************************************************/

    /**
     * @covers Slim\Http\Message::getProtocolVersion
     */
    public function testGetProtocolVersion()
    {
        $message = new MessageStub();
        $message->protocolVersion = '1.0';

        $this->assertEquals('1.0', $message->getProtocolVersion());
    }

    /**
     * @covers Slim\Http\Message::withProtocolVersion
     */
    public function testWithProtocolVersion()
    {
        $message = new MessageStub();
        $clone = $message->withProtocolVersion('1.0');

        $this->assertEquals('1.0', $clone->protocolVersion);
    }

    /**
     * @covers Slim\Http\Message::withProtocolVersion
     * @expectedException \InvalidArgumentException
     */
    public function testWithProtocolVersionInvalidThrowsException()
    {
        $message = new MessageStub();
        $message->withProtocolVersion('3.0');
    }

    /*******************************************************************************
     * Headers
     ******************************************************************************/

    /**
     * @covers Slim\Http\Message::getHeaders
     */
    public function testGetHeaders()
    {
        $headers = new Headers();
        $headers->add('X-Foo', 'one');
        $headers->add('X-Foo', 'two');
        $headers->add('X-Foo', 'three');

        $message = new MessageStub();
        $message->headers = $headers;

        $shouldBe = [
            'X-Foo' => [
                'one',
                'two',
                'three',
            ],
        ];

        $this->assertEquals($shouldBe, $message->getHeaders());
    }

    /**
     * @covers Slim\Http\Message::hasHeader
     */
    public function testHasHeader()
    {
        $headers = new Headers();
        $headers->add('X-Foo', 'one');

        $message = new MessageStub();
        $message->headers = $headers;

        $this->assertTrue($message->hasHeader('X-Foo'));
        $this->assertFalse($message->hasHeader('X-Bar'));
    }

    /**
     * @covers Slim\Http\Message::getHeaderLine
     */
    public function testGetHeaderLine()
    {
        $headers = new Headers();
        $headers->add('X-Foo', 'one');
        $headers->add('X-Foo', 'two');
        $headers->add('X-Foo', 'three');

        $message = new MessageStub();
        $message->headers = $headers;

        $this->assertEquals('one,two,three', $message->getHeaderLine('X-Foo'));
        $this->assertEquals('', $message->getHeaderLine('X-Bar'));
    }

    /**
     * @covers Slim\Http\Message::getHeader
     */
    public function testGetHeader()
    {
        $headers = new Headers();
        $headers->add('X-Foo', 'one');
        $headers->add('X-Foo', 'two');
        $headers->add('X-Foo', 'three');

        $message = new MessageStub();
        $message->headers = $headers;

        $this->assertEquals(['one', 'two', 'three'], $message->getHeader('X-Foo'));
        $this->assertEquals([], $message->getHeader('X-Bar'));
    }

    /**
     * @covers Slim\Http\Message::withHeader
     */
    public function testWithHeader()
    {
        $headers = new Headers();
        $headers->add('X-Foo', 'one');
        $message = new MessageStub();
        $message->headers = $headers;
        $clone = $message->withHeader('X-Foo', 'bar');

        $this->assertEquals('bar', $clone->getHeaderLine('X-Foo'));
    }

    /**
     * @covers Slim\Http\Message::withAddedHeader
     */
    public function testWithAddedHeader()
    {
        $headers = new Headers();
        $headers->add('X-Foo', 'one');
        $message = new MessageStub();
        $message->headers = $headers;
        $clone = $message->withAddedHeader('X-Foo', 'two');

        $this->assertEquals('one,two', $clone->getHeaderLine('X-Foo'));
    }

    /**
     * @covers Slim\Http\Message::withoutHeader
     */
    public function testWithoutHeader()
    {
        $headers = new Headers();
        $headers->add('X-Foo', 'one');
        $headers->add('X-Bar', 'two');
        $response = new MessageStub();
        $response->headers = $headers;
        $clone = $response->withoutHeader('X-Foo');
        $shouldBe = [
            'X-Bar' => ['two'],
        ];

        $this->assertEquals($shouldBe, $clone->getHeaders());
    }

    /*******************************************************************************
     * Body
     ******************************************************************************/

    /**
     * @covers Slim\Http\Message::getBody
     */
    public function testGetBody()
    {
        $body = $this->getBody();
        $message = new MessageStub();
        $message->body = $body;

        $this->assertSame($body, $message->getBody());
    }

    /**
     * @covers Slim\Http\Message::withBody
     */
    public function testWithBody()
    {
        $body = $this->getBody();
        $body2 = $this->getBody();
        $message = new MessageStub();
        $message->body = $body;
        $clone = $message->withBody($body2);

        $this->assertSame($body, $message->body);
        $this->assertSame($body2, $clone->body);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Slim\Http\Body
     */
    protected function getBody()
    {
        return $this->getMockBuilder('Slim\Http\Body')->disableOriginalConstructor()->getMock();
    }
}


text:
localStorage, Session Storage and Cookies API wrapper for browser

## TL;DR
```javascript
import browserStorage from '../index'; // import Storage API Object
browserStorage.local.prefix = 'myApp'; // use localStorage and set a prefix
browserStorage.local.key('key', 'value'); // store 'key' with 'value'
console.log(browserStorage.local.key('key')); // read 'key'

const session = require('../index').default.session; // import SessionStorage API wrapper
session.key('session_id', '2017'); // store a key 'sesion_id' with value '2017'
console.log(session.key('session_id')); // read 'session_id'
```

## localStorage/sessionStorage Class
### Initialization
```javascript
import StorageClass from '../storage'; // import Storage API wrapper
const Local = new StorageClass(); // create localStorage Class new instance
const Session = new StorageClass('sessionStorage'); // create sessionStorage Class new instance
```

### Methods
**isAvailable:** check for availability.
```javascript
const hasLocalStorage = Local.isAvailable(); // returns Boolean
```

**prefix:** set or read a prefix
```javascript
Local.prefix = 'abc'; // set a prefix
const thisPrefix = Local.prefix; // read for a prefix, returns String
```

**hasKey:** check for a key
```javascript
const res = Local.hasKey(key); // returns Boolean
```

**key:** write & read a key-value pair
```javascript
Local.key(key, value); // store a Key with a defined Value, returns True if successful
const thisKey = Local.key(key); // read a key, returns String
```

**removeKey:** delete a key
```javascript
Local.removeKey(key); // returns True if successful
```

**length:** get quantity of keys in DB
```javascript
let keysNumber = Local.length; // returns a number of keys
```

**clear:** clear localStorage using prefix
```javascript
let res = Local.clear(); // returns True if cleared
```

**each:** get all elements in the storage
```javascript
let res = Local.each(); // returns an array of elements in the storage
```

**forEach:** iterate over all elements and run a callback function
```javascript
Local.forEach((key, value, index) = > {}); // returns True always
```

## Cookies Class
### Initialization
```javascript
import CookiesClass from '../cookies'; // import Cookies API wrapper
const Cookies = new CookiesClass(); // create Cookies Class new instance
```

### Methods
**isAvailable:** check for availability.
```javascript
const hasCookies = Cookies.isAvailable(); // returns Boolean
```

**hasKey:** check for a key
```javascript
const res = Cookies.hasKey(key); // returns Boolean
```

**key:** write & read a key-value pair
```javascript
Cookies.key(key, value, options); // store a Key with a defined Value and {Options}, returns True if successful
const thisKey = Cookies.key(key); // read a key, returns String
```

**removeKey:** delete a key
```javascript
Cookies.removeKey(key); // returns always True
```

**each:** get all cookies
```javascript
let res = Cookies.each(); // returns an array of elements
```

## Copyright
coded by Anatol Marezhanyi @e1r0nd_crg

http://linkedin.com/in/merezhany/<br>
https://www.youtube.com/c/AnatolMerezhanyi

## License
[MIT License](LICENSE.md)


text:
package com.store.assistant.repositories;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.store.assistant.core.data.objects.Offers;

@Repository("OffersRepository")
@Transactional
public interface OffersRepository extends JpaRepository<Offers, Integer> {

	public List<Offers> findBySku(String sku);
}


text:
<?php

namespace Teknasyon\Stage\Job;

use DI\ContainerBuilder;
use PHPUnit\Framework\TestCase;
use Teknasyon\Stage\EnvironmentSetting;
use Teknasyon\Stage\SuiteSetting\DockerImageSuiteSetting;
use Teknasyon\Stage\Command;

class DockerImageJobTest extends TestCase
{
    public function testGetCommands()
    {
        $environmentSetting = new EnvironmentSetting([
            'builds_dir' => '/builds',
            'output_dir' => '/outputs'
        ]);
        $container = ContainerBuilder::buildDevContainer();
        $container->set(EnvironmentSetting::class, $environmentSetting);
        $suiteSetting = new DockerImageSuiteSetting('suitename', []);
        $job = new DockerImageJob($container, $suiteSetting);
        $expected = [
            Command\SetupBuildCommand::class,
            Command\DockerRunImageCommand::class,
            Command\MoveOutputCommand::class,
            Command\CleanBuildCommand::class
        ];
        $this->assertEquals($expected, $job->getCommands());
    }
}


text:
require 'spec_helper'
require 'component_helper'
require 'java_buildpack/framework/java_opts'

describe JavaBuildpack::Framework::JavaOpts do
  include_context 'component_helper'

  context do
    let(:configuration) { super().merge('java_opts' => '-Xmx1024M') }

    it 'should detect with java.opts configuration' do
      expect(component.detect).to eq('java-opts')
    end
  end

  it 'should not detect without java_opts configuration' do
    expect(component.detect).to be_nil
  end

  context do
    let(:configuration) do
      super().merge('java_opts' => '-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,address=8000,suspend=y ' \
          "-XX:OnOutOfMemoryError='kill -9 %p'")
    end

    it 'should add split java_opts to context' do
      component.release

      expect(java_opts).to include('-Xdebug')
      expect(java_opts).to include('-Xnoagent')
      expect(java_opts).to include('-Xrunjdwp:transport=dt_socket,server=y,address=8000,suspend=y')
      expect(java_opts).to include('-XX:OnOutOfMemoryError=kill\ -9\ %p')
    end
  end

  context do
    let(:configuration) { super().merge('java_opts' => '-Xms1024M') }

    it 'should raise an error if a -Xms is configured' do
      expect { component.compile }.to raise_error(/-Xms/)
    end
  end

  context do
    let(:configuration) { super().merge('java_opts' => '-Xmx1024M') }

    it 'should raise an error if a -Xmx is configured' do
      expect { component.compile }.to raise_error(/-Xmx/)
    end
  end

  context do
    let(:configuration) { super().merge('java_opts' => '-XX:MaxMetaspaceSize=128M') }

    it 'should raise an error if a -XX:MaxMetaspaceSize is configured' do
      expect { component.compile }.to raise_error(/-XX:MaxMetaspaceSize/)
    end
  end

  context do
    let(:configuration) { super().merge('java_opts' => '-XX:MetaspaceSize=128M') }

    it 'should raise an error if a -XX:MetaspaceSize is configured' do
      expect { component.compile }.to raise_error(/-XX:MetaspaceSize/)
    end
  end

  context do
    let(:configuration) { super().merge('java_opts' => '-XX:MaxPermSize=128M') }

    it 'should raise an error if a -XX:MaxPermSize is configured' do
      expect { component.compile }.to raise_error(/-XX:MaxPermSize/)
    end
  end

  context do
    let(:configuration) { super().merge('java_opts' => '-XX:PermSize=128M') }

    it 'should raise an error if a -XX:PermSize is configured' do
      expect { component.compile }.to raise_error(/-XX:PermSize/)
    end
  end

  context do
    let(:configuration) { super().merge('java_opts' => '-Xss1M') }

    it 'should raise an error if a -Xss is configured' do
      expect { component.compile }.to raise_error(/-Xss/)
    end
  end

  context do
    let(:java_opts) { super() << '-Xmx30m -Xms30m' }

    it 'should not allow multiple options in a single array entry' do
      expect { component.release }.to raise_error(/Invalid Java option contains more than one option/)
    end
  end

end


text:
"use strict";

const Editor = (function(){

    // For now dom elements are
    // are hardcoded into the
    // editor.
    //
    const editor=dom_Cache.add('editor_0001')
    const toggle=dom_Cache.add('toggle_0001')

    let ital_button=document.getElementById('italic_0001')
    let bold_button=document.getElementById('bold_0001')

    let editor_w = editor.offsetWidth
    let editor_h = editor.offsetHeidght

    let Document = []

    //
    let Cursor_Index = -1

    let shift_down = false

    const DEFAULT_STYLE = 'normal'
    const DEFAULT_COLOR = 'black'
    const DEFAULT_UNIT = 'pt'
    const DEFAULT_SIZE = '12'
    const DEFAULT_FAMILY = 'sansSerif'

    const STYLE_DEFAULTS = { italic : DEFAULT_STYLE,
			     weight : DEFAULT_STYLE,
			     strikethrough : DEFAULT_STYLE,
			     color : DEFAULT_COLOR,
			     unit : DEFAULT_UNIT,
			     size : DEFAULT_SIZE,
			     family : DEFAULT_FAMILY }
    //
    // @doc
    //
    // When weight, italic, underline, or strikethrough
    // is set to normal, no styling is applied.
    //
    // @
    let Character_Prototype =  { index : 0,

				 text : { on : false,
					  value : ''
					},

				 italic : { value : DEFAULT_STYLE,
					    on : false },

				 weight : { value : DEFAULT_STYLE,
					    on : false },

				 strikethrough : { value : DEFAULT_STYLE,
						   on : false },

				 color : { value : DEFAULT_COLOR,
					   on : false },

				 unit : { value : DEFAULT_UNIT,
					  on : false },

				 size : { value : DEFAULT_SIZE,
					  on : false },

				 family : { value : DEFAULT_FAMILY,
					    on : false }
			       }

    function deep_copy( Json_Obj ){
	  return JSON.parse(JSON.stringify( Json_Obj ))
    }
    // An unmodified version of the Character_Prototype
    // for use as a reference. This is necessary because the
    // the global prototype is mutable.
    //
    const Character_Prototype_Reference = deep_copy(Character_Prototype)

    //const Character_Prototype_Reference = JSON.parse(JSON.stringify(Character_Prototype))

    function Character( opts ){
	//const prototype = JSON.parse(JSON.stringify(Character_Prototype))
	const prototype = deep_copy(Character_Prototype)

	if ( opts ){
	    for ( let key in opts ){

		prototype[key].on=true
		prototype[key].value=opts[key]
	    }
	}
	return prototype
    }
    function change_prototype(key, value){
	Character_Prototype[key]=value
    }
    function toggle_formatting(format_type,value,node){

	return ()=>{

	    if ( Character_Prototype[format_type] ){

		if ( Character_Prototype[format_type].on ){

		    Character_Prototype[format_type].value= STYLE_DEFAULTS[format_type]
		    Character_Prototype[format_type].on=false
		    change_prototype(Character_Prototype)

		}else{

		    Character_Prototype[format_type].value=value
		    Character_Prototype[format_type].on=true
		    change_prototype(Character_Prototype)
		}
	    }
	    node.blur()
	}
    }
    ital_button.addEventListener('click', toggle_formatting('italic','em', ital_button))
    bold_button.addEventListener('click', toggle_formatting('weight','strong', bold_button))

    function new_node( designator ){
	if ( designator = 'text' ){
	    return document.createTextNode()
	}else{
	    return document.createElement(designator)
	}
    }

    function open_node(node){

	let nodes = { nodes : [],
		      text : '' }

	for( let key in node ){
	    nodes.nodes.push(document.createElement(node))
	}
	return nodes
    }

    // TODO: this will deal with the portion of the editor
    // that is viewable.
    //
    function array_contents_equal(array1, array2){

	if ( array1.length === array2.length ){
	    array1.forEach((e)=>{

		if ( array2.includes(e) !== true ){
		    return false
		}
	    })
	}else{
	    return false
	}
	return true

    }
    // This function assumes a json structure that matches
    // the Tracker_Node object in redraw_view_port
    //
    function highest_value( tracker_node, key ){

	for ( let other_key in tracker_node ){

	if ( other_key !== key ){

	    console.log( tracker_node[other_key].weight )

	    if ( tracker_node[other_key].weight > tracker_node[other_key].weight ){
		return false
	    }
	}
    }
	return true
    }
    function redraw_view_port(){

	if ( Document.length !== 0 ){

	    let segment_id = 0

	    let Node = function(){
//		const prototype = JSON.parse(JSON.stringify(Character_Prototype_Reference))
		const prototype = deep_copy(Character_Prototype_Reference)
		prototype.text_node = ''
		return prototype
	    }
	    let document_object  = {}

	    document_object[segment_id] = Document[0]
	    document_object[segment_id].text_node = ''

	    let current_node_types = []

	    editor.innerHTML = ''

	    // TODO: rename
	    let node=[]

	    for(let format in document_object[segment_id]){
		if ( document_object[segment_id][format].on ){
		    node.push(format)
		}
	    }
	    // Group characters with the same formatting
	    // together. A necessary step toward converting
	    // individually styled characters to HTML.
	    //
	    Document.forEach((ch)=>{

		let tmp_node_array=[]
		let tmp_node=Node()

		for( let key in ch ){

		    // Note: at one point I had this if statement
		    // filter out 'text' keys and it introduced a
		    // bug.
		    //

		    if ( key !== 'index' && ch[key].on ){
			tmp_node_array.push(key)
			tmp_node[key].on=true
			tmp_node[key].value = ch[key].value
		    }
		}
		// If the new character's formatting keys are set
		// to the same values as the previous character,
		// this new character's formatting is identical to
		// the previous, so its text value can be concatenated
		// with the current character, and this new
		// character can be considered as being part of
		// the same doc_segment as the previous one.
		//
		if( array_contents_equal(node, tmp_node_array) ){

		    document_object[segment_id].text_node =
			document_object[segment_id].text_node + ch.text.value

		}else{

		    segment_id++
		    document_object[segment_id]=tmp_node
		    document_object[segment_id].text_node =
			document_object[segment_id].text_node + ch.text.value
		    node=tmp_node_array

		}
		tmp_node_array=[]
		tmp_node=Node()
	    })
	    let master_node = { node : null, tagname : '' }

	    // Note:
	    //
	    // If the state_tracker is a reference
	    // ( i.e. state_tracker = Document[0] )
	    // it mutates global state, causing very
	    // erratic behavior. It's important that
	    // it's a copy here.
	    //
	    let state_tracker = deep_copy( Document[0] )

	    //
	    function Tracker_Node( tagname ){
		return { node : document.createElement(tagname), tagname : tagname, weight: 0 }
	    }
	    let dependency_map = {}

	    for ( let index in document_object ){
		let new_node = { node : null, tagname : '' }
		let last_node = { node : null, tagname : '' }

		let format_nodes = []

		let doc_segment = document_object[index]

		// TODO:
		//
		// In one complete sweep, determine the exact
		// pattern of opening and closing tags.
		//
		// Then, in a second sweep, do the encoding.
		//
		// This way it should be possible to avoid
		// redundant encodings.
		//
		for( let format in doc_segment ){

		    if ( doc_segment[ format ].on !== state_tracker[format].on ){
			// console.log( 'state change detected' )
			state_tracker[ format ].on = doc_segment[ format ].on
			state_tracker[ format ].value = doc_segment[ format ].value

			// I'm reasoning here that if a state change is detected,
			// and that the 'on' value is now set to false, it must
			// necessarily have been previously set to true. Therefore
			// one can assume that formatting had been applied to the
			// previous character, and is no longer being applied.
			//
			// console.log( 'Formatting ' + format + ' has been changed to ' +
			// 	     doc_segment[ format ].value + ' in segment ' + index + '.' )

			// If there are no tags in the dependency cache, add one.
			//
			//
			if ( doc_segment[ format ].on && dependency_map[ format ] === undefined ){

			    dependency_map[ format ] = Tracker_Node( doc_segment[ format ].value )

			    console.log({ 'added' : dependency_map[ format ],
					  index : index })

			    // If the tag *is* found in the dependency cache already,
			    // what exactly does that mean? I believe it means that
			    // the tag belongs higher up in the dependency chain than
			    // tags that haven't been repeated.
			    //

			}else if( doc_segment[ format ].on === false && dependency_map[ format ] !== undefined ){

			    console.log( { 'format' : format, is_highest : highest_value( dependency_map ) })

			}else if( dependency_map[ format ] !== undefined ){

			    dependency_map[ format ].weight =
				dependency_map[ format ].weight + 1

			}else {
			    //
			}
		    }
		    // Filter out 'text' keyword, too?
		    //
		    if ( format !== 'index' && format !== 'text' && format !== 'text_node' ){

			if ( doc_segment[format].on ){

			    format_nodes.push(doc_segment[format].value)

			}

		    }
		}
		let text_node = document.createTextNode(doc_segment.text_node)

		if ( format_nodes.length > 0 ){

		    format_nodes.forEach((tagname)=>{
			let tmp_node = document.createElement(tagname)

			if ( new_node.node === null ){

			    new_node.node = tmp_node

			}else{
			    new_node.node.appendChild(tmp_node)
			}
			last_node.node = tmp_node
		    })

		    last_node.node.appendChild(text_node)
		    editor.appendChild(new_node.node)

		}else{
		    editor.appendChild(text_node)
		}
	    }
	    console.log( dependency_map )
	}else{

	    editor.innerHTML=''
	}
    }
    //
    // @character = Character
    function insert_character( character, opts ){
	let encoded_character = Character({ text : character })
	Document.push(encoded_character)
	Cursor_Index++
	redraw_view_port()
    }
    //
    function delete_character( text_array, index ){

	if ( Document.length > 0  && index > -1 ){

	    if ( index <= -1 ){

		// do nothing
		index = -1

	    }else if (index === 0){
		Document = []
		Cursor_Index--
		redraw_view_port()

	    }else if ( index === Document.length - 1 ){

		Document.pop()
		Cursor_Index--
		redraw_view_port()

	    }else{

		Document.splice(index, 1)
		Cursor_Index--
		redraw_view_port()
	    }
	}
    }

    window.addEventListener('keydown', (e)=>{
	//
	// Listen for the 'shift' key
	//
	if ( e.keyCode === 16 ) shift_down = true
	//
	// Listen for 'tab' and 'space' keys; if
	// pressed, suppress default behavior.
	//
	if ( e.keyCode === 9 || e.keyCode === 32 ) {
	    e.preventDefault()
	    editor.focus()
	}
    })

    let character_set = {  65 : "a", 66 : "b", 67 : "c", 68 : "d", 69 : "e",
			   70 : "f", 71 : "g", 72 : "h", 73 : "i", 74: "j",
			   75 : "k", 76 : "l", 77 : "m", 78 : "n", 79 : "o",
			   80 : "p", 81 : "q", 82 : "r", 83 : "s", 84 : "t",
			   85 : "u", 86 : "v", 87 : "w", 88 : "x", 89 : "y",
			   90 : "z" }

    let upcase_character_set= {65 : "A", 66 : "B", 67 : "C", 68 : "D", 69 : "E",
			       70 : "F", 71 : "G", 72 : "H", 73 : "I", 74: "J",
			       75 : "K", 76 : "L", 77 : "M", 78 : "N", 79 : "O",
			       80 : "P", 81 : "Q", 82 : "R", 83 : "S", 84 : "T",
			       85 : "U", 86 : "V", 87 : "W", 88 : "X", 89 : "Y",
			       90 : "Z" }

    let others = { 48 : "0", 49 : "1", 50 : "2", 51 : "3",  52 : "4",  53 : "5",
		   54 : "6",  55 : "7",  56 : "8", 57 : "9", 9 : '    ',
		   32 : " ", 188: ",", 190 : ".", 191 : "/", 220 : "\"", 222 : "'" }

    let upcase_others = { 48 : ")", 49 : "!", 50 : "@", 51 : "#", 52 : "$", 53 : "%",
			  54 : "^", 55 : "&", 56 : "*", 57 : "(", 188 : "<", 9 : '   ',
			  190 : ">", 191 : "?", 220: "|", 222 : "\"" }

    const BACKSPACE = 8
    const SHIFT = 16
    const ENTER = 13 // as in the 'Enter' key

    function parse_keycode(e){
	let key_c =e.keyCode

	// Check for Caps Lock
	//
	let caps_down = false

	if(e.getModifierState('CapsLock')){
	    caps_down = true
	}else {

	    caps_down = false
	}

	if ( character_set[key_c] ){

	    let ch =  shift_down || caps_down ?
		upcase_character_set[ key_c ] :
		character_set[ key_c ]

	    insert_character( ch )

	}else if( others[ key_c ] ){

	    let ch = shift_down ?
		upcase_others[ key_c ] :
		others[ key_c ]

	    insert_character( ch )

	}else if( key_c === SHIFT ){

	    shift_down =  false

	}else if( key_c === BACKSPACE ){

	    delete_character(Document, Cursor_Index)

	}else if( key_c === ENTER ){

	    insert_character( '/n' )

	}else{
	    console.log( key_c )
	}
    }

    window.addEventListener('keyup', parse_keycode )

    // Temporary
    //
  //   window.addEventListener('keyup', ()=>{
// //	console.log(Document)
// //	console.log(Cursor_Index)

//     })

    // Keypress Rollover ----------------------------------
    //
    let Interval = 100

    window.addEventListener('keydown', (e)=>{
	if( e.repeat ){
	    setTimeout(()=>{
		Interval = 50
		parse_keycode(e)
	    },Interval)
	}
    })
    window.addEventListener('keyup', ()=>{ Interval = 100 })
    /// ----------------------------------------------------

    dom_Cache.toggle_0001.addEventListener('click', ()=>{

    })
    document.getElementById('status_0001').addEventListener('click',()=>{
	console.log(editor.innerHTML)
    })
})()


text:
<?php
class UploadBehavior extends ModelBehavior {
	public function uploadPic(Model $Model, $destination, $resize_override = null){
		if (!$destination) {
			$destination = 'posts';
		}
		$pics = $Model->data[$Model->alias];

		$pics_dir = WWW_ROOT.'files'.DS.$destination;

		$allowed_types = array('image/gif','image/jpeg','image/pjpeg','image/png', 'application/x-shockwave-flash', 'application/vnd.adobe.flash.movie');

		$filename = false; //in case there is no file to be uploaded we return false.

		if ($pics['pic']['name'] != '' && $pics['pic']['error'] == 0) {     //make sure there is a file to upload and there is no error
			$new_file = pathinfo($pics['pic']['name']);

			if (empty($new_file['extension'])) {
				return false;
			}

			$new_name = $new_file['filename'] . '_' . date('dmHis') . '.' . $new_file['extension'];
			$filename = str_replace(' ', '_', $new_name);

			$typeOK = false;

			$finfo = finfo_open(FILEINFO_MIME_TYPE);
			$file_type = finfo_file($finfo, $pics['pic']['tmp_name']);

			foreach ($allowed_types as $type) {     //check to make sure file type is allowed
				if ($type == $file_type) {
					$typeOK = true;
					break;
				}
			}

			if ($typeOK) {  //upload
				if(move_uploaded_file($pics['pic']['tmp_name'], $pics_dir.DS.$filename)) {
					if($this->resize_image($filename, $options=array('files_dir' => $pics_dir, 'ext' => $new_file['extension'], 'resize_override' => $resize_override))) {
						return $filename;
					}
				}
			}
		}

		return false;
	}

	public function resize_image($filename, $options=array())
	{
		if ($options['resize_override']) {
			return true;
		}

		$thumbs_width = isset($options['width']) ? intval($options['width']) : 600;
		$thumbs_height = isset($options['height']) ? intval($options['height']) : 450;
		$files_dir = $options['files_dir'];

		if (is_file($files_dir . DS . $filename)) {
			list($width, $height) = getimagesize($files_dir . DS . $filename);

			if ($width > 600) {
				$v_fact = $thumbs_height / $height;
				$h_fact = $thumbs_width / $width;
				$im_fact = min($v_fact, $h_fact);
				$new_height = $height * $im_fact;
				$new_width = $width * $im_fact;

				$canvas = imagecreatetruecolor($new_width, $new_height);

				switch ($options['ext']) {
					case 'jpg':
					case 'jpeg':
						$image = imagecreatefromjpeg($files_dir . DS . $filename);
						break;
					case 'bmp':
						$image = imagecreatefromwbmp($files_dir . DS . $filename);
						break;
					case 'png':
						$image = imagecreatefrompng($files_dir . DS . $filename);
						break;
					case 'gif':
						$image = imagecreatefromgif($files_dir . DS . $filename);
						break;
				}

				imagecopyresampled($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

				if (imagejpeg($canvas, $files_dir . DS . $filename, 100) || imagepng($canvas, $files_dir . DS . $filename, 100)
					|| imagewbmp($canvas, $files_dir . DS . $filename, 100)  || imagegif($canvas, $files_dir . DS . $filename, 100) ) {
					return true;
				}

				//small image, nothing to do
				return true;
			}
		}

		return false;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Biblioteca.Camadas.DAL
{
    public class Avaliacao
    {
        private string strCon = Conexao.getConexao();

        public List<MODEL.Avaliacao> Select()
        {

            List<MODEL.Avaliacao> lstAvaliacao = new List<MODEL.Avaliacao>();
            SqlConnection conexao = new SqlConnection(strCon);
            string sql = "Select * from Avaliacao";
            SqlCommand cmd = new SqlCommand(sql, conexao);
            conexao.Open();

            try
            {

                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); //chama as informacoes do banco
                while (reader.Read())
                {
                    MODEL.Avaliacao Avaliacao = new MODEL.Avaliacao();
                    Avaliacao.nota = Convert.ToInt32(reader[0].ToString());
                    Avaliacao.ano = Convert.ToDateTime(reader["aniversario"].ToString());

                    lstAvaliacao.Add(Avaliacao);
                }
            }
            catch
            {
                Console.WriteLine("Deu erro na Seleção de Avaliacao");
            }
            finally
            {
                conexao.Close();
            }

            return lstAvaliacao;
        }

        public List<MODEL.Avaliacao> SelectByNota(int nota)
        {
            List<MODEL.Avaliacao> lstAvaliacao = new List<MODEL.Avaliacao>();
            SqlConnection conexao = new SqlConnection(strCon);
            string sql = "Select * from Avaliacao where nota=@nota;";
            SqlCommand cmd = new SqlCommand(sql, conexao);
            cmd.Parameters.AddWithValue("@nota", nota);// parametros por id
            conexao.Open();
            try
            {
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (reader.Read())
                {
                    MODEL.Avaliacao Avaliacao = new MODEL.Avaliacao();
                    Avaliacao.nota = Convert.ToInt32(reader[0].ToString());
                    Avaliacao.ano = Convert.ToDateTime(reader["aniversario"].ToString());

                    lstAvaliacao.Add(Avaliacao);

                }
            }
            catch
            {
                Console.WriteLine("Deu erro na Seleção de Avaliacao  por ID...");
            }
            finally
            {
                conexao.Close();
            }

            return lstAvaliacao;
        }// int id

        public List<MODEL.Avaliacao> SelectByAno(string ano)
        {
            List<MODEL.Avaliacao> lstAvaliacao = new List<MODEL.Avaliacao>();
            SqlConnection conexao = new SqlConnection(strCon);
            string sql = "Select * from Avaliacao where (ano like @ano);";
            SqlCommand cmd = new SqlCommand(sql, conexao);
            cmd.Parameters.AddWithValue("@ano", ano.Trim() + "%");// parametros por nome
            conexao.Open();
            try
            {
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (reader.Read())
                {
                    MODEL.Avaliacao Avaliacao = new MODEL.Avaliacao();
                    Avaliacao.nota = Convert.ToInt32(reader[0].ToString());
                    Avaliacao.ano = Convert.ToDateTime(reader["aniversario"].ToString());

                    lstAvaliacao.Add(Avaliacao);

                }
            }
            catch
            {
                Console.WriteLine("Deu erro na Seleção de Avaliacao por Nome...");
            }
            finally
            {
                conexao.Close();
            }

            return lstAvaliacao;
        }// string nome

        public void Insert(MODEL.Avaliacao avaliacao)
        {
            SqlConnection conexao = new SqlConnection(strCon);
            string sql = "Insert into Avaliacao values (@ano )";
            SqlCommand cmd = new SqlCommand(sql, conexao);
            cmd.Parameters.AddWithValue("@ano", avaliacao.ano);
            cmd.Parameters.AddWithValue("@nota", avaliacao.nota);

            conexao.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch
            {
                Console.WriteLine("Deu erro na inserção deAvaliação...");
            }
            finally
            {
                conexao.Close();
            }
        }

        public void Update(MODEL.Avaliacao avaliacao)
        {
            SqlConnection conexao = new SqlConnection(strCon);
            string sql = "Update Avaliacao set ano=@ano, ";
            sql += " where nota=@nota;";
            SqlCommand cmd = new SqlCommand(sql, conexao);
            cmd.Parameters.AddWithValue("@nota", avaliacao.nota);
            cmd.Parameters.AddWithValue("@ano", avaliacao.ano);

            conexao.Open();

            try
            {

                cmd.ExecuteNonQuery();
            }
            catch
            {
                Console.WriteLine("Erro na atualização de Avaliacao");
            }
            finally
            {
                conexao.Close();
            }
        }

        public void Delete(MODEL.Avaliacao avaliacao)
        {
            SqlConnection conexao = new SqlConnection(strCon);
            string sql = "Delete from Avaliacao where nota=@nota;";
            SqlCommand cmd = new SqlCommand(sql, conexao);
            cmd.Parameters.AddWithValue("@nota", avaliacao.nota);
            conexao.Open();

            try
            {

                cmd.ExecuteNonQuery();
            }
            catch
            {
                Console.WriteLine("Erro na Remoção de Avaliacaop");
            }
            finally
            {
                conexao.Close();
            }

        }

    }
}


text:
from django import forms

class FileUpload(forms.Form):
	YESNO = (
		(None, "Select one . . ."),
		(True, "Yes"),
		(False, "No")
	)

	file = forms.FileField(
		required=True, widget=forms.FileInput(attrs={'class': 'form-control col-md-7 col-xs-12'}))
	has_header_row = forms.BooleanField(required=False,
										widget=forms.Select(choices=YESNO, attrs={'class': 'form-control col-md-7 col-xs-12', 'required': 'True'}))


text:
default['mongodb']['authentication']['username'] = 'admin'
default['mongodb']['authentication']['password'] = 'admin'

default['mongodb']['admin'] = {
  'username' => default['mongodb']['authentication']['username'],
  'password' => default['mongodb']['authentication']['password'],
  'roles' => %w(userAdminAnyDatabase dbAdminAnyDatabase clusterAdmin),
  'database' => 'admin',
}

default['mongodb']['users'] = []

# Force creation of admin user. auth=true is an invalid
# setting for mongos so this is needed to ensure the admin
# user is created
default['mongodb']['mongos_create_admin'] = false

# For connecting to mongo on localhost, retries to make after
# connection failures and delay in seconds to retry
default['mongodb']['user_management']['connection']['retries'] = 2
default['mongodb']['user_management']['connection']['delay'] = 2

# For mongod replicasets, the delay in seconds and number
# of times to retry adding a user. Used to handle election
# of primary not being completed immediately
default['mongodb']['mongod_create_user']['retries'] = 2
default['mongodb']['mongod_create_user']['delay'] = 10


text:
#ifndef TYPE_INFO_HPP
#define TYPE_INFO_HPP

#include <string>
#include <vector>

#include "utils/util.hpp"
#include "utils/error.hpp"

/**
  \brief Stores info about the type of something.
*/
class TypeInfo {
protected:
  /// Types stored by this object. Can be empty.
  TypeList evalValue;
  /// If this type is actually the void type
  bool isVoidType = false;

  inline void throwIfVoid() const {
    if (isVoidType) throw InternalError("Void types have undefined type lists", {METADATA_PAIRS});
  }
public:
  /// Store only one type. Convenience constructor.
  TypeInfo(TypeName type) noexcept: evalValue(TypeList({type})) {}
  /// \copydoc TypeInfo(TypeName)
  TypeInfo(const char* type) noexcept: TypeInfo(std::string(type)) {}
  /// Store a list of types. If list is empty, the type is dynamic.
  TypeInfo(TypeList evalValue) noexcept: evalValue(evalValue) {}
  /// Construct TypeInfo for a void type.
  TypeInfo(std::nullptr_t voidType) noexcept: isVoidType(true) {UNUSED(voidType);}
  /// Construct a dynamic TypeInfo (can have any type).
  TypeInfo() noexcept: evalValue({}) {}

  virtual ~TypeInfo() {}
  TypeInfo(const TypeInfo&) = default;
  TypeInfo& operator=(const TypeInfo&) = default;

  inline TypeList getEvalTypeList() const {
    throwIfVoid();
    return evalValue;
  }

  inline bool isDynamic() const {
    throwIfVoid();
    return evalValue.size() == 0;
  }

  inline bool isVoid() const noexcept {
    return isVoidType;
  }

  /// Get a string representation of the held types
  std::string getTypeNameString() const noexcept;

  virtual std::string toString() const noexcept;

  bool operator==(const TypeInfo& rhs) const noexcept;
  bool operator!=(const TypeInfo& rhs) const noexcept;
};

inline std::ostream& operator<<(std::ostream& os, const TypeInfo& ti) noexcept {
  return os << ti.toString();
}

/**
  \brief TypeInfo that can't be void.

  Has the same constructors as TypeInfo, except for the void one.
*/
class DefiniteTypeInfo: public TypeInfo {
public:
  /// \copydoc TypeInfo::TypeInfo(TypeList)
  DefiniteTypeInfo(TypeList evalValue);
  /// \copydoc TypeInfo::TypeInfo()
  DefiniteTypeInfo();
  DefiniteTypeInfo(std::nullptr_t voidType) = delete;

  std::string toString() const noexcept override;
};

inline std::ostream& operator<<(std::ostream& os, const DefiniteTypeInfo& dti) noexcept {
  return os << dti.toString();
}

/**
  \brief TypeInfo with a singular non-void, non-dynamic type.
*/
class StaticTypeInfo: public DefiniteTypeInfo {
public:
  /**
    \param type name of type to store
  */
  StaticTypeInfo(std::string type);
  /// \copydoc StaticTypeInfo(std::string)
  StaticTypeInfo(const char* type);

  std::string toString() const noexcept override;
};

inline std::ostream& operator<<(std::ostream& os, const StaticTypeInfo& sti) noexcept {
  return os << sti.toString();
}

/**
  \brief Signature for a function. Stores return type and argument types.
*/
class FunctionSignature {
public:
  using Arguments = std::vector<std::pair<std::string, DefiniteTypeInfo>>;
private:
  TypeInfo returnType;
  Arguments arguments;
public:
  FunctionSignature(TypeInfo returnType, Arguments arguments);

  inline TypeInfo getReturnType() const noexcept {
    return returnType;
  }

  inline Arguments getArguments() const noexcept {
    return arguments;
  }

  std::string toString() const noexcept;

  inline bool operator==(const FunctionSignature& rhs) const noexcept {
    return returnType == rhs.returnType && arguments == rhs.arguments;
  }
  inline bool operator!=(const FunctionSignature& rhs) const noexcept {
    return !operator==(rhs);
  }};

inline std::ostream& operator<<(std::ostream& os, const FunctionSignature& fs) noexcept {
  return os << fs.toString();
}

#endif


text:
require 'optparse'

module VagrantPlugins
  module CommandDns
    module Command
      module Host
        class Destroy < Vagrant.plugin('2', :command)

          def execute
            options = {}
            options[:skip] = false

            opts = OptionParser.new do |o|
              o.banner = 'Usage: vagrant dns host destroy'
              o.separator ''
              o.separator 'Options:'
              o.separator ''

              o.on('-s', '--skip', 'Skip ip check before record destruction. Use with extreme caution.') do |skip|
                options[:skip] = skip
              end

              o.separator ''
              o.separator 'Additional documentation can be found on the plugin homepage'
              o.separator ''
            end

            argv = parse_options(opts)
            return if !argv

            with_target_vms(argv) do |machine|
              machine.config.dns.__skip = options[:skip] if options[:skip]
              @env.action_runner.run(Action::Host.host_destroy, {
                  machine: machine,
                  ui: Vagrant::UI::Prefixed.new(@env.ui, 'dns host'),
              })
            end

            0
          end

        end
      end
    end
  end
end