text:
from collections import defaultdict
from datetime import date, datetime, timedelta
from typing import Callable
from itertools import product
from functools import lru_cache
from time import time
import multiprocessing
import random
import traceback

import numpy as np
from pandas import DataFrame
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from deap import creator, base, tools, algorithms

from vnpy.trader.constant import (Direction, Offset, Exchange,
                                  Interval, Status)
from vnpy.trader.database import database_manager
from vnpy.trader.object import OrderData, TradeData, BarData, TickData
from vnpy.trader.utility import round_to

from .base import (
    BacktestingMode,
    EngineType,
    STOPORDER_PREFIX,
    StopOrder,
    StopOrderStatus,
    INTERVAL_DELTA_MAP
)
from .template import CtaTemplate

# Set deap algo
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)

class OptimizationSetting:
    """
    Setting for runnning optimization.
    """

    def __init__(self):
        """"""
        self.params = {}
        self.target_name = ""

    def add_parameter(
        self, name: str, start: float, end: float = None, step: float = None
    ):
        """"""
        if not end and not step:
            self.params[name] = [start]
            return

        if start >= end:
            print("参数优化起始点必须小于终止点")
            return

        if step <= 0:
            print("参数优化步进必须大于0")
            return

        value = start
        value_list = []

        while value <= end:
            value_list.append(value)
            value += step

        self.params[name] = value_list

    def set_target(self, target_name: str):
        """"""
        self.target_name = target_name

    def generate_setting(self):
        """"""
        keys = self.params.keys()
        values = self.params.values()
        products = list(product(*values))

        settings = []
        for p in products:
            setting = dict(zip(keys, p))
            settings.append(setting)

        return settings

    def generate_setting_ga(self):
        """"""
        settings_ga = []
        settings = self.generate_setting()
        for d in settings:
            param = [tuple(i) for i in d.items()]
            settings_ga.append(param)
        return settings_ga

