text:
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise

class wazirx(Exchange):

    def describe(self):
        return self.deep_extend(super(wazirx, self).describe(), {
            'id': 'wazirx',
            'name': 'WazirX',
            'countries': ['IN'],
            'version': 'v2',
            'rateLimit': 1000,
            'pro': True,
            'has': {
                'CORS': False,
                'spot': True,
                'margin': None,  # has but unimplemented
                'swap': False,
                'future': False,
                'option': False,
                'cancelAllOrders': True,
                'cancelOrder': True,
                'createOrder': True,
                'createStopLimitOrder': True,
                'createStopMarketOrder': True,
                'createStopOrder': True,
                'fetchBalance': True,
                'fetchBidsAsks': False,
                'fetchClosedOrders': False,
                'fetchCurrencies': False,
                'fetchDepositAddress': False,
                'fetchDepositAddressesByNetwork': False,
                'fetchDeposits': True,
                'fetchFundingHistory': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': False,
                'fetchMarginMode': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': False,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrders': True,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': True,
                'fetchPositionMode': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchStatus': True,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchTransactionFees': False,
                'fetchTransactions': False,
                'fetchTransfers': False,
                'fetchWithdrawals': False,
                'transfer': False,
                'withdraw': False,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/148647666-c109c20b-f8ac-472f-91c3-5f658cb90f49.jpeg',
                'api': {
                    'rest': 'https://api.wazirx.com/sapi/v1',
                },
                'www': 'https://wazirx.com',
                'doc': 'https://docs.wazirx.com/#public-rest-api-for-wazirx',
                'fees': 'https://wazirx.com/fees',
                'referral': 'https://wazirx.com/invite/k7rrnks5',
            },
            'api': {
                'public': {
                    'get': {
                        'exchangeInfo': 1,
                        'depth': 1,
                        'ping': 1,
                        'systemStatus': 1,
                        'tickers/24hr': 1,
                        'ticker/24hr': 1,
                        'time': 1,
                        'trades': 1,
                        'klines': 1,
                    },
                },
                'private': {
                    'get': {
                        'account': 1,
                        'allOrders': 1,
                        'funds': 1,
                        'historicalTrades': 1,
                        'openOrders': 1,
                        'order': 1,
                        'myTrades': 1,
                    },
                    'post': {
                        'order': 1,
                        'order/test': 1,
                    },
                    'delete': {
                        'order': 1,
                        'openOrders': 1,
                    },
                },
            },
            'fees': {
                'WRX': {'maker': self.parse_number('0.0'), 'taker': self.parse_number('0.0')},
            },
            'precisionMode': TICK_SIZE,
            'exceptions': {
                'exact': {
                    '-1121': BadSymbol,  # {"code": -1121, "message": "Invalid symbol."}
                    '1999': BadRequest,  # {"code":1999,"message":"symbol is missing, symbol does not have a valid value"} message varies depending on the error
                    '2002': InsufficientFunds,  # {"code":2002,"message":"Not enough USDT balance to execute self order"}
                    '2005': BadRequest,  # {"code":2005,"message":"Signature is incorrect."}
                    '2078': PermissionDenied,  # {"code":2078,"message":"Permission denied."}
                    '2098': BadRequest,  # {"code":2098,"message":"Request out of receiving window."}
                    '2031': InvalidOrder,  # {"code":2031,"message":"Minimum buy amount must be worth 2.0 USDT"}
                    '2113': BadRequest,  # {"code":2113,"message":"RecvWindow must be in range 1..60000"}
                    '2115': BadRequest,  # {"code":2115,"message":"Signature not found."}
                    '2136': RateLimitExceeded,  # {"code":2136,"message":"Too many api request"}
                    '94001': InvalidOrder,  # {"code":94001,"message":"Stop price not found."}
                },
            },
            'timeframes': {
                '1m': '1m',
                '5m': '5m',
                '30m': '30m',
                '1h': '1h',
                '2h': '2h',
                '4h': '4h',
                '6h': '6h',
                '12h': '12h',
                '1d': '1d',
                '1w': '1w',
            },
            'options': {
                # 'fetchTradesMethod': 'privateGetHistoricalTrades',
                'recvWindow': 10000,
            },
        })

    def fetch_markets(self, params={}):
        """
        retrieves data on all markets for wazirx
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [dict]: an array of objects representing market data
        """
        response = self.publicGetExchangeInfo(params)
        #
        # {
        #     "timezone":"UTC",
        #     "serverTime":1641336850932,
        #     "symbols":[
        #     {
        #         "symbol":"btcinr",
        #         "status":"trading",
        #         "baseAsset":"btc",
        #         "quoteAsset":"inr",
        #         "baseAssetPrecision":5,
        #         "quoteAssetPrecision":0,
        #         "orderTypes":[
        #             "limit",
        #             "stop_limit"
        #         ],
        #         "isSpotTradingAllowed":true,
        #         "filters":[
        #             {
        #                 "filterType":"PRICE_FILTER",
        #                 "minPrice":"1",
        #                 "tickSize":"1"
        #             }
        #         ]
        #     },
        #
        markets = self.safe_value(response, 'symbols', [])
        result = []
        for i in range(0, len(markets)):
            market = markets[i]
            id = self.safe_string(market, 'symbol')
            baseId = self.safe_string(market, 'baseAsset')
            quoteId = self.safe_string(market, 'quoteAsset')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            isSpot = self.safe_value(market, 'isSpotTradingAllowed')
            filters = self.safe_value(market, 'filters')
            minPrice = None
            for j in range(0, len(filters)):
                filter = filters[j]
                filterType = self.safe_string(filter, 'filterType')
                if filterType == 'PRICE_FILTER':
                    minPrice = self.safe_number(filter, 'minPrice')
            fee = self.safe_value(self.fees, quote, {})
            takerString = self.safe_string(fee, 'taker', '0.2')
            takerString = Precise.string_div(takerString, '100')
            makerString = self.safe_string(fee, 'maker', '0.2')
            makerString = Precise.string_div(makerString, '100')
            status = self.safe_string(market, 'status')
            result.append({
                'id': id,
                'symbol': base + '/' + quote,
                'base': base,
                'quote': quote,
                'settle': None,
                'baseId': baseId,
                'quoteId': quoteId,
                'settleId': None,
                'type': 'spot',
                'spot': isSpot,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'active': (status == 'trading'),
                'contract': False,
                'linear': None,
                'inverse': None,
                'taker': self.parse_number(takerString),
                'maker': self.parse_number(makerString),
                'contractSize': None,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'precision': {
                    'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'baseAssetPrecision'))),
                    'price': self.parse_number(self.parse_precision(self.safe_string(market, 'quoteAssetPrecision'))),
                },
                'limits': {
                    'leverage': {
                        'min': None,
                        'max': None,
                    },
                    'price': {
                        'min': minPrice,
                        'max': None,
                    },
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'cost': {
                        'min': None,
                        'max': None,
                    },
                },
                'info': market,
            })
        return result

    def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents. Available values [1m,5m,15m,30m,1h,2h,4h,6h,12h,1d,1w]
        :param int|None since: timestamp in ms of the earliest candle to fetch
        :param int|None limit: the maximum amount of candles to fetch
        :param dict params: extra parameters specific to the wazirx api endpoint
        :param int|None params['until']: timestamp in s of the latest candle to fetch
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'interval': self.timeframes[timeframe],
        }
        if limit is not None:
            request['limit'] = limit
        until = self.safe_integer(params, 'until')
        params = self.omit(params, ['until'])
        if since is not None:
            request['startTime'] = int(since / 1000)
        if until is not None:
            request['endTime'] = until
        response = self.publicGetKlines(self.extend(request, params))
        #
        #    [
        #        [1669014360,1402001,1402001,1402001,1402001,0],
        #        ...
        #    ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    def parse_ohlcv(self, ohlcv, market=None):
        #
        #    [1669014300,1402001,1402001,1402001,1402001,0],
        #
        return [
            self.safe_timestamp(ohlcv, 0),
            self.safe_number(ohlcv, 1),
            self.safe_number(ohlcv, 2),
            self.safe_number(ohlcv, 3),
            self.safe_number(ohlcv, 4),
            self.safe_number(ohlcv, 5),
        ]

    def fetch_order_book(self, symbol, limit=None, params={}):
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int|None limit: the maximum amount of order book entries to return
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit  # [1, 5, 10, 20, 50, 100, 500, 1000]
        response = self.publicGetDepth(self.extend(request, params))
        #
        #     {
        #          "timestamp":1559561187,
        #          "asks":[
        #                     ["8540.0","1.5"],
        #                     ["8541.0","0.0042"]
        #                 ],
        #          "bids":[
        #                     ["8530.0","0.8814"],
        #                     ["8524.0","1.4"]
        #                 ]
        #      }
        #
        timestamp = self.safe_integer(response, 'timestamp')
        return self.parse_order_book(response, symbol, timestamp)

    def fetch_ticker(self, symbol, params={}):
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        ticker = self.publicGetTicker24hr(self.extend(request, params))
        #
        # {
        #     "symbol":"wrxinr",
        #     "baseAsset":"wrx",
        #     "quoteAsset":"inr",
        #     "openPrice":"94.77",
        #     "lowPrice":"92.7",
        #     "highPrice":"95.17",
        #     "lastPrice":"94.03",
        #     "volume":"1118700.0",
        #     "bidPrice":"94.02",
        #     "askPrice":"94.03",
        #     "at":1641382455000
        # }
        #
        return self.parse_ticker(ticker, market)

    def fetch_tickers(self, symbols=None, params={}):
        """
        fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
        :param [str]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        tickers = self.publicGetTickers24hr()
        #
        # [
        #     {
        #        "symbol":"btcinr",
        #        "baseAsset":"btc",
        #        "quoteAsset":"inr",
        #        "openPrice":"3698486",
        #        "lowPrice":"3641155.0",
        #        "highPrice":"3767999.0",
        #        "lastPrice":"3713212.0",
        #        "volume":"254.11582",
        #        "bidPrice":"3715021.0",
        #        "askPrice":"3715022.0",
        #     }
        #     ...
        # ]
        #
        result = {}
        for i in range(0, len(tickers)):
            ticker = tickers[i]
            parsedTicker = self.parse_ticker(ticker)
            symbol = parsedTicker['symbol']
            result[symbol] = parsedTicker
        return result

    def fetch_trades(self, symbol, since=None, limit=None, params={}):
        """
        get the list of most recent trades for a particular symbol
        :param str symbol: unified symbol of the market to fetch trades for
        :param int|None since: timestamp in ms of the earliest trade to fetch
        :param int|None limit: the maximum amount of trades to fetch
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit  # Default 500; max 1000.
        method = self.safe_string(self.options, 'fetchTradesMethod', 'publicGetTrades')
        response = getattr(self, method)(self.extend(request, params))
        # [
        #     {
        #         "id":322307791,
        #         "price":"93.7",
        #         "qty":"0.7",
        #         "quoteQty":"65.59",
        #         "time":1641386701000,
        #         "isBuyerMaker":false
        #     },
        # ]
        return self.parse_trades(response, market, since, limit)

    def parse_trade(self, trade, market=None):
        #
        #     {
        #         "id":322307791,
        #         "price":"93.7",
        #         "qty":"0.7",
        #         "quoteQty":"65.59",
        #         "time":1641386701000,
        #         "isBuyerMaker":false
        #     }
        #
        id = self.safe_string(trade, 'id')
        timestamp = self.safe_integer(trade, 'time')
        datetime = self.iso8601(timestamp)
        market = self.safe_market(None, market)
        isBuyerMaker = self.safe_value(trade, 'isBuyerMaker')
        side = 'sell' if isBuyerMaker else 'buy'
        price = self.safe_number(trade, 'price')
        amount = self.safe_number(trade, 'qty')
        cost = self.safe_number(trade, 'quoteQty')
        return self.safe_trade({
            'info': trade,
            'id': id,
            'timestamp': timestamp,
            'datetime': datetime,
            'symbol': market['symbol'],
            'order': id,
            'type': None,
            'side': side,
            'takerOrMaker': None,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': None,
        }, market)

    def fetch_status(self, params={}):
        """
        the latest known information on the availability of the exchange API
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/en/latest/manual.html#exchange-status-structure>`
        """
        response = self.publicGetSystemStatus(params)
        #
        #     {
        #         "status":"normal",  # normal, system maintenance
        #         "message":"System is running normally."
        #     }
        #
        status = self.safe_string(response, 'status')
        return {
            'status': 'ok' if (status == 'normal') else 'maintenance',
            'updated': None,
            'eta': None,
            'url': None,
            'info': response,
        }

    def fetch_time(self, params={}):
        """
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = self.publicGetTime(params)
        #
        #     {
        #         "serverTime":1635467280514
        #     }
        #
        return self.safe_integer(response, 'serverTime')

    def parse_ticker(self, ticker, market=None):
        #
        #     {
        #        "symbol":"btcinr",
        #        "baseAsset":"btc",
        #        "quoteAsset":"inr",
        #        "openPrice":"3698486",
        #        "lowPrice":"3641155.0",
        #        "highPrice":"3767999.0",
        #        "lastPrice":"3713212.0",
        #        "volume":"254.11582",  # base volume
        #        "bidPrice":"3715021.0",
        #        "askPrice":"3715022.0",
        #        "at":1641382455000  # only on fetchTicker
        #     }
        #
        marketId = self.safe_string(ticker, 'symbol')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        last = self.safe_string(ticker, 'lastPrice')
        open = self.safe_string(ticker, 'openPrice')
        high = self.safe_string(ticker, 'highPrice')
        low = self.safe_string(ticker, 'lowPrice')
        baseVolume = self.safe_string(ticker, 'volume')
        bid = self.safe_string(ticker, 'bidPrice')
        ask = self.safe_string(ticker, 'askPrice')
        timestamp = self.safe_integer(ticker, 'at')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': high,
            'low': low,
            'bid': bid,
            'bidVolume': None,
            'ask': ask,
            'askVolume': None,
            'vwap': None,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': None,
            'info': ticker,
        }, market)

    def parse_balance(self, response):
        result = {}
        for i in range(0, len(response)):
            balance = response[i]
            id = self.safe_string(balance, 'asset')
            code = self.safe_currency_code(id)
            account = self.account()
            account['free'] = self.safe_string(balance, 'free')
            account['used'] = self.safe_string(balance, 'locked')
            result[code] = account
        return self.safe_balance(result)

    def fetch_balance(self, params={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        self.load_markets()
        response = self.privateGetFunds(params)
        #
        # [
        #       {
        #          "asset":"inr",
        #          "free":"0.0",
        #          "locked":"0.0"
        #       },
        # ]
        #
        return self.parse_balance(response)

    def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetches information on multiple orders made by the user
        :param str symbol: unified market symbol of the market orders were made in
        :param int|None since: the earliest time in ms to fetch orders for
        :param int|None limit: the maximum number of  orde structures to retrieve
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' fetchOrders() requires a `symbol` argument')
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['limit'] = limit
        response = self.privateGetAllOrders(self.extend(request, params))
        #
        #   [
        #       {
        #           "id": 28,
        #           "symbol": "wrxinr",
        #           "price": "9293.0",
        #           "origQty": "10.0",
        #           "executedQty": "8.2",
        #           "status": "cancel",
        #           "type": "limit",
        #           "side": "sell",
        #           "createdTime": 1499827319559,
        #           "updatedTime": 1499827319559
        #       },
        #       {
        #           "id": 30,
        #           "symbol": "wrxinr",
        #           "price": "9293.0",
        #           "stopPrice": "9200.0",
        #           "origQty": "10.0",
        #           "executedQty": "0.0",
        #           "status": "cancel",
        #           "type": "stop_limit",
        #           "side": "sell",
        #           "createdTime": 1499827319559,
        #           "updatedTime": 1507725176595
        #       }
        #   ]
        #
        orders = self.parse_orders(response, market, since, limit)
        orders = self.filter_by(orders, 'symbol', symbol)
        return orders

    def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all unfilled currently open orders
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch open orders for
        :param int|None limit: the maximum number of  open orders structures to retrieve
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        request = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        response = self.privateGetOpenOrders(self.extend(request, params))
        # [
        #     {
        #         "id": 28,
        #         "symbol": "wrxinr",
        #         "price": "9293.0",
        #         "origQty": "10.0",
        #         "executedQty": "8.2",
        #         "status": "cancel",
        #         "type": "limit",
        #         "side": "sell",
        #         "createdTime": 1499827319559,
        #         "updatedTime": 1499827319559
        #     },
        #     {
        #         "id": 30,
        #         "symbol": "wrxinr",
        #         "price": "9293.0",
        #         "stopPrice": "9200.0",
        #         "origQty": "10.0",
        #         "executedQty": "0.0",
        #         "status": "cancel",
        #         "type": "stop_limit",
        #         "side": "sell",
        #         "createdTime": 1499827319559,
        #         "updatedTime": 1507725176595
        #     }
        # ]
        orders = self.parse_orders(response, market, since, limit)
        return orders

    def cancel_all_orders(self, symbol=None, params={}):
        """
        cancel all open orders in a market
        :param str symbol: unified market symbol of the market to cancel orders in
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelAllOrders() requires a `symbol` argument')
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        return self.privateDeleteOpenOrders(self.extend(request, params))

    def cancel_order(self, id, symbol=None, params={}):
        """
        cancels an open order
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        if symbol is None:
            raise ArgumentsRequired(self.id + ' cancelOrder() requires a `symbol` argument')
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'orderId': id,
        }
        response = self.privateDeleteOrder(self.extend(request, params))
        return self.parse_order(response)

    def create_order(self, symbol, type, side, amount, price=None, params={}):
        """
        create a trade order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float|None price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict params: extra parameters specific to the wazirx api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        type = type.lower()
        if (type != 'limit') and (type != 'stop_limit'):
            raise ExchangeError(self.id + ' createOrder() supports limit and stop_limit orders only')
        if price is None:
            raise ExchangeError(self.id + ' createOrder() requires a price argument')
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'side': side,
            'quantity': amount,
            'type': 'limit',
        }
        request['price'] = self.price_to_precision(symbol, price)
        stopPrice = self.safe_string(params, 'stopPrice')
        if stopPrice is not None:
            request['type'] = 'stop_limit'
        response = self.privatePostOrder(self.extend(request, params))
        # {
        #     "id": 28,
        #     "symbol": "wrxinr",
        #     "price": "9293.0",
        #     "origQty": "10.0",
        #     "executedQty": "8.2",
        #     "status": "wait",
        #     "type": "limit",
        #     "side": "sell",
        #     "createdTime": 1499827319559,
        #     "updatedTime": 1499827319559
        # }
        return self.parse_order(response, market)

    def parse_order(self, order, market=None):
        # {
        #     "id":1949417813,
        #     "symbol":"ltcusdt",
        #     "type":"limit",
        #     "side":"sell",
        #     "status":"done",
        #     "price":"146.2",
        #     "origQty":"0.05",
        #     "executedQty":"0.05",
        #     "createdTime":1641252564000,
        #     "updatedTime":1641252564000
        # },
        created = self.safe_integer(order, 'createdTime')
        updated = self.safe_integer(order, 'updatedTime')
        marketId = self.safe_string(order, 'symbol')
        symbol = self.safe_symbol(marketId, market)
        amount = self.safe_string(order, 'quantity')
        filled = self.safe_string(order, 'executedQty')
        status = self.parse_order_status(self.safe_string(order, 'status'))
        id = self.safe_string(order, 'id')
        price = self.safe_string(order, 'price')
        type = self.safe_string_lower(order, 'type')
        side = self.safe_string_lower(order, 'side')
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': None,
            'timestamp': created,
            'datetime': self.iso8601(created),
            'lastTradeTimestamp': updated,
            'status': status,
            'symbol': symbol,
            'type': type,
            'timeInForce': None,
            'postOnly': None,
            'side': side,
            'price': price,
            'amount': amount,
            'filled': filled,
            'remaining': None,
            'cost': None,
            'fee': None,
            'average': None,
            'trades': [],
        }, market)

    def parse_order_status(self, status):
        statuses = {
            'wait': 'open',
            'done': 'closed',
            'cancel': 'canceled',
        }
        return self.safe_string(statuses, status, status)

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api']['rest'] + '/' + path
        if api == 'public':
            if params:
                url += '?' + self.urlencode(params)
        if api == 'private':
            self.check_required_credentials()
            timestamp = self.milliseconds()
            data = self.extend({'recvWindow': self.options['recvWindow'], 'timestamp': timestamp}, params)
            data = self.keysort(data)
            signature = self.hmac(self.encode(self.urlencode(data)), self.encode(self.secret), hashlib.sha256)
            url += '?' + self.urlencode(data)
            url += '&signature=' + signature
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Api-Key': self.apiKey,
            }
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        #
        # {"code":2098,"message":"Request out of receiving window."}
        #
        if response is None:
            return
        errorCode = self.safe_string(response, 'code')
        if errorCode is not None:
            feedback = self.id + ' ' + body
            self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
            raise ExchangeError(feedback)


text:
<?php
$language["DELETE_READED"]="Usuń przeczytane";
$language["USER_LANGUE"]="Język";
$language["USER_STYLE"]="Styl";
$language["CURRENTLY_PEER"]="Aktualnie seedujesz bądź ściągasz jakieś torrenty.";
$language["STOP_PEER"]="Musisz zatrzymać swojego klienta.";
$language["USER_PWD_AGAIN"]="Powtórz hasło";
$language["EMAIL_FAILED"]="Wysłanie emaila zakończone niepowodzeniem!";
$language["NO_SUBJECT"]="Brak Tematu";
$language["MUST_ENTER_PASSWORD"]="
Musisz wpisać hasło aby zmienić powyższe ustawienia.";
$language["ERR_PASS_WRONG"]="Hasło puste lub nieprawidłowe, nie można uaktualnić profilu.";
$language["MSG_DEL_ALL_PM"]="Jeżeli wybierzesz PM-y, których nie czytałeś nie zostaną one usunięte";
$language["ERR_PM_GUEST"]="Przepraszamy nie możesz wysyłać PM do konta gościa lub samego siebie!";
?>

redpajama_set_name: RedPajamaGithub


text:
if (OS_IOS) {
    Alloy.Globals.navgroup = $.nav;
    $.nav.open();
    // menu = Alloy.createController('Menu').getView();
    // $.nav.add(menu);
} else if (OS_ANDROID) {
    $.index.getView().open();

} else {
    alert(L('unsupportedPlatform', 'Unsupported Platform'));
}

var animateRight = Ti.UI.createAnimation({
    left : "80%",
    curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,
    duration : 150
});

var animateReset = Ti.UI.createAnimation({
    left : 0,
    curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,
    duration : 150
});

var animateLeft = Ti.UI.createAnimation({
    left : -250,
    curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,
    duration : 150
});
var openmenu=false;
Ti.App.addEventListener('menuhit', function(e){
    if(openmenu == true){
        $.nav.animate(animateReset);
        openmenu = false;
    } else {
        $.nav.animate(animateRight);
        openmenu = true;
    }

});


text:
package org.waveprotocol.wave.model.document;

import junit.framework.TestCase;

import org.waveprotocol.wave.model.document.indexed.RawAnnotationSet;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.StringSet;

import java.util.NoSuchElementException;

/**
 * Abstract test for implementations of {@link AnnotationCursor}
 *
 * @author danilatos@google.com (Daniel Danilatos)
 */
public abstract class AnnotationCursorTestBase extends TestCase {

  protected abstract RawAnnotationSet<Object> getNewSet();

  public void testNoChange() {
    RawAnnotationSet<Object> m = getNewSet();

    m.begin();
    m.insert(100);
    m.finish();

    expectFinished(m.annotationCursor(40, 60, strs()));
    expectFinished(m.annotationCursor(40, 60, strs("a", "b")));
    expectFinished(m.annotationCursor(0, 100, strs()));
    expectFinished(m.annotationCursor(0, 100, strs("a", "b")));

    m.begin();
    m.skip(10);
    m.startAnnotation("a", "1");
    m.skip(80);
    m.endAnnotation("a");
    m.finish();

    expectFinished(m.annotationCursor(40, 60, strs()));
    expectFinished(m.annotationCursor(40, 60, strs("a")));
    expectFinished(m.annotationCursor(40, 60, strs("a", "b")));

    m.begin();
    m.skip(20);
    m.startAnnotation("b", "2");
    m.skip(60);
    m.endAnnotation("b");
    m.finish();

    expectFinished(m.annotationCursor(40, 60, strs()));
    expectFinished(m.annotationCursor(40, 60, strs("a")));
    expectFinished(m.annotationCursor(40, 60, strs("a", "b")));
    expectFinished(m.annotationCursor(40, 60, strs("a", "b", "c")));

    m.begin();
    m.skip(25);
    m.startAnnotation("a", "3");
    m.skip(70);
    m.endAnnotation("a");
    m.finish();

    expectFinished(m.annotationCursor(40, 60, strs()));
    expectFinished(m.annotationCursor(40, 60, strs("a")));
    expectFinished(m.annotationCursor(40, 60, strs("a", "b")));
    expectFinished(m.annotationCursor(40, 60, strs("a", "b", "c")));
  }

  public void testChange() {
    RawAnnotationSet<Object> m = fancySet();

    for (int i = 0; i <= 1; i++) {
      AnnotationCursor c1 = m.annotationCursor(i, 100 - i, strs("a"));
      AnnotationCursor c2 = m.annotationCursor(i, 100 - i, strs("a", "b"));
      AnnotationCursor c3 = m.annotationCursor(i, 100 - i, strs("a", "b", "c"));
      AnnotationCursor c4 = m.annotationCursor(i, 100 - i, strs("c", "d"));
      AnnotationCursor ca = m.annotationCursor(i, 100 - i, strs("a", "b", "c", "d"));
      AnnotationCursor cx = m.annotationCursor(i, 100 - i, strs("x", "y", "z"));

      expectFinished(cx);

      checkAdvance(c1, 10, "a");
      checkAdvance(c1, 30, "a");
      checkAdvance(c1, 60, "a");
      expectFinished(c1);

      checkAdvance(c2, 10, "a");
      checkAdvance(c2, 20, "b");
      checkAdvance(c2, 30, "a");
      checkAdvance(c2, 40, "b");
      checkAdvance(c2, 50, "b");
      checkAdvance(c2, 60, "a");
      expectFinished(c2);

      checkAdvance(c3, 10, "a");
      checkAdvance(c3, 20, "b");
      checkAdvance(c3, 30, "a", "c");
      checkAdvance(c3, 40, "b", "c");
      checkAdvance(c3, 50, "b");
      checkAdvance(c3, 60, "a");
      expectFinished(c3);

      checkAdvance(c4, 30, "c", "d");
      checkAdvance(c4, 40, "c", "d");
      expectFinished(c4);

      checkAdvance(ca, 10, "a");
      checkAdvance(ca, 20, "b");
      checkAdvance(ca, 30, "a", "c", "d");
      checkAdvance(ca, 40, "b", "c", "d");
      checkAdvance(ca, 50, "b");
      checkAdvance(ca, 60, "a");
      expectFinished(ca);
    }

    AnnotationCursor c5 = m.annotationCursor(30, 40, strs("c", "d"));
    expectFinished(c5);

    c5 = m.annotationCursor(29, 40, strs("c", "d"));
    checkAdvance(c5, 30, "c", "d");
    expectFinished(c5);

    c5 = m.annotationCursor(30, 41, strs("c", "d"));
    checkAdvance(c5, 40, "c", "d");
    expectFinished(c5);
  }

  public void testInitialStartLocation() {

    RawAnnotationSet<Object> m = getNewSet();

    m.begin();
    m.insert(100);
    m.finish();

    // -1 if no hasNext()
    AnnotationCursor c = m.annotationCursor(40, 80, strs("a"));
    assertEquals(-1, c.currentLocation());

    m.begin();
    m.skip(50);
    m.startAnnotation("a", "1");
    m.skip(10);
    m.endAnnotation("a");
    m.finish();

    // start value, if hasNext();
    c = m.annotationCursor(40, 80, strs("a"));
    assertEquals(40, c.currentLocation());

  }

  protected RawAnnotationSet<Object> fancySet() {
    RawAnnotationSet<Object> m = getNewSet();

    m.begin();
    m.insert(100);
    m.finish();

    m.begin();
    m.skip(10);
    m.startAnnotation("a", "1");
    m.skip(10);
    m.startAnnotation("b", "2");
    m.skip(10);
    m.startAnnotation("c", "3");
    m.startAnnotation("a", "3");
    m.startAnnotation("d", "3");
    m.skip(10);
    m.endAnnotation("c");
    m.endAnnotation("d");
    m.startAnnotation("b", "4");
    m.skip(10);
    m.endAnnotation("b");
    m.skip(10);
    m.endAnnotation("a");
    m.finish();

    return m;
  }

  protected void checkAdvance(AnnotationCursor cursor, int location, String ... keys) {
    assertTrue(cursor.hasNext());
    assertEquals(
        CollectionUtils.newJavaSet(strs(keys)),
        CollectionUtils.newJavaSet(cursor.nextLocation()));
    assertEquals(location, cursor.currentLocation());
  }

  protected void expectFinished(AnnotationCursor cursor) {
    assertFalse(cursor.hasNext());
    try {
      cursor.nextLocation();
      fail("Expected NoSuchElementException");
    } catch (NoSuchElementException e) {
      // OK
    }
  }

  protected StringSet strs(String ... strings) {
    return CollectionUtils.newStringSet(strings);
  }

  public void testEmptySet() {
    RawAnnotationSet<Object> m = getNewSet();

    m.begin();
    m.insert(1);
    m.startAnnotation("a", "1");
    m.insert(1);
    m.endAnnotation("a");
    m.finish();

    expectFinished(m.annotationCursor(0, m.size(), strs()));
  }
}


text:
module Fastbill
  module Automatic
    class Base
      include Fastbill::Automatic::Services::Get
      include Fastbill::Automatic::Services::Create

      def initialize(attributes = {})
        set_attributes(attributes)
      end

      def set_attributes(attributes)
        attributes.each_pair do |key, value|
          instance_variable_set("@#{key.downcase}", value)
        end
      end
    end
  end
end


text:
;(function(){
  angular.module('angular-toc', []);
})();

//toc.directive.js
;(function(){
  angular.module('angular-toc').directive('toc', directiveFactory);
  function directiveFactory(){
    return {
      scope: {
        startHeadingElement: '@',
        fromHeadingLevel: '@',
        toHeadingLevel: '@',
        onFilter: '&'
      },
      link: function(scope, el, attr, vm){
        vm.init(scope, el, attr);
      },
      controller: controller
    }
    controller.$inject = ['$compile'];
    function controller($compile){
      this.init = function(scope, el, attr){
        var headingArray = TOC.createHeadingArray(
          document.querySelector(scope.startHeadingElement),
          scope.fromHeadingLevel,
          scope.toHeadingLevel
        )
        headingArray = headingArray.filter(function(heading){
          var ret = scope.onFilter({heading: heading});
          return ret == undefined || ret;
        });
        if(headingArray){
          TOC.addRelationShip(headingArray);
          var toc = TOC.toTocUi(headingArray);
          el.append(toc);
        }
      }
    }
  }
})();


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title> Map Generator </title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="styles/main.css">

        Number of rooms :
        <input id="nbRooms" type="range" min="2" max="20">
        <button  type="button" class="btn btn-default" onclick=reload()>Reload</button>

        export JSON data:
        <textarea class="form-control" rows="5" id="export" readonly></textarea>

        jsonFile:
        <textarea class="form-control" rows="5" id="import" placeholder="Paste your json file here"></textarea>

      <button type="submit" class="btn btn-default" onclick=submitFile()>Submit</button>


text:
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
    'Datetime\Module'                        => __DIR__ . '/Module.php',
    'Datetime\Controller\IndexController' => __DIR__ . '/src/Datetime/Controller/IndexController.php',
    'DatetimeTest\Framework\TestCase'        => __DIR__ . '/tests/Datetime/Framework/TestCase.php',
    'DatetimeTest\SampleTest'                => __DIR__ . '/tests/Datetime/SampleTest.php',
);


text:
'use strict';

/**
 * @ngdoc function
 * @name sopheAuthorApp.controller:ValueSetPropertiesController
 * @description
 * # ValueSetPropertiesController
 * Controller of the sopheAuthorApp
 */
angular.module('sopheAuthorApp')
  .controller('ValueSetPropertiesController', ['$scope', '$uibModalInstance', 'ValueSetService', 'valueSet', function ($scope, $uibModalInstance, ValueSetService, valueSet) {
    $scope.valueSet = valueSet;
    $scope.terms = [];
    ValueSetService.handleLoadDetails(valueSet, function(result) {
      $scope.terms = result.terms;
    });

    $scope.ok = function () {
      $uibModalInstance.close();
    };

    $scope.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };
  }]);


text:
import io
import unittest
from unittest.mock import patch
from kattis import k_pebblesolitaire

###############################################################################

class SampleInput(unittest.TestCase):
    '''Problem statement sample inputs and outputs'''

    def test_sample_input(self):
        '''Run and assert problem statement sample input and output.'''
        inputs = []
        inputs.append('5')
        inputs.append('---oo-------')
        inputs.append('-o--o-oo----')
        inputs.append('-o----ooo---')
        inputs.append('oooooooooooo')
        inputs.append('oooooooooo-o')
        inputs = '\n'.join(inputs) + '\n'

        outputs = []
        outputs.append('1')
        outputs.append('2')
        outputs.append('3')
        outputs.append('12')
        outputs.append('1')
        outputs = '\n'.join(outputs) + '\n'

        with patch('sys.stdin', io.StringIO(inputs)) as stdin,\
             patch('sys.stdout', new_callable=io.StringIO) as stdout:
            k_pebblesolitaire.main()
            self.assertEqual(stdout.getvalue(), outputs)
            self.assertEqual(stdin.read(), '')

###############################################################################

if __name__ == '__main__':
    unittest.main()


text:
package org.apereo.cas.services.web;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.core.Ordered;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import javax.annotation.Nonnull;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * {@link ThemeBasedViewResolver} is a View Resolver that takes the active theme into account to selectively choose
 * which set of UI views will be used to generate the standard views.
 *
 * @author Daniel Frett
 * @since 5.2.0
 */
@Slf4j
@Setter
@Getter
@RequiredArgsConstructor
public class ThemeBasedViewResolver implements ViewResolver, Ordered {

    private final ThemeResolver themeResolver;

    private final ThemeViewResolverFactory viewResolverFactory;

    private final Map<String, ViewResolver> resolvers = new ConcurrentHashMap<>();

    private int order = LOWEST_PRECEDENCE;

    @Override
    public View resolveViewName(
        @Nonnull
        final String viewName, @Nonnull
        final Locale locale) {
        try {
            val theme = Optional.of(RequestContextHolder.currentRequestAttributes())
                .filter(ServletRequestAttributes.class::isInstance)
                .map(ServletRequestAttributes.class::cast)
                .map(ServletRequestAttributes::getRequest)
                .map(themeResolver::resolveThemeName);
            val delegate = theme.map(this::getViewResolver);
            if (delegate.isPresent()) {
                return delegate.get().resolveViewName(viewName, locale);
            }
        } catch (final Exception e) {
            LOGGER.debug("error resolving view [{}] for theme", viewName, e);
        }
        return null;
    }

    /**
     * Get (or create) the view resolver for the theme.
     *
     * @param theme the theme
     * @return the view resolver
     */
    protected ViewResolver getViewResolver(final String theme) {
        if (resolvers.containsKey(theme)) {
            return resolvers.get(theme);
        }
        val resolver = viewResolverFactory.create(theme);
        resolvers.put(theme, resolver);
        return resolver;
    }
}


text:
A module of classes useful for defining object models that are serialized
and deserialized via JSON.

One specific use case would be when using a REST client. In python,
dicts and lists are easy to use, and the stock json library is quite good
and creating and using them. However, if you want to define actual object
Models, possibly with some logic in them, it becomes cumbersome having to
insert each property on deserialization and extracting only set properties
on serialization.

These classes attempt to solve this problem.

```
Sample Usage:

class Model1(jsonmodels.JsonModel):
    # These are simple types (like strings and ints) that JSON can already handle ok.
    Field1 = jsonmodels.JsonProperty('Field1')  # You can use the same name
    Field2 = jsonmodels.JsonProperty('field_2') # Or a different name

class Model2(jsonmodels.JsonModel):
    # If you need a nested Model:
    Nested = jsonmodels.JsonModelProperty('Nested', Model1)

    # Or even a list of nested Models..
    ListOfNested = jsonmodels.JsonModelListProperty('Nested2', Model1)

some_json_thingy = .... # A dict object returned from something like json.loads(...)

# Assuming the dict in some_json_thingy represents a Model2, you can...
model = Model2.from_json_entity(some_json_thing)

# Only the properties it recognizes will be populated and unkonwn values will be ignored.

print model.Nested.Field1 # Assuming it was there, this will print the Field1 of the Nested model.

# Go ahead and use the setter properties
model.ListOfNested = [Model2(), Model2(Nested=Model1())]

# And you can send it off via JSON again!

json.dumps(model.to_json_entity()) # A string fit for whatever
```


text:
using Generic.DataAccess;
using RyanLiu.CodingTask.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace RyanLiu.CodingTask.Web.Utilities
{
    public static class SelectListItemsUtility
    {
        public static async Task<IEnumerable<SelectListItem>> GetOptimizationGoals()
        {
            var _dataRepository = DataRepositoryTool.GetDataRepository();

            var optimizationGoalListItems = await _dataRepository.GetListProjectedAsync<optimization_goal, SelectListItem>(
                g =>  new SelectListItem()
                                            {
                                                Text = g.optimization_goal1,
                                                Value = g.optimization_goal_id.ToString()
                                            }
                );

            return optimizationGoalListItems;

        }
    }
}


text:
from __future__ import unicode_literals
from ..base import MRTrix3Base

def test_MRTrix3Base_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    terminal_output=dict(deprecated='1.0.0',
    nohash=True,
    ),
    )
    inputs = MRTrix3Base.input_spec()

    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(inputs.traits()[key], metakey) == value


text:
package model.utilities.pid;

import static org.junit.Assert.*;import org.junit.Test;

/**
 *
Description

 *
 this just makes sure I always remember which direction MV changes when residual is positive!
 *

 *

 *
Notes

 * Created with IntelliJ
 *

 *

 *
References

 *
 * @author carrknight
 * @version 2013-02-02
 * @see
 */
public class PIDTestSimple {

    @Test
    public void direction()
    {
        PIDController controller = new PIDController(1,1,0);
        controller.setOffset(100, true);

        //if the residual is positive, the mv should go up
        assertEquals(controller.getCurrentMV(),100f,.0001f);
        controller.adjustOnce(50,true);
        assertTrue(controller.getCurrentMV() > 100f);

        controller.setOffset(100, true);

        //if the residual is negative, the mv should go down
        assertEquals(controller.getCurrentMV(),100f,.0001f);
        controller.adjustOnce(-50,true);
        assertTrue(controller.getCurrentMV() < 100f);

    }

}


text:
using System;
using UnityEngine;

namespace Vuforia
{
    /// <summary>
    /// This class serves both as an augmentation definition for a Marker in the editor
    /// as well as a tracked marker result at runtime
    /// This class is deprecated. The same functionality
    /// is provided by using a rectangular VuMark.
    /// </summary>
    [Obsolete("This class is deprecated. The same functionality is provided by using a rectangular VuMark.")]
    public class MarkerBehaviour : MarkerAbstractBehaviour
    {

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Moyasar.Abstraction;
using Moyasar.Exceptions;
using Moyasar.Helpers;
using Newtonsoft.Json;

namespace Moyasar.Models
{
    /// <summary>
    /// Model that contains credit card information needed to create a new payment
    /// </summary>
    [DataContract]
    public class CreditCardSource : IPaymentSource
    {
        [JsonProperty("type")]
        public string Type { get; } = "creditcard";

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("number")]
        public string Number { get; set; }

        [JsonProperty("cvc")]
        public int Cvc { get; set; }

        [JsonProperty("month")]
        public int Month { get; set; }

        [JsonProperty("year")]
        public int Year { get; set; }

        // By default TRUE according to documentation
        [JsonProperty("3ds", NullValueHandling = NullValueHandling.Ignore)]
        public bool _3Ds { get; set; } = true;

        [JsonProperty("manual", NullValueHandling = NullValueHandling.Ignore)]
        public bool Manual { get; set; } = false;

        public void Validate()
        {
            var errors = new List<FieldError>();

            if (String.IsNullOrEmpty(Name)) errors.Add(new FieldError()
            {
                Field = nameof(Name),
                Error = "Credit card holder name is required"
            });

            if(CreditCardHelper.GetCreditCardType(Number) == null) errors.Add(new FieldError()
            {
                Field = nameof(Number),
                Error = $"The number {Number} is not a valid credit card number"
            });

            if(!(Cvc >= 1 && Cvc <= 999)) errors.Add(new FieldError()
            {
                Field = nameof(Month),
                Error = "Cvc must be a three digit number"
            });

            if(!(Month >= 1 && Month <= 12)) errors.Add(new FieldError()
            {
                Field = nameof(Month),
                Error = "Month must be an integer between 1 and 12"
            });

            if(Year < 1) errors.Add(new FieldError()
            {
                Field = nameof(Month),
                Error = "Year must be a positive integer greater than or equals to 1"
            });

            if (errors.Any())
            {
                throw new ValidationException("Credit card information is incorrect")
                {
                    FieldErrors = errors
                };
            }
        }
    }
}


text:
package com.thed.zephyr.cloud.rest.client;

import com.atlassian.connect.play.java.AC;
import com.atlassian.connect.play.java.AcHost;
import com.atlassian.connect.play.java.http.HttpMethod;
import com.atlassian.fugue.Option;
import com.atlassian.jwt.SigningAlgorithm;
import com.atlassian.jwt.core.TimeUtil;
import com.atlassian.jwt.core.writer.JsonSmartJwtJsonBuilder;
import com.atlassian.jwt.core.writer.JwtClaimsBuilder;
import com.atlassian.jwt.exception.JwtIssuerLacksSharedSecretException;
import com.atlassian.jwt.exception.JwtSigningException;
import com.atlassian.jwt.exception.JwtUnknownIssuerException;
import com.atlassian.jwt.httpclient.CanonicalHttpUriRequest;
import com.atlassian.jwt.writer.JwtJsonBuilder;
import com.atlassian.jwt.writer.JwtWriter;
import com.atlassian.jwt.writer.JwtWriterFactory;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeaderValueParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.util.CharArrayBuffer;

//@GeneratedAccessor
//@RewrittenAccessor
public class JwtAuthorizationGenerator {
    private static final char[] QUERY_DELIMITERS = new char[]{'&'};
    private static final int JWT_EXPIRY_WINDOW_SECONDS_DEFAULT = 180;
    private final int jwtExpiryWindowSeconds;
    private final JwtWriterFactory jwtWriterFactory;

    public JwtAuthorizationGenerator(JwtWriterFactory jwtWriterFactory) {
        this(jwtWriterFactory, JWT_EXPIRY_WINDOW_SECONDS_DEFAULT);
    }

    public JwtAuthorizationGenerator(JwtWriterFactory jwtWriterFactory, int jwtExpiryWindowSeconds) {
        this.jwtWriterFactory = Preconditions.checkNotNull(jwtWriterFactory);
        this.jwtExpiryWindowSeconds = jwtExpiryWindowSeconds;
    }

    public Option<String> generate(String httpMethodStr, String url, Map<String, List<String>> parameters, AcHost acHost, Option<String> accountId) throws JwtIssuerLacksSharedSecretException, JwtUnknownIssuerException, URISyntaxException {
        HttpMethod method = HttpMethod.valueOf(httpMethodStr);
        URI uri = new URI(url);
        String path = uri.getPath();
        URI baseUrl = new URI(acHost.getBaseUrl());
        String productContext = baseUrl.getPath();
        String pathWithoutProductContext = path.substring(productContext.length());
    //    Utils.LOGGER.trace("Creating Jwt signature for:");
    //    Utils.LOGGER.trace(String.format("httpMethod: \'%s\'", new Object[]{httpMethodStr}));
     //   Utils.LOGGER.trace(String.format("URL: \'%s\'", new Object[]{url}));
    //    Utils.LOGGER.trace(String.format("acHost key: \'%s\'", new Object[]{acHost.getKey()}));
    //    Utils.LOGGER.trace(String.format("accountId: \'%s\'", new Object[]{accountId}));
    //    Utils.LOGGER.trace(String.format("Parameters: %s", new Object[]{parameters}));
    //    Utils.LOGGER.trace(String.format("pathWithoutProductContext: \'%s\'", new Object[]{pathWithoutProductContext}));
        URI uriWithoutProductContext = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), pathWithoutProductContext, uri.getQuery(), uri.getFragment());
    //    Utils.LOGGER.trace(String.format("uriWithoutProductContext: \'%s\'", new Object[]{uriWithoutProductContext}));
        return this.generate(method, uriWithoutProductContext, parameters, acHost, accountId);
    }

    public Option<String> generate(HttpMethod httpMethod, URI url, Map<String, List<String>> parameters, AcHost acHost, Option<String> accountId) throws JwtIssuerLacksSharedSecretException, JwtUnknownIssuerException {
        Preconditions.checkArgument(null != parameters, "Parameters Map argument cannot be null");
        Preconditions.checkNotNull(acHost);
        Map paramsAsArrays = Maps.transformValues(parameters, new Function<List<String>, String[]>() {
            @Override
            public String[] apply(List<String> input) {
                return (String[]) ((List) Preconditions.checkNotNull(input)).toArray(new String[input.size()]);
            }
        });

        return Option.some("JWT " + this.encodeJwt(httpMethod, url, paramsAsArrays, (String)accountId.getOrNull(), acHost));
    }

    private String encodeJwt(HttpMethod httpMethod, URI targetPath, Map<String, String[]> params, String accountId, AcHost acHost) throws JwtUnknownIssuerException, JwtIssuerLacksSharedSecretException {
        Preconditions.checkArgument(null != httpMethod, "HttpMethod argument cannot be null");
        Preconditions.checkArgument(null != targetPath, "URI argument cannot be null");
        JwtJsonBuilder jsonBuilder = (new JsonSmartJwtJsonBuilder()).issuedAt(TimeUtil.currentTimeSeconds()).expirationTime(TimeUtil.currentTimePlusNSeconds((long)this.jwtExpiryWindowSeconds)).issuer(AC.PLUGIN_KEY).audience(acHost.getKey());
        if(null != accountId) {
            jsonBuilder = jsonBuilder.subject(accountId);
        }

        Object completeParams = params;

        try {
            if(!StringUtils.isEmpty(targetPath.getQuery())) {
                completeParams = new HashMap(params);
                ((Map)completeParams).putAll(constructParameterMap(targetPath));
            }

            CanonicalHttpUriRequest e = new CanonicalHttpUriRequest(httpMethod.toString(), targetPath.getPath(), "", (Map)completeParams);
        //    Utils.LOGGER.debug("Canonical request is: " + CanonicalRequestUtil.toVerboseString(e));
            JwtClaimsBuilder.appendHttpRequestClaims(jsonBuilder, e);
        } catch (UnsupportedEncodingException var9) {
            throw new RuntimeException(var9);
        } catch (NoSuchAlgorithmException var10) {
            throw new RuntimeException(var10);
        }

        return this.issueJwt(jsonBuilder.build(), acHost);
    }

    private String issueJwt(String jsonPayload, AcHost acHost) throws JwtSigningException, JwtIssuerLacksSharedSecretException, JwtUnknownIssuerException {
        return this.getJwtWriter(acHost).jsonToJwt(jsonPayload);
    }

    private JwtWriter getJwtWriter(AcHost acHost) throws JwtUnknownIssuerException, JwtIssuerLacksSharedSecretException {
        return this.jwtWriterFactory.macSigningWriter(SigningAlgorithm.HS256, acHost.getSharedSecret());
    }

    private static Map<String, String[]> constructParameterMap(URI uri) throws UnsupportedEncodingException {
        String query = uri.getQuery();
        if(query == null) {
            return Collections.emptyMap();
        } else {
            HashMap queryParams = new HashMap();
            CharArrayBuffer buffer = new CharArrayBuffer(query.length());
            buffer.append(query);
            ParserCursor cursor = new ParserCursor(0, buffer.length());

            while(!cursor.atEnd()) {
                NameValuePair nameValuePair = BasicHeaderValueParser.DEFAULT.parseNameValuePair(buffer, cursor, QUERY_DELIMITERS);
                if(!StringUtils.isEmpty(nameValuePair.getName())) {
                    String decodedName = urlDecode(nameValuePair.getName());
                    String decodedValue = urlDecode(nameValuePair.getValue());
                    String[] oldValues = (String[])queryParams.get(decodedName);
                    String[] newValues = null == oldValues?new String[1]:(String[]) Arrays.copyOf(oldValues, oldValues.length + 1);
                    newValues[newValues.length - 1] = decodedValue;
                    queryParams.put(decodedName, newValues);
                }
            }

            return queryParams;
        }
    }

    private static String urlDecode(String content) throws UnsupportedEncodingException {
        return null == content?null: URLDecoder.decode(content, "UTF-8");
    }
}


text:
"use strict";

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

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var util = require("../util");
var AudioNode = require("./AudioNode");
var ChannelMergerNodeDSP = require("./dsp/ChannelMergerNode");

var ChannelMergerNode = function (_AudioNode) {
  _inherits(ChannelMergerNode, _AudioNode);

  /**
   * @param {AudioContext} context
   * @param {object}       opts
   * @param {number}       opts.numberOfInputs
   */

  function ChannelMergerNode(context, opts) {
    _classCallCheck(this, ChannelMergerNode);

    opts = opts || /* istanbul ignore next */{};

    var numberOfInputs = util.defaults(opts.numberOfInputs, 6);

    numberOfInputs = util.toValidNumberOfChannels(numberOfInputs);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(ChannelMergerNode).call(this, context, {
      inputs: new Array(numberOfInputs).fill(1),
      outputs: [numberOfInputs],
      channelCount: 1,
      channelCountMode: "explicit"
    }));
  }

  _createClass(ChannelMergerNode, [{
    key: "getChannelCount",
    value: function getChannelCount() {
      return 1;
    }
  }, {
    key: "setChannelCount",
    value: function setChannelCount() {
      // This node's channelCount cannot be changed.
    }
  }, {
    key: "getChannelCountMode",
    value: function getChannelCountMode() {
      return "explicit";
    }
  }, {
    key: "setChannelCountMode",
    value: function setChannelCountMode() {
      // This node's channelCountMode cannot be changed.
    }
  }, {
    key: "getChannelInterpretation",
    value: function getChannelInterpretation() {
      return this.inputs[0].getChannelInterpretation();
    }

    /**
     * @param {string} value
     */

  }, {
    key: "setChannelInterpretation",
    value: function setChannelInterpretation(value) {
      this.inputs.forEach(function (input) {
        input.setChannelInterpretation(value);
      });
    }
  }, {
    key: "disableOutputsIfNecessary",
    value: function disableOutputsIfNecessary() {
      // disable if all inputs are disabled

      /* istanbul ignore else */
      if (this.isEnabled()) {
        var inputs = this.inputs;

        for (var i = 0, imax = inputs.length; i < imax; i++) {
          if (inputs[i].isEnabled()) {
            return;
          }
        }

        _get(Object.getPrototypeOf(ChannelMergerNode.prototype), "disableOutputsIfNecessary", this).call(this);
      }
    }
  }]);

  return ChannelMergerNode;
}(AudioNode);

Object.assign(ChannelMergerNode.prototype, ChannelMergerNodeDSP);

module.exports = ChannelMergerNode;


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

BOOL LaunchWinPostProcess(const WCHAR *installationDir,
                          const WCHAR *updateInfoDir,
                          bool forceSync,
                          HANDLE userToken);
BOOL StartServiceUpdate(LPCWSTR installDir);
BOOL GetUpdateDirectoryPath(LPWSTR path);
DWORD LaunchServiceSoftwareUpdateCommand(int argc, LPCWSTR *argv);
BOOL WriteStatusFailure(LPCWSTR updateDirPath, int errorCode);
BOOL WriteStatusPending(LPCWSTR updateDirPath);
DWORD WaitForServiceStop(LPCWSTR serviceName, DWORD maxWaitSeconds);
DWORD WaitForProcessExit(LPCWSTR filename, DWORD maxSeconds);
BOOL DoesFallbackKeyExist();
BOOL IsLocalFile(LPCWSTR file, BOOL &isLocal);
DWORD StartServiceCommand(int argc, LPCWSTR* argv);
BOOL IsUnpromptedElevation(BOOL &isUnpromptedElevation);

#define SVC_NAME L"MozillaMaintenance"

#define BASE_SERVICE_REG_KEY \
  L"SOFTWARE\\Mozilla\\MaintenanceService"

// The test only fallback key, as its name implies, is only present on machines
// that will use automated tests.  Since automated tests always run from a
// different directory for each test, the presence of this key bypasses the
// "This is a valid installation directory" check.  This key also stores
// the allowed name and issuer for cert checks so that the cert check
// code can still be run unchanged.
#define TEST_ONLY_FALLBACK_KEY_PATH \
  BASE_SERVICE_REG_KEY L"\\3932ecacee736d366d6436db0f55bce4"


text:
[![pod version](https://img.shields.io/cocoapods/v/GuillotineMenu.svg)](https://img.shields.io/cocoapods/v/GuillotineMenu.svg)
[![Platform](https://img.shields.io/cocoapods/p/GuillotineMenu.svg?style=flat)](https://github.com/Yalantis/GuillotineMenu)
[![Yalantis](https://github.com/Yalantis/GuillotineMenu/blob/master/badge_dark.png)](https://yalantis.com/?utm_source=github)

![Preview](https://github.com/Yalantis/GuillotineMenu/blob/master/example.gif)

Inspired by [this project on Dribbble](https://dribbble.com/shots/2018249-Side-Topbar-Animation)

Also, read how it was done in our [blog](https://yalantis.com/blog/how-we-created-guillotine-menu-animation/)

## Requirements

- iOS 8.0+
- Xcode 10
- Swift 5.0 (v 4.1+)
- Swift 4.2 (v 4.0)

## Installation

#### [CocoaPods](http://cocoapods.org)

```ruby
pod 'GuillotineMenu'
```

#### Manual Installation

You are welcome to see the sample of the project for fully operating sample in the Example folder.

* You must add "GuillotineMenuTransitionAnimation.swift" to your project, that's all.

### Usage

* Now, it's for you to decide, should or not your menu drop from top left corner of the screen or from your navigation bar, because if you want animation like in example, you must make your menu view controller confirm to "GuillotineMenu" protocol. When you confirm to this protocol, you must make a menu button and title, you don't need to make frame for them, because animator will make it itself.
* In view controller, that will present your menu, you must make a property for "GuillotineMenuTransitionAnimator". It's necessary for proper animation when you show or dismiss menu.
* When you present menu, you must ensure, that model presentation style set to Custom and menu's transition delegate set to view controller, that presents menu:

```swift
let menuViewController = storyboard!.instantiateViewController(withIdentifier: "MenuViewController")
menuViewController.modalPresentationStyle = .custom
menuViewController.transitioningDelegate = self
```

* Implement UIViewControllerTransitionDelegate methods in your presenting view controller:

```swift
extension ViewController: UIViewControllerTransitioningDelegate {

func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
	presentationAnimator.mode = .presentation
	return presentationAnimator
}

func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
	presentationAnimator.mode = .dismissal
	return presentationAnimator
}
```

* At last, you can assign offset view, from where your menu will be dropped and button for it, and present your menu:

```swift
presentationAnimator.supportView = navigationController!.navigationBar
presentationAnimator.presentButton = sender
present(menuViewController, animated: true, completion: nil)
```

### Customisation

Of course, you can assign different "supportView" or "presentButton" for menu, but we think that's the best case would be behaviour like in Example project.

To specify the length of an animation effect, change the value of the "duration" property.

Also, you have wonderful delegate methods of animator:

```swift
public protocol GuillotineAnimationDelegate: class {

    func animatorDidFinishPresentation(_ animator: GuillotineTransitionAnimation)
    func animatorDidFinishDismissal(_ animator: GuillotineTransitionAnimation)
    func animatorWillStartPresentation(_ animator: GuillotineTransitionAnimation)
    func animatorWillStartDismissal(_ animator: GuillotineTransitionAnimation)
}
```
You can do whatever you want alongside menu is animating.

### Let us know!

We'd be really happy if you sent us links to your projects where you use our component. Just send an email to github@yalantis.com And do let us know if you have any questions or suggestion regarding the animation.

P.S. We're going to publish more awesomeness wrapped in code and a tutorial on how to make UI for iOS (Android) better than better. Stay tuned!

### License

	The MIT License (MIT)

	Copyright © 2017 Yalantis

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.


text:
<?php

namespace PhpSpec\CodeAnalysis;

use PhpSpec\Loader\Transformer\TypeHintIndex;

final class TokenizedTypeHintRewriter implements TypeHintRewriter
{
    const STATE_DEFAULT = 0;
    const STATE_READING_CLASS = 1;
    const STATE_READING_FUNCTION = 2;
    const STATE_READING_ARGUMENTS = 3;

    private $state = self::STATE_DEFAULT;

    private $currentClass;
    private $currentFunction;

    private $typehintTokens = array(
        T_WHITESPACE, T_STRING, T_NS_SEPARATOR
    );

    /**
     * @var TypeHintIndex
     */
    private $typeHintIndex;
    /**
     * @var NamespaceResolver
     */
    private $namespaceResolver;

    /**
     * @param TypeHintIndex $typeHintIndex
     * @param NamespaceResolver $namespaceResolver
     */
    public function __construct(TypeHintIndex $typeHintIndex, NamespaceResolver $namespaceResolver)
    {
        $this->typeHintIndex = $typeHintIndex;
        $this->namespaceResolver = $namespaceResolver;
    }

    /**
     * @param string $classDefinition
     *
     * @return string
     */
    public function rewrite($classDefinition)
    {
        $this->namespaceResolver->analyse($classDefinition);

        $this->reset();
        $tokens = $this->stripTypeHints(token_get_all($classDefinition));
        $tokensToString = $this->tokensToString($tokens);

        return $tokensToString;
    }

    private function reset()
    {
        $this->state = self::STATE_DEFAULT;
        $this->currentClass = '';
        $this->currentFunction = '';
    }
    /**
     * @param array $tokens
     * @return array $tokens
     */
    private function stripTypeHints($tokens)
    {
        foreach ($tokens as $index => $token) {

            switch ($this->state) {
                case self::STATE_READING_ARGUMENTS:
                    if (')' == $token) {
                        $this->state = self::STATE_READING_CLASS;
                        $this->currentFunction = '';
                    }
                    elseif ($this->tokenHasType($token, T_VARIABLE)) {
                        $this->extractTypehints($tokens, $index, $token);
                    }
                    break;
                case self::STATE_READING_FUNCTION:
                    if ('(' == $token) {
                        $this->state = self::STATE_READING_ARGUMENTS;
                    }
                    elseif ($this->tokenHasType($token, T_STRING) && !$this->currentFunction) {
                        $this->currentFunction = $token[1];
                    }
                    break;
                case self::STATE_READING_CLASS:
                    if ($this->tokenHasType($token, T_STRING) && !$this->currentClass) {
                        $this->currentClass = $token[1];
                    }
                    elseif($this->tokenHasType($token, T_FUNCTION)) {
                        $this->state = self::STATE_READING_FUNCTION;
                    }
                    break;
                default:
                    if ($this->tokenHasType($token, T_CLASS)) {
                        $this->state = self::STATE_READING_CLASS;
                    }
            }
        }

        return $tokens;
    }

    /**
     * @param array $tokens
     * @return string
     */
    private function tokensToString($tokens)
    {
        return join('', array_map(function ($token) {
            return is_array($token) ? $token[1] : $token;
        }, $tokens));
    }

    /**
     * @param array $tokens
     * @param integer $index
     * @param array $token
     */
    private function extractTypehints(&$tokens, $index, $token)
    {
        $typehint = '';
        for ($i = $index - 1; in_array($tokens[$i][0], $this->typehintTokens); $i--) {
            $typehint = $tokens[$i][1] . $typehint;
            unset($tokens[$i]);
        }

        if ($typehint = trim($typehint)) {
            $class = $this->namespaceResolver->resolve($this->currentClass);
            try {
                $typehintFcqn = $this->namespaceResolver->resolve($typehint);
                $this->typeHintIndex->add(
                    $class,
                    trim($this->currentFunction),
                    $token[1],
                    $typehintFcqn
                );
            } catch (DisallowedScalarTypehintException $e) {
                $this->typeHintIndex->addInvalid(
                    $class,
                    trim($this->currentFunction),
                    $token[1],
                    $e
                );
            }
        }
    }

    /**
     * @param array|string $token
     * @param string $type
     *
     * @return bool
     */
    private function tokenHasType($token, $type)
    {
        return is_array($token) && $type == $token[0];
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>NcmSplineGsl: NumCosmo Reference Manual</title>
<meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" />
<link rel="home" href="index.html" title="NumCosmo Reference Manual" />
<link rel="up" href="ch02s05.html" title="Splines 1D" />
<link rel="prev" href="NcmSpline.html" title="NcmSpline" />
<link rel="next" href="NcmSplineCubic.html" title="NcmSplineCubic" />
<meta name="generator" content="GTK-Doc V1.33.1 (XML mode)" />
<link rel="stylesheet" href="style.css" type="text/css" />
<link rel="stylesheet" href="container.css" type="text/css" />

Top  |
                  Description  |
                  Object Hierarchy  |
                  Properties

NcmSplineGsl

NcmSplineGsl — GSL spline object wrapper.

Stability Level

<acronym title="The intention of a Stable interface is to enable arbitrary third parties to
develop applications to these interfaces, release them, and have confidence that
they will run on all minor releases of the product (after the one in which the
interface was introduced, and within the same major release). Even at a major
release, incompatible changes are expected to be rare, and to have strong
justifications.
">Stable</acronym>, unless otherwise indicated

Functions

<colgroup>
<col width="150px" class="functions_proto_type" />
<col class="functions_proto_name" />
</colgroup>

NcmSpline *

ncm_spline_gsl_new ()

NcmSpline *

ncm_spline_gsl_new_full ()

NcmSpline *

ncm_spline_gsl_new_by_id ()

NcmSpline *

ncm_spline_gsl_new_full_by_id ()

void

ncm_spline_gsl_set_type ()

void

ncm_spline_gsl_set_type_by_id ()

void

ncm_spline_gsl_set_type_by_name ()

Properties

<colgroup>
<col width="150px" class="properties_type" />
<col width="300px" class="properties_name" />
<col width="200px" class="properties_flags" />
</colgroup>

char *
type-name
Read / Write / Construct

Types and Values

<colgroup>
<col width="150px" class="other_proto_type" />
<col class="other_proto_name" />
</colgroup>

enum
NcmSplineGslType

Object Hierarchy

    GEnum
    ╰── NcmSplineGslType
    GObject
    ╰── NcmSpline
        ╰── NcmSplineGsl

Includes

#include <numcosmo/math/ncm_spline_gsl.h>

Description

This object comprises the proper functions to use the GNU Scientific
Library (GSL) spline functions and interpolation methods.

Functions

ncm_spline_gsl_new ()

NcmSpline *
ncm_spline_gsl_new (const gsl_interp_type *type);

This function returns a new gsl NcmSpline which will use type

interpolation method.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

type

gsl interpolation method

Returns

 a new NcmSpline.

ncm_spline_gsl_new_full ()

NcmSpline *
ncm_spline_gsl_new_full (const gsl_interp_type *type,
                         NcmVector *xv,
                         NcmVector *yv,
                         gboolean init);

This function returns a new gsl NcmSpline setting all its members.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

type

gsl interpolation method

xv

NcmVector of knots

yv

NcmVector of the values of the function, to be interpolated, computed at xv

init

TRUE to prepare the new NcmSpline or FALSE to not prepare it

Returns

 a new NcmSpline.

ncm_spline_gsl_new_by_id ()

NcmSpline *
ncm_spline_gsl_new_by_id (NcmSplineGslType type_id);

This function returns a new gsl NcmSpline which will use type

interpolation method.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

type_id

gsl interpolation method id

Returns

 a new NcmSpline.

ncm_spline_gsl_new_full_by_id ()

NcmSpline *
ncm_spline_gsl_new_full_by_id (NcmSplineGslType type_id,
                               NcmVector *xv,
                               NcmVector *yv,
                               gboolean init);

This function returns a new gsl NcmSpline setting all its members.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

type_id

gsl interpolation method id

xv

NcmVector of knots

yv

NcmVector of the values of the function, to be interpolated, computed at xv

init

TRUE to prepare the new NcmSpline or FALSE to not prepare it

Returns

 a new NcmSpline.

ncm_spline_gsl_set_type ()

void
ncm_spline_gsl_set_type (NcmSplineGsl *sg,
                         const gsl_interp_type *type);

This function sets the interpolation method type
 to sg
.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

sg

a NcmSplineGsl

type

gsl interpolation method

ncm_spline_gsl_set_type_by_id ()

void
ncm_spline_gsl_set_type_by_id (NcmSplineGsl *sg,
                               NcmSplineGslType type_id);

This function sets the interpolation method type_id
 to sg
.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

sg

a NcmSplineGsl

type_id

gsl interpolation method id

ncm_spline_gsl_set_type_by_name ()

void
ncm_spline_gsl_set_type_by_name (NcmSplineGsl *sg,
                                 const gchar *type_name);

This function sets the interpolation method type_name
 to sg
.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

sg

a NcmSplineGsl

type_name

gsl interpolation method name

Types and Values

enum NcmSplineGslType

Enumeration to choose which GSL interpolation method as backend to be used by the object. It can be used with the function ncm_spline_gsl_new_by_id() when a new NcmSplineGsl is created.

Members

<colgroup>
<col width="300px" class="enum_members_name" />
<col class="enum_members_description" />
<col width="200px" class="enum_members_annotations" />
</colgroup>

NCM_SPLINE_GSL_LINEAR

Uses gsl_interp_linear interpolation method.

NCM_SPLINE_GSL_POLYNOMIAL

Uses gsl_interp_polynomial interpolation method.

NCM_SPLINE_GSL_CSPLINE

Uses gsl_interp_cspline interpolation method.

NCM_SPLINE_GSL_CSPLINE_PERIODIC

Uses gsl_interp_cspline_periodic interpolation method.

NCM_SPLINE_GSL_AKIMA

Uses gsl_interp_akima interpolation method.

NCM_SPLINE_GSL_AKIMA_PERIODIC

Uses gsl_interp_akima_periodic interpolation method.

Property Details

The "type-name" property

  "type-name"                char *

The name of the interpolation method from GNU Scientific Library (GSL).

Owner: NcmSplineGsl

Flags: Read / Write / Construct

Default value: "NCM_SPLINE_GSL_CSPLINE"

Generated by GTK-Doc V1.33.1


text:
package com.bobwilsonsgarage.staffing

import akka.actor.ActorSystem
import akka.cluster.singleton.{ClusterSingletonManagerSettings, ClusterSingletonProxy, ClusterSingletonProxySettings}
import com.bobwilsonsgarage.staffing.StaffingServiceEndpointOverseerProtocol.CreateStaffingServiceEndpoint
import com.typesafe.config.ConfigFactory
import common.util.Logging

/**
 * Staffing Service Hosting Akka Cluster Node.

 * @author dbolene
 */
object StaffingServiceNode extends Logging {
  def main(args: Array[String]): Unit = {
    // Override the configuration of the port when specified as program argument
    val config = ConfigFactory.parseString("akka.cluster.roles = [staffingservice]").
      withFallback(ConfigFactory.load())

    val system = ActorSystem("ClusterSystem", config)

    val registry = system.actorOf(ClusterSingletonProxy.props(
      singletonManagerPath = "/user/registry",
      settings = ClusterSingletonProxySettings(system)),
      name = "registryProxy")

    val staffingServiceEndpointOverseer = system.actorOf(StaffingServiceEndpointOverseer.props())

    staffingServiceEndpointOverseer ! CreateStaffingServiceEndpoint(registry = registry)
  }
}


text:
describe Tag do
  context 'taggings' do
    subject(:tag) { Tag.create!(value: 'test') }

    context 'without taggings' do
      it 'has no taggings' do
        expect(subject.taggings_size).to eq(0)
      end

      it 'is not in use' do
        expect(subject).to_not be_in_use
      end
    end

    context 'with taggings' do
      before { Tagging.create!(tag: tag, taggable_type: 'test', taggable_id: 1) }

      it 'return count of taggings that use the tag' do
        expect(subject.taggings_size).to eq(1)
      end

      it 'is in use' do
        expect(subject).to be_in_use
      end
    end
  end
end


text:
@extends('layouts.material_user')
@section('pageTitle') GOODS RECEIPT NOTE  Purchase Order Number : {{ $purchase_order->purchase_order_number }} @stop

@section('content')

      GOODS RECEIPT NOTE  Purchase Order Number : {{ $purchase_order->purchase_order_number }}

          Department : {{ $purchase_order->department['name'] }} Detpt. Code :  {{ $purchase_order->department['department_code'] }}

 Vendor : {{ $purchase_order->material_vendor['name']}}

        {{ $purchase_order->material_vendor['vendor_address']}}

        {{ $purchase_order->material_vendor['vendor_phone']}}

         Purchase Order Number : {{ $purchase_order->purchase_order_number }}

         Purchase Order Date : {{ date('d-m-Y', strtotime($purchase_order->purchase_order_date)) }}

            {!! Form::open(array('route' => ['material_user.receipt_section.offline.grn.save', Crypt::encrypt($purchase_order->id)], 'id' => 'material_user.receipt_section.save_grn', 'class' => 'form-horizontal row-border')) !!}

                    #
                    Item Name
                    Item Code
                    Unit of Measurement
                    Qty Ordered
                    Qty Received
                    Qty Balance

                  @foreach($purchase_order_items as $k => $v)
                  <?php
                    $receives =$v->offline_purchase_order_item_receive;
                    $receive = 0;
                    foreach($receives as $rk => $rv) {
                      //dump($rv);
                      $receive += $rv->receive_quantity;
                    }
                  ?>

                    {{ $k+1}}
                    {{$v->item['item_name']}}
                    {{$v->item['item_code']}}
                    {{$v->item->measurement_unit['name']}}

                    {!! Form::number('quantity_required', $v->required_quantity, ['class' => 'form-control required', 'id' => 'quantity_required_'.$k, 'readonly' => true, 'required' => 'true']) !!}

                    {!! Form::number('quantity_received[]', $receive, ['class' => 'form-control required', 'id' => 'quantity_received_'.$k, 'autocomplete' => 'off', 'readonly' => true, 'required' => 'true', 'onkeyup' => 'calculateBalance('.$k.')']) !!}

                    {!! Form::number('quantity_balance', $v->required_quantity-$receive, ['class' => 'form-control required', 'id' => 'quantity_balance_'.$k, 'readonly' => true, 'required' => 'true']) !!}

                  <input type="hidden" name="po_item_ids[]" value="{{ $v->id }}">
                  @endforeach

has('grn_number') ? 'has-error' : ''}}">
                  {!! Form::label('grn_number', 'GRN/Control Number', array('class' => 'col-md-3 control-label')) !!}

                    {!! Form::text('grn_number', null, ['class' => 'form-control required', 'id' => 'grn_number', 'placeholder' => 'GRN/Control Number', 'autocomplete' => 'off', 'required' => 'true']) !!}

                  {!! $errors->first('grn_number', ':message') !!}

has('grn_date') ? 'has-error' : ''}}">
                  {!! Form::label('date', '', array('class' => 'col-md-3 control-label')) !!}

                    {!! Form::text('grn_date', date('d-m-Y'), ['class' => 'zebra form-control required', 'id' => 'grn_date', 'placeholder' => 'Date', 'autocomplete' => 'off', 'required' => 'true']) !!}

                  {!! $errors->first('grn_date', ':message') !!}

has('cn_number') ? 'has-error' : ''}}">
                  {!! Form::label('cn_number', 'R.R/C.N. No', array('class' => 'col-md-3 control-label')) !!}

                    {!! Form::text('cn_number', null, ['class' => 'form-control required', 'id' => 'cn_number', 'placeholder' => 'R.R/C.N. No', 'autocomplete' => 'off']) !!}

                  {!! $errors->first('cn_number', ':message') !!}

has('invoice_number') ? 'has-error' : ''}}">
                  {!! Form::label('invoice_number', 'Challan/Invoice Number', array('class' => 'col-md-3 control-label')) !!}

                    {!! Form::text('invoice_number', $challan_numbers, ['class' => 'form-control required', 'id' => 'invoice_number', 'autocomplete' => 'off', 'required' => 'true']) !!}

                  {!! $errors->first('invoice_number', ':message') !!}

has('invoice_date') ? 'has-error' : ''}}">
                  {!! Form::label('invoice_date', 'Date', array('class' => 'col-md-3 control-label')) !!}

                    {!! Form::text('invoice_date', $challan_date, ['class' => 'zebra form-control required', 'id' => 'invoice_date','autocomplete' => 'off', 'required' => 'true']) !!}

                  {!! $errors->first('invoice_date', ':message') !!}

                  1. a]

                    <input name="indigenous" type="checkbox" value="1">Indigenous

                  b]

                    <input type="checkbox" name="imported" value="1">Imported

has('remarks') ? 'has-error' : ''}}">
                  {!! Form::label('remarks', 'Remarks', array('class' => 'col-md-2 control-label')) !!}

                    {!! Form::textarea('remarks', null, ['class' => 'form-control required', 'id' => 'remarks', 'placeholder' => 'Remarks', 'cols' => 12, 'rows' => 4, 'autocomplete' => 'off']) !!}

                  {!! $errors->first('remarks', ':message') !!}

                <button class="btn btn-primary pull-right" type="submit">Submit and Forward</button>

            {!! Form::close() !!}

@stop

@section('page_js')

@stop


text:
""" Build all the projects of the given pml file """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function

import qipkg.parsers
import qibuild.parsers

def configure_parser(parser):
    """ Configure parser for this action """
    qipkg.parsers.pml_parser(parser)
    qibuild.parsers.cmake_build_parser(parser, with_build_parser=False)

def do(args):
    """ Main entry point """
    pml_builder = qipkg.parsers.get_pml_builder(args)
    pml_builder.build()


text:
package com.quetwo.iaug.VoteApp;

import java.io.IOException;
import java.net.URI;

import javax.websocket.*;

@ClientEndpoint
public class wsClient
{

	private Session userSession = null;
	private MessageHandler messageHandler = null;
	private URI endpoint = null;

	public wsClient(final URI endpoint)
	{
		this.endpoint = endpoint;
		try
		{
			WebSocketContainer container = ContainerProvider.getWebSocketContainer();
			container.connectToServer(this,  endpoint);
		}
		catch (Exception e)
		{
			throw new RuntimeException(e);
		}
	}

	@OnOpen
	public void onOpen(final Session userSession)
	{
		this.userSession = userSession;
	}

	@OnClose
	public void onClose(final Session userSession, final CloseReason reason)
	{
		this.userSession = null;
	}

	@OnMessage
	public void onMessage(final String message)
	{
		if (messageHandler != null)
		{
			messageHandler.handleMessage(message);
		}
	}

	public boolean isConnected()
	{
		return (this.userSession != null);
	}

	public void reconnect() throws Exception
	{
		if (!isConnected())
		{
			WebSocketContainer container = ContainerProvider.getWebSocketContainer();
			container.connectToServer(this, this.endpoint);
		}
	}

	public void closeConnection()
	{
		try
		{
			userSession.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public void addMessageHandler(final MessageHandler msgHandler)
	{
		messageHandler = msgHandler;
	}

	public void sendMessage(final String message)
	{
		userSession.getAsyncRemote().sendText(message);
	}

	public static interface MessageHandler
	{
		public void handleMessage(String message);
	}
}


text:
<?php

namespace Predis\Command;

/**
 * @link http://redis.io/commands/hset
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class HashSet extends Command
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'HSET';
    }

    /**
     * {@inheritdoc}
     */
    public function parseResponse($data)
    {
        return (bool) $data;
    }
}


text:
vim configuration  for golang

## Usage:
``` bash
cd ~
[ -d .vim ] && mv  .vim  .bak_vim
git clone --recursive git@github.com:ahnan4arch/.vim.git
```


text:
package org.apache.archiva.reports;

import org.apache.archiva.metadata.model.MetadataFacet;
import org.apache.archiva.metadata.model.MetadataFacetFactory;
import org.apache.archiva.metadata.model.facets.RepositoryProblemFacet;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service( "metadataFacetFactory#org.apache.archiva.reports" )
public class RepositoryProblemFacetFactory
    implements MetadataFacetFactory
{
    @Override
    public MetadataFacet createMetadataFacet()
    {
        return new RepositoryProblemFacet();
    }

    @Override
    public MetadataFacet createMetadataFacet( String repositoryId, String name )
    {
        return new RepositoryProblemFacet();
    }
}


text:
// Include some base code
#include "app.h"

// Include object #defines
#include "object_Defs.h"

// These are the base objects to be further specialized
#include "physics_Object.h"
#include "scene_Object.h"

// The system classes control the use of the objects derived from the bases
#include "physics_System.h"
#include "scene_System.h"

/////////////////////////////////////////////////////////////////////
#endif // !defined(_OBJECT_H_)


text: tfenv install latest


text:
import tagTester from './_tagTester.js';

export default tagTester('WeakSet');