text:
var express = require('express');
var app = express();
module.exports = app;

var path = require('path');
var config = require('./config.json');

// Connect to mongodb
var mongoose = require('mongoose');

var dbname = config.dbname;
process.argv.forEach(function(val, index) {
  if (val.indexOf('--dbname=') === 0) {
    dbname = val.slice('--dbname='.length);
  }
});

mongoose.connect('mongodb://' + config.dbserver + '/' + dbname);

// Setup application configuration
global.kRootDirPath = __dirname;

app.set('port', process.env.PORT || 80);
app.set('views', path.join(__dirname, 'views'));

app.use(app.router);
app.use(express.cookieParser());
app.use(express.cookieParser(config.secret));
app.use(express.favicon());
app.use(express.json());
app.use(express.logger('dev'));
app.use(express.methodOverride());
app.use(express.urlencoded());
app.use(express.session({
  secret: config.secret
}));

// Development only
if (app.get('env') == 'development') {
  app.use(express.errorHandler());
}

// Setup router
var router = require('./routes');
router.setup(app);


text:
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@protocol SINRegionInfo <NSObject>

/**
 * ISO-3366-1 country code.
 *
 * Example: The ISO 3366-1 country for the United States is "US".
 */
@property (nonatomic, strong, readonly) NSString* isoCountryCode;

/**
 * Display name for country, given the locale that the SINRegionList
 * was created with.
 *
 * Example: Given the NSLocale "en_US", the display name would be
 *          "United States".
 */
@property (nonatomic, strong, readonly) NSString* countryDisplayName;

/**
 * ITU-T country calling code.
 *
 * Example: The ITU-T calling code for the region representing United
 *          States is 1.
 */
@property (nonatomic, strong, readonly) NSNumber* countryCallingCode;

@end

/**
 * SINRegionList provides a full list of countries / regions that can
 * be iterated, and it also provides lookup based on ISO 3366-1
 * country.
 */
@protocol SINRegionList <NSObject>

/**
 * Returns all region info entries (not sorted in any particular order).
 *
 * Example usage:
 *
 * // Get a list of regions sorted by display name (e.g. for
 * // displaying in a UITableView for example).
 *
 * NSLocale locale = [NSLocale currentLocale];
 * id<SINRegionList> regions = [SINPhoneNumberUtil() regionListWithLocale:locale];
 * NSSortDescriptor* sortDescriptor;
 * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"countryDisplayName"
 *                                               ascending:YES];
 * NSArray<id<SINRegionInfo>>* sorted;
 * sorted = [regions.entries sortedArrayUsingDescriptors:@[ sortDescriptor ]];
 *
 */
@property (nonatomic, strong, readonly) NSArray<id<SINRegionInfo>>* entries;

/**
 * Get a display name for a particular ISO-3166-1 country code.
 *
 * @return A display name given an ISO-3166-1 countryCode. Returns
 *         empty string if no display name can be found.
 */
- (NSString*)displayNameForRegion:(NSString*)isoCountryCode;

/**
 * Get ITU-T country calling code by ISO-3166-1 country code. E.g. returns 1 for "US".
 *
 * @return An ITU-T country calling code. Returns nil if no calling code can be determined.
 */
- (nullable NSNumber*)countryCallingCodeForRegion:(NSString*)isoCountryCode;

@end

NS_ASSUME_NONNULL_END

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Algorithm;
using QuantConnect.Brokerages;
using QuantConnect.Brokerages.Backtesting;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.Results;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Securities;
using QuantConnect.Securities.Crypto;
using QuantConnect.Securities.Positions;
using QuantConnect.Tests.Engine;
using QuantConnect.Tests.Engine.DataFeeds;

namespace QuantConnect.Tests.Common.Securities
{
    [TestFixture, Parallelizable(ParallelScope.Fixtures)]
    public class CashBuyingPowerModelTests
    {
        private Crypto _btcusd;
        private Crypto _btceur;
        private Crypto _ethusd;
        private Crypto _ethbtc;
        private SecurityPortfolioManager _portfolio;
        private BacktestingTransactionHandler _transactionHandler;
        private BacktestingBrokerage _brokerage;
        private IBuyingPowerModel _buyingPowerModel;
        private QCAlgorithm _algorithm;
        private LocalTimeKeeper _timeKeeper;
        private ITimeKeeper _globalTimeKeeper;
        private IResultHandler _resultHandler;

        [SetUp]
        public void Initialize()
        {
            _algorithm = new QCAlgorithm();
            _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm));
            _portfolio = _algorithm.Portfolio;
            _portfolio.CashBook.Add("EUR", 0, 1.20m);
            _portfolio.CashBook.Add("BTC", 0, 15000m);
            _portfolio.CashBook.Add("ETH", 0, 1000m);

            _algorithm.SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash);

            _transactionHandler = new BacktestingTransactionHandler();
            _brokerage = new BacktestingBrokerage(_algorithm);
            _resultHandler = new TestResultHandler();
            _transactionHandler.Initialize(_algorithm, _brokerage, _resultHandler);

            _algorithm.Transactions.SetOrderProcessor(_transactionHandler);

            var tz = TimeZones.NewYork;
            _btcusd = new Crypto(
                SecurityExchangeHours.AlwaysOpen(tz),
                _portfolio.CashBook[Currencies.USD],
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCUSD, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("BTCUSD", Currencies.USD, 1, 0.01m, 0.00000001m, string.Empty),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
            );

            _ethusd = new Crypto(
                SecurityExchangeHours.AlwaysOpen(tz),
                _portfolio.CashBook[Currencies.USD],
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHUSD, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("ETHUSD", Currencies.USD, 1, 0.01m, 0.00000001m, string.Empty),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
            );

            _btceur = new Crypto(
                SecurityExchangeHours.AlwaysOpen(tz),
                _portfolio.CashBook["EUR"],
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCEUR, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("BTCEUR", "EUR", 1, 0.01m, 0.00000001m, string.Empty),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
            );

            _ethbtc = new Crypto(
                SecurityExchangeHours.AlwaysOpen(tz),
                _portfolio.CashBook["BTC"],
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHBTC, Resolution.Minute, tz, tz, true, false, false),
                new SymbolProperties("ETHBTC", "BTC", 1, 0.00001m, 0.00000001m, string.Empty),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
            );

            _globalTimeKeeper = new TimeKeeper(new DateTime(2019, 4, 22));
            _timeKeeper = _globalTimeKeeper.GetLocalTimeKeeper(tz);
            _buyingPowerModel = new BuyingPowerModelComparator(
                new CashBuyingPowerModel(),
                new SecurityPositionGroupBuyingPowerModel(),
                _portfolio,
                _globalTimeKeeper
            );

            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _ethusd.SetLocalTimeKeeper(_timeKeeper);
            _btceur.SetLocalTimeKeeper(_timeKeeper);
            _ethbtc.SetLocalTimeKeeper(_timeKeeper);
        }

        [TearDown]
        public void TearDown()
        {
            _transactionHandler.Exit();
            _resultHandler.Exit();
        }

        [Test]
        public void InitializesCorrectly()
        {
            Assert.AreEqual(1m, _buyingPowerModel.GetLeverage(_btcusd));
            Assert.AreEqual(0m, _buyingPowerModel.GetReservedBuyingPowerForPosition(_btcusd));
        }

        [Test]
        public void SetLeverageDoesNotUpdateLeverage()
        {
            Assert.Throws<InvalidOperationException>(() => _buyingPowerModel.SetLeverage(_btcusd, 50m));
        }

        [Test]
        public void LimitBuyBtcWithUsdRequiresUsdInPortfolio()
        {
            _portfolio.SetCash(20000);

            // Available cash = 20000 USD, can buy 2 BTC at 10000
            var order = new LimitOrder(_btcusd.Symbol, 2m, 10000m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // Available cash = 20000 USD, cannot buy 2.1 BTC at 10000, need 21000
            order = new LimitOrder(_btcusd.Symbol, 2.1m, 10000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // Available cash = 20000 USD, cannot buy 2 BTC at 11000, need 22000
            order = new LimitOrder(_btcusd.Symbol, 2m, 11000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void LimitBuyBtcWithEurRequiresEurInPortfolio()
        {
            _portfolio.SetCash("EUR", 20000m, 1.20m);

            // Available cash = 20000 EUR, can buy 2 BTC at 10000
            var order = new LimitOrder(_btceur.Symbol, 2m, 10000m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient);

            // Available cash = 20000 EUR, cannot buy 2.1 BTC at 10000, need 21000
            order = new LimitOrder(_btceur.Symbol, 2.1m, 10000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient);

            // Available cash = 20000 EUR, cannot buy 2 BTC at 11000, need 22000
            order = new LimitOrder(_btceur.Symbol, 2m, 11000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient);
        }

        [Test]
        public void LimitSellOrderRequiresBaseCurrencyInPortfolio()
        {
            _portfolio.SetCash(0);
            _portfolio.CashBook["BTC"].SetAmount(0.5m);

            // 0.5 BTC in portfolio, can sell 0.5 BTC at any price
            var order = new LimitOrder(_btcusd.Symbol, -0.5m, 10000m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // 0.5 BTC in portfolio, cannot sell 0.6 BTC at any price
            order = new LimitOrder(_btcusd.Symbol, -0.6m, 10000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void LimitBuyOrderChecksOpenOrders()
        {
            _portfolio.SetCash(5000);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 15000m });

            _ethusd = _algorithm.AddCrypto("ETHUSD");
            _ethusd.SetMarketPrice(new Tick { Value = 1000m });
            _algorithm.SetFinishedWarmingUp();

            // BTCUSD buy order decreases available USD (5000 - 1500 = 3500 USD)
            SubmitLimitOrder(_btcusd.Symbol, 0.1m, 15000m);

            // ETHUSD buy order decreases available USD (3500 - 3000 = 500 USD)
            SubmitLimitOrder(_ethusd.Symbol, 3m, 1000m);

            // 500 USD available, can buy 0.048 BTC at 10000
            var order = new LimitOrder(_btcusd.Symbol, 0.048m, 10000m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // 500 USD available, cannot buy 0.06 BTC at 10000
            order = new LimitOrder(_btcusd.Symbol, 0.06m, 10000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void LimitSellOrderChecksOpenOrders()
        {
            _portfolio.SetCash(5000);
            _portfolio.CashBook["BTC"].SetAmount(1m);
            _portfolio.CashBook["ETH"].SetAmount(3m);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 15000m });

            _ethusd = _algorithm.AddCrypto("ETHUSD");
            _ethusd.SetMarketPrice(new Tick { Value = 1000m });

            _ethbtc = _algorithm.AddCrypto("ETHBTC");
            _ethbtc.SetMarketPrice(new Tick { Value = 0.1m });
            _algorithm.SetFinishedWarmingUp();

            // BTCUSD sell limit order decreases available BTC (1 - 0.1 = 0.9 BTC)
            SubmitLimitOrder(_btcusd.Symbol, -0.1m, 15000m);

            // ETHUSD sell limit order decreases available ETH (3 - 1 = 2 ETH)
            SubmitLimitOrder(_ethusd.Symbol, -1m, 1000m);

            // ETHBTC buy limit order decreases available BTC (0.9 - 0.1 = 0.8 BTC)
            SubmitLimitOrder(_ethbtc.Symbol, 1m, 0.1m);

            // BTCUSD sell stop order decreases available BTC (0.8 - 0.1 = 0.7 BTC)
            SubmitStopMarketOrder(_btcusd.Symbol, -0.1m, 5000m);

            // 0.7 BTC available, can sell 0.7 BTC at any price
            var order = new LimitOrder(_btcusd.Symbol, -0.7m, 10000m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // 0.7 BTC available, cannot sell 0.8 BTC at any price
            order = new LimitOrder(_btcusd.Symbol, -0.8m, 10000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // 2 ETH available, can sell 2 ETH at any price
            order = new LimitOrder(_ethusd.Symbol, -2m, 1200m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _ethusd, order).IsSufficient);

            // 2 ETH available, cannot sell 2.1 ETH at any price
            order = new LimitOrder(_ethusd.Symbol, -2.1m, 2000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _ethusd, order).IsSufficient);

            // 0.7 BTC available, can sell stop 0.7 BTC at any price
            var stopOrder = new StopMarketOrder(_btcusd.Symbol, -0.7m, 5000m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, stopOrder).IsSufficient);

            // 0.7 BTC available, cannot sell stop 0.8 BTC at any price
            stopOrder = new StopMarketOrder(_btcusd.Symbol, -0.8m, 5000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, stopOrder).IsSufficient);
        }

        [Test]
        public void MarketBuyBtcWithUsdRequiresUsdInPortfolioPlusFees()
        {
            _portfolio.SetCash(20000);
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m });

            // Available cash = 20000 USD, cannot buy 2 BTC at 10000 (fees are excluded)
            var order = new MarketOrder(_btcusd.Symbol, 2m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // Maximum we can market buy with 20000 USD is 1.99501246 BTC
            Assert.AreEqual(1.99501246m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1, 0).Quantity);

            _btcusd.SetMarketPrice(new Tick { Value = 9900m });

            // Available cash = 20000 USD, can buy 2 BTC at 9900 (plus fees)
            order = new MarketOrder(_btcusd.Symbol, 2m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void MarketBuyBtcWithEurRequiresEurInPortfolioPlusFees()
        {
            _portfolio.SetCash("EUR", 20000m, 1.20m);
            _btceur.SetLocalTimeKeeper(_timeKeeper);
            _btceur.SetMarketPrice(new Tick { Value = 10000m });

            // Available cash = 20000 EUR, cannot buy 2 BTC at 10000 (fees are excluded)
            var order = new MarketOrder(_btceur.Symbol, 2m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient);

            // Maximum we can market buy with 20000 EUR is 1.99501246 BTC
            var targetValue = 20000m * _portfolio.CashBook["EUR"].ConversionRate / _portfolio.TotalPortfolioValue;
            Assert.AreEqual(1.99501246m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btceur, targetValue, 0).Quantity);

            _btceur.SetMarketPrice(new Tick { Value = 9900m });

            // Available cash = 20000 EUR, can buy 2 BTC at 9900 (plus fees)
            order = new MarketOrder(_btceur.Symbol, 2m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient);
        }

        [Test]
        public void MarketSellOrderRequiresBaseCurrencyInPortfolioPlusFees()
        {
            _portfolio.SetCash(0);

            _btcusd.SetMarketPrice(new Tick { Value = 10000m });
            _portfolio.SetCash("BTC", 0.5m, 10000m);

            // 0.5 BTC in portfolio, can sell 0.5 BTC
            var order = new MarketOrder(_btcusd.Symbol, -0.5m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // 0.5 BTC in portfolio, cannot sell 0.51 BTC
            order = new MarketOrder(_btcusd.Symbol, -0.51m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // Maximum we can market sell with 0.5 BTC is 0.5 BTC
            Assert.AreEqual(-0.5m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 0, 0).Quantity);
        }

        [Test]
        public void MarketBuyOrderChecksOpenOrders()
        {
            _portfolio.SetCash(5000);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 15000m });

            _ethusd = _algorithm.AddCrypto("ETHUSD");
            _ethusd.SetMarketPrice(new Tick { Value = 1000m });
            _algorithm.SetFinishedWarmingUp();

            // BTCUSD buy order decreases available USD (5000 - 1500 = 3500 USD)
            SubmitLimitOrder(_btcusd.Symbol, 0.1m, 15000m);

            // ETHUSD buy order decreases available USD (3500 - 3000 = 500 USD)
            SubmitLimitOrder(_ethusd.Symbol, 3m, 1000m);

            // Maximum we can market buy with 500 USD is 0.0332502 BTC
            var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 500 / _portfolio.TotalPortfolioValue, 0).Quantity;
            Assert.AreEqual(0.0332502m, quantity);

            // 500 USD available, can buy `quantity` BTC at 15000
            var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // 500 USD available, cannot buy `quantity` + _btcusd.SymbolProperties.LotSize BTC at 15000
            order = new MarketOrder(_btcusd.Symbol, quantity + _btcusd.SymbolProperties.LotSize, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void MarketSellOrderChecksOpenOrders()
        {
            _portfolio.SetCash(5000);
            _portfolio.CashBook["BTC"].SetAmount(1m);
            _portfolio.CashBook["ETH"].SetAmount(3m);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 15000m });

            _ethusd = _algorithm.AddCrypto("ETHUSD");
            _ethusd.SetMarketPrice(new Tick { Value = 1000m });

            _ethbtc = _algorithm.AddCrypto("ETHBTC");
            _ethbtc.SetMarketPrice(new Tick { Value = 0.1m });
            _algorithm.SetFinishedWarmingUp();

            // BTCUSD sell order decreases available BTC (1 - 0.1 = 0.9 BTC)
            SubmitLimitOrder(_btcusd.Symbol, -0.1m, 15000m);

            // ETHBTC buy order decreases available BTC (0.9 - 0.1 = 0.8 BTC)
            SubmitLimitOrder(_ethbtc.Symbol, 1m, 0.1m);

            // Maximum we can market sell with 0.8 BTC is -0.79800498m BTC (for a target position of 0.2 BTC)
            // target value = (1 - 0.8) * price
            Assert.AreEqual(-0.79800498m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 0.2m * 15000 / _portfolio.TotalPortfolioValue, 0).Quantity);

            // 0.8 BTC available, can sell 0.80 BTC at market
            var order = new MarketOrder(_btcusd.Symbol, -0.80m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // 0.8 BTC available, cannot sell 0.81 BTC at market
            order = new MarketOrder(_btcusd.Symbol, -0.81m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void LimitBuyOrderIncludesFees()
        {
            _portfolio.SetCash(20000);
            _btcusd.FeeModel = new ConstantFeeModel(50);

            // Available cash = 20000, cannot buy 2 BTC at 10000 because of order fee
            var order = new LimitOrder(_btcusd.Symbol, 2m, 10000m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // deposit another 50 USD
            _portfolio.CashBook[Currencies.USD].AddAmount(50);

            // now the order is allowed
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void CalculatesMaximumOrderQuantityCorrectly()
        {
            _portfolio.SetCash(10000);
            _portfolio.SetCash("EUR", 10000m, 1.20m);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 15000m });

            _ethusd = _algorithm.AddCrypto("ETHUSD");
            _ethusd.SetLocalTimeKeeper(_timeKeeper);
            _ethusd.SetMarketPrice(new Tick { Value = 1000m });

            _ethbtc = _algorithm.AddCrypto("ETHBTC");
            _ethbtc.SetLocalTimeKeeper(_timeKeeper);
            _ethbtc.SetMarketPrice(new Tick { Value = 0.1m });

            _btceur = _algorithm.AddCrypto("BTCEUR");
            _btceur.SetLocalTimeKeeper(_timeKeeper);
            _btceur.SetMarketPrice(new Tick { Value = 12000m });
            _algorithm.SetFinishedWarmingUp();

            // 0.66500415m * 15000 + fees + price buffer <= 10000 USD
            var targetValue = 10000 / _portfolio.TotalPortfolioValue;

            var getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, targetValue, 0).Quantity;
            Assert.AreEqual(0.66500415m, getMaximumOrderQuantityForTargetValueResult);

            var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            // 9.97506234 * 1000 + fees <= 10000 USD
            getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _ethusd, targetValue, 0).Quantity;
            Assert.AreEqual(9.97506234m, getMaximumOrderQuantityForTargetValueResult);

            order = new MarketOrder(_ethusd.Symbol, getMaximumOrderQuantityForTargetValueResult, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _ethusd, order).IsSufficient);

            // no BTC in portfolio, but GetMaximumOrderQuantityForTargetBuyingPower does not care
            var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _ethbtc, 1, 0).Quantity;
            Assert.AreNotEqual(0m, quantity);
            // HasSufficientBuyingPowerForOrder does check margin requirements
            order = new MarketOrder(_ethbtc.Symbol, quantity, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _ethbtc, order).IsSufficient);

            // 0.83125519 * 12000 + fees <= 10000 EUR
            targetValue = 10000m * _portfolio.CashBook["EUR"].ConversionRate / _portfolio.TotalPortfolioValue;
            getMaximumOrderQuantityForTargetValueResult  = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btceur, targetValue, 0).Quantity;
            Assert.AreEqual(0.83125519m, getMaximumOrderQuantityForTargetValueResult);

            order = new MarketOrder(_btceur.Symbol, getMaximumOrderQuantityForTargetValueResult, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient);
        }

        [Test]
        public void CalculatesMaximumOrderQuantityCorrectlySmallerTarget()
        {
            _portfolio.SetCash(10000);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 15000m });

            _algorithm.SetFinishedWarmingUp();

            var getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 0.1m, 0);
            // Quantity * 15000m + fees + price buffer <= 1000 USD Target
            Assert.AreEqual(0.06650041m, getMaximumOrderQuantityForTargetValueResult.Quantity);

            var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult.Quantity, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void CalculatesMaximumOrderQuantityCorrectlyBiggerTarget()
        {
            _portfolio.SetCash(10000);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 15000m });

            _algorithm.SetFinishedWarmingUp();

            var getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 10m, 0);
            // Quantity * 15000m + fees + price buffer <= 100000 USD Target
            Assert.AreEqual(6.65004156m, getMaximumOrderQuantityForTargetValueResult.Quantity);

            var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult.Quantity, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void CalculatesMaximumOrderQuantityCorrectlyForAlmostNoCashRemaining()
        {
            _portfolio.SetCash(0.00000000001m);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 15000m });

            _algorithm.SetFinishedWarmingUp();

            var getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 10000 / _portfolio.TotalPortfolioValue, 0);
            // We don't have enough cash, but GetMaximumOrderQuantityForTargetValue does not care about this :)
            Assert.AreEqual(0.66500415m, getMaximumOrderQuantityForTargetValueResult.Quantity);

            var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult.Quantity, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void CalculatesMaximumOrderQuantityCorrectlyForNoOrderFee()
        {
            _portfolio.SetCash(100000m);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _algorithm.Securities[_btcusd.Symbol].SetFeeModel(new ConstantFeeModel(0));

            _btcusd.SetMarketPrice(new Tick { Value = 15000m });

            _algorithm.SetFinishedWarmingUp();
            var getMaximumOrderQuantityForTargetValueResult  = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 0.1m, 0);
            // Quantity * 15000m + fees (0) + price buffer <= 10000 USD Target
            Assert.AreEqual(0.66666666m, getMaximumOrderQuantityForTargetValueResult.Quantity);

            var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult.Quantity, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void MarketBuyOrderChecksExistingHoldings()
        {
            _portfolio.SetCash(8000);
            _portfolio.CashBook.Add("BTC", 0.2m, 10000m);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m });
            _algorithm.SetFinishedWarmingUp();

            Assert.AreEqual(10000m, _portfolio.TotalPortfolioValue);

            // Maximum we can market buy for (10000-2000) = 8000 USD is 0.79800498 BTC
            var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 10000m / _portfolio.TotalPortfolioValue, 0).Quantity;
            Assert.AreEqual(0.79800498m, quantity);

            // the maximum order quantity can be executed
            var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void MarketBuyBtcWithEurCalculatesBuyingPowerProperlyWithExistingHoldings()
        {
            _portfolio.SetCash("EUR", 20000m, 1.20m);
            _portfolio.CashBook.Add("BTC", 1m, 12000m);
            _btceur.SetLocalTimeKeeper(_timeKeeper);
            _btceur.SetMarketPrice(new Tick { Value = 10000m });
            // Maximum we can market buy with 20000 EUR is 1.99501246m BTC
            // target value = 30000 EUR = 20000 EUR in cash + 10000 EUR in BTC
            var targetValue = 30000m * _portfolio.CashBook["EUR"].ConversionRate / _portfolio.TotalPortfolioValue;
            Assert.AreEqual(1.99501246m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btceur, targetValue, 0).Quantity);

            // Available cash = 20000 EUR, can buy 1.994 BTC at 10000 (plus fees)
            var order = new MarketOrder(_btceur.Symbol, 1.99401794m, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient);

            // Available cash = 20000 EUR, cannot buy 2 BTC at 10000 (plus fees)
            order = new MarketOrder(_btceur.Symbol, 2m, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient);
        }

        [Test]
        public void MarketBuyOrderUsesAskPriceIfAvailable()
        {
            _portfolio.SetCash(10000);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();

            Assert.AreEqual(10000m, _portfolio.TotalPortfolioValue);

            // Maximum we can market buy at ask price with 10000 USD is 0.99254351 BTC
            var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity;
            Assert.AreEqual(0.99254351m, quantity);

            // the maximum order quantity can be executed
            var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void ZeroTargetWithZeroHoldingsIsNotAnError()
        {
            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);

            var result = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_algorithm.Portfolio, _btcusd, 0, 0);

            var order = new MarketOrder(_btcusd.Symbol, result.Quantity, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            Assert.AreEqual(0, result.Quantity);
            Assert.AreEqual(string.Empty, result.Reason);
            Assert.AreEqual(false, result.IsError);
        }

        [Test]
        public void ZeroTargetWithNonZeroHoldingsReturnsNegativeOfQuantity()
        {
            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _portfolio.CashBook.Add("BTC", 1m, 12000m);

            var result = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_algorithm.Portfolio, _btcusd, 0, 0);

            var order = new MarketOrder(_btcusd.Symbol, result.Quantity, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);

            Assert.AreEqual(-1, result.Quantity);
            Assert.AreEqual(string.Empty, result.Reason);
            Assert.AreEqual(false, result.IsError);
        }

        [Test]
        public void NonAccountCurrencyFees()
        {
            _portfolio.SetCash(10000);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();
            _btcusd.FeeModel = new NonAccountCurrencyCustomFeeModel();
            Assert.AreEqual(10000m, _portfolio.TotalPortfolioValue);

            // 0.24875621 * 100050 (ask price) + 0.5 (fee) * 15000 (conversion rate, because its BTC) = 9999.9999105
            var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity;
            Assert.AreEqual(0.24875621m, quantity);

            // the maximum order quantity can be executed
            var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void NonAccountCurrency_NoQuoteCurrencyCash()
        {
            _algorithm.Portfolio.CashBook.Clear();
            _algorithm.Portfolio.SetAccountCurrency("EUR");
            _algorithm.Portfolio.SetCash(10000);
            Assert.AreEqual(10000m, _portfolio.TotalPortfolioValue);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();

            _algorithm.Portfolio.CashBook[Currencies.USD].ConversionRate = 0.88m;

            // we don't have any USD ! cash model shouldn't let us trade
            var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity;
            Assert.AreNotEqual(0m, quantity);

            // HasSufficientBuyingPowerForOrder does check margin requirements
            var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow);
            var result = _buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order);
            Assert.IsFalse(result.IsSufficient);
            Assert.IsTrue(result.Reason.Contains("only a total value of 0 USD is available."));
        }

        [TestCase("EUR")]
        [TestCase("ARG")]
        public void ZeroNonAccountCurrency_GetMaximumOrderQuantityForTargetValue(string accountCurrency)
        {
            _algorithm.Portfolio.CashBook.Clear();
            _algorithm.Portfolio.SetAccountCurrency(accountCurrency);
            _algorithm.Portfolio.SetCash(0);
            _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m);
            Assert.AreEqual(8800m, _portfolio.TotalPortfolioValue);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();

            // Maximum we can market buy at ask price with 10000 USD is 0.99254351 BTC => Account currency should not matter
            var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity;
            Assert.AreEqual(0.99254351m, quantity);

            var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow);
            var fee = _btcusd.FeeModel.GetOrderFee(new OrderFeeParameters(_btcusd, order));
            var feeAsAccountCurrency = _algorithm.Portfolio.CashBook.ConvertToAccountCurrency(fee.Value);
            var expectedQuantity = (8800 - feeAsAccountCurrency.Amount) / (_btcusd.AskPrice * 0.88m);
            expectedQuantity -= expectedQuantity % _btcusd.SymbolProperties.LotSize;
            Assert.AreEqual(expectedQuantity, quantity);

            // the maximum order quantity can be executed
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [Test]
        public void ZeroNonAccountCurrency_GetBuyingPower()
        {
            _algorithm.Portfolio.CashBook.Clear();
            _algorithm.Portfolio.SetAccountCurrency("EUR");
            _algorithm.Portfolio.SetCash(0);
            _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m);
            Assert.AreEqual(8800m, _portfolio.TotalPortfolioValue);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();

            var quantity = _buyingPowerModel.GetBuyingPower(new BuyingPowerParameters(_portfolio, _btcusd, OrderDirection.Buy)).Value;

            Assert.AreEqual(1m, quantity);
        }

        [Test]
        public void ZeroNonAccountCurrency_GetReservedBuyingPowerForPosition()
        {
            _algorithm.Portfolio.CashBook.Clear();
            _algorithm.Portfolio.SetAccountCurrency("EUR");
            _algorithm.Portfolio.SetCash(0);
            _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m);
            Assert.AreEqual(8800m, _portfolio.TotalPortfolioValue);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();
            _btcusd.Holdings.SetHoldings(_btcusd.Price, 100);

            var res = _buyingPowerModel.GetReservedBuyingPowerForPosition(
                new ReservedBuyingPowerForPositionParameters(_btcusd));

            // Always returns 0. Since we're purchasing currencies outright, the position doesn't consume buying power
            Assert.AreEqual(0m, res.AbsoluteUsedBuyingPower);
        }

        [Test]
        public void NonAccountCurrency_GetBuyingPower()
        {
            _algorithm.Portfolio.CashBook.Clear();
            _algorithm.Portfolio.SetAccountCurrency("EUR");
            _algorithm.Portfolio.SetCash(10000);
            _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m);
            Assert.AreEqual(18800m, _portfolio.TotalPortfolioValue);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();

            var quantity = _buyingPowerModel.GetBuyingPower(new BuyingPowerParameters(_portfolio, _btcusd, OrderDirection.Buy)).Value;

            Assert.AreEqual(1m, quantity);
        }

        [Test]
        public void NonAccountCurrency_ZeroQuoteCurrency_GetBuyingPower()
        {
            _algorithm.Portfolio.CashBook.Clear();
            _algorithm.Portfolio.SetAccountCurrency("EUR");
            _algorithm.Portfolio.SetCash(10000);
            _algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m);
            Assert.AreEqual(10000, _portfolio.TotalPortfolioValue);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();

            var quantity = _buyingPowerModel.GetBuyingPower(new BuyingPowerParameters(_portfolio, _btcusd, OrderDirection.Buy)).Value;

            Assert.AreEqual(0m, quantity);
        }

        [TestCase("EUR")]
        [TestCase("ARG")]
        public void NonZeroNonAccountCurrency_UnReachableTarget(string accountCurrency)
        {
            _algorithm.Portfolio.CashBook.Clear();
            _algorithm.Portfolio.SetAccountCurrency("EUR");
            _algorithm.Portfolio.SetCash(10000);
            _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m);
            Assert.AreEqual(18800m, _portfolio.TotalPortfolioValue);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();

            // Maximum we can market buy at ask price with 10000 USD + (10000 EUR / 0.88 rate) is 2.12043387 BTC
            var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity;
            Assert.AreEqual(2.12043387m, quantity);

            // the maximum order quantity can be executed
            var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow);
            Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        [TestCase("EUR")]
        [TestCase("ARG")]
        public void NonZeroNonAccountCurrency_ReachableTarget(string accountCurrency)
        {
            _algorithm.Portfolio.CashBook.Clear();
            _algorithm.Portfolio.SetAccountCurrency(accountCurrency);
            _algorithm.Portfolio.SetCash(10000);
            _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m);
            Assert.AreEqual(18800m, _portfolio.TotalPortfolioValue);

            _btcusd = _algorithm.AddCrypto("BTCUSD");
            _btcusd.SetLocalTimeKeeper(_timeKeeper);
            _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote });
            _algorithm.SetFinishedWarmingUp();

            // only use the USD for determining the target
            var reachableTarget = 8800m / 18800m;
            // Maximum we can market buy at ask price with 10000 USD is 0.99254351 BTC => Account currency should not matter
            var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, reachableTarget, 0).Quantity;
            Assert.AreEqual(0.99254351m, quantity);

            // the maximum order quantity can be executed
            var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow);
            Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient);
        }

        private void SubmitLimitOrder(Symbol symbol, decimal quantity, decimal limitPrice)
        {
            using (var resetEvent = new ManualResetEvent(false))
            {
                EventHandler<OrderEvent> handler = (s, e) => { resetEvent.Set(); };

                _brokerage.OrderStatusChanged += handler;

                _algorithm.LimitOrder(symbol, quantity, limitPrice);

                if (!resetEvent.WaitOne(5000))
                {
                    throw new TimeoutException("SubmitLimitOrder");
                }

                _brokerage.OrderStatusChanged -= handler;
            }
        }

        private void SubmitStopMarketOrder(Symbol symbol, decimal quantity, decimal stopPrice)
        {
            using (var resetEvent = new ManualResetEvent(false))
            {
                EventHandler<OrderEvent> handler = (s, e) => { resetEvent.Set(); };

                _brokerage.OrderStatusChanged += handler;

                _algorithm.StopMarketOrder(symbol, quantity, stopPrice);

                if (!resetEvent.WaitOne(5000))
                {
                    throw new TimeoutException("SubmitStopMarketOrder");
                }

                _brokerage.OrderStatusChanged -= handler;
            }
        }

        internal class NonAccountCurrencyCustomFeeModel : FeeModel
        {
            public string FeeCurrency = "BTC";
            public decimal FeeAmount = 0.5m;

            public override OrderFee GetOrderFee(OrderFeeParameters parameters)
            {
                return new OrderFee(new CashAmount(FeeAmount, FeeCurrency));
            }
        }
    }
}


text:
// ------------------------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

namespace Microsoft.Graph.Core.Test.TestModels
{
    using System.Runtime.Serialization;

    using Newtonsoft.Json;

    /// <summary>
    /// A property bag class for testing derived type deserialization.
    /// </summary>
    [JsonConverter(typeof(DerivedTypeConverter))]
    [DataContract]
    public class DerivedTypeClass : AbstractEntityType
    {
        /// <summary>
        /// Gets or sets enumType.
        /// </summary>
        [DataMember(Name = "enumType", EmitDefaultValue = false, IsRequired = false)]
        public EnumType? EnumType { get; set; }

        /// <summary>
        /// Gets or sets id.
        /// </summary>
        [DataMember(Name = "name", EmitDefaultValue = false, IsRequired = false)]
        public string Name { get; set; }
    }
}


text:
<?xml version="1.0"?>
<!--
  ~ Copyright 2013-2020 the original author or authors.
  ~
  ~ 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
  ~
  ~     https://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.
  ~
  -->

<!DOCTYPE suppressions PUBLIC
		"-//Puppy Crawl//DTD Suppressions 1.1//EN"
		"https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
	<!-- Xeger is repackaged -->
	<suppress files=".*xeger.*" checks=".*"/>
	<suppress files=".*functionalTest.*" checks="(Javadoc*|HideUtility*|LineLengthCheck)"/>
	<suppress files=".*MessagingApplication.*" checks="(Javadoc*|HideUtility*)"/>
	<suppress files=".*AutoConfigureWireMock.*" checks="LineLengthCheck"/>
	<suppress files=".*ConditionalOnStubbedDiscoveryEnabled.*" checks="LineLengthCheck"/>
	<suppress files=".*ConvertMojo.*" checks="LineLengthCheck"/>
	<suppress files=".*LoanApplicationServiceTests.*" checks="LineLengthCheck"/>
	<suppress files=".*MessageSubscriberRabbitListener.*" checks="LineLengthCheck"/>
	<suppress files=".*PluginUnitTest.*" checks="LineLengthCheck"/>
	<suppress files=".*RabbitManager.*" checks="LineLengthCheck"/>
	<suppress files=".*GenerateTestsMojo.*" checks="LineLengthCheck"/>
	<suppress files=".*StubRunnerBoot.*" checks="LineLengthCheck"/>
	<suppress files=".*StubRunnerBoot.*" checks="HideUtilityClassConstructor"/>
	<suppress files=".*StubRunnerBoot.*" checks="FinalClass"/>
	<suppress files=".*StubRunnerMain.*" checks="FinalClass"/>
	<suppress files=".*StubRunnerJUnit5ExtensionCustomMessageVerifierTests.*" checks="RegexpSinglelineJavaCheck"/>
	<suppress files=".*StubRunnerJUnit5ExtensionExceptionThrowingTests.*" checks="RegexpSinglelineJavaCheck"/>
	<suppress files=".*StubRunnerSliceTests.*" checks="LineLengthCheck"/>
	<suppress files=".*WiremockServerApplicationTests.*" checks="LineLengthCheck"/>
	<suppress files=".*ContractVerifierConfigProperties.*" checks="JavadocStyle"/>
	<suppress files=".*YamlContract.*" checks="JavadocVariable"/>
	<suppress files=".*HttpHeaders.*" checks="HideUtility*"/>
	<suppress files=".*HttpMethods.*" checks="(Javadoc*|HideUtility*)"/>
	<suppress files=".*HttpStatus.*" checks="HideUtility*"/>
	<suppress files=".*contractsToCompile.*" checks=".*"/>
	<suppress files=".*RegexPatterns.*" checks="HideUtility*"/>
	<suppress files=".*gradle.*" checks=".*"/>
</suppressions>


text:
title: Overview
page_title: Connections - RadDiagram
description: RadDiagram offers flexible and interactive diagramming layouts for your rich data-visualization applications.
slug: winforms/diagram/diagram-items/connections
tags: connections
published: True
position: 0
previous_url: diagram-diagram-items-connections
---

# Connections

This tutorial will walk you through the functionality and the main features of __RadDiagramConnection__.

>note Before proceeding with this topic, it is recommended to get familiar with the [visual structure]({%slug winforms/diagram/structure%}) of the __RadDiagram__.
>

## Overview

__RadDiagramConnection__ is basically an object that connects zero, one or two shapes:

![diagram-diagram-items-connections 001](images/diagram-diagram-items-connections001.png)

You can use its extensive API to configure its source and target points or shapes. You can choose from a list of predefined cap types thus customizing the start and end point of the connection to better fit in your application scenario. You can also control the type of a connection using the __ConnectionType__ property, add a custom content and customize the overall look and feel of the items.

## Configure the Source and Target of a Connection

The __RadDiagramConnection__ class exposes the following properties that allow you to control the start and end points of a connection:

* __StartPoint/EndPoint__ - these properties are of type Telerik.Windows.Diagrams.Core.*Point* and they set or get the start/end point of a connection.

* __Source/Target__ - these properties get or set the source/target __RadDiagramShape__ of a connection.

* __SourceConnectorPosition/TargetConnectorPosition__ - there are five predefined strings that you can use to define where to position the connectors of the connection:

	* __Auto__ - use it if you want to automatically determine the start/end point of a connection. This option will allow the connection to dynamically determine which shape connector to be used as a start/end point. Based on the end point position, the __SourceConnectorPosition__ will be set to the nearest shape connector. Alternatively, the __TargetConnectorPosition__ will be set to the nearest shape connector, based on the start point position of the connection.

	* __Left__ - use it to define the left connector of a shape as the source/target point of the connection

	* __Top__ - use it to define the top connector of a shape as the source/target point of the connection

	* __Right__ - use it to define the right connector of a shape as the source/target point of the connection

	* __Bottom__ - use it to define the bottom connector of a shape as the source/target point of the connection

![diagram-diagram-items-connections 009](images/diagram-diagram-items-connections009.png)

* __SourceCapType/TargetCapType__ - both properties are an enumeration of type __CapType__ that allow you to choose a cap from a set of predefined Cap types. For more detailed information, please, view the CapTypes section below.

![diagram-diagram-items-connections 010](images/diagram-diagram-items-connections010.png)

* __SourceCapSize/TargetCapSize__ - these properties are of type Size and they get or set the size of the __SourceCap/TargetCap__.

![diagram-diagram-items-connections 011](images/diagram-diagram-items-connections011.png)

## Set Content

You can label a connection by setting its __Content__ property.

![diagram-diagram-items-connections 024](images/diagram-diagram-items-connections024.png)

{{source=..\SamplesCS\Diagram\DiagramItems.cs region=Content}}
{{source=..\SamplesVB\Diagram\DiagramItems.vb region=Content}}

````C#

connection1.Content = "connection label";

````
````VB.NET
connection1.Content = "connection label"

````

{{endregion}}

## Customize the Connection Appearance

You can easily customize the visual appearance of the __RadDiagramConnection__ by using the following properties:

* __BackColor__: gets or sets the color that specifies how the __RadDiagramConnection__ is painted.

![diagram-diagram-items-connections 025](images/diagram-diagram-items-connections025.png)

{{source=..\SamplesCS\Diagram\DiagramItems.cs region=ConnectionBackColor}}
{{source=..\SamplesVB\Diagram\DiagramItems.vb region=ConnectionBackColor}}

````C#

connection1.BackColor = Color.Red;

````
````VB.NET
connection1.BackColor = Color.Red

````

{{endregion}}

* __StrokeThickness__: gets or sets the width of the __RadDiagramConnection__ outline.

![diagram-diagram-items-connections 026](images/diagram-diagram-items-connections026.png)

{{source=..\SamplesCS\Diagram\DiagramItems.cs region=StrokeThickness}}
{{source=..\SamplesVB\Diagram\DiagramItems.vb region=StrokeThickness}}

````C#
connection1.StrokeThickness = 5;

````
````VB.NET
connection1.StrokeThickness = 5

````

{{endregion}}

* __ForeColor__: gets or sets the color that specifies how the __RadDiagramConnection__'s text is painted.

![diagram-diagram-items-connections 027](images/diagram-diagram-items-connections027.png)

{{source=..\SamplesCS\Diagram\DiagramItems.cs region=ConnectionForeColor}}
{{source=..\SamplesVB\Diagram\DiagramItems.vb region=ConnectionForeColor}}

````C#

connection1.ForeColor = Color.Blue;

````
````VB.NET
connection1.ForeColor = Color.Blue

````

{{endregion}}

* __StrokeDashArray__: gets or sets a collection of Double values that indicate the pattern of dashes and gaps that is used to outline the __RadDiagramConnection__.

{{source=..\SamplesCS\Diagram\DiagramItems.cs region=StrokeDashArray}}
{{source=..\SamplesVB\Diagram\DiagramItems.vb region=StrokeDashArray}}

````C#
connection1.StrokeDashArray = new Telerik.WinControls.UI.Diagrams.DoubleCollection(new List<float> { 2, 2, 2, 2 });

````
````VB.NET
connection1.StrokeDashArray = New Telerik.WinControls.UI.Diagrams.DoubleCollection(New List(Of Single)() From { _
    2, _
    2, _
    2, _
    2 _
})

````

{{endregion}}

![diagram-diagram-items-connections 029](images/diagram-diagram-items-connections029.png)

## Connection Edit Mode

You can set the __RadDiagramConnection__ in edit mode by using the __IsInEditMode__ property. By default, when an item enters edit mode, the RadDiagramConnection.__Content__ is displayed inside a TextBox control so that you can change its value.
![diagram-diagram-items-connections 028](images/diagram-diagram-items-connections028.png)

>note Apart from setting the __IsInEditMode__ property to *true*, you can also enter edit mode by pressing F2 or double-clicking on the connection. For more information please refer to the [Editing]({%slug winforms/diagram/items-manipulation/editing%}) article.
>

## Connection Bridge

The connection bridge is essentially what you see when two connections collide. __RadDiagram__ allows you to define what kind of bridge to display through the RadDiagram.__ConnectionBridge__ property. It is an enumeration of type __Telerik.Windows.Diagrams.Core.BridgeType__ that exposes the following members:

* __None__ - there is no bridge to visualize the intersection of the connections

![diagram-diagram-items-connections 030](images/diagram-diagram-items-connections030.png)

* __Bow__- a half circle is displayed to indicate the intersection of the connections

![diagram-diagram-items-connections 031](images/diagram-diagram-items-connections031.png)

* __Gap__ - a gap is displayed to indicate the intersection of the connections

![diagram-diagram-items-connections 032](images/diagram-diagram-items-connections032.png)

## Connection Selection State

The following properties allow you to track and control the selection state of a connection:

* __IsSelected__ - gets or sets whether the connection is selected.

## Connection ZIndex

You can get or set the z-order rendering behavior of the RadDiagramConnection through the __ZIndex__ property.

## Connection Bounds

You can get the bounds of a __RadDiagramConnection__ through the __Bounds__ property. It is of type __Rect__ and it describes the width, height and location of the connection's bounds.

# See Also

* [ContainerShapes]({%slug winforms/diagram/diagram-items/containershapes%})
* [Shapes]({%slug winforms/diagram/diagram-items/shapes%})


text:
package com.siyeh.ig.performance;

import com.intellij.codeInspection.InspectionProfileEntry;
import com.siyeh.ig.LightJavaInspectionTestCase;
import org.jetbrains.annotations.Nullable;

public class StringConcatenationInsideStringBufferAppendInspectionTest extends LightJavaInspectionTestCase {

  public void testStringConcatenationInsideStringBufferAppend() {
    doTest();
  }

  @Nullable
  @Override
  protected InspectionProfileEntry getInspection() {
    return new StringConcatenationInsideStringBufferAppendInspection();
  }
}


text:
import {
  STATE_CANCELLED,
  STATE_ENDED,
  STATE_CHANGED,
  STATE_BEGAN
} from './recognizer-consts';

/**
* @private
* get a usable string, used as event postfix
* @param {constant} state
* @returns {String} state
*/
export default function stateStr(state) {
if (state & STATE_CANCELLED) {
  return 'cancel';
} else if (state & STATE_ENDED) {
  return 'end';
} else if (state & STATE_CHANGED) {
  return 'move';
} else if (state & STATE_BEGAN) {
  return 'start';
}
return '';
}


text:
/**
 * Manages support structures that give bonuses to stamina regen, combat strength,
 * research speed, building speed, and maybe others.
 */
export class Support
{
    constructor(tf) {
        this.tf = tf;

        // we need a registry to keep track of all completed and partial structures.
        // when using the build command it will check partial structures and resume if necessary.
        // this data will be persisted in the save file.
        // support entries can stack, but devices (not stored here) are all unique.

        // completed support entries, id -> qty.
        this.activeRegistry = {};
        this.activeCache = [];

        // incomplete support entries. id -> progress.
        this.partialRegistry = {};
        this.partialCache = [];

        this.totalStaminaRegen = 0;
        this.totalResearchBonus = 0;
        this.totalLandBonus = 0;
    }

    startConstruction(id) {
        this.partialRegistry[id] = 0;
        this.rebuildCache();
    }

    incrementProgress(id) {
        this.partialRegistry[id]++;
    }

    getProgress(id) {
        return this.partialRegistry[id];
    }

    finishConstruction(id) {
        delete this.partialRegistry[id];

        if ( !this.activeRegistry[id] ) {
            this.activeRegistry[id] = 0;
        }
        this.activeRegistry[id]++;

        this.recalcBonuses();
        this.rebuildCache();
    }

    hasIncomplete(id) {
        return this.partialRegistry.hasOwnProperty(id);
    }

    recalcBonuses() {
        this.tf.player.staminaChange -= this.totalStaminaRegen;
        this.tf.maxLand -= this.totalLandBonus;

        this.totalStaminaRegen = 0;
        this.totalResearchBonus = 0;
        this.totalLandBonus = 0;

        Object.entries(this.activeRegistry).forEach(kv => {
            let data = this.tf.items.get(kv[0]);
            if ( kv[1] >= 1 ) {
                let multiplier = 1 + this.logBase(data.logBase, kv[1]);

                this.totalStaminaRegen += data.staminaRegen * multiplier * this.tf.player.staminaMultiplier();
                this.totalResearchBonus += data.researchBonus * multiplier;
                this.totalLandBonus += data.landBonus * multiplier;
            }
        });

        this.tf.player.staminaChange += this.totalStaminaRegen;
        this.tf.maxLand += this.totalLandBonus;

        this.tf.events.checkAll(); // handles support check and land check.
    }

    rebuildCache() {
        let cache = Object.entries(this.activeRegistry).map(kv => {
            return {"name": this.tf.items.get(kv[0]).name, "qty": kv[1]};
        });
        cache.sort((a, b) => a.name.localeCompare(b.name));
        this.activeCache = cache;

        let inactive = Object.keys(this.partialRegistry).map(id => this.tf.items.get(id).name);
        inactive.sort((a, b) => a.localeCompare(b));
        this.partialCache = inactive;
    }

    logBase(base, value) {
        return Math.log(value) / Math.log(base);
    }

    tick() {
        this.tf.player.giveStamina(this.totalStaminaRegen);
    }
}


text:
#pragma once
#include <aws/codeguru-reviewer/CodeGuruReviewer_EXPORTS.h>
#include <aws/codeguru-reviewer/CodeGuruReviewerRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace CodeGuruReviewer
{
namespace Model
{

  /**
   */
  class AWS_CODEGURUREVIEWER_API ListTagsForResourceRequest : public CodeGuruReviewerRequest
  {
  public:
    ListTagsForResourceRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListTagsForResource"; }

    Aws::String SerializePayload() const override;

    /**
     *
 The Amazon Resource Name (ARN) of the
     * RepositoryAssociation  object. You can retrieve this ARN by
     * calling
     * ListRepositoryAssociations .

     */
    inline const Aws::String& GetResourceArn() const{ return m_resourceArn; }

    /**
     *
 The Amazon Resource Name (ARN) of the
     * RepositoryAssociation  object. You can retrieve this ARN by
     * calling
     * ListRepositoryAssociations .

     */
    inline bool ResourceArnHasBeenSet() const { return m_resourceArnHasBeenSet; }

    /**
     *
 The Amazon Resource Name (ARN) of the
     * RepositoryAssociation  object. You can retrieve this ARN by
     * calling
     * ListRepositoryAssociations .

     */
    inline void SetResourceArn(const Aws::String& value) { m_resourceArnHasBeenSet = true; m_resourceArn = value; }

    /**
     *
 The Amazon Resource Name (ARN) of the
     * RepositoryAssociation  object. You can retrieve this ARN by
     * calling
     * ListRepositoryAssociations .

     */
    inline void SetResourceArn(Aws::String&& value) { m_resourceArnHasBeenSet = true; m_resourceArn = std::move(value); }

    /**
     *
 The Amazon Resource Name (ARN) of the
     * RepositoryAssociation  object. You can retrieve this ARN by
     * calling
     * ListRepositoryAssociations .

     */
    inline void SetResourceArn(const char* value) { m_resourceArnHasBeenSet = true; m_resourceArn.assign(value); }

    /**
     *
 The Amazon Resource Name (ARN) of the
     * RepositoryAssociation  object. You can retrieve this ARN by
     * calling
     * ListRepositoryAssociations .

     */
    inline ListTagsForResourceRequest& WithResourceArn(const Aws::String& value) { SetResourceArn(value); return *this;}

    /**
     *
 The Amazon Resource Name (ARN) of the
     * RepositoryAssociation  object. You can retrieve this ARN by
     * calling
     * ListRepositoryAssociations .

     */
    inline ListTagsForResourceRequest& WithResourceArn(Aws::String&& value) { SetResourceArn(std::move(value)); return *this;}

    /**
     *
 The Amazon Resource Name (ARN) of the
     * RepositoryAssociation  object. You can retrieve this ARN by
     * calling
     * ListRepositoryAssociations .

     */
    inline ListTagsForResourceRequest& WithResourceArn(const char* value) { SetResourceArn(value); return *this;}

  private:

    Aws::String m_resourceArn;
    bool m_resourceArnHasBeenSet;
  };

} // namespace Model
} // namespace CodeGuruReviewer
} // namespace Aws


text:
[![Build Status](https://travis-ci.org/osrg/gobgp.svg?branch=master)](https://travis-ci.org/osrg/gobgp/builds)
[![Slack Status](https://slackin-gobgp.mybluemix.net/badge.svg)](https://slackin-gobgp.mybluemix.net/)

GoBGP is an open source BGP implementation designed from scratch for
modern environment and implemented in a modern programming language,
[the Go Programming Language](http://golang.org/).

## Getting started

Installing GoBGP is quite easy (just one command!):

```bash
$ go get github.com/osrg/gobgp/...
```

## Documentation

### Using GoBGP
 * [Getting Started](https://github.com/osrg/gobgp/blob/master/docs/sources/getting-started.md)
 * CLI
   * [Typical operation examples](https://github.com/osrg/gobgp/blob/master/docs/sources/cli-operations.md)
   * [Complete syntax](https://github.com/osrg/gobgp/blob/master/docs/sources/cli-command-syntax.md)
 * [Route Server](https://github.com/osrg/gobgp/blob/master/docs/sources/route-server.md)
 * [Route Reflector](https://github.com/osrg/gobgp/blob/master/docs/sources/route-reflector.md)
 * [Policy](https://github.com/osrg/gobgp/blob/master/docs/sources/policy.md)
 * [FIB manipulation](https://github.com/osrg/gobgp/blob/master/docs/sources/zebra.md)
 * [MRT](https://github.com/osrg/gobgp/blob/master/docs/sources/mrt.md)
 * [BMP](https://github.com/osrg/gobgp/blob/master/docs/sources/bmp.md)
 * [EVPN](https://github.com/osrg/gobgp/blob/master/docs/sources/evpn.md)
 * [Flowspec](https://github.com/osrg/gobgp/blob/master/docs/sources/flowspec.md)
 * [RPKI](https://github.com/osrg/gobgp/blob/master/docs/sources/rpki.md)
 * [Managing GoBGP with your favorite language with GRPC](https://github.com/osrg/gobgp/blob/master/docs/sources/grpc-client.md)
 * [Using GoBGP as a Go Native BGP library](https://github.com/osrg/gobgp/blob/master/docs/sources/lib.md)
 * [Graceful Restart](https://github.com/osrg/gobgp/blob/master/docs/sources/graceful-restart.md)
 * Data Center Networking
   * [Unnumbered BGP](https://github.com/osrg/gobgp/blob/master/docs/sources/unnumbered-bgp.md)

### Externals
 * [Tutorial: Using GoBGP as an IXP connecting router](http://www.slideshare.net/shusugimoto1986/tutorial-using-gobgp-as-an-ixp-connecting-router)

## Community, discussion and support

We have the [Slack](https://slackin-gobgp.mybluemix.net/) and [mailing
list](https://lists.sourceforge.net/lists/listinfo/gobgp-devel) for
questions, discussion, suggestions, etc.

You have code or documentation for GoBGP? Awesome! Send a pull
request. No CLA, board members, governance, or other mess.

## Licensing

GoBGP is licensed under the Apache License, Version 2.0. See
[LICENSE](https://github.com/osrg/gobgp/blob/master/LICENSE) for the full
license text.


text:
const cheerio = require('cheerio')

class BreakException {
	constructor(command, transcript) {
		this.command = command
		this.transcript = transcript
	}
}

function min(a, b) {
	return a  b ? a : b
}

function youtube_parser(url) {
	var ID = ''
	url = url.replace(/(>|<)/gi, '').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/)
	if (url[2] !== undefined) {
		ID = url[2].split(/[^0-9a-z_-]/i)
		ID = ID[0]
	} else {
		ID = url
	}
	return ID
}

function convertISO8601ToSring(input) {
	const dur = convertISO8601ToObject(input)
	let str = ""
	if (dur.hours > 0) {
		if (str.length > 0 && dur.hours < 10) str += "0"
		str += dur.hours + ":"
	}
	if (dur.minutes < 10) str += "0"
	str += dur.minutes + ":"

	if (dur.seconds < 10) str += "0"
	str += dur.seconds
	return str
}

function convertISO8601ToSeconds(input) {
	return convertISO8601ToObject(input).totalseconds
}

function convertISO8601ToObject(input) {
	var reptms = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/
	var hours = 0,
		minutes = 0,
		seconds = 0,
		totalseconds

	if (reptms.test(input)) {
		var matches = reptms.exec(input)
		if (matches[1]) hours = Number(matches[1])
		if (matches[2]) minutes = Number(matches[2])
		if (matches[3]) seconds = Number(matches[3])
		totalseconds = hours * 3600 + minutes * 60 + seconds
	}

	return {
		hours,
		minutes,
		seconds,
		totalseconds
	}
}

/**
 * Parts a string into substrings of max length maxLength using separator sep
 *
 * @param {string} string
 * @param {number} maxLength
 * @param {string} sep
 * @returns {array} the strings of max length maxLength
 */
function autoPartsString(string, maxLength, sep) {
	const sepLength = sep.length
	const strings = string.split(sep);
	const lengths = strings.map(e => e.length)
	const result = []
	lengths.reduce((acc, val, i, arr) => {
		if (val + acc + sepLength <= maxLength)
			arr[i] += acc + sepLength
		else {
			let str = ""
			for (let y = 0; y < i; y++)
				str += strings.shift() + sep
			result.push(str)
		}
		return arr[i]
	})
	result.push(strings.join(sep))
	return result
}

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items The array containing the items.
 */
function shuffle(a) {
	for (let i = a.length; i; i--) {
		let j = Math.floor(Math.random() * i);
		[a[i - 1], a[j]] = [a[j], a[i - 1]];
	}
}

/**
 * Translates seconds into human readable format of seconds, minutes, hours, days, and years
 * https://stackoverflow.com/questions/8211744/convert-time-interval-given-in-seconds-into-more-human-readable-form
 *
 * @param  {number} seconds The number of seconds to be processed
 * @return {string}         The phrase describing the the amount of time
 */
function humanTime(seconds) {
	var levels = [
		[Math.floor(seconds / 31536000), 'years'],
		[Math.floor((seconds % 31536000) / 86400), 'days'],
		[Math.floor(((seconds % 31536000) % 86400) / 3600), 'hours'],
		[Math.floor((((seconds % 31536000) % 86400) % 3600) / 60), 'minutes'],
		[(((seconds % 31536000) % 86400) % 3600) % 60, 'seconds'],
	];
	var returntext = '';

	for (var i = 0, max = levels.length; i < max; i++) {
		if (levels[i][0] === 0) continue;
		returntext += ' ' + levels[i][0].toFixed(0) + ' ' + (levels[i][0] === 1 ? levels[i][1].substr(0, levels[i][1].length - 1) : levels[i][1]);
	}
	return returntext.trim();
}

module.exports = {
	BreakException,
	min,
	max,
	youtube_parser,
	convertISO8601ToSeconds,
	convertISO8601ToObject,
	convertISO8601ToSring,
	autoPartsString,
	shuffle,
	humanTime
}
module.exports.link_with_title = (link, title = link) => "" + title + ""
module.exports.video_link = (id) => "https://youtu.be/" + id
module.exports.breakTag = "
"
module.exports.getLinks = function (txt) {
	let links = []
	cheerio.load(txt)('a').each((_, el) => {
		const attr = el.attribs['href']
		if (attr) links.push(attr)
	})
	return links
}


text:
class PagesController < ApplicationController

  def home
    I18n.locale = :es if params[:locale] == 'es'
  end
end


text:
local maxMessages = 5; 		-- The max messages that will show (on each bar)
local DefaultTime = 8; 		-- The max time each message will show if time isn't defined.

------------------------------------------
-- For scripters only					--
------------------------------------------
local sx_, sy_ = guiGetScreenSize ( )
local sx, sy = sx_/1920, sy_/1080 -- you got xXMADEXx's resolution :3 plz no hak mi
local DefaultPos = true;
local messages_top = { }
local messages_btm = { }

function sendClientMessage ( msg, r, g, b, pos, time )
	-- Msg: String
	-- R: Int (0-255)
	-- G: Int (0-255)
	-- B: Int (0-255)
	-- Pos: Boolean
	-- Time: Int
	if ( not msg ) then return false end

	if ( pos == nil ) then pos = DefaultPos end
	local r, g, b = r or 255, g or 255, b or 255
	local time = tonumber ( time ) or DefaultTime
	local data = {
		message = msg,
		r = r,
		g = g,
		b = b,
		alpha=0,
		locked=true,
		rTick = getTickCount ( ) + (time*1000)
	}
	--> Scripters note:
		--> The remove and intro fades are handled in the render event
	if ( pos == true or pos == "top" ) then
		table.insert ( messages_top, data )
		return true
	elseif ( pos == false or pos == "bottom" ) then
		table.insert ( messages_btm, data )
		return true
	end
	return false
end
addEvent ( getResourceName ( getThisResource ( ) )..":sendClientMessage", true )
addEventHandler ( getResourceName ( getThisResource ( ) )..":sendClientMessage", root, sendClientMessage )

function dxDrawNotificationBar ( )
	local doRemove = { top = { }, bottom = { } }	-- This is used so it prevents the next message from flashing

	-- Top Message Bar
	for i, v in pairs ( messages_top ) do
		local i = i - 1
		if ( not v.locked ) then
			v.alpha = v.alpha - 3
			if ( v.alpha <= 20 ) then
				table.insert ( doRemove.top, i+1 )
			end
			messages_top[i+1].alpha = v.alpha
		else
			if ( v.alpha < 160 ) then
				v.alpha = v.alpha + 1
				messages_top[i+1].alpha = v.alpha
			end
			if ( v.rTick <= getTickCount ( ) ) then
				v.locked = false
				messages_top[i+1].locked=false
			end
		end
		dxDrawRectangle ( (sx_/2-530/2), i*25, 530, 25, tocolor ( 0, 0, 0, v.alpha ) )
		dxDrawText ( tostring ( v.message ), 0, i*25, sx_, (i+1)*25, tocolor ( v.r, v.g, v.b, v.alpha*1.59375 ), sy*1.3, "clear", "center", "center", false, false, false, true)
	end
	if ( #messages_top > maxMessages and messages_top[1].locked ) then
		messages_top[1].locked = false
	end

	-- Bottom Message Bar
	for i, v in pairs ( messages_btm ) do
		if ( not v.locked ) then
			v.alpha = v.alpha - 3
			if ( v.alpha <= 20 ) then
				table.insert ( doRemove.bottom, i )
			end
			messages_btm[i].alpha = v.alpha
		else
			if ( v.alpha < 160 ) then
				v.alpha = v.alpha + 1
				messages_btm[i].alpha = v.alpha
			end
			if ( v.rTick <= getTickCount ( ) ) then
				v.locked = false
				messages_btm[i].locked=false
			end
		end

		local textWidth = dxGetTextWidth(tostring ( v.message ), sy*1.5, "clear", true)+10*sx
		dxDrawRectangle ( (sx_/2-textWidth/2), sy_-(i*27*sy), textWidth, 27*sy, tocolor ( 0, 0, 0, v.alpha ) )
		dxDrawText ( tostring ( v.message ), 0, sy_-(i*27*sy), sx_, sy_-((i-1)*27*sy), tocolor ( v.r, v.g, v.b, v.alpha*1.59375 ), sy*1.5, "clear", "center", "center", false, false, false, true, true)
	end
	if ( #messages_btm > maxMessages and messages_btm[1].locked ) then
		messages_btm[1].locked = false
	end

	-- handle message removes
	if ( #doRemove.top > 0 )then
		for i, v in pairs ( doRemove.top ) do
			table.remove ( messages_top, v )
		end
	end
	if ( #doRemove.bottom > 0 ) then
		for i, v in pairs ( doRemove.bottom ) do
			table.remove ( messages_btm, v )
		end
	end
end
addEventHandler ( "onClientRender", root, dxDrawNotificationBar )

------------------------------
-- For development			--
------------------------------
addCommandHandler ( 'rt', function ( )
	for i=1, 5 do
		sendClientMessage ( "Testing - Index ".. tostring ( i ), 255, 255, 255, false )
		sendClientMessage ( "Testing - Index ".. tostring ( i ), 255, 255, 255, true )
	end
end )


text:
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkLoggerOutput_h
#define itkLoggerOutput_h

#include "itkOutputWindow.h"
#include "itkLogger.h"

namespace itk
{
/** \class LoggerOutput
 * \brief Used for overriding itk::OutputWindow to redirect
 *        messages to itk::Logger.
 *
 * Text messages that the system should display to the user are sent to
 * this object (or subclasses of this object).
 *
 *
 * \author Hee-Su Kim, Compute Science Dept. Kyungpook National University,
 *                     ISIS Center, Georgetown University.
 *
 * \ingroup OSSystemObjects
 * \ingroup ITKCommon
 */
class ITKCommon_EXPORT LoggerOutput : public OutputWindow
{
public:
  /** Standard class type aliases. */
  using Self = LoggerOutput;
  using Superclass = OutputWindow;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Run-time type information (and related methods). */
  itkTypeMacro(LoggerOutput, OutputWindow);

  itkNewMacro(LoggerOutput);

  using LoggerType = Logger *;

  /** Send a string to display. */
  void
  DisplayText(const char * t) override;

  /** Send a string as an error message to display.
   * The default implementation calls DisplayText() but subclasses
   * could present this message differently. */
  void
  DisplayErrorText(const char * t) override;

  /** Send a string as a warningmessage to display.
   * The default implementation calls DisplayText() but subclasses
   * could present this message differently. */
  void
  DisplayWarningText(const char * t) override;

  /** Send a string as a message to display.
   * The default implementation calls DisplayText() but subclasses
   * could present this message differently. */
  void
  DisplayGenericOutputText(const char * t) override;

  /** Send a string as a debug message to display.
   * The default implementation calls DisplayText() but subclasses
   * could present this message differently. */
  void
  DisplayDebugText(const char * t) override;

  itkSetMacro(Logger, LoggerType);

  itkGetConstMacro(Logger, LoggerType);

  virtual void
  OverrideITKWindow()
  {
    itk::OutputWindow::SetInstance(this);
  }

protected:
  LoggerOutput() = default;
  ~LoggerOutput() override = default;
  void
  PrintSelf(std::ostream & os, Indent indent) const override;

private:
  Logger * m_Logger{ nullptr };
};
} // end namespace itk

#endif // itkLoggerOutput_h


text:
package ehttp

import (
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"testing"
)

func TestError(t *testing.T) {
	err := Error{}
	assertString(t, "<nil>", err.Error())

	err = Error{code: http.StatusTeapot, error: fmt.Errorf("fail")}
	assertString(t, "fail", err.Error())

}

func TestNewError(t *testing.T) {
	err := NewError(http.StatusTeapot, io.EOF)
	assertString(t, "EOF", err.Error())

	err = NewErrorf(http.StatusTeapot, "hello %s", "world")
	assertString(t, "hello world", err.Error())
}

func TestGetError(t *testing.T) {
	var opError error = &net.OpError{Op: "op", Err: errors.New("fail")}

	e1 := NewError(http.StatusTeapot, opError)
	e2 := e1.(*Error).GetError()

	if expect, got := fmt.Sprintf("%v (%T)", opError, opError), fmt.Sprintf("%v (%T)", e2, e2); expect != got {
		t.Fatalf("Unexpected error returned by GetError().\nExpect:\t%s\nGot:\t%s\n", expect, got)
	}

}


text:
import sys, os
import subprocess
import traceback
import urllib
import zipfile

WORKING_DIR = os.path.dirname(os.path.realpath(__file__))
annotation_tools = os.path.join(WORKING_DIR, "annotation-tools")

def find_or_download_tools():
  if not os.path.isdir(annotation_tools):
    annotation_tools_zip = annotation_tools+".zip"
    print("Downloading annotation tools to %s" % annotation_tools_zip)
    urllib.urlretrieve("http://types.cs.washington.edu/annotation-file-utilities/current/annotation-tools-3.6.27.zip", annotation_tools_zip)
    with zipfile.ZipFile(annotation_tools_zip, "r") as z:
      z.extractall(WORKING_DIR)
    subprocess.call(['chmod', '-R', '+x', annotation_tools])

def run_command(cmd):
  try:
    print (subprocess.check_output(cmd, stderr=subprocess.STDOUT))
  except:
    print ('calling {cmd} failed\n{trace}'.format(cmd=' '.join(cmd),trace=traceback.format_exc()))

def merge_jaif_into_class(class_file_name, jaif_file_name):
  script = os.path.join(annotation_tools, "annotation-file-utilities/scripts/insert-annotations")
  cmd = [script, os.path.abspath(class_file_name), os.path.abspath(jaif_file_name)]
  run_command(cmd)

def test():
  test_java = os.path.join(annotation_tools, "annotation-file-utilities/tests/MethodMultiple.java")
  test_jaif = os.path.join(annotation_tools, "annotation-file-utilities/tests/MethodMultiple.jaif")
  print ("Running test with {}".format(test_jaif))
  cmd = ["javac", "-g", test_java, "-d", WORKING_DIR]
  print ("Compiling: {}".format(" ".join(cmd)))
  run_command(cmd)
  print ("Done Compiling.")
  test_class = os.path.join(WORKING_DIR, "annotator/tests/MethodMultiple.class")
  if not os.path.isfile(test_class):
    print "Failed to compile test. Stopping."
    return
  print ("Inserting into {}".format(test_class))
  merge_jaif_into_class(test_class, test_jaif)
  print ("Done. Annotated class written to: {}".format(test_class))
  cmd = ["javap", "-v", test_class]
  run_command(cmd)

def main():
  find_or_download_tools()
  test()

if __name__ == '__main__':
  main()


text:
<?php

namespace PH7;

defined('PH7') or exit('Restricted access');

use PFBC\Element\Button;
use PFBC\Element\CCaptcha;
use PFBC\Element\Hidden;
use PFBC\Element\HTMLExternal;
use PFBC\Element\Password;
use PFBC\Element\Radio;
use PFBC\Element\Textarea;
use PFBC\Element\Token;
use PFBC\Validation\Str;
use PH7\Framework\Url\Header;

/** For "user" and "affiliate" module **/
class DeleteUserCoreForm
{
    public static function display()
    {
        if (isset($_POST['submit_delete_account'])) {
            if (\PFBC\Form::isValid($_POST['submit_delete_account'])) {
                new DeleteUserCoreFormProcess();
            }

            Header::redirect();
        }

        $oForm = new \PFBC\Form('form_delete_account');
        $oForm->configure(['action' => '']);
        $oForm->addElement(new Hidden('submit_delete_account', 'form_delete_account'));
        $oForm->addElement(new Token('delete_account'));
        $oForm->addElement(new Password(t('Your Password:'), 'password', ['required' => 1]));
        $oForm->addElement(new Textarea(t('Your Reason:'), 'message', ['id' => 'str_reason', 'onblur' => 'CValid(this.value, this.id,5,500)', 'description' => t('Please be specific why you want to leave us.') . '
' . t('It will hep us to improve our service and make it the best one for you!'), 'required' => 1, 'validation' => new Str(5, 500)]));
        $oForm->addElement(new HTMLExternal(''));
        $oForm->addElement(
            new Radio(
                t('Why:'),
                'why_delete',
                [
                    t("I'm not happy with the service."),
                    t('I met someone.'),
                    t('My email address has changed.'),
                    t('Other. I said the reason above.')
                ],
                ['required' => 1]
            )
        );
        $oForm->addElement(new CCaptcha(t('Captcha'), 'captcha', ['id' => 'ccaptcha', 'onkeyup' => 'CValid(this.value, this.id)', 'description' => t('Enter the below code:')]));
        $oForm->addElement(new HTMLExternal(''));
        $oForm->addElement(new Button);
        $oForm->addElement(new HTMLExternal(''));
        $oForm->render();
    }
}


text:
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const { execSync } = require('child_process');
const _ = require('lodash');

async function set_vcgencmd(mode) {
  const { stdout, stderr } = await exec(`/opt/vc/bin/vcgencmd display_power ${mode}`);
 // return stdout;
}

async function test_vcgencmd(type) {
  const { stdout, stderr } = await exec('echo ' + type);
  console.log('Output: ' + stdout);
}

async function putMonitorToSleep() {
  await set_vcgencmd(0)
}

async function wakeMonitor() {
  await set_vcgencmd(1)
}
module.exports = { putMonitorToSleep: putMonitorToSleep, wakeMonitor: wakeMonitor }


text:
"""
Adds the concept of trends.

See :doc:`/specs/trends`.

"""

from lino import ad

from django.utils.translation import gettext_lazy as _

class Plugin(ad.Plugin):
    "See :class:`lino.core.plugins.Plugin`."
    verbose_name = _("Trends")

    subject_model = None
    """The Django model used to represent the "subject" being observed.

    For example in :ref:`avanti` this points to a client.

    """

    def on_site_startup(self, site):
        self.subject_model = site.models.resolve(self.subject_model)
        super(Plugin, self).on_site_startup(site)

    def setup_config_menu(self, site, user_type, m):
        mg = self.get_menu_group()
        m = m.add_menu(mg.app_label, mg.verbose_name)
        m.add_action('trends.TrendAreas')
        m.add_action('trends.TrendStages')

    def setup_explorer_menu(self, site, user_type, m):
        mg = self.get_menu_group()
        m = m.add_menu(mg.app_label, mg.verbose_name)
        m.add_action('trends.AllTrendEvents')


text:
package io.fabric8.dmp.samples.buildcache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class Application {

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @RestController
    public static class HelloController {

        @RequestMapping("/")
        public String greeting() {
            return "Hello World!";
        }
    }
}


text:
import java.net.InetSocketAddress

import argonaut._, Argonaut._

import io.finch._
import io.finch.{Endpoint => _, _}

import io.finch.route._
import io.finch.route.Endpoint
import io.finch.response._

import com.twitter.finagle.Service
import com.twitter.finagle.Httpx

import com.twitter.util.Await

object WebServer extends App {

  val json: Endpoint[HttpRequest, HttpResponse] = {
    import io.finch.argonaut._
    Get / "json" /> Ok(Json("message" -> jString("Hello, World!"))).toFuture
  }

  val plaintext: Endpoint[HttpRequest, HttpResponse] =
    Get / "plaintext" /> Ok("Hello, World!").toFuture

  val api: Service[HttpRequest, HttpResponse] = plaintext | json

  Await.ready(
    Httpx.serve(
      "0.0.0.0:9000", api
    )
  )
}


text:
<?php
namespace Chamilo\Libraries\Calendar\Package;

/**
 *
 * @package Chamilo\Libraries\Calendar\Package
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 */
class Installer extends \Chamilo\Configuration\Package\Action\Installer
{
}


text:
from homeassistant.helpers.entity import Entity
from homeassistant.const import (CONF_NAME)
import logging
import time
from datetime import timedelta
from homeassistant.util import Throttle

REQUIREMENTS = [
    'https://github.com/koen01/pybuienradar/archive/v0.5.zip#pybuienradar==0.5']

MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5)
ATTR_TOTAL = 'Total'
ATTR_AVERAGE = 'Average'
ATTR_TIMEFRAME = 'Timeframe'
ATTR_UPDATED = 'Update'
CONF_TIMEFRAME = 'timeframe'

_LOGGER = logging.getLogger(__name__)

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the buienradar platform."""
    name = config.get(CONF_NAME)
    latitude = hass.config.latitude
    longitude = hass.config.longitude
    timeframe = config.get(CONF_TIMEFRAME)
    add_devices([BuienradarSensor(name, latitude, longitude, timeframe)])

class BuienradarSensor(Entity):
    """Representation of a Sensor."""
    def __init__(self, name, latitude, longitude, timeframe):
        """Initialize the sensor."""
        import pybuienradar
        self._buienradar = pybuienradar.forecast(
            latitude, longitude)
        self._timeframe = timeframe
        self._state = None
        self._name = name
        self._unit_of_measurement = 'mm/h'
        self.update()

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement."""
        return self._unit_of_measurement

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        if self.data is not None:
            return {
                ATTR_TOTAL: self.data['totalrain'] ,
                ATTR_AVERAGE: self.data['averagerain'],
                ATTR_TIMEFRAME: self.data['timeframe'],
                ATTR_UPDATED: self.data['time']
            }

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Get the latest data and updates the state."""
        now = time.strftime("%H:%M")
        self.data = self._buienradar.get_forecast(now, self._timeframe)
        self._state = self.data["averagerain"]