class BacktestingEngine:
    """"""

    engine_type = EngineType.BACKTESTING
    gateway_name = "BACKTESTING"

    def __init__(self):
        """"""
        self.vt_symbol = ""
        self.symbol = ""
        self.exchange = None
        self.start = None
        self.end = None
        self.rate = 0
        self.slippage = 0
        self.size = 1
        self.pricetick = 0
        self.capital = 1_000_000
        self.risk_free: float = 0.02
        self.mode = BacktestingMode.BAR
        self.inverse = False

        self.strategy_class = None
        self.strategy = None
        self.tick: TickData
        self.bar: BarData
        self.datetime = None

        self.interval = None
        self.days = 0
        self.callback = None
        self.history_data = []

        self.stop_order_count = 0
        self.stop_orders = {}
        self.active_stop_orders = {}

        self.limit_order_count = 0
        self.limit_orders = {}
        self.active_limit_orders = {}

        self.trade_count = 0
        self.trades = {}

        self.logs = []

        self.daily_results = {}
        self.daily_df = None

    def clear_data(self):
        """
        Clear all data of last backtesting.
        """
        self.strategy = None
        self.tick = None
        self.bar = None
        self.datetime = None

        self.stop_order_count = 0
        self.stop_orders.clear()
        self.active_stop_orders.clear()

        self.limit_order_count = 0
        self.limit_orders.clear()
        self.active_limit_orders.clear()

        self.trade_count = 0
        self.trades.clear()

        self.logs.clear()
        self.daily_results.clear()

    def set_parameters(
        self,
        vt_symbol: str,
        interval: Interval,
        start: datetime,
        rate: float,
        slippage: float,
        size: float,
        pricetick: float,
        capital: int = 0,
        end: datetime = None,
        mode: BacktestingMode = BacktestingMode.BAR,
        inverse: bool = False,
        risk_free: float = 0
    ):
        """"""
        self.mode = mode
        self.vt_symbol = vt_symbol
        self.interval = Interval(interval)
        self.rate = rate
        self.slippage = slippage
        self.size = size
        self.pricetick = pricetick
        self.start = start

        self.symbol, exchange_str = self.vt_symbol.split(".")
        self.exchange = Exchange(exchange_str)

        self.capital = capital
        self.end = end
        self.mode = mode
        self.inverse = inverse
        self.risk_free = risk_free

    def add_strategy(self, strategy_class: type, setting: dict):
        """"""
        self.strategy_class = strategy_class
        self.strategy = strategy_class(
            self, strategy_class.__name__, self.vt_symbol, setting
        )

    def load_data(self):
        """"""
        self.output("开始加载历史数据")

        if not self.end:
            self.end = datetime.now()

        if self.start >= self.end:
            self.output("起始日期必须小于结束日期")
            return

        self.history_data.clear()       # Clear previously loaded history data

        # Load 30 days of data each time and allow for progress update
        total_days = (self.end - self.start).days
        progress_days = max(int(total_days / 10), 1)
        progress_delta = timedelta(days=progress_days)
        interval_delta = INTERVAL_DELTA_MAP[self.interval]

        start = self.start
        end = self.start + progress_delta
        progress = 0

        while start < self.end:
            progress_bar = "#" * int(progress * 10 + 1)
            self.output(f"加载进度:{progress_bar} [{progress:.0%}]")

            end = min(end, self.end)  # Make sure end time stays within set range

            if self.mode == BacktestingMode.BAR:
                data = load_bar_data(
                    self.symbol,
                    self.exchange,
                    self.interval,
                    start,
                    end
                )
            else:
                data = load_tick_data(
                    self.symbol,
                    self.exchange,
                    start,
                    end
                )

            self.history_data.extend(data)

            progress += progress_days / total_days
            progress = min(progress, 1)

            start = end + interval_delta
            end += progress_delta

        self.output(f"历史数据加载完成,数据量:{len(self.history_data)}")

    def run_backtesting(self):
        """"""
        if self.mode == BacktestingMode.BAR:
            func = self.new_bar
        else:
            func = self.new_tick

        self.strategy.on_init()

        # Use the first [days] of history data for initializing strategy
        day_count = 1
        ix = 0

        for ix, data in enumerate(self.history_data):
            if self.datetime and data.datetime.day != self.datetime.day:
                day_count += 1
                if day_count >= self.days:
                    break

            self.datetime = data.datetime

            try:
                self.callback(data)
            except Exception:
                self.output("触发异常,回测终止")
                self.output(traceback.format_exc())
                return

        self.strategy.inited = True
        self.output("策略初始化完成")

        self.strategy.on_start()
        self.strategy.trading = True
        self.output("开始回放历史数据")

        # Use the rest of history data for running backtesting
        backtesting_data = self.history_data[ix + 1:]
        if not backtesting_data:
            self.output("历史数据不足,回测终止")
            return

        total_size = len(backtesting_data)
        batch_size = max(int(total_size / 10), 1)

        for ix, i in enumerate(range(0, total_size, batch_size)):
            batch_data = backtesting_data[i: i + batch_size]
            for data in batch_data:
                try:
                    func(data)
                except Exception:
                    self.output("触发异常,回测终止")
                    self.output(traceback.format_exc())
                    return

            progress = min(ix / 10, 1)
            progress_bar = "=" * (ix + 1)
            self.output(f"回放进度:{progress_bar} [{progress:.0%}]")

        self.strategy.on_stop()
        self.output("历史数据回放结束")

    def calculate_result(self):
        """"""
        self.output("开始计算逐日盯市盈亏")

        if not self.trades:
            self.output("成交记录为空,无法计算")
            return

        # Add trade data into daily reuslt.
        for trade in self.trades.values():
            d = trade.datetime.date()
            daily_result = self.daily_results[d]
            daily_result.add_trade(trade)

        # Calculate daily result by iteration.
        pre_close = 0
        start_pos = 0

        for daily_result in self.daily_results.values():
            daily_result.calculate_pnl(
                pre_close,
                start_pos,
                self.size,
                self.rate,
                self.slippage,
                self.inverse
            )

            pre_close = daily_result.close_price
            start_pos = daily_result.end_pos

        # Generate dataframe
        results = defaultdict(list)

        for daily_result in self.daily_results.values():
            for key, value in daily_result.__dict__.items():
                results[key].append(value)

        self.daily_df = DataFrame.from_dict(results).set_index("date")

        self.output("逐日盯市盈亏计算完成")
        return self.daily_df

    def calculate_statistics(self, df: DataFrame = None, output=True):
        """"""
        self.output("开始计算策略统计指标")

        # Check DataFrame input exterior
        if df is None:
            df = self.daily_df

        # Check for init DataFrame
        if df is None:
            # Set all statistics to 0 if no trade.
            start_date = ""
            end_date = ""
            total_days = 0
            profit_days = 0
            loss_days = 0
            end_balance = 0
            max_drawdown = 0
            max_ddpercent = 0
            max_drawdown_duration = 0
            total_net_pnl = 0
            daily_net_pnl = 0
            total_commission = 0
            daily_commission = 0
            total_slippage = 0
            daily_slippage = 0
            total_turnover = 0
            daily_turnover = 0
            total_trade_count = 0
            daily_trade_count = 0
            total_return = 0
            annual_return = 0
            daily_return = 0
            return_std = 0
            sharpe_ratio = 0
            return_drawdown_ratio = 0
        else:
            # Calculate balance related time series data
            df["balance"] = df["net_pnl"].cumsum() + self.capital

            # When balance falls below 0, set daily return to 0
            x = df["balance"] / df["balance"].shift(1)
            x[x <= 0] = np.nan
            df["return"] = np.log(x).fillna(0)

            df["highlevel"] = (
                df["balance"].rolling(
                    min_periods=1, window=len(df), center=False).max()
            )
            df["drawdown"] = df["balance"] - df["highlevel"]
            df["ddpercent"] = df["drawdown"] / df["highlevel"] * 100

            # Calculate statistics value
            start_date = df.index[0]
            end_date = df.index[-1]

            total_days = len(df)
            profit_days = len(df[df["net_pnl"] > 0])
            loss_days = len(df[df["net_pnl"] < 0])

            end_balance = df["balance"].iloc[-1]
            max_drawdown = df["drawdown"].min()
            max_ddpercent = df["ddpercent"].min()
            max_drawdown_end = df["drawdown"].idxmin()

            if isinstance(max_drawdown_end, date):
                max_drawdown_start = df["balance"][:max_drawdown_end].idxmax()
                max_drawdown_duration = (max_drawdown_end - max_drawdown_start).days
            else:
                max_drawdown_duration = 0

            total_net_pnl = df["net_pnl"].sum()
            daily_net_pnl = total_net_pnl / total_days

            total_commission = df["commission"].sum()
            daily_commission = total_commission / total_days

            total_slippage = df["slippage"].sum()
            daily_slippage = total_slippage / total_days

            total_turnover = df["turnover"].sum()
            daily_turnover = total_turnover / total_days

            total_trade_count = df["trade_count"].sum()
            daily_trade_count = total_trade_count / total_days

            total_return = (end_balance / self.capital - 1) * 100
            annual_return = total_return / total_days * 240
            daily_return = df["return"].mean() * 100
            return_std = df["return"].std() * 100

            if return_std:
                daily_risk_free = self.risk_free / np.sqrt(240)
                sharpe_ratio = (daily_return - daily_risk_free) / return_std * np.sqrt(240)
            else:
                sharpe_ratio = 0

            return_drawdown_ratio = -total_return / max_ddpercent

        # Output
        if output:
            self.output("-" * 30)
            self.output(f"首个交易日:\t{start_date}")
            self.output(f"最后交易日:\t{end_date}")

            self.output(f"总交易日:\t{total_days}")
            self.output(f"盈利交易日:\t{profit_days}")
            self.output(f"亏损交易日:\t{loss_days}")

            self.output(f"起始资金:\t{self.capital:,.2f}")
            self.output(f"结束资金:\t{end_balance:,.2f}")

            self.output(f"总收益率:\t{total_return:,.2f}%")
            self.output(f"年化收益:\t{annual_return:,.2f}%")
            self.output(f"最大回撤: \t{max_drawdown:,.2f}")
            self.output(f"百分比最大回撤: {max_ddpercent:,.2f}%")
            self.output(f"最长回撤天数: \t{max_drawdown_duration}")

            self.output(f"总盈亏:\t{total_net_pnl:,.2f}")
            self.output(f"总手续费:\t{total_commission:,.2f}")
            self.output(f"总滑点:\t{total_slippage:,.2f}")
            self.output(f"总成交金额:\t{total_turnover:,.2f}")
            self.output(f"总成交笔数:\t{total_trade_count}")

            self.output(f"日均盈亏:\t{daily_net_pnl:,.2f}")
            self.output(f"日均手续费:\t{daily_commission:,.2f}")
            self.output(f"日均滑点:\t{daily_slippage:,.2f}")
            self.output(f"日均成交金额:\t{daily_turnover:,.2f}")
            self.output(f"日均成交笔数:\t{daily_trade_count}")

            self.output(f"日均收益率:\t{daily_return:,.2f}%")
            self.output(f"收益标准差:\t{return_std:,.2f}%")
            self.output(f"Sharpe Ratio:\t{sharpe_ratio:,.2f}")
            self.output(f"收益回撤比:\t{return_drawdown_ratio:,.2f}")

        statistics = {
            "start_date": start_date,
            "end_date": end_date,
            "total_days": total_days,
            "profit_days": profit_days,
            "loss_days": loss_days,
            "capital": self.capital,
            "end_balance": end_balance,
            "max_drawdown": max_drawdown,
            "max_ddpercent": max_ddpercent,
            "max_drawdown_duration": max_drawdown_duration,
            "total_net_pnl": total_net_pnl,
            "daily_net_pnl": daily_net_pnl,
            "total_commission": total_commission,
            "daily_commission": daily_commission,
            "total_slippage": total_slippage,
            "daily_slippage": daily_slippage,
            "total_turnover": total_turnover,
            "daily_turnover": daily_turnover,
            "total_trade_count": total_trade_count,
            "daily_trade_count": daily_trade_count,
            "total_return": total_return,
            "annual_return": annual_return,
            "daily_return": daily_return,
            "return_std": return_std,
            "sharpe_ratio": sharpe_ratio,
            "return_drawdown_ratio": return_drawdown_ratio,
        }

        # Filter potential error infinite value
        for key, value in statistics.items():
            if value in (np.inf, -np.inf):
                value = 0
            statistics[key] = np.nan_to_num(value)

        self.output("策略统计指标计算完成")
        return statistics

    def show_chart(self, df: DataFrame = None):
        """"""
        # Check DataFrame input exterior
        if df is None:
            df = self.daily_df

        # Check for init DataFrame
        if df is None:
            return

        fig = make_subplots(
            rows=4,
            cols=1,
            subplot_titles=["Balance", "Drawdown", "Daily Pnl", "Pnl Distribution"],
            vertical_spacing=0.06
        )

        balance_line = go.Scatter(
            x=df.index,
            y=df["balance"],
            mode="lines",
            name="Balance"
        )
        drawdown_scatter = go.Scatter(
            x=df.index,
            y=df["drawdown"],
            fillcolor="red",
            fill='tozeroy',
            mode="lines",
            name="Drawdown"
        )
        pnl_bar = go.Bar(y=df["net_pnl"], name="Daily Pnl")
        pnl_histogram = go.Histogram(x=df["net_pnl"], nbinsx=100, name="Days")

        fig.add_trace(balance_line, row=1, col=1)
        fig.add_trace(drawdown_scatter, row=2, col=1)
        fig.add_trace(pnl_bar, row=3, col=1)
        fig.add_trace(pnl_histogram, row=4, col=1)

        fig.update_layout(height=1000, width=1000)
        fig.show()

    def run_optimization(self, optimization_setting: OptimizationSetting, output=True):
        """"""
        # Get optimization setting and target
        settings = optimization_setting.generate_setting()
        target_name = optimization_setting.target_name

        if not settings:
            self.output("优化参数组合为空,请检查")
            return

        if not target_name:
            self.output("优化目标未设置,请检查")
            return

        # Use multiprocessing pool for running backtesting with different setting
        # Force to use spawn method to create new process (instead of fork on Linux)
        ctx = multiprocessing.get_context("spawn")
        pool = ctx.Pool(multiprocessing.cpu_count())

        results = []
        for setting in settings:
            result = (pool.apply_async(optimize, (
                target_name,
                self.strategy_class,
                setting,
                self.vt_symbol,
                self.interval,
                self.start,
                self.rate,
                self.slippage,
                self.size,
                self.pricetick,
                self.capital,
                self.end,
                self.mode,
                self.inverse
            )))
            results.append(result)

        pool.close()
        pool.join()

        # Sort results and output
        result_values = [result.get() for result in results]
        result_values.sort(reverse=True, key=lambda result: result[1])

        if output:
            for value in result_values:
                msg = f"参数:{value[0]}, 目标:{value[1]}"
                self.output(msg)

        return result_values

    def run_ga_optimization(self, optimization_setting: OptimizationSetting, population_size=100, ngen_size=30, output=True):
        """"""
        # Clear lru_cache before running ga optimization
        _ga_optimize.cache_clear()

        # Get optimization setting and target
        settings = optimization_setting.generate_setting_ga()
        target_name = optimization_setting.target_name

        if not settings:
            self.output("优化参数组合为空,请检查")
            return

        if not target_name:
            self.output("优化目标未设置,请检查")
            return

        # Define parameter generation function
        def generate_parameter():
            """"""
            return random.choice(settings)

        def mutate_individual(individual, indpb):
            """"""
            size = len(individual)
            paramlist = generate_parameter()
            for i in range(size):
                if random.random() < indpb:
                    individual[i] = paramlist[i]
            return individual,

        # Create ga object function
        global ga_target_name
        global ga_strategy_class
        global ga_setting
        global ga_vt_symbol
        global ga_interval
        global ga_start
        global ga_rate
        global ga_slippage
        global ga_size
        global ga_pricetick
        global ga_capital
        global ga_end
        global ga_mode
        global ga_inverse

        ga_target_name = target_name
        ga_strategy_class = self.strategy_class
        ga_setting = settings[0]
        ga_vt_symbol = self.vt_symbol
        ga_interval = self.interval
        ga_start = self.start
        ga_rate = self.rate
        ga_slippage = self.slippage
        ga_size = self.size
        ga_pricetick = self.pricetick
        ga_capital = self.capital
        ga_end = self.end
        ga_mode = self.mode
        ga_inverse = self.inverse

        # Set up genetic algorithm
        toolbox = base.Toolbox()
        toolbox.register("individual", tools.initIterate, creator.Individual, generate_parameter)
        toolbox.register("population", tools.initRepeat, list, toolbox.individual)
        toolbox.register("mate", tools.cxTwoPoint)
        toolbox.register("mutate", mutate_individual, indpb=1)
        toolbox.register("evaluate", ga_optimize)
        toolbox.register("select", tools.selNSGA2)

        total_size = len(settings)
        pop_size = population_size                      # number of individuals in each generation
        lambda_ = pop_size                              # number of children to produce at each generation
        mu = int(pop_size * 0.8)                        # number of individuals to select for the next generation

        cxpb = 0.95         # probability that an offspring is produced by crossover
        mutpb = 1 - cxpb    # probability that an offspring is produced by mutation
        ngen = ngen_size    # number of generation

        pop = toolbox.population(pop_size)
        hof = tools.ParetoFront()               # end result of pareto front

        stats = tools.Statistics(lambda ind: ind.fitness.values)
        np.set_printoptions(suppress=True)
        stats.register("mean", np.mean, axis=0)
        stats.register("std", np.std, axis=0)
        stats.register("min", np.min, axis=0)
        stats.register("max", np.max, axis=0)

        # Multiprocessing is not supported yet.
        # pool = multiprocessing.Pool(multiprocessing.cpu_count())
        # toolbox.register("map", pool.map)

        # Run ga optimization
        self.output(f"参数优化空间:{total_size}")
        self.output(f"每代族群总数:{pop_size}")
        self.output(f"优良筛选个数:{mu}")
        self.output(f"迭代次数:{ngen}")
        self.output(f"交叉概率:{cxpb:.0%}")
        self.output(f"突变概率:{mutpb:.0%}")

        start = time()

        algorithms.eaMuPlusLambda(
            pop,
            toolbox,
            mu,
            lambda_,
            cxpb,
            mutpb,
            ngen,
            stats,
            halloffame=hof
        )

        end = time()
        cost = int((end - start))

        self.output(f"遗传算法优化完成,耗时{cost}秒")

        # Return result list
        results = []

        for parameter_values in hof:
            setting = dict(parameter_values)
            target_value = ga_optimize(parameter_values)[0]
            results.append((setting, target_value, {}))

        return results

    def update_daily_close(self, price: float):
        """"""
        d = self.datetime.date()

        daily_result = self.daily_results.get(d, None)
        if daily_result:
            daily_result.close_price = price
        else:
            self.daily_results[d] = DailyResult(d, price)

    def new_bar(self, bar: BarData):
        """"""
        self.bar = bar
        self.datetime = bar.datetime

        self.cross_limit_order()
        self.cross_stop_order()
        self.strategy.on_bar(bar)

        self.update_daily_close(bar.close_price)

    def new_tick(self, tick: TickData):
        """"""
        self.tick = tick
        self.datetime = tick.datetime

        self.cross_limit_order()
        self.cross_stop_order()
        self.strategy.on_tick(tick)

        self.update_daily_close(tick.last_price)

    def cross_limit_order(self):
        """
        Cross limit order with last bar/tick data.
        """
        if self.mode == BacktestingMode.BAR:
            long_cross_price = self.bar.low_price
            short_cross_price = self.bar.high_price
            long_best_price = self.bar.open_price
            short_best_price = self.bar.open_price
        else:
            long_cross_price = self.tick.ask_price_1
            short_cross_price = self.tick.bid_price_1
            long_best_price = long_cross_price
            short_best_price = short_cross_price

        for order in list(self.active_limit_orders.values()):
            # Push order update with status "not traded" (pending).
            if order.status == Status.SUBMITTING:
                order.status = Status.NOTTRADED
                self.strategy.on_order(order)

            # Check whether limit orders can be filled.
            long_cross = (
                order.direction == Direction.LONG
                and order.price >= long_cross_price
                and long_cross_price > 0
            )

            short_cross = (
                order.direction == Direction.SHORT
                and order.price <= short_cross_price
                and short_cross_price > 0
            )

            if not long_cross and not short_cross:
                continue

            # Push order udpate with status "all traded" (filled).
            order.traded = order.volume
            order.status = Status.ALLTRADED
            self.strategy.on_order(order)

            self.active_limit_orders.pop(order.vt_orderid)

            # Push trade update
            self.trade_count += 1

            if long_cross:
                trade_price = min(order.price, long_best_price)
                pos_change = order.volume
            else:
                trade_price = max(order.price, short_best_price)
                pos_change = -order.volume

            trade = TradeData(
                symbol=order.symbol,
                exchange=order.exchange,
                orderid=order.orderid,
                tradeid=str(self.trade_count),
                direction=order.direction,
                offset=order.offset,
                price=trade_price,
                volume=order.volume,
                datetime=self.datetime,
                gateway_name=self.gateway_name,
            )

            self.strategy.pos += pos_change
            self.strategy.on_trade(trade)

            self.trades[trade.vt_tradeid] = trade

    def cross_stop_order(self):
        """
        Cross stop order with last bar/tick data.
        """
        if self.mode == BacktestingMode.BAR:
            long_cross_price = self.bar.high_price
            short_cross_price = self.bar.low_price
            long_best_price = self.bar.open_price
            short_best_price = self.bar.open_price
        else:
            long_cross_price = self.tick.last_price
            short_cross_price = self.tick.last_price
            long_best_price = long_cross_price
            short_best_price = short_cross_price

        for stop_order in list(self.active_stop_orders.values()):
            # Check whether stop order can be triggered.
            long_cross = (
                stop_order.direction == Direction.LONG
                and stop_order.price <= long_cross_price
            )

            short_cross = (
                stop_order.direction == Direction.SHORT
                and stop_order.price >= short_cross_price
            )

            if not long_cross and not short_cross:
                continue

            # Create order data.
            self.limit_order_count += 1

            order = OrderData(
                symbol=self.symbol,
                exchange=self.exchange,
                orderid=str(self.limit_order_count),
                direction=stop_order.direction,
                offset=stop_order.offset,
                price=stop_order.price,
                volume=stop_order.volume,
                traded=stop_order.volume,
                status=Status.ALLTRADED,
                gateway_name=self.gateway_name,
                datetime=self.datetime
            )

            self.limit_orders[order.vt_orderid] = order

            # Create trade data.
            if long_cross:
                trade_price = max(stop_order.price, long_best_price)
                pos_change = order.volume
            else:
                trade_price = min(stop_order.price, short_best_price)
                pos_change = -order.volume

            self.trade_count += 1

            trade = TradeData(
                symbol=order.symbol,
                exchange=order.exchange,
                orderid=order.orderid,
                tradeid=str(self.trade_count),
                direction=order.direction,
                offset=order.offset,
                price=trade_price,
                volume=order.volume,
                datetime=self.datetime,
                gateway_name=self.gateway_name,
            )

            self.trades[trade.vt_tradeid] = trade

            # Update stop order.
            stop_order.vt_orderids.append(order.vt_orderid)
            stop_order.status = StopOrderStatus.TRIGGERED

            if stop_order.stop_orderid in self.active_stop_orders:
                self.active_stop_orders.pop(stop_order.stop_orderid)

            # Push update to strategy.
            self.strategy.on_stop_order(stop_order)
            self.strategy.on_order(order)

            self.strategy.pos += pos_change
            self.strategy.on_trade(trade)

    def load_bar(
        self,
        vt_symbol: str,
        days: int,
        interval: Interval,
        callback: Callable,
        use_database: bool
    ):
        """"""
        self.days = days
        self.callback = callback

    def load_tick(self, vt_symbol: str, days: int, callback: Callable):
        """"""
        self.days = days
        self.callback = callback

    def send_order(
        self,
        strategy: CtaTemplate,
        direction: Direction,
        offset: Offset,
        price: float,
        volume: float,
        stop: bool,
        lock: bool
    ):
        """"""
        price = round_to(price, self.pricetick)
        if stop:
            vt_orderid = self.send_stop_order(direction, offset, price, volume)
        else:
            vt_orderid = self.send_limit_order(direction, offset, price, volume)
        return [vt_orderid]

    def send_stop_order(
        self,
        direction: Direction,
        offset: Offset,
        price: float,
        volume: float
    ):
        """"""
        self.stop_order_count += 1

        stop_order = StopOrder(
            vt_symbol=self.vt_symbol,
            direction=direction,
            offset=offset,
            price=price,
            volume=volume,
            stop_orderid=f"{STOPORDER_PREFIX}.{self.stop_order_count}",
            strategy_name=self.strategy.strategy_name,
        )

        self.active_stop_orders[stop_order.stop_orderid] = stop_order
        self.stop_orders[stop_order.stop_orderid] = stop_order

        return stop_order.stop_orderid

    def send_limit_order(
        self,
        direction: Direction,
        offset: Offset,
        price: float,
        volume: float
    ):
        """"""
        self.limit_order_count += 1

        order = OrderData(
            symbol=self.symbol,
            exchange=self.exchange,
            orderid=str(self.limit_order_count),
            direction=direction,
            offset=offset,
            price=price,
            volume=volume,
            status=Status.SUBMITTING,
            gateway_name=self.gateway_name,
            datetime=self.datetime
        )

        self.active_limit_orders[order.vt_orderid] = order
        self.limit_orders[order.vt_orderid] = order

        return order.vt_orderid

    def cancel_order(self, strategy: CtaTemplate, vt_orderid: str):
        """
        Cancel order by vt_orderid.
        """
        if vt_orderid.startswith(STOPORDER_PREFIX):
            self.cancel_stop_order(strategy, vt_orderid)
        else:
            self.cancel_limit_order(strategy, vt_orderid)

    def cancel_stop_order(self, strategy: CtaTemplate, vt_orderid: str):
        """"""
        if vt_orderid not in self.active_stop_orders:
            return
        stop_order = self.active_stop_orders.pop(vt_orderid)

        stop_order.status = StopOrderStatus.CANCELLED
        self.strategy.on_stop_order(stop_order)

    def cancel_limit_order(self, strategy: CtaTemplate, vt_orderid: str):
        """"""
        if vt_orderid not in self.active_limit_orders:
            return
        order = self.active_limit_orders.pop(vt_orderid)

        order.status = Status.CANCELLED
        self.strategy.on_order(order)

    def cancel_all(self, strategy: CtaTemplate):
        """
        Cancel all orders, both limit and stop.
        """
        vt_orderids = list(self.active_limit_orders.keys())
        for vt_orderid in vt_orderids:
            self.cancel_limit_order(strategy, vt_orderid)

        stop_orderids = list(self.active_stop_orders.keys())
        for vt_orderid in stop_orderids:
            self.cancel_stop_order(strategy, vt_orderid)

    def write_log(self, msg: str, strategy: CtaTemplate = None):
        """
        Write log message.
        """
        msg = f"{self.datetime}\t{msg}"
        self.logs.append(msg)

    def send_email(self, msg: str, strategy: CtaTemplate = None):
        """
        Send email to default receiver.
        """
        pass

    def sync_strategy_data(self, strategy: CtaTemplate):
        """
        Sync strategy data into json file.
        """
        pass

    def get_engine_type(self):
        """
        Return engine type.
        """
        return self.engine_type

    def get_pricetick(self, strategy: CtaTemplate):
        """
        Return contract pricetick data.
        """
        return self.pricetick

    def put_strategy_event(self, strategy: CtaTemplate):
        """
        Put an event to update strategy status.
        """
        pass

    def output(self, msg):
        """
        Output message of backtesting engine.
        """
        print(f"{datetime.now()}\t{msg}")

    def get_all_trades(self):
        """
        Return all trade data of current backtesting result.
        """
        return list(self.trades.values())

    def get_all_orders(self):
        """
        Return all limit order data of current backtesting result.
        """
        return list(self.limit_orders.values())

    def get_all_daily_results(self):
        """
        Return all daily result data.
        """
        return list(self.daily_results.values())

class DailyResult:
    """"""

    def __init__(self, date: date, close_price: float):
        """"""
        self.date = date
        self.close_price = close_price
        self.pre_close = 0

        self.trades = []
        self.trade_count = 0

        self.start_pos = 0
        self.end_pos = 0

        self.turnover = 0
        self.commission = 0
        self.slippage = 0

        self.trading_pnl = 0
        self.holding_pnl = 0
        self.total_pnl = 0
        self.net_pnl = 0

    def add_trade(self, trade: TradeData):
        """"""
        self.trades.append(trade)

    def calculate_pnl(
        self,
        pre_close: float,
        start_pos: float,
        size: int,
        rate: float,
        slippage: float,
        inverse: bool
    ):
        """"""
        # If no pre_close provided on the first day,
        # use value 1 to avoid zero division error
        if pre_close:
            self.pre_close = pre_close
        else:
            self.pre_close = 1

        # Holding pnl is the pnl from holding position at day start
        self.start_pos = start_pos
        self.end_pos = start_pos

        if not inverse:     # For normal contract
            self.holding_pnl = self.start_pos * \
                (self.close_price - self.pre_close) * size
        else:               # For crypto currency inverse contract
            self.holding_pnl = self.start_pos * \
                (1 / self.pre_close - 1 / self.close_price) * size

        # Trading pnl is the pnl from new trade during the day
        self.trade_count = len(self.trades)

        for trade in self.trades:
            if trade.direction == Direction.LONG:
                pos_change = trade.volume
            else:
                pos_change = -trade.volume

            self.end_pos += pos_change

            # For normal contract
            if not inverse:
                turnover = trade.volume * size * trade.price
                self.trading_pnl += pos_change * \
                    (self.close_price - trade.price) * size
                self.slippage += trade.volume * size * slippage
            # For crypto currency inverse contract
            else:
                turnover = trade.volume * size / trade.price
                self.trading_pnl += pos_change * \
                    (1 / trade.price - 1 / self.close_price) * size
                self.slippage += trade.volume * size * slippage / (trade.price ** 2)

            self.turnover += turnover
            self.commission += turnover * rate

        # Net pnl takes account of commission and slippage cost
        self.total_pnl = self.trading_pnl + self.holding_pnl
        self.net_pnl = self.total_pnl - self.commission - self.slippage

def optimize(
    target_name: str,
    strategy_class: CtaTemplate,
    setting: dict,
    vt_symbol: str,
    interval: Interval,
    start: datetime,
    rate: float,
    slippage: float,
    size: float,
    pricetick: float,
    capital: int,
    end: datetime,
    mode: BacktestingMode,
    inverse: bool
):
    """
    Function for running in multiprocessing.pool
    """
    engine = BacktestingEngine()

    engine.set_parameters(
        vt_symbol=vt_symbol,
        interval=interval,
        start=start,
        rate=rate,
        slippage=slippage,
        size=size,
        pricetick=pricetick,
        capital=capital,
        end=end,
        mode=mode,
        inverse=inverse
    )

    engine.add_strategy(strategy_class, setting)
    engine.load_data()
    engine.run_backtesting()
    engine.calculate_result()
    statistics = engine.calculate_statistics(output=False)

    target_value = statistics[target_name]
    return (str(setting), target_value, statistics)

@lru_cache(maxsize=1000000)
def _ga_optimize(parameter_values: tuple):
    """"""
    setting = dict(parameter_values)

    result = optimize(
        ga_target_name,
        ga_strategy_class,
        setting,
        ga_vt_symbol,
        ga_interval,
        ga_start,
        ga_rate,
        ga_slippage,
        ga_size,
        ga_pricetick,
        ga_capital,
        ga_end,
        ga_mode,
        ga_inverse
    )
    return (result[1],)

def ga_optimize(parameter_values: list):
    """"""
    return _ga_optimize(tuple(parameter_values))

@lru_cache(maxsize=999)
def load_bar_data(
    symbol: str,
    exchange: Exchange,
    interval: Interval,
    start: datetime,
    end: datetime
):
    """"""
    return database_manager.load_bar_data(
        symbol, exchange, interval, start, end
    )

@lru_cache(maxsize=999)
def load_tick_data(
    symbol: str,
    exchange: Exchange,
    start: datetime,
    end: datetime
):
    """"""
    return database_manager.load_tick_data(
        symbol, exchange, start, end
    )

# GA related global value
ga_end = None
ga_mode = None
ga_target_name = None
ga_strategy_class = None
ga_setting = None
ga_vt_symbol = None
ga_interval = None
ga_start = None
ga_rate = None
ga_slippage = None
ga_size = None
ga_pricetick = None
ga_capital = None


text:
package org.apache.hadoop.yarn.util;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.net.URISyntaxException;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.api.TestContainerId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.URL;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.junit.Test;

public class TestConverterUtils {

  @Test
  public void testConvertUrlWithNoPort() throws URISyntaxException {
    Path expectedPath = new Path("hdfs://foo.com");
    URL url = URL.fromPath(expectedPath);
    Path actualPath = url.toPath();
    assertEquals(expectedPath, actualPath);
  }

  @Test
  public void testConvertUrlWithUserinfo() throws URISyntaxException {
    Path expectedPath = new Path("foo://username:password@example.com:8042");
    URL url = URL.fromPath(expectedPath);
    Path actualPath = url.toPath();
    assertEquals(expectedPath, actualPath);
  }

  @Test
  public void testContainerId() throws URISyntaxException {
    ContainerId id = TestContainerId.newContainerId(0, 0, 0, 0);
    String cid = id.toString();
    assertEquals("container_0_0000_00_000000", cid);
    ContainerId gen = ContainerId.fromString(cid);
    assertEquals(gen, id);
  }

  @Test
  public void testContainerIdWithEpoch() throws URISyntaxException {
    ContainerId id = TestContainerId.newContainerId(0, 0, 0, 25645811);
    String cid = id.toString();
    assertEquals("container_0_0000_00_25645811", cid);
    ContainerId gen = ContainerId.fromString(cid);
    assertEquals(gen.toString(), id.toString());

    long ts = System.currentTimeMillis();
    ContainerId id2 =
        TestContainerId.newContainerId(36473, 4365472, ts, 4298334883325L);
    String cid2 = id2.toString();
    assertEquals(
        "container_e03_" + ts + "_36473_4365472_999799999997", cid2);
    ContainerId gen2 = ContainerId.fromString(cid2);
    assertEquals(gen2.toString(), id2.toString());

    ContainerId id3 =
        TestContainerId.newContainerId(36473, 4365472, ts, 844424930131965L);
    String cid3 = id3.toString();
    assertEquals(
        "container_e767_" + ts + "_36473_4365472_1099511627773", cid3);
    ContainerId gen3 = ContainerId.fromString(cid3);
    assertEquals(gen3.toString(), id3.toString());
  }

  @Test
  @SuppressWarnings("deprecation")
  public void testContainerIdNull() throws URISyntaxException {
    assertNull(ConverterUtils.toString((ContainerId)null));
  }

  @Test
  public void testNodeIdWithDefaultPort() throws URISyntaxException {
    NodeId nid;

    nid = ConverterUtils.toNodeIdWithDefaultPort("node:10");
    assertThat(nid.getPort()).isEqualTo(10);
    assertThat(nid.getHost()).isEqualTo("node");

    nid = ConverterUtils.toNodeIdWithDefaultPort("node");
    assertThat(nid.getPort()).isEqualTo(0);
    assertThat(nid.getHost()).isEqualTo("node");
  }

  @Test(expected = IllegalArgumentException.class)
  @SuppressWarnings("deprecation")
  public void testInvalidContainerId() {
    ContainerId.fromString("container_e20_1423221031460_0003_01");
  }

  @Test(expected = IllegalArgumentException.class)
  @SuppressWarnings("deprecation")
  public void testInvalidAppattemptId() {
    ConverterUtils.toApplicationAttemptId("appattempt_1423221031460");
  }

  @Test(expected = IllegalArgumentException.class)
  @SuppressWarnings("deprecation")
  public void testApplicationId() {
    ConverterUtils.toApplicationId("application_1423221031460");
  }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import { render, fireEvent } from '../../../test-utils/react-testing'
import { useTable } from '../../hooks/useTable'
import { useFilters } from '../useFilters'
import { useGlobalFilter } from '../useGlobalFilter'

const makeData = () => [
  {
    firstName: 'tanner',
    lastName: 'linsley',
    age: 29,
    visits: 100,
    status: 'In Relationship',
    progress: 50,
  },
  {
    firstName: 'derek',
    lastName: 'perkins',
    age: 40,
    visits: 40,
    status: 'Single',
    progress: 80,
  },
  {
    firstName: 'joe',
    lastName: 'bergevin',
    age: 45,
    visits: 20,
    status: 'Complicated',
    progress: 10,
  },
  {
    firstName: 'jaylen',
    lastName: 'linsley',
    age: 26,
    visits: 99,
    status: 'In Relationship',
    progress: 70,
  },
]

const defaultColumn = {
  Cell: ({ value, column: { id } }) => `${id}: ${value}`,
  Filter: ({ column: { filterValue, setFilter } }) => (
    <input
      value={filterValue || ''}
      onChange={e => {
        setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
      }}
      placeholder="Search..."
    />
  ),
}

function App(props) {
  const [data, setData] = React.useState(makeData)

  const columns = React.useMemo(() => {
    if (props.columns) {
      return props.columns
    }
    return [
      {
        Header: 'Name',
        columns: [
          {
            Header: 'First Name',
            accessor: 'firstName',
          },
          {
            Header: 'Last Name',
            accessor: 'lastName',
          },
        ],
      },
      {
        Header: 'Info',
        columns: [
          {
            Header: 'Age',
            accessor: 'age',
          },
          {
            Header: 'Visits',
            accessor: 'visits',
          },
          {
            Header: 'Status',
            accessor: 'status',
          },
          {
            Header: 'Profile Progress',
            accessor: 'progress',
          },
        ],
      },
    ]
  }, [props.columns])

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    visibleColumns,
    state,
    setGlobalFilter,
  } = useTable(
    {
      columns,
      data,
      defaultColumn,
    },
    useFilters,
    useGlobalFilter
  )

  const reset = () => setData(makeData())

  return (
    <>
      <button onClick={reset}>Reset Data</button>

          {headerGroups.map(headerGroup => (

              {headerGroup.headers.map(column => (

                  {column.render('Header')}
                  {column.canFilter ? column.render('Filter') : null}

              ))}

          ))}

                <input
                  value={state.globalFilter || ''}
                  onChange={e => {
                    setGlobalFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
                  }}
                  placeholder={`Global search...`}
                  style={{
                    fontSize: '1.1rem',
                    border: '0',
                  }}
                />

          {rows.map(
            (row, i) =>
              prepareRow(row) || (

                  {row.cells.map(cell => (
                    {cell.render('Cell')}
                  ))}

              )
          )}

    </>
  )
}

test('renders a filterable table', async () => {
  const rendered = render(<App />)

  const resetButton = rendered.getByText('Reset Data')
  const globalFilterInput = rendered.getByPlaceholderText('Global search...')
  const filterInputs = rendered.getAllByPlaceholderText('Search...')

  expect(filterInputs).toHaveLength(6)

  fireEvent.change(filterInputs[1], { target: { value: 'l' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual(['firstName: tanner', 'firstName: jaylen'])

  fireEvent.change(filterInputs[1], { target: { value: 'er' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual(['firstName: derek', 'firstName: joe'])

  fireEvent.change(filterInputs[2], { target: { value: 'nothing' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual([])

  fireEvent.change(filterInputs[1], { target: { value: '' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual([])

  fireEvent.change(filterInputs[2], { target: { value: '' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual([
    'firstName: tanner',
    'firstName: derek',
    'firstName: joe',
    'firstName: jaylen',
  ])

  fireEvent.change(globalFilterInput, { target: { value: 'li' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual(['firstName: tanner', 'firstName: joe', 'firstName: jaylen'])

  fireEvent.click(resetButton)
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual([
    'firstName: tanner',
    'firstName: derek',
    'firstName: joe',
    'firstName: jaylen',
  ])
})

test('does not filter columns marked as disableFilters', () => {
  const columns = [
    {
      Header: 'Name',
      columns: [
        {
          Header: 'First Name',
          accessor: 'firstName',
          disableFilters: true,
        },
        {
          Header: 'Last Name',
          accessor: 'lastName',
          disableFilters: true,
        },
      ],
    },
    {
      Header: 'Info',
      columns: [
        {
          Header: 'Age',
          accessor: 'age',
        },
        {
          Header: 'Visits',
          accessor: 'visits',
        },
        {
          Header: 'Status',
          accessor: 'status',
        },
        {
          Header: 'Profile Progress',
          accessor: 'progress',
        },
      ],
    },
  ]
  const rendered = render(<App columns={columns} />)

  const filterInputs = rendered.getAllByPlaceholderText('Search...')

  expect(filterInputs).toHaveLength(4)

  // should be Age column
  fireEvent.change(filterInputs[0], { target: { value: '45' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual(['firstName: joe'])

  fireEvent.change(filterInputs[0], { target: { value: '' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual([
    'firstName: tanner',
    'firstName: derek',
    'firstName: joe',
    'firstName: jaylen',
  ])
})

test('does not filter columns with GlobalFilter if marked disableGlobalFilter', () => {
  const columns = [
    {
      Header: 'Name',
      columns: [
        {
          Header: 'First Name',
          accessor: 'firstName',
          disableGlobalFilter: true,
        },
        {
          Header: 'Last Name',
          accessor: 'lastName',
          disableGlobalFilter: true,
        },
      ],
    },
    {
      Header: 'Info',
      columns: [
        {
          Header: 'Age',
          accessor: 'age',
        },
        {
          Header: 'Visits',
          accessor: 'visits',
        },
        {
          Header: 'Status',
          accessor: 'status',
        },
        {
          Header: 'Profile Progress',
          accessor: 'progress',
        },
      ],
    },
  ]
  const rendered = render(<App columns={columns} />)

  const globalFilterInput = rendered.getByPlaceholderText('Global search...')

  fireEvent.change(globalFilterInput, { target: { value: '' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual([
    'firstName: tanner',
    'firstName: derek',
    'firstName: joe',
    'firstName: jaylen',
  ])

  // global filter shouldn't apply to firstName or lastName
  fireEvent.change(globalFilterInput, { target: { value: 'li' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual(['firstName: joe'])

  // double check global filter ignore (should ignore joe bergevin)
  fireEvent.change(globalFilterInput, { target: { value: 'in' } })
  expect(
    rendered
      .queryAllByRole('row')
      .slice(3)
      .map(row => Array.from(row.children)[0].textContent)
  ).toEqual(['firstName: tanner', 'firstName: derek', 'firstName: jaylen'])
})

test('test custom filter type', () => {
  const columns = [
    {
      Header: 'Name',
      columns: [
        {
          Header: 'First Name',
          accessor: 'firstName',
          disableFilters: true,
        },
        {
          Header: 'Last Name',
          accessor: 'lastName',
          disableFilters: true,
        },
      ],
    },
    {
      Header: 'Status',
      columns: [
        {
          Header: 'In Relationship',
          id: 'inRelationship',
          accessor: ({status}) => status === 'In Relationship',
          Filter: ({column: {filterValue, setFilter}}) => {
            const onClick = () => {
              if (typeof filterValue === 'undefined') {
                setFilter(false);
              } else {
                setFilter(undefined);
              }
            }

            return <button onClick={onClick}>
              {typeof filterValue === 'undefined' ? 'Any status' : 'Single'}
            </button>

          },
          // could use 'exact' filter type, but we want to use a custom filter method for this test
          filter: function strictEquals(rows, id, filterValue) {
            return rows.filter( row => {
              const rowValue = row.values[id];
              return rowValue === filterValue;
            })
          }
        }
      ]
    }
  ]

  const rendered = render(<App columns={columns} />)

  // check button cycles through states undefined ->  false -> undefined

  const filterButton = rendered.getByText('Any status')

  fireEvent.click(filterButton, {});
  let nextButtonState = rendered.getByText('Single')
  expect(nextButtonState).toEqual(filterButton);
  expect(
      rendered
          .queryAllByRole('row')
          .slice(3)
          .map(row => Array.from(row.children)[0].textContent)
  ).toEqual([
    'firstName: derek',
    'firstName: joe',
  ])

  fireEvent.click(filterButton, {});
  nextButtonState = rendered.getByText('Any status')
  expect(nextButtonState).toEqual(filterButton);
  expect(
      rendered
          .queryAllByRole('row')
          .slice(3)
          .map(row => Array.from(row.children)[0].textContent)
  ).toEqual([
    'firstName: tanner',
    'firstName: derek',
    'firstName: joe',
    'firstName: jaylen',
  ])

})


text:
<?php

namespace Admin\Service;
class Pages
{
    protected $_pages;

    public function __construct($pages) {
        $this->_pages = $pages;
    }

    public function getPages() {
        return $this->_pages->fetchAll();
    }

    public function getPage($id) {
        return $this->_pages->getPage($id);
    }

    public function createPage($page) {
        return $this->_pages->createPage($page);
    }

    public function getPageByUrl($url) {
        return $this->_posts->getPageByUrl($url);
    }

    public function updatePage($page) {
        $result = $this->_pages->editPage($page);
        return $result;
    }
}


text:
"""Run a runner for each set of flags generated by an argfile."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import subprocess
import fire

def run(runner, argfile):
  flags = subprocess.check_output(['python', argfile])
  for flag in flags.split('\n'):
    subprocess.call(['python', runner, flag])

def main(unused_argv):
  fire.Fire(run)

if __name__ == '__main__':
  main()


text:
package com.showka.service.validator.u17;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.showka.domain.z00.Busho;
import com.showka.entity.MBushoDate;
import com.showka.repository.i.MBushoDateRepository;
import com.showka.service.validator.u17.i.BushoDateValidator;
import com.showka.system.exception.validate.CanNotUpdateOrDeleteException;
import com.showka.value.EigyoDate;

@Service
public class BushoDateValidatorImpl implements BushoDateValidator {

	@Autowired
	private MBushoDateRepository repo;

	@Override
	public void validateForClosing(Busho busho, EigyoDate today) {
		MBushoDate dateEntity = repo.getOne(busho.getRecordId());
		EigyoDate trueDate = new EigyoDate(dateEntity.getEigyoDate());
		if (!trueDate.isEqual(today)) {
			throw new CanNotUpdateOrDeleteException("すでに営業日が更新されている可能性があります(現在の営業日 : " + trueDate + ")");
		}
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
TouchClientRequest
</TITLE>

<META NAME="date" CONTENT="2009-09-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

PQSDKMultiTouch

Class TouchClientRequest

java.lang.Object
  PQSDKMultiTouch.TouchClientRequest

public class TouchClientRequest
extends java.lang.Object

represents a client request object

See Also:
PQMTClient.SendRequest(TouchClientRequest)

Field Summary

 java.util.UUID
app_id

          use PQMTClient.GetTrialAppID() for trial

 java.lang.String
param

 int
type

          type of request.

Constructor Summary

TouchClientRequest()

Method Summary

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

type

public int type

type of request. It can be a combination of values
 PQMTClientConstant.RQST_RAWDATA_INSIDE_ONLY
 PQMTClientConstant.RQST_RAWDATA_INSIDE
 PQMTClientConstant.RQST_RAWDATA_ALL
 PQMTClientConstant.RQST_GESTURE_INSIDE
 PQMTClientConstant.RQST_GESTURE_ALL

app_id

public java.util.UUID app_id

use PQMTClient.GetTrialAppID() for trial

param

public java.lang.String param

Constructor Detail

TouchClientRequest

public TouchClientRequest()

      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
class UtilityClassInner {
	static final class UtilClass {
		@java.lang.SuppressWarnings("all")
		private UtilClass() {
			throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated");
		}
	}
}


text:
using Autodesk.Revit.DB;
using RevitLookup.Views;
using Form = System.Windows.Forms.Form;

namespace RevitLookup.Core.RevitTypes;

public class TableDataSectionData : Data
{
    private readonly TableData _tableData;

    public TableDataSectionData(string label, TableData tableData) : base(label)
    {
        _tableData = tableData;
    }

    public override bool HasDrillDown => _tableData is {NumberOfSections: > 0};

    public override string AsValueString()
    {
        return "< Get Section Data >";
    }

    public override Form DrillDown()
    {
        if (!HasDrillDown) return null;

        var sectionDataObjects = new List<SnoopableWrapper>();

        foreach (SectionType type in Enum.GetValues(typeof(SectionType)))
        {
            var sectionData = _tableData.GetSectionData(type);
            if (sectionData is null) continue;
            sectionDataObjects.Add(new SnoopableWrapper(type.ToString(), sectionData));
        }

        if (sectionDataObjects.Count == 0) return null;

        var form = new ObjectsView(sectionDataObjects);
        return form;
    }
}


text:
<head>
	<meta charset="utf-8">
	<!--IE=EDGE?-->
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="google-site-verification" content="yc_wtypGWi5i3J-Eb4lyMaV1Fd85IN6X_6GbfoGBHR0" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>
		{% if page.title %} {{ page.title | append: ' | ' |append: site.name }} {% else %} {{ site.name }} {% endif %}
	</title>

	<link rel="shortcut icon" href="{{ '/styles/images/favicon.jpg' | prepend: site.baseurl }}">
	<link rel="icon" href="{{ '/styles/images/favicon.jpg' | prepend: site.baseurl }}">
	<link rel="apple-touch-icon" href="{{ '/styles/images/favicon.jpg' | prepend: site.baseurl }}">

	<link rel="stylesheet" href="{{ '/styles/css/index.css' | prepend: site.baseurl }}">
	<link rel="stylesheet" href="{{ '/styles/css/yxy_add.css' | prepend: site.baseurl }}">

	<!--<link rel="stylesheet" href="{{ '/styles/css/fontawesome/css/font-awesome.min.css' | prepend: site.baseurl }}">-->
	<link rel="stylesheet" href="https://apps.bdimg.com/libs/fontawesome/4.4.0/css/font-awesome.min.css">

	<link rel="stylesheet" href="{{ '/styles/css/syntax.css' | prepend: site.baseurl }}">
	<!--link rel=canonical 用法-->
	<link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl }}">
	<link rel="apple-touch-icon" href="{{ '/styles/images/avatar.jpg' | prepend: site.baseurl }}">
	<!--rss?-->
	<link rel="alternate" type="application/rss+xml" title="{{ site.name }}" href="{{ '/feed.xml' | prepend: site.baseurl }}">

	<meta name="keywords" content="{{ page.title | append: ', ' | append: site.name | append: ', ' | append: site.meta_description}}">
	<meta name="description" content="{{site.meta_description}}">

	<!--<script src="{{ '/styles/js/jquery.min.js' | prepend: site.baseurl }}"></script>-->
	<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

	<!--[if lt IE 9]>
    	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  	<![endif]-->

	<!--baidu_analysis-->
	<!--<script>
		var _hmt = _hmt || [];
		(function() {
		  var hm = document.createElement("script");
		  hm.src = "//hm.baidu.com/hm.js?{{ site.baidu_analysis }}";
		  var s = document.getElementsByTagName("script")[0];
		  s.parentNode.insertBefore(hm, s);
		})();
	</script>-->
	<!--
	    <script src="https://s19.cnzz.com/z_stat.php?id=1262259306&web_id=1262259306" language="JavaScript"></script>-->
	<script>
		var _hmt = _hmt || [];
		(function () {
			var hm = document.createElement("script");
			hm.src = "https://hm.baidu.com/hm.js?2ada36e5e085c2b37c9fe0070cd742bd";
			var s = document.getElementsByTagName("script")[0];
			s.parentNode.insertBefore(hm, s);
		})();
	</script>

	<style type="text/css">
		.docs-content {
			margin-bottom: 10px;
		}
	</style>
</head>


text:
export MPLBACKEND='Agg'
export R_LIBS_USER=$CONDA_PREFIX/lib/R/library/
export PYTHONNOUSERSITE=$CONDA_PREFIX/lib/python*/site-packages/


text:
package com.github.cleancattinder.imageservice.google;

import java.util.List;

public class GoogleImageSearchResponse {
    public List<GoogleImageSearchItem> items;
}


text:
package pdp.web;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import org.apache.openaz.xacml.api.Decision;
import org.apache.openaz.xacml.std.json.JSONResponse;
import org.apache.openaz.xacml.std.json.JSONStructureException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import pdp.AbstractPdpIntegrationTest;
import pdp.domain.JsonPolicyRequest;
import pdp.domain.PdpPolicy;
import pdp.domain.PdpPolicyDefinition;
import pdp.domain.PdpPolicyViolation;
import pdp.policies.PolicyLoader;
import pdp.teams.VootClientConfig;
import pdp.xacml.PolicyTemplateEngine;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static pdp.util.StreamUtils.singletonCollector;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles({"dev", "no-csrf"})
public class PdpControllerShibbolethIntegrationTest extends AbstractPdpIntegrationTest {

    private static final ParameterizedTypeReference<List<PdpPolicyDefinition>> pdpPolicyDefinitionsType = new ParameterizedTypeReference<>() {
    };

    private final TestRestTemplate restTemplate = new TestRestTemplate();

    @Before
    public void before() throws IOException {
        super.before();
        addShibHeaders();
    }

    @Test
    public void testPolicyDefinitionsImpersonated() {
        impersonate(PolicyLoader.authenticatingAuthority, VootClientConfig.URN_COLLAB_PERSON_EXAMPLE_COM_ADMIN, "John Doe");

        List<PdpPolicyDefinition> definitions = getForObject("/internal/policies", pdpPolicyDefinitionsType);

        assertEquals(2, definitions.size());
    }

    @Test
    public void testInternalDecide() throws IOException, JSONStructureException {
        ResponseEntity<String> response = post("/internal/decide/policy", getJsonPolicyRequest());

        assertEquals(Decision.NOTAPPLICABLE, JSONResponse.load(response.getBody()).getResults().stream().collect(singletonCollector()).getDecision());
    }

    @Test
    public void testPolicyDefinitionsAdmin() {
        List<PdpPolicyDefinition> definitions = getForObject("/internal/policies", pdpPolicyDefinitionsType);

        assertThat(definitions, hasSize(greaterThan(2)));
    }

    @Test
    public void testPolicyDefinitionsByServiceProvider() {
        List<PdpPolicyDefinition> definitions = getForObject("/internal/policies/sp?serviceProvider=http://mock-sp", pdpPolicyDefinitionsType);

        assertThat(definitions, hasSize(1));
    }

    @Test
    public void testViolations() {
        setUpViolation(policyId);
        setUpViolation(policyId);
        List<PdpPolicyViolation> violations = getForObject("/internal/violations", new ParameterizedTypeReference<List<PdpPolicyViolation>>() {
        });

        assertViolations(violations, 2);
    }

    @Test
    public void testViolationsByPolicyId() {
        Long policyId = setUpViolation(PdpControllerShibbolethIntegrationTest.policyId).getId();
        List<PdpPolicyViolation> violations = getForObject("/internal/violations/" + policyId, new ParameterizedTypeReference<List<PdpPolicyViolation>>() {
        });

        assertViolations(violations, 1);
    }

    @Test
    public void findPolicyById() {
        PdpPolicy policy = getExistingPolicy();
        PdpPolicyDefinition definition = getForObject("/internal/policies/" + policy.getId(), new ParameterizedTypeReference<PdpPolicyDefinition>() {
        });

        assertNotNull(definition.getId());
    }

    @Test
    public void testRevisionsByPolicyIdWithExistingPolicy() {
        //we use the API to set up the revisions
        PdpPolicy policy = getExistingPolicy();
        PdpPolicyDefinition policyDefinition = pdpPolicyDefinitionParser.parse(policy);
        String initialDenyAdvice = policyDefinition.getDenyAdvice();
        policyDefinition.setDenyAdvice("advice_changed");
        Map<String, Object> map = objectMapper.convertValue(policyDefinition, new TypeReference<>() {
        });
        map.put("unknown", "value");
        assertThat(post("/internal/policies", map).getStatusCode(), is(HttpStatus.OK));

        policyDefinition.setDenyAdvice("advice_changed_again");
        assertThat(post("/internal/policies", policyDefinition).getStatusCode(), is(HttpStatus.OK));

        List<PdpPolicyDefinition> definitions = getForObject("/internal/revisions/" + policy.getId(), pdpPolicyDefinitionsType);

        assertThat(definitions, hasSize(3));
        assertEquals(initialDenyAdvice, findByRevisionNbr(definitions, 0).getDenyAdvice());
        assertEquals("advice_changed", findByRevisionNbr(definitions, 1).getDenyAdvice());
        assertEquals("advice_changed_again", findByRevisionNbr(definitions, 2).getDenyAdvice());

        PdpPolicy newRevision = getExistingPolicy();
        assertEquals("advice_changed_again", pdpPolicyDefinitionParser.parse(newRevision).getDenyAdvice());
    }

    @Test
    public void testRevisionsByPolicyIdWithNewPolicy() {
        PdpPolicy policy = getExistingPolicy();
        PdpPolicyDefinition policyDefinition = pdpPolicyDefinitionParser.parse(policy);

        // this will ensure a new policy is created
        policyDefinition.setId(null);
        policyDefinition.setName("some name");

        assertThat(post("/internal/policies", policyDefinition).getStatusCode(), is(HttpStatus.OK));

        PdpPolicy saved = pdpPolicyRepository.findFirstByPolicyIdAndLatestRevision(
                PolicyTemplateEngine.getPolicyId(policyDefinition.getName()), true).get();

        List<PdpPolicyDefinition> definitions = getForObject("/internal/revisions/" + saved.getId(), pdpPolicyDefinitionsType);

        assertThat(definitions, hasSize(1));
        assertEquals(policyDefinition.getName(), definitions.get(0).getName());
    }

    @Test
    public void testDefaultPolicy() {
        PdpPolicyDefinition definition = getForObject("/internal/default-policy", new ParameterizedTypeReference<>() {
        });

        assertFalse(definition.isAllAttributesMustMatch());
        assertFalse(definition.isDenyRule());
    }

    @Test
    public void testAllowedAttributes() {
        List<JsonPolicyRequest.Attribute> allowedAttributes = getForObject("/internal/attributes", new ParameterizedTypeReference<>() {
        });

        assertThat(allowedAttributes, hasSize(9));
        assertAttributes(allowedAttributes);
    }

    @Test
    public void testAllowedSamlAttributes() {
        List<JsonPolicyRequest.Attribute> samlAttributes = getForObject("/internal/saml-attributes", new ParameterizedTypeReference<List<JsonPolicyRequest.Attribute>>() {
        });

        assertThat(samlAttributes, hasSize(11));

        JsonPolicyRequest.Attribute nameId = samlAttributes.get(0);

        assertEquals("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified", nameId.attributeId);
        assertNotNull(nameId.value);
        assertAttributes(samlAttributes);
    }

    @Test
    public void testDeletePdpPolicy() {
        // verify that violations are also deleted - so we create one
        setUpViolation(policyIdToDelete);

        PdpPolicy policy = getExistingPolicy(policyIdToDelete);
        PdpPolicyDefinition policyDefinition = pdpPolicyDefinitionParser.parse(policy);

        // verify that revisions are also deleted - so we create one
        assertThat(post("/internal/policies", policyDefinition).getStatusCode(), is(HttpStatus.OK));

        PdpPolicy latestRevision = getExistingPolicy(policyIdToDelete);

        assertThat(delete("/internal/policies/" + latestRevision.getId()).getStatusCode(), is(HttpStatus.OK));

        List<PdpPolicyViolation> violations = getForObject("/internal/violations", new ParameterizedTypeReference<List<PdpPolicyViolation>>() {
        });
        assertViolations(violations, 0);
        assertPolicyIsDeleted(policy);
        assertPolicyIsDeleted(latestRevision);
    }

    @Test
    public void testUser() {
        Map<String, Object> shibbolethUser = getForObject("/internal/users/me", new ParameterizedTypeReference<Map<String, Object>>() {
        });

        assertEquals("urn:collab:person:example.com:admin", shibbolethUser.get("username"));
        assertEquals("John Doe", shibbolethUser.get("displayName"));
        assertEquals(PolicyLoader.authenticatingAuthority, shibbolethUser.get("authenticatingAuthority"));

        assertEquals(1, ((Collection) shibbolethUser.get("idpEntities")).size());
        assertEquals(1, ((Collection) shibbolethUser.get("spEntities")).size());
    }

    @Test
    public void testCreatePolicyWithNameError() throws JsonParseException, JsonMappingException, IOException {
        PdpPolicyDefinition policyDefinition = pdpPolicyDefinitionParser.parse(getExistingPolicy());
        policyDefinition.setId(null);

        ResponseEntity<String> response = post("/internal/policies", policyDefinition);

        assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());

        Map<String, Object> map = objectMapper.readValue(response.getBody(), new TypeReference<Map<String, Object>>() {
        });
        String message = (String) ((Map<?, ?>) map.get("details")).get("name");

        assertTrue(message.contains("Policy name must be unique"));
    }

    @Test
    public void testAssertBadRequestUnknownIdentityProvider() {
        PdpPolicyDefinition policyDefinition = getPdpPolicyDefinitionFromExistingPolicy();

        impersonate("http://xxx-idp", "urn:collab:person:example.com:mary.doe", "Mary Doe");

        ResponseEntity<String> post = post("/internal/policies", policyDefinition);

        assertEquals(HttpStatus.BAD_REQUEST, post.getStatusCode());
        assertTrue(post.getBody().contains("http://xxx-idp is not a valid or known IdP / SP entityId"));
    }

    @Test
    public void testConflicts() {
        ResponseEntity<String> response = get("/internal/conflicts");

        assertNotNull(response.getBody());
    }

    @Override
    public TestRestTemplate getRestTemplate() {
        return restTemplate;
    }

    private PdpPolicyDefinition findByRevisionNbr(List<PdpPolicyDefinition> definitions, int revisionNbr) {
        return definitions.stream().filter(def -> def.getRevisionNbr() == revisionNbr).collect(singletonCollector());
    }

    private void assertViolations(List<PdpPolicyViolation> violations, int expectedSize) {
        assertThat(violations, hasSize(expectedSize));
        violations.forEach(v -> assertNotNull(v.getCreated()));
    }

    private void assertAttributes(List<JsonPolicyRequest.Attribute> allowedAttributes) {
        allowedAttributes.forEach(attr -> {
            assertTrue(attr.attributeId.startsWith("urn"));
            assertNotNull(attr.value);
        });
    }

}


text:
package edu.rutgers.css.Rutgers.channels.bus.model;

import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.nhaarman.listviewanimations.itemmanipulation.expandablelistitem.ExpandableListItemAdapter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import edu.rutgers.css.Rutgers.R;
import edu.rutgers.css.Rutgers.api.bus.model.Prediction;

/**
 * Bus arrival time predictions adapter.
 */
public class PredictionAdapter extends ExpandableListItemAdapter<Prediction> {

    private static final String TAG = "PredictionAdapter";

    private static final SimpleDateFormat arriveDf12 = new SimpleDateFormat("h:mm a", Locale.US);
    private static final SimpleDateFormat arriveDf24 = new SimpleDateFormat("H:mm", Locale.US);
    private static final Calendar cal = Calendar.getInstance(Locale.US);

    private Context mContext;

    private final Handler handler = new Handler();

    static class ViewHolder {
        TextView titleTextView;
        TextView directionTextView;
        TextView minutesTextView;
    }

    static class PopViewHolder {
        TextView popdownTextView;
    }

    public PredictionAdapter(Context context, List<Prediction> objects) {
        super(context, R.layout.row_bus_prediction, R.id.titleFrame, R.id.contentFrame, objects);
        mContext = context;
    }

    @Override
    public boolean areAllItemsEnabled() {
        return false;
    }

    @Override
    public boolean isEnabled(int position) {
        if (position < 0 || position >= getCount()) {
            return false;
        }
        Prediction prediction = this.getItem(position);
        return !(prediction.getMinutes()).isEmpty();
    }

    @NonNull
    @Override
    public View getTitleView(final int position, @Nullable View convertView, @NonNull ViewGroup viewGroup) {
        LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ViewHolder holder;

        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.row_bus_prediction_title, null);
            holder = new ViewHolder();
            holder.titleTextView = (TextView) convertView.findViewById(R.id.title);
            holder.directionTextView = (TextView) convertView.findViewById(R.id.direction);
            holder.minutesTextView = (TextView) convertView.findViewById(R.id.minutes);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Prediction prediction = this.getItem(position);
        Resources res = mContext.getResources();

        // Set title
        holder.titleTextView.setText(prediction.getTitle());

        // Set prediction minutes
        if (!prediction.getMinutes().isEmpty()) {
            // Reset title color to default
            holder.titleTextView.setTextColor(res.getColor(R.color.black));
            holder.directionTextView.setTextColor(res.getColor(R.color.black));

            // Change color of text based on how much time is remaining before the first bus arrives
            int first = prediction.getMinutes().get(0);

            if (first < 2) {
                holder.minutesTextView.setTextColor(res.getColor(R.color.bus_soonest));
            } else if (first < 6) {
                holder.minutesTextView.setTextColor(res.getColor(R.color.bus_soon));
            } else {
                holder.minutesTextView.setTextColor(res.getColor(R.color.bus_later));
            }

            holder.minutesTextView.setText(formatMinutes(prediction.getMinutes()));
        } else {
            // No predictions loaded - gray out all text
            holder.titleTextView.setTextColor(res.getColor(R.color.light_gray));
            holder.minutesTextView.setTextColor(res.getColor(R.color.light_gray));
            holder.minutesTextView.setText(R.string.bus_no_predictions);
        }

        // Set direction
        if (prediction.getDirection() == null || prediction.getDirection().isEmpty()) {
            // If there's no direction string, don't let that text field take up space
            holder.directionTextView.setVisibility(View.GONE);
        } else {
            holder.directionTextView.setText(prediction.getDirection());
            holder.directionTextView.setVisibility(View.VISIBLE);
        }

        return convertView;
    }

    @NonNull
    @Override
    public View getContentView(final int position, @Nullable View convertView, @NonNull ViewGroup viewGroup) {
        LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        PopViewHolder holder;

        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.popdown, null);
            holder = new PopViewHolder();
            holder.popdownTextView = (TextView) convertView.findViewById(R.id.popdownTextView);
            convertView.setTag(holder);
        } else {
            holder = (PopViewHolder) convertView.getTag();
        }

        Prediction prediction = getItem(position);

        // Set prediction minutes
        if (!prediction.getMinutes().isEmpty()) {
            // Set pop-down contents
            holder.popdownTextView.setText(formatMinutesDetails(prediction.getMinutes()));
            holder.popdownTextView.setGravity(Gravity.RIGHT);
        } else {
            // No predictions loaded
            holder.popdownTextView.setText("");
        }

        return convertView;
    }

    public void setPredictions(final List<Prediction> predictions) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                clear();
                addAll(predictions);
            }
        });
    }

    /**
     * Create "Arriving in..." string, e.g.

     *      Arriving in 2 minutes.

     *         Arriving in 2 and 4 minutes.

     *         Arriving in 2, 3, and 4 minutes.

     *         Arriving in 1 minute.

     * @param minutes Array of arrival times in minutes
     * @return Formatted arrival time string
     */
    private String formatMinutes(List<Integer> minutes) {
        Resources resources = mContext.getResources();
        StringBuilder result = new StringBuilder(resources.getString(R.string.bus_prediction_begin));

        for (int i = 0; i < minutes.size(); i++) {
            if (i != 0 && i == minutes.size() - 1) result.append(resources.getString(R.string.bus_and));

            if (minutes.get(i) < 1) result.append(" <1");
            else result.append(" ").append(minutes.get(i));

            if (minutes.size() > 2 && i != minutes.size() - 1) result.append(",");
        }

        if (minutes.size() == 1 && minutes.get(0) == 1) result.append(resources.getString(R.string.bus_minute_singular));
        else result.append(resources.getString(R.string.bus_minute_plural));

        return result.toString();
    }

    /**
     * Create pop-down details string

     * e.g. 10 minutes at 12:30
     * @param minutes Array of arrival times in minutes
     * @return Formatted and stylized arrival time details string
     */
    private CharSequence formatMinutesDetails(List<Integer> minutes) {
        Resources resources = mContext.getResources();
        SpannableStringBuilder result = new SpannableStringBuilder();

        for (int i = 0; i < minutes.size(); i++) {
            // Hack so that it displays "<1 minute" instead of "0 minutes"
            int mins = minutes.get(i) == 0 ? 1 : minutes.get(i);
            String minString = minutes.get(i) < 1 ? "<1" : Integer.toString(mins);

            // Determine bus arrival time
            Date date = new Date();
            cal.setTime(date);
            cal.add(Calendar.MINUTE, minutes.get(i));
            String arrivalTime = android.text.format.DateFormat.is24HourFormat(mContext) ?
                    PredictionAdapter.arriveDf24.format(cal.getTime()) :
                    PredictionAdapter.arriveDf12.format(cal.getTime());

            // Get appropriate string & format, stylize
            String line = resources.getQuantityString(R.plurals.bus_minute_details, mins, minString, arrivalTime);
            CharSequence styledLine = Html.fromHtml(line);
            result.append(styledLine);
            if (i != minutes.size() - 1) result.append("\n");
        }

        return result;
    }

}


text:
dojo.provide("dojo.lang.func");

dojo.require("dojo.lang.common");

/**
 * Runs a function in a given scope (thisObject), can
 * also be used to preserve scope.
 *
 * hitch(foo, "bar"); // runs foo.bar() in the scope of foo
 * hitch(foo, myFunction); // runs myFunction in the scope of foo
 */
dojo.lang.hitch = function(thisObject, method){
	var fcn = (dojo.lang.isString(method) ? thisObject[method] : method) || function(){};

	return function() {
		return fcn.apply(thisObject, arguments);
	};
}

dojo.lang.anonCtr = 0;
dojo.lang.anon = {};
dojo.lang.nameAnonFunc = function(anonFuncPtr, namespaceObj, searchForNames){
	var nso = (namespaceObj || dojo.lang.anon);
	if( (searchForNames) ||
		((dj_global["djConfig"])&&(djConfig["slowAnonFuncLookups"] == true)) ){
		for(var x in nso){
			try{
				if(nso[x] === anonFuncPtr){
					return x;
				}
			}catch(e){} // window.external fails in IE embedded in Eclipse (Eclipse bug #151165)
		}
	}
	var ret = "__"+dojo.lang.anonCtr++;
	while(typeof nso[ret] != "undefined"){
		ret = "__"+dojo.lang.anonCtr++;
	}
	nso[ret] = anonFuncPtr;
	return ret;
}

dojo.lang.forward = function(funcName){
	// Returns a function that forwards a method call to this.func(...)
	return function(){
		return this[funcName].apply(this, arguments);
	};
}

dojo.lang.curry = function(ns, func /* args ... */){
	var outerArgs = [];
	ns = ns||dj_global;
	if(dojo.lang.isString(func)){
		func = ns[func];
	}
	for(var x=2; x<arguments.length; x++){
		outerArgs.push(arguments[x]);
	}
	// since the event system replaces the original function with a new
	// join-point runner with an arity of 0, we check to see if it's left us
	// any clues about the original arity in lieu of the function's actual
	// length property
	var ecount = (func["__preJoinArity"]||func.length) - outerArgs.length;
	// borrowed from svend tofte
	function gather(nextArgs, innerArgs, expected){
		var texpected = expected;
		var totalArgs = innerArgs.slice(0); // copy
		for(var x=0; x<nextArgs.length; x++){
			totalArgs.push(nextArgs[x]);
		}
		// check the list of provided nextArgs to see if it, plus the
		// number of innerArgs already supplied, meets the total
		// expected.
		expected = expected-nextArgs.length;
		if(expected<=0){
			var res = func.apply(ns, totalArgs);
			expected = texpected;
			return res;
		}else{
			return function(){
				return gather(arguments,// check to see if we've been run
										// with enough args
							totalArgs,	// a copy
							expected);	// how many more do we need to run?;
			};
		}
	}
	return gather([], outerArgs, ecount);
}

dojo.lang.curryArguments = function(ns, func, args, offset){
	var targs = [];
	var x = offset||0;
	for(x=offset; x<args.length; x++){
		targs.push(args[x]); // ensure that it's an arr
	}
	return dojo.lang.curry.apply(dojo.lang, [ns, func].concat(targs));
}

dojo.lang.tryThese = function(){
	for(var x=0; x<arguments.length; x++){
		try{
			if(typeof arguments[x] == "function"){
				var ret = (arguments[x]());
				if(ret){
					return ret;
				}
			}
		}catch(e){
			dojo.debug(e);
		}
	}
}

dojo.lang.delayThese = function(farr, cb, delay, onend){
	/**
	 * alternate: (array funcArray, function callback, function onend)
	 * alternate: (array funcArray, function callback)
	 * alternate: (array funcArray)
	 */
	if(!farr.length){
		if(typeof onend == "function"){
			onend();
		}
		return;
	}
	if((typeof delay == "undefined")&&(typeof cb == "number")){
		delay = cb;
		cb = function(){};
	}else if(!cb){
		cb = function(){};
		if(!delay){ delay = 0; }
	}
	setTimeout(function(){
		(farr.shift())();
		cb();
		dojo.lang.delayThese(farr, cb, delay, onend);
	}, delay);
}


text:
#ifndef _VC_HDCP2_RX_SERVICE_H_
#define _VC_HDCP2_RX_SERVICE_H_

#include "vcinclude/common.h"
#include "interface/vcos/vcos.h"
#include "interface/vchi/vchi.h"
#include "interface/vmcs_host/vc_hdcp2service_defs.h"

/**
 * \file
 *
 * This API defines the Rx host side HDCP2 service.
 * Define ENABLE_HDCP2_LOOPBACK_TEST in HDCP2 Tx/Rx services/state machine
 * to test HDCP2 local loopback. The API is much more simpler than Tx because
 * Rx is passive.
 */

/**
 * <DFN>vc_vchi_hdcp2_rx_init</DFN> is called at the beginning of the application
 * to initialise the client to Rx side HDCP2 service
 *
 * @param initialise_instance is the VCHI instance [in]
 *
 * @param connections is the array of pointers of connections [in]
 *
 * @param num_connections is the length of the array [in]
 *
 * @return void
 */
VCHPRE_ void VCHPOST_ vc_vchi_hdcp2_rx_init(VCHI_INSTANCE_T initialise_instance, VCHI_CONNECTION_T **connections, uint32_t num_connections );

/**
 * <DFN>vc_vchi_hdcp2_rx_stop</DNF> stops the Rx host side HDCP2 service
 *
 * @param none
 *
 * @return void
 */
VCHPRE_ void VCHPOST_ vc_vchi_hdcp2_rx_stop( void );

/**
 * Host applications must call <DFN>vc_hdcp2_rx_register_callback</DNF> at
 * the beginning to register a function to handle all outgoing message
 * from HDCP2 Rx state machine. Note that notifications from
 * state machine also come in the form of outgoing message, so you have
 * to look at the message type.
 *
 * @param callback function [in]
 *
 * @param callback_data is the context to be passed when function is called [in]
 *
 * @return void
 */
VCHPRE_ void VCHPOST_ vc_hdcp2_rx_register_callback(HDCP2SERVICE_CALLBACK_T callback, void *callback_data);

/**
 * Use <DFN>vc_hdcp2_rx_send_message</DFN> to send message [from Tx] to
 * HDCP2 Rx state machine. You should only use this to send genuine
 * HDCP2 message. Use <DFN>vc_hdcp2_rx_send_loopback_message</DFN> to
 * send loopback test data.
 *
 * @param buffer is the message buffer [in]
 *
 * @param buffer_size is the size [in]
 *
 * @return zero if message is successfully transmitted, non-zero otherwise
 */
VCHPRE_ int VCHPOST_ vc_hdcp2_rx_send_message(const void *buffer, uint32_t buffer_size);

/**
 * Use <DFN>vc_hdcp2_rx_send_loopback_message</DFN> to send loopback message
 * [from Tx] to HDCP2 Rx service. This message does NOT travel to
 * HDCP2 Rx state machine. This function is only available if you are running loopback
 * test.
 *
 * @param streamCtr is the stream counter (NOT the stream id) [in]
 *
 * @param inputCtr is the input counter (big endian) [in]
 *
 * @param encrypted_buffer is the encrypted buffer [in]
 *
 * @param buffer_size if the length of encrypted buffer [in]
 *
 * @param plaintext_buffer is the expected data (same size as encrypted buffer) [in]
 *
 * @param last_packet is non-zero if this is the last packet [in], which will
 *        terminate the loopback test.
 *
 * @return 1 if message is decrypted successfully, 0 if decrypt failed
 *         -1 if message failed to be sent to Videocore
 */
#ifdef ENABLE_HDCP2_LOOPBACK_TEST
VCHPRE_ int VCHPOST_ vc_hdcp2_rx_send_loopback_message(uint32_t streamCtr, uint64_t inputCtr,
                                                       const uint8_t *encrypted_buffer,
                                                       uint32_t buffer_size,
                                                       const uint8_t *plaintext_buffer,
                                                       uint32_t last_packet);
#endif

/**
 * <DFN>vc_hdcp2_rx_is_authenticated</DFN> returns whether there is
 * currently an authenticated link or not. Note that the result here does
 * not necessarily agree with the result from <DFN>vc_hdcp2_tx_is_authenticated</DFN>
 * because Rx is passive in the context of authentication.
 *
 * @param pointer to auth [in], non-zero if the link is authenticated, zero otherwise
 *
 * @return zero if the command is sent successfully, auth is also set to zero if
 *         command failed
 *
 */
VCHPRE_ int VCHPOST_ vc_hdcp2_rx_is_authenticated(uint32_t *auth);
#endif


text:
class Test {
    public final int anInt = Integer.parseInt("");

    void foo() {int i = anInt;}
}


text:
namespace sandbox {

namespace syscall_broker {

class BrokerClient;

// Create a new "broker" process to which we can send requests via an IPC
// channel by forking the current process.
// This is a low level IPC mechanism that is suitable to be called from a
// signal handler.
// A process would typically create a broker process before entering
// sandboxing.
// 1. BrokerProcess open_broker(read_allowlist, write_allowlist);
// 2. CHECK(open_broker.Init(NULL));
// 3. Enable sandbox.
// 4. Use open_broker.Open() to open files.
class SANDBOX_EXPORT BrokerProcess {
 public:
  enum class BrokerType { SIGNAL_BASED };

  using BrokerSideCallback =
      base::OnceCallback<bool(const BrokerSandboxConfig&)>;

  // |policy| is the policy for the broker process.
  //
  // |denied_errno| is the error code returned when methods such as Open() or
  // Access() are invoked on a file which is not in the allowlist (EACCESS would
  // be a typical value).
  //
  // |fast_check_in_client| controls whether requests are
  // first filtered on the client side before being proxied. Apart from tests,
  // this should always be true since our main clients are not always
  // well-behaved. They may have third party libraries that don't know about
  // sandboxing, and typically try to open all sorts of stuff they don't really
  // need. It's important to reduce this load given that there is only one
  // pipeline to the broker process, and it is not multi-threaded.
  //
  // |quiet_failures_for_tests| is reserved for unit tests, don't use it.
  BrokerProcess(absl::optional<BrokerSandboxConfig> policy,
                BrokerType broker_type,
                bool fast_check_in_client = true,
                bool quiet_failures_for_tests = false);

  BrokerProcess(const BrokerProcess&) = delete;
  BrokerProcess& operator=(const BrokerProcess&) = delete;

  ~BrokerProcess();

  // Will initialize the broker process. There should be no threads at this
  // point, since we need to fork().
  // broker_process_init_callback will be called in the new broker process,
  // after fork() returns.
  bool Fork(BrokerSideCallback broker_process_init_callback);

  // Return the PID of the child created by Fork().
  int broker_pid() const { return broker_pid_; }

  // Can be used in bpf_dsl::Policy::EvaluateSyscall() implementations to
  // determine if the system call |sysno| should be trapped and forwarded
  // to the broker process for handling. This examines the
  // |policy_->allowed_command_set| iff |fast_check_in_client_| is true. If
  // the fast checks are disabled, then all possible brokerable system
  // calls are forwarded to the broker process for handling.
  bool IsSyscallAllowed(int sysno) const;

  // Gets the signal-based BrokerClient created by Fork().
  syscall_broker::BrokerClient* GetBrokerClientSignalBased() const {
    return broker_client_.get();
  }

 private:
  friend class BrokerProcessTestHelper;
  friend class HandleFilesystemViaBrokerPolicy;

  // IsSyscallBrokerable() answers the same question as IsSyscallAllowed(),
  // but takes |fast_check| as a parameter. If |fast_check| is false, do not
  // check |policy_->allowed_command_set| before returning true for a syscall
  // that is brokerable.
  bool IsSyscallBrokerable(int sysno, bool fast_check) const;

  // Close the IPC channel with the other party. This should only be used
  // by tests and none of the class methods should be used afterwards.
  void CloseChannel();

  // Forks the signal-based broker, where syscall emulation is performed using
  // signals in the sandboxed process that connect to the broker via Unix
  // socket.
  bool ForkSignalBasedBroker(BrokerSideCallback broker_process_init_callback);

  // Variables initialized by the constructor.
  absl::optional<BrokerSandboxConfig>
      policy_;  // Can also be created by SendPolicy().
  const BrokerType broker_type_;
  const bool fast_check_in_client_;
  const bool quiet_failures_for_tests_;

  bool initialized_ = false;  // Whether we've been through Fork() yet.
  pid_t broker_pid_ = -1;  // The PID of the broker (child) created in Fork().

  // Created in the parent process.
  std::unique_ptr<syscall_broker::BrokerClient> broker_client_;
};

}  // namespace syscall_broker

}  // namespace sandbox

#endif  // SANDBOX_LINUX_SYSCALL_BROKER_BROKER_PROCESS_H_


text:
  Balot est
       un village
       géographiquement positionné dans le département de Côte-d'Or en Bourgogne. Elle comptait 91 habitants en 2008.

Le nombre d'habitations, à Balot, se décomposait en 2011 en zero appartements et 60 maisons soit
 un marché plutôt équilibré.

À coté de Balot sont localisées les villes de
Nesle-et-Massoult localisée à 4 km, 89 habitants,
Fontaines-les-Sèches à 6 km, 42 habitants,
Larrey à 7 km, 92 habitants,
Cérilly à 7 km, 246 habitants,
Poinçon-lès-Larrey localisée à 7 km, 200 habitants,
Montmain localisée à 6 km, 91 habitants,
 entre autres. De plus, Balot est située à seulement onze km de Châtillon-sur-Seine.

Si vous pensez venir habiter à Balot, vous pourrez facilement trouver une maison à acheter.