text:
package com.navercorp.pinpoint.bootstrap.plugin.reactor;

import com.navercorp.pinpoint.bootstrap.context.AsyncContext;
import com.navercorp.pinpoint.common.util.ArrayUtils;

public final class ReactorContextAccessorUtils {

    public static AsyncContext getAsyncContext(Object[] array, int index) {
        if (!ArrayUtils.isArrayIndexValid(array, index)) {
            return null;
        }
        return getAsyncContext(array[index]);
    }

    public static AsyncContext getAsyncContext(Object object) {
        if (object instanceof ReactorContextAccessor) {
            return ((ReactorContextAccessor) object)._$PINPOINT$_getReactorContext();
        }
        return null;
    }

    public static void setAsyncContext(final AsyncContext asyncContext, final Object object) {
        if (object instanceof ReactorContextAccessor) {
            final AsyncContext argAsyncContext = ReactorContextAccessorUtils.getAsyncContext(object);
            if (argAsyncContext == null) {
                ((ReactorContextAccessor) object)._$PINPOINT$_setReactorContext(asyncContext);
            }
        }
    }

    public static void setAsyncContext(final AsyncContext asyncContext, final Object[] array, int index) {
        if (!ArrayUtils.isArrayIndexValid(array, index)) {
            return;
        }
        setAsyncContext(asyncContext, array[index]);
    }

    public static AsyncContext findAsyncContext(Object[] array, int beginIndex) {
        if (array == null || array.length == 0) {
            return null;
        }
        final int endIndex = array.length - 1;
        return findAsyncContext(array, beginIndex, endIndex);
    }

    public static AsyncContext findAsyncContext(Object[] array, int beginIndex, int endIndex) {
        if (array == null || array.length == 0) {
            return null;
        }
        final int length = array.length - 1;
        if (beginIndex < 0 || beginIndex > endIndex || endIndex > length) {
            return null;
        }
        for (int i = beginIndex; i <= endIndex; i++) {
            if (array[i] instanceof Object[]) {
                final Object[] objects = (Object[]) array[i];
                for (Object object : objects) {
                    final AsyncContext asyncContext = ReactorContextAccessorUtils.getAsyncContext(object);
                    if (asyncContext != null) {
                        return asyncContext;
                    }
                }
            } else {
                final AsyncContext asyncContext = ReactorContextAccessorUtils.getAsyncContext(array[i]);
                if (asyncContext != null) {
                    return asyncContext;
                }
            }
        }
        return null;
    }
}


text:
#include <stdlib.h>

#include <exception>
#include <iostream>

#include <isl/options.h>
#include <isl/cpp-checked.h>

/* Select the "checked" interface.
 */
namespace isl { using namespace checked; }

/* Print an error message and abort.
 */
static void die_impl(const char *file, int line, const char *message)
{
	std::cerr << file << ":" << line << ": " << message << "\n";
	exit(EXIT_FAILURE);
}

#define die(msg) die_impl(__FILE__, __LINE__, msg)

#include "isl_test_cpp17-generic.cc"

/* Test the C++17 specific features of the isl checked C++ interface
 *
 * In particular, test
 *  - id::try_user
 */
int main()
{
	isl_ctx *ctx = isl_ctx_alloc();

	isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);

	test_try_user(ctx);

	isl_ctx_free(ctx);

	return EXIT_SUCCESS;
}

redpajama_set_name: RedPajamaGithub


text:
title: NuGet Warning NU5501
description: NU5501 Warning code
author: zkat
ms.author: kmarchan
ms.date: 10/6/2020
ms.topic: reference
ms.reviewer: TBD
f1_keywords:
  - NU5501
---

# NuGet Warning NU5501

## Scenario 1

The following dependency group(s) require(s) dots in the framework version: net50-windows7.0

### Issue

The dependency group framework must included dots in their framework version number. This is required for frameworks newer than `net5.0`.

This issue generally occurs when a nuspec is authored manually, like for example:

```xml
  <metadata>
      <dependencies>
          <group targetFramework="net50-windows7.0">
              <dependency id=""Dependency"" version=""1.0.0"" />
          </group>
      </dependencies>
  </metadata>
```

### Solution

Change `net50` to `net5.0`.

```xml
  <metadata>
      <dependencies>
          <group targetFramework="net5.0-windows7.0">
              <dependency id=""Dependency"" version=""1.0.0"" />
          </group>
      </dependencies>
  </metadata>
```

## Scenario 2

The following packaged file folder(s) require(s) dots in the framework version: contentFiles/any/net50/a.img.

### Issue

The folders denoting a framework must included dots in their framework version number. This is required for frameworks newer than `net5.0`.

This issue generally occurs when manually adding items to a package, using something like the following in your `.csproj`:

```xml
<ItemGroup>
  <None Include="a.img" Pack="true" PackagePath="contentFiles/any/net50" />
</ItemGroup>
```

or a nuspec:

```xml
  <files>
    <file src="resources/a.img" target="contentFiles/any/net50" />
  </files>
```

### Solution

Change `net50` to `net5.0`.

```xml
<ItemGroup>
  <None Include="a.img" Pack="true" PackagePath="contentFiles/any/net5.0" />
</ItemGroup>
```

or the nuspec:

```xml
  <files>
    <file src="resources/a.img" target="contentFiles/any/net5.0" />
  </files>
```


text:
import fetch from '../../util/fetchWrapper';
import { error } from '../media/MediaActions';

export function force() {
  return {
    type: 'DECORATION_FORCE',
    force: true,
  };
}

export function changeSearch(search) {
  return {
    type: 'DECORATION_SEARCH',
    search,
  };
}

export function changePage(page) {
  return {
    type: 'DECORATION_PAGE',
    page,
  };
}

export function request() {
  return { type: 'DECORATION_REQUEST' };
}

export function receive(pages, items) {
  return {
    type: 'DECORATION_RECEIVE',
    pages,
    items,
  };
}

export function fetchTmdb(search, page) {
  return (dispatch, getState) => {
    const isFetching = getState().decoration.isFetching;
    if (isFetching) {
      return Promise.resolve();
    }
    if (!search) {
      return Promise.resolve();
    }

    dispatch(request());

    const query = {
      page: {
        number: page,
      },
      filter: {
        search: search || undefined,
      },
    };
    if (search) {
      query.filter.search = search;
    }

    return fetch('/api/tmdb', query)
      .then(response => {
        if (response.error) {
          return Promise.reject(new Error(response.error.title));
        }

        return dispatch(receive(response.meta['total-pages'], response.data));
      })
      .catch(err => dispatch(error(err)));
  };
}

export function choose(chosen) {
  return {
    type: 'DECORATION_CHOOSE',
    chosen,
  };
}

export function confirm() {
  return { type: 'DECORATION_CONFIRM' };
}

export function cancel() {
  return { type: 'DECORATION_CANCEL' };
}


text:
package com.egzosn.pay.baidu.api;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.egzosn.pay.baidu.bean.BaiduBillType;
import com.egzosn.pay.baidu.bean.BaiduPayOrder;
import com.egzosn.pay.baidu.bean.BaiduTransactionType;
import com.egzosn.pay.baidu.bean.type.AuditStatus;
import com.egzosn.pay.baidu.util.Asserts;
import com.egzosn.pay.common.api.BasePayService;
import com.egzosn.pay.common.bean.AssistOrder;
import com.egzosn.pay.common.bean.BaseRefundResult;
import com.egzosn.pay.common.bean.BillType;
import com.egzosn.pay.common.bean.CurType;
import com.egzosn.pay.common.bean.MethodType;
import com.egzosn.pay.common.bean.NoticeParams;
import com.egzosn.pay.common.bean.PayMessage;
import com.egzosn.pay.common.bean.PayOrder;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.bean.RefundOrder;
import com.egzosn.pay.common.bean.TransactionType;
import com.egzosn.pay.common.http.HttpConfigStorage;
import com.egzosn.pay.common.http.UriVariables;
import com.egzosn.pay.common.util.DateUtils;
import com.egzosn.pay.common.util.Util;
import com.egzosn.pay.common.util.sign.SignTextUtils;
import com.egzosn.pay.common.util.sign.SignUtils;
import com.egzosn.pay.common.util.sign.encrypt.Base64;
import com.egzosn.pay.common.util.str.StringUtils;

public class BaiduPayService extends BasePayService<BaiduPayConfigStorage> {
    public static final String APP_KEY = "appKey";
    public static final String APP_ID = "appId";
    public static final String DEAL_ID = "dealId";
    public static final String TP_ORDER_ID = "tpOrderId";
    public static final String DEAL_TITLE = "dealTitle";
    public static final String TOTAL_AMOUNT = "totalAmount";
    public static final String SIGN_FIELDS_RANGE = "signFieldsRange";
    public static final String BIZ_INFO = "bizInfo";
    public static final String RSA_SIGN = "rsaSign";
    public static final String ORDER_ID = "orderId";
    public static final String USER_ID = "userId";
    public static final String SITE_ID = "siteId";
    public static final String SIGN = "sign";
    public static final String METHOD = "method";
    public static final String TYPE = "type";

    public static final Integer RESPONSE_SUCCESS = 2;
    public static final String RESPONSE_STATUS = "status";

    private static final String CHARSET = "UTF-8";
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    private static final String SIGN_TYPE_RSA = "RSA";
    private static final String SIGN_KEY = "rsaSign";

    public BaiduPayService(BaiduPayConfigStorage payConfigStorage) {
        super(payConfigStorage);
    }

    public BaiduPayService(BaiduPayConfigStorage payConfigStorage,
                           HttpConfigStorage configStorage) {
        super(payConfigStorage, configStorage);
    }

    /**
     * 验证响应
     *
     * @param params 回调回来的参数集
     * @return 结果
     */
    @Deprecated
    @Override
    public boolean verify(Map<String, Object> params) {

        return verify(new NoticeParams(params));
    }

    /**
     * 回调校验
     *
     * @param noticeParams 回调回来的参数集
     * @return 签名校验 true通过
     */
    @Override
    public boolean verify(NoticeParams noticeParams) {
        final Map<String, Object> params = noticeParams.getBody();
        if (!RESPONSE_SUCCESS.equals(params.get(RESPONSE_STATUS)) && !RESPONSE_SUCCESS.toString().equals(params.get(RESPONSE_STATUS))) {
            return false;
        }
        LOG.info("开始验证回调签名参数:" + params);
        try {
            return this.checkReturnSign(params, payConfigStorage.getKeyPublic(), (String) params.get(RSA_SIGN));
        }
        catch (Exception e) {
            LOG.info("验签失败", e);
        }
        return false;
    }
    public boolean checkReturnSign(Map<String, Object> params, String publicKey, String rsaSign) {
        try {
            String content = signContent(params);
            Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
            signature.initVerify(this.getPublicKeyX509(publicKey));
            signature.update(content.getBytes(CHARSET));
            boolean verify = signature.verify(Base64.decode(rsaSign));
            LOG.info("使用公钥进行验签: " + verify);
            return verify;
        }
        catch (Exception e) {
            LOG.info("使用公钥进行验签出错, 返回false", e);
        }
        return false;
    }

    /**
     * 将公钥字符串进行Base64 decode之后,生成X509标准公钥
     *
     * @param publicKey 公钥原始字符串
     * @return X509标准公钥
     * @throws InvalidKeySpecException InvalidKeySpecException
     * @throws NoSuchAlgorithmException NoSuchAlgorithmException
     */
    private static PublicKey getPublicKeyX509(String publicKey) throws InvalidKeySpecException, NoSuchAlgorithmException {
        if (StringUtils.isEmpty(publicKey)) {
            return null;
        }
        KeyFactory keyFactory = KeyFactory.getInstance(SIGN_TYPE_RSA);
        byte[] decodedKey = Base64.decode(publicKey);
        return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
    }

    /**
     * 对输入参数进行key过滤排序和字符串拼接
     *
     * @param params 待签名参数集合
     * @return 待签名内容
     * @throws UnsupportedEncodingException UnsupportedEncodingException
     */
    private String signContent(Map<String, Object> params) throws UnsupportedEncodingException {
        Map<String, String> sortedParams = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            if (legalKey(key)) {
                String value =
                        entry.getValue() == null ? null : URLEncoder.encode(entry.getValue().toString(), CHARSET);
                sortedParams.put(key, value);
            }
        }

        StringBuilder builder = new StringBuilder();
        if (sortedParams != null && sortedParams.size() > 1) {
            for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
                if (StringUtils.equals(entry.getKey(), RSA_SIGN)) continue;
                builder.append(entry.getKey());
                builder.append("=");
                builder.append(entry.getValue());
                builder.append("&");
            }
            builder.deleteCharAt(builder.length() - 1);
        }
        LOG.info("验签字符串:\n" + builder);
        return builder.toString();
    }

    /**
     * 有效的待签名参数key值
     * 非空、且非签名字段
     *
     * @param key 待签名参数key值
     * @return true | false
     */
    private static boolean legalKey(String key) {
        return StringUtils.isNotBlank(key) && !SIGN_KEY.equalsIgnoreCase(key);
    }

    /**
     * 返回创建的订单信息
     *
     * @param order 支付订单
     * @return 结果
     */
    @Override
    public Map<String, Object> orderInfo(PayOrder order) {
        LOG.info("百度支付配置:" + JSON.toJSONString(payConfigStorage));
        Map<String, Object> params = this.getUseOrderInfoParams(order);
        String rsaSign = this.getRsaSign(params, RSA_SIGN);
        params.put(RSA_SIGN, rsaSign);
        return params;
    }

    /**
     * 获取"查询支付状态"所需参数
     *
     * @return 结果
     */
    public Map<String, Object> getUseQueryPay() {
        String appKey = payConfigStorage.getAppKey();
        Map<String, Object> result = new HashMap<>();
        result.put(APP_KEY, appKey);
        result.put(APP_ID, payConfigStorage.getAppId());
        return result;
    }

    /**
     * 获取"创建订单"所需参数
     *
     * @param order 订单信息
     * @return 结果
     */
    private Map<String, Object> getUseOrderInfoParams(PayOrder order) {
        BaiduPayOrder payOrder = (BaiduPayOrder) order;
        Map<String, Object> result = new HashMap<>();
        String appKey = payConfigStorage.getAppKey();
        String dealId = payConfigStorage.getDealId();
        result.put(APP_KEY, appKey);
        result.put(DEAL_ID, dealId);
        result.put(TOTAL_AMOUNT, String.valueOf(Util.conversionCentAmount(order.getPrice())));
        result.put(TP_ORDER_ID, payOrder.getOutTradeNo());

        result.put(DEAL_TITLE, payOrder.getSubject());
        result.put(SIGN_FIELDS_RANGE, payOrder.getSignFieldsRange());
        result.put(BIZ_INFO, JSON.toJSONString(payOrder.getBizInfo()));

        LOG.info("百度支付 getUseOrderInfoParams:" + JSON.toJSONString(result));

        return result;
    }

    /**
     * 获取输出消息,用户返回给支付端
     *
     * @param code    状态
     * @param message 消息
     * @return 结果
     */
    @Override
    @Deprecated
    public PayOutMessage getPayOutMessage(String code, String message) {
        throw new UnsupportedOperationException("请使用 " + getClass().getName() + "#getPayOutMessageUseBaidu");
    }

    /**
     * 请求业务方退款审核/响应处理
     * http://smartprogram.baidu.com/docs/develop/function/tune_up_examine/
     *
     * @param errno          错误代码
     * @param message        消息
     * @param auditStatus    状态
     * @param refundPayMoney 退款金额
     * @return 结果
     */
    public PayOutMessage getApplyRefundOutMessageUseBaidu(Integer errno,
                                                          String message,
                                                          AuditStatus auditStatus,
                                                          BigDecimal refundPayMoney) {
        JSONObject data = new JSONObject();
        data.put("auditStatus", auditStatus.getCode());
        JSONObject calculateRes = new JSONObject();
        calculateRes.put("refundPayMoney", refundPayMoney);
        data.put("calculateRes", calculateRes);
        return PayOutMessage.JSON()
                .content("errno", errno)
                .content("message", message)
                .content("data", data)
                .build();

    }

    /**
     * 通知退款状态/响应处理
     * http://smartprogram.baidu.com/docs/develop/function/tune_up_drawback/
     *
     * @param errno   错误代码
     * @param message 消息
     * @return 结果
     */
    public PayOutMessage getRefundOutMessageUseBaidu(Integer errno,
                                                     String message) {
        return PayOutMessage.JSON()
                .content("errno", errno)
                .content("message", message)
                .content("data", "{}")
                .build();

    }

    /**
     * 支付通知/响应处理
     *
     * @param errno        错误代码
     * @param message      消息
     * @param isConsumed   是否消费
     * @param isErrorOrder 错误订单
     * @return 结果
     */
    public PayOutMessage getPayOutMessageUseBaidu(Integer errno,
                                                  String message,
                                                  Integer isConsumed,
                                                  Integer isErrorOrder) {
        Asserts.isNoNull(errno, "errno 是必填的");
        Asserts.isNoNull(message, "message 是必填的");
        Asserts.isNoNull(isConsumed, "isConsumed 是必填的");
        JSONObject data = new JSONObject();
        data.put("isConsumed", isConsumed);
        if (isErrorOrder != null) {
            data.put("isErrorOrder", isErrorOrder);
        }
        return PayOutMessage.JSON()
                .content("errno", errno)
                .content("message", message)
                .content("data", data)
                .build();
    }

    /**
     * 支付通知/响应处理
     * http://smartprogram.baidu.com/docs/develop/function/tune_up_notice/
     *
     * @param code       状态码
     * @param message    消息
     * @param isConsumed 是否消费
     * @return 结果
     */
    public PayOutMessage getPayOutMessageUseBaidu(Integer code,
                                                  String message,
                                                  Integer isConsumed) {
        return getPayOutMessageUseBaidu(code, message, isConsumed, null);
    }

    /**
     * 支付通知/响应处理
     * http://smartprogram.baidu.com/docs/develop/function/tune_up_notice/
     *
     * @param payMessage 支付回调消息
     * @return 结果
     */
    @Override
    public PayOutMessage successPayOutMessage(PayMessage payMessage) {
        return getPayOutMessageUseBaidu(0, "success", 2);
    }

    /**
     * 获取输出消息,用户返回给支付端, 针对于web端
     *
     * @param orderInfo 发起支付的订单信息
     * @param method    请求方式  "post" "get",
     * @return 结果
     */
    @Override
    public String buildRequest(Map<String, Object> orderInfo,
                               MethodType method) {
        throw new UnsupportedOperationException("百度不支持PC支付");
    }

    /**
     * 百度不支持扫码付
     *
     * @param order 发起支付的订单信息
     * @return 结果
     */
    @Override
    public String getQrPay(PayOrder order) {
        throw new UnsupportedOperationException("百度不支持扫码付");
    }

    /**
     * 百度不支持刷卡付
     *
     * @param order 发起支付的订单信息
     * @return 结果
     */
    @Override
    public Map<String, Object> microPay(PayOrder order) {
        throw new UnsupportedOperationException("百度不支持刷卡付");
    }

    /**
     * 查询订单
     *
     * @param tradeNo    支付平台订单号
     * @param outTradeNo 商户单号
     * @return 结果
     */
    @Override
    public Map<String, Object> query(String tradeNo, String outTradeNo) {
        return secondaryInterface(tradeNo, outTradeNo, BaiduTransactionType.PAY_QUERY);
    }

    /**
     * 交易查询接口
     *
     * @param assistOrder 查询条件
     * @return 返回查询回来的结果集,支付方原值返回
     */
    @Override
    public Map<String, Object> query(AssistOrder assistOrder) {
        return secondaryInterface(assistOrder.getTradeNo(), assistOrder.getOutTradeNo(), BaiduTransactionType.PAY_QUERY);
    }

    /**
     * 百度不支持该操作
     *
     * @param tradeNo    支付平台订单号
     * @param outTradeNo 商户单号
     * @return 结果
     */
    @Override
    public Map<String, Object> close(String tradeNo, String outTradeNo) {
        throw new UnsupportedOperationException("不支持该操作");
    }
    /**
     * 交易关闭接口
     *
     * @param assistOrder    关闭订单
     * @return 返回支付方交易关闭后的结果
     */
    @Override
    public Map<String, Object> close(AssistOrder assistOrder){
        throw new UnsupportedOperationException("不支持该操作");
    }

    /**
     * 退款
     *
     * @param refundOrder 退款订单信息
     * @return 退款结果
     */
    @Override
    public BaseRefundResult refund(RefundOrder refundOrder) {
        Map<String, Object> parameters = getUseQueryPay();
        BaiduTransactionType transactionType = BaiduTransactionType.APPLY_REFUND;
        parameters.put(METHOD, transactionType.getMethod());
        parameters.put(ORDER_ID, refundOrder.getOutTradeNo());
        parameters.put(USER_ID, refundOrder.getUserId());
        setParameters(parameters, "refundType", refundOrder);
        parameters.put("refundReason", refundOrder.getDescription());
        parameters.put(TP_ORDER_ID, refundOrder.getTradeNo());
        parameters.put("applyRefundMoney", refundOrder.getRefundAmount());
        parameters.put("bizRefundBatchId", refundOrder.getRefundNo());
        parameters.put(APP_KEY, payConfigStorage.getAppKey());
        parameters.put(RSA_SIGN, getRsaSign(parameters, RSA_SIGN));
        final JSONObject result = requestTemplate.getForObject(String.format("%s?%s", getReqUrl(transactionType), UriVariables.getMapToParameters(parameters)), JSONObject.class);
        return new BaseRefundResult(result) {
            @Override
            public String getCode() {
                return getAttrString(RESPONSE_STATUS);
            }

            @Override
            public String getMsg() {
                return null;
            }

            @Override
            public String getResultCode() {
                return null;
            }

            @Override
            public String getResultMsg() {
                return null;
            }

            @Override
            public BigDecimal getRefundFee() {
                return null;
            }

            @Override
            public CurType getRefundCurrency() {
                return null;
            }

            @Override
            public String getTradeNo() {
                return null;
            }

            @Override
            public String getOutTradeNo() {
                return null;
            }

            @Override
            public String getRefundNo() {
                return null;
            }
        };

    }

    /**
     * 退费查询
     *
     * @param refundOrder 退款订单单号信息
     * @return 退款查询结果
     */
    @Override
    public Map<String, Object> refundquery(RefundOrder refundOrder) {

        Map<String, Object> parameters = getUseQueryPay();
        BaiduTransactionType transactionType = BaiduTransactionType.REFUND_QUERY;
        parameters.put(METHOD, transactionType.getMethod());
        parameters.put(TYPE, 3);
        parameters.put(ORDER_ID, refundOrder.getTradeNo());
        parameters.put(USER_ID, refundOrder.getUserId());
        parameters.put(APP_KEY, payConfigStorage.getAppKey());
        parameters.put(RSA_SIGN, getRsaSign(parameters, RSA_SIGN));
        return requestTemplate.getForObject(String.format("%s?%s", getReqUrl(transactionType), UriVariables.getMapToParameters(parameters)), JSONObject.class);
    }

    /**
     * 下载订单对账单
     *
     * @param billDate    账单时间:日账单格式为yyyy-MM-dd
     * @param accessToken 用户token
     * @return 对账单
     */
    @Override
    public Map<String, Object> downloadBill(Date billDate, String accessToken) {
        return downloadBill(billDate, new BaiduBillType(accessToken, BaiduTransactionType.DOWNLOAD_ORDER_BILL.name()));
    }

    /**
     * 下载对账单
     *
     * @param billDate 账单时间:日账单格式为yyyy-MM-dd,月账单格式为yyyy-MM。
     * @param billType 账单类型 {@link BaiduBillType}
     * @return 返回支付方下载对账单的结果
     */
    @Override
    public Map<String, Object> downloadBill(Date billDate, BillType billType) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("access_token", billType.getCustom());
        parameters.put("billTime", DateUtils.formatDate(billDate, billType.getDatePattern()));
        final String type = billType.getType();
        BaiduTransactionType transactionType = BaiduTransactionType.DOWNLOAD_ORDER_BILL;
        if (BaiduTransactionType.DOWNLOAD_BILL.name().equals(type)) {
            transactionType = BaiduTransactionType.DOWNLOAD_BILL;
        }
        return requestTemplate.getForObject(String.format("%s?%s", getReqUrl(transactionType),
                UriVariables.getMapToParameters(parameters)), JSONObject.class);
    }

    /**
     * 下载资金账单
     *
     * @param billDate    账单时间:日账单格式为yyyy-MM-dd
     * @param accessToken 用户token
     * @return 账单结果
     */
    @Deprecated
    public Map<String, Object> downloadMoneyBill(Date billDate, String accessToken) {
        return downloadBill(billDate, new BaiduBillType(accessToken, BaiduTransactionType.DOWNLOAD_BILL.name()));
    }

    /**
     * 通用查询接口
     *
     * @param orderId         订单id
     * @param siteId          用户id
     * @param transactionType 交易类型
     * @return 结果
     */
    public Map<String, Object> secondaryInterface(Object orderId,
                                                  String siteId,
                                                  TransactionType transactionType) {
        if (!BaiduTransactionType.PAY_QUERY.equals(transactionType)) {
            throw new UnsupportedOperationException("不支持该操作");
        }

        Map<String, Object> parameters = getUseQueryPay();
        parameters.put(ORDER_ID, orderId);
        parameters.put(SITE_ID, siteId);
        parameters.put(SIGN, getRsaSign(parameters, SIGN));
        return requestTemplate.getForObject(String.format("%s?%s", getReqUrl(transactionType), UriVariables.getMapToParameters(parameters)), JSONObject.class);
    }

    /**
     * 获取支付请求地址
     *
     * @param transactionType 交易类型
     * @return 请求URL
     */
    @Override
    public String getReqUrl(TransactionType transactionType) {
        return ((BaiduTransactionType) transactionType).getUrl();
    }

    /**
     * 签名
     *
     * @param params     参数
     * @param ignoreKeys 忽略字段
     * @return 签名结果
     */
    private String getRsaSign(Map<String, Object> params, String... ignoreKeys) {
        Map<String, Object> result = new HashMap<>();
        String appKey = payConfigStorage.getAppKey();
        String dealId = payConfigStorage.getDealId();
        result.put(APP_KEY, appKey);
        result.put(DEAL_ID, dealId);
        result.put(TOTAL_AMOUNT, params.get(TOTAL_AMOUNT));
        result.put(TP_ORDER_ID, params.get(TP_ORDER_ID));

        LOG.info("百度支付签名参数:" + JSON.toJSONString(result));

        String waitSignVal = SignTextUtils.parameterText(result, "&", false, ignoreKeys);
        return SignUtils.RSA.createSign(waitSignVal, payConfigStorage.getKeyPrivate(), payConfigStorage.getInputCharset());
    }
}


text:
<?php

return [
    'interfaces' => [
        'google.cloud.channel.v1.CloudChannelService' => [
            'ActivateEntitlement' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Cloud\Channel\V1\Entitlement',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'CancelEntitlement' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Protobuf\GPBEmpty',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'ChangeOffer' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Cloud\Channel\V1\Entitlement',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'ChangeParameters' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Cloud\Channel\V1\Entitlement',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'ChangeRenewalSettings' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Cloud\Channel\V1\Entitlement',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'CreateEntitlement' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Cloud\Channel\V1\Entitlement',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'ProvisionCloudIdentity' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Cloud\Channel\V1\Customer',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'StartPaidService' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Cloud\Channel\V1\Entitlement',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'SuspendEntitlement' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Cloud\Channel\V1\Entitlement',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'TransferEntitlements' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Cloud\Channel\V1\TransferEntitlementsResponse',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'TransferEntitlementsToGoogle' => [
                'longRunning' => [
                    'operationReturnType' => '\Google\Protobuf\GPBEmpty',
                    'metadataReturnType' => '\Google\Cloud\Channel\V1\OperationMetadata',
                    'initialPollDelayMillis' => '500',
                    'pollDelayMultiplier' => '1.5',
                    'maxPollDelayMillis' => '5000',
                    'totalPollTimeoutMillis' => '300000',
                ],
            ],
            'ListChannelPartnerLinks' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getChannelPartnerLinks',
                ],
            ],
            'ListCustomers' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getCustomers',
                ],
            ],
            'ListEntitlements' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getEntitlements',
                ],
            ],
            'ListOffers' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getOffers',
                ],
            ],
            'ListProducts' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getProducts',
                ],
            ],
            'ListPurchasableOffers' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getPurchasableOffers',
                ],
            ],
            'ListPurchasableSkus' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getPurchasableSkus',
                ],
            ],
            'ListSkus' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getSkus',
                ],
            ],
            'ListSubscribers' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getServiceAccounts',
                ],
            ],
            'ListTransferableOffers' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getTransferableOffers',
                ],
            ],
            'ListTransferableSkus' => [
                'pageStreaming' => [
                    'requestPageTokenGetMethod' => 'getPageToken',
                    'requestPageTokenSetMethod' => 'setPageToken',
                    'requestPageSizeGetMethod' => 'getPageSize',
                    'requestPageSizeSetMethod' => 'setPageSize',
                    'responsePageTokenGetMethod' => 'getNextPageToken',
                    'resourcesGetMethod' => 'getTransferableSkus',
                ],
            ],
        ],
    ],
];


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Arch.CFramework.StartUp.Tracing.Url
{
    /// <summary>
    /// 请求相关Tag信息
    /// </summary>
    internal class RequestTagInfo
    {
        /// <summary>
        /// 请求耗时区间
        /// </summary>
        public Range RequestCostRange { get; set; }

        /// <summary>
        /// 响应内容大小区间
        /// </summary>
        public Range ResponseSizeRange { get; set; }

        /// <summary>
        /// 完整Tag信息
        /// </summary>
        public Dictionary<string, string> FullTags { get; set; }
    }
}


text:
package founderio.chaoscrystal.items;

import java.util.List;

import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import founderio.chaoscrystal.ChaosCrystalMain;
import founderio.chaoscrystal.Constants;
import founderio.chaoscrystal.aspects.Aspect;
import founderio.chaoscrystal.entities.EntityChaosCrystal;

public class ItemChaosCrystal extends Item {

	public ItemChaosCrystal() {
		super();
		setMaxStackSize(1);
	}

	@Override
	@SideOnly(Side.CLIENT)
	public boolean hasEffect(ItemStack par1ItemStack, int pass) {
		return pass == 0;
	}

	@Override
	@SideOnly(Side.CLIENT)
	protected String getIconString() {
		return Constants.MOD_ID + ":chaoscrystal";
	}

	@Override
	@SideOnly(Side.CLIENT)
	public void registerIcons(IIconRegister par1IconRegister) {
		itemIcon = par1IconRegister.registerIcon(Constants.MOD_ID
				+ ":chaoscrystal");
	}

	@Override
	public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World,
			EntityPlayer par3EntityPlayer) {
		if (par2World.isRemote) {
			return new ItemStack(Blocks.air, 0, 0);
		}

		EntityChaosCrystal entity = new EntityChaosCrystal(par2World,
				par3EntityPlayer.posX, par3EntityPlayer.posY + 2,
				par3EntityPlayer.posZ, 0f, 0f);
		if (par1ItemStack.getTagCompound() != null) {
			NBTTagCompound aspectStore = par1ItemStack.getTagCompound()
					.getCompoundTag("aspectStore");
			if (aspectStore != null) {
				for (Aspect aspect : Aspect.values()) {
					entity.setAspect(aspect, aspectStore.getInteger(aspect.stringRep));
				}
			}
		}
		entity.setSuckMode(par3EntityPlayer.isSneaking());

		par2World.spawnEntityInWorld(entity);
		entity.playSpawnSound();

		return new ItemStack(ChaosCrystalMain.itemChaosCrystal, 0);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	@SideOnly(Side.CLIENT)
	public void addInformation(ItemStack par1ItemStack,
			EntityPlayer par2EntityPlayer, List par3List, boolean par4) {
		NBTTagCompound tag = par1ItemStack.getTagCompound();
		if (tag == null) {
			par3List.add("This ChaosCrystal is new and empty.");
			return;
		}
		NBTTagCompound aspectStore = tag.getCompoundTag("aspectStore");
		if (aspectStore == null) {
			par3List.add("This ChaosCrystal is used and empty.");
			return;
		}
		boolean hasAspects = false;
		for (Aspect aspect : Aspect.values()) {
			int asp = aspectStore.getInteger(aspect.stringRep);
			if (asp > 0) {
				hasAspects = true;

				par3List.add(String.format(
						"%s: %d",
						StatCollector.translateToLocal(Constants.MOD_ID
								+ ".aspect." + aspect), asp));
			}
		}
		if (!hasAspects) {
			par3List.add("This ChaosCrystal has no aspects stored.");
		}

	}

}


text:
namespace jnc {
namespace ct {

class DerivableType;
class ClassType;
class PropertyType;
class Property;
class Scope;

//..............................................................................

// shared between Function, FunctionOverload and Orphan

class FunctionName {
	friend class Parser;

protected:
	FunctionKind m_functionKind;

	union {
		UnOpKind m_unOpKind;
		BinOpKind m_binOpKind;
		Type* m_castOpType;
		Function* m_asyncLauncher;
	};

	uint_t m_thisArgTypeFlags;

public:
	FunctionName() {
		m_functionKind = FunctionKind_Undefined;
		m_castOpType = NULL;
		m_thisArgTypeFlags = 0;
	}

	FunctionKind
	getFunctionKind() {
		return m_functionKind;
	}

	UnOpKind
	getUnOpKind() {
		ASSERT(m_functionKind == FunctionKind_UnaryOperator);
		return m_unOpKind;
	}

	BinOpKind
	getBinOpKind() {
		ASSERT(m_functionKind == FunctionKind_BinaryOperator);
		return m_binOpKind;
	}

	Type*
	getCastOpType() {
		ASSERT(m_functionKind == FunctionKind_CastOperator);
		return m_castOpType;
	}

	Function*
	getAsyncLauncher() {
		ASSERT(m_functionKind == FunctionKind_AsyncSequencer);
		return m_asyncLauncher;
	}

	uint_t
	getThisArgTypeFlags() {
		return m_thisArgTypeFlags;
	}
};

//..............................................................................

} // namespace ct
} // namespace jnc


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Speaking with a webpage</title>
<script src="/javascript/main.js"></script>
<link href="/css/main.css" rel="stylesheet" type="text/css">
<body>
  Hello world, from html.


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('bundle-version-settings', 'Integration | Component | bundle version settings', {
  integration: true
});

test('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });"

  this.render(hbs`{{bundle-version-settings}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:"
  this.render(hbs`
    {{#bundle-version-settings}}
      template block text
    {{/bundle-version-settings}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});


text:
import logging, os

from tero.setup import stageFile, postinst, SetupTemplate

class sssdSetup(SetupTemplate):

    def __init__(self, name, files, **kwargs):
        super(sssdSetup, self).__init__(name, files, **kwargs)
        self.daemons = ['sssd']

    def run(self, context):
        complete = super(sssdSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        ldapHost = context.value('ldapHost')
        companyDomain = context.value('companyDomain')
        if not (ldapHost and companyDomain):
            logging.warning('ldapHost(%s) or companyDomain(%s) are undefined.'\
                ' skipping configuration of sssd.',
                ldapHost, companyDomain)
            return complete

        domain_parts = tuple(companyDomain.split('.'))
        if len(domain_parts) < 2:
            logging.warning('companyDomain(%s) cannot be split in 2 parts.',
                companyDomain)
            return complete

        ldapCertPath = os.path.join(context.value('etcDir'),
            'pki', 'tls', 'certs', '%s.crt' % ldapHost)
        names = {
            'ldapHost': ldapHost,
            'domainNat': domain_parts[0],
            'domainTop': domain_parts[1],
            'ldapCertPath': ldapCertPath
        }

        sssd_conf = os.path.join(context.value('etcDir'), 'sssd', 'sssd.conf')
        _, new_config_path = stageFile(sssd_conf, context)
        with open(new_config_path, 'w') as new_config:
            new_config.write("""[sssd]
config_file_version = 2
reconnection_retries = 3
services = nss, pam, sudo
# SSSD will not start if you do not configure any domains.
# Add new domain configurations as [domain/] sections, and
# then add the list of domains (in the order you want them to be
# queried) to the "domains" attribute below and uncomment it.
domains = LDAP

[nss]
filter_users = root,ldap,named,avahi,haldaemon,dbus,radiusd,news,nscd
reconnection_retries = 3

[pam]
reconnection_retries = 3

[sudo]

[domain/LDAP]
# Debugging:
debug_level = 1

ldap_tls_reqcert = demand
# Note that enabling enumeration will have a moderate performance impact.
# Consequently, the default value for enumeration is FALSE.
# Refer to the sssd.conf man page for full details.
enumerate = true
auth_provider = ldap
# ldap_schema can be set to "rfc2307", which stores group member names in the
# "memberuid" attribute, or to "rfc2307bis", which stores group member DNs in
# the "member" attribute. If you do not know this value, ask your LDAP
# administrator.
#ldap_schema = rfc2307bis
ldap_schema = rfc2307
ldap_search_base = dc=%(domainNat)s,dc=%(domainTop)s
ldap_group_member = uniquemember
id_provider = ldap
ldap_id_use_start_tls = False
chpass_provider = ldap
ldap_uri = ldaps://%(ldapHost)s/
ldap_chpass_uri = ldaps://%(ldapHost)s/
# Allow offline logins by locally storing password hashes (default: false).
cache_credentials = True
ldap_tls_cacert = %(ldapCertPath)s
entry_cache_timeout = 600
ldap_network_timeout = 3
sudo_provider = ldap
ldap_sudo_search_base = ou=sudoers,dc=%(domainNat)s,dc=%(domainTop)s
ldap_sudo_full_refresh_interval=86400
ldap_sudo_smart_refresh_interval=3600
# Enable group mapping otherwise only the user's primary group will map
# correctly. Without this defined group membership won't work
ldap_group_object_class = posixGroup
ldap_group_search_base = ou=groups,dc=%(domainNat)s,dc=%(domainTop)s
ldap_group_name = cn
ldap_group_member = memberUid
""" % names)

        postinst.shellCommand(['chmod', '600', sssd_conf])
        postinst.shellCommand(['authconfig',
            '--update', '--enablesssd', '--enablesssdauth'])
        postinst.shellCommand(['setsebool',
            '-P', 'authlogin_nsswitch_use_ldap', '1'])
        return complete


text:
/* -*-mode:java; c-basic-offset:2; -*- */
/*
 Copyright (c) 2005 ymnk, JCraft,Inc. All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
 this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in
 the documentation and/or other materials provided with the distribution.

 3. The names of the authors may not be used to endorse or promote products
 derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
 INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.jcraft.jhttptunnel;

import java.io.*;
import java.net.*;

public class IOBoundDoJa
{
	OutBoundDoJa obdj = null;
	InBoundDoJa ibdj = null;
	private String sessionid = null;

	public IOBoundDoJa ()
	{
		obdj = new OutBoundDoJa ();
		ibdj = new InBoundDoJa ();
	}

	public OutBound getOutBound ()
	{
		return obdj;
	}

	public InBound getInBound ()
	{
		return ibdj;
	}

	class OutBoundDoJa extends OutBound
	{
		private InputStream in = null;
		private OutputStream out = null;
		private HttpURLConnection con = null;
		private final byte[] _TUNNEL_DISCONNECT = {
			(byte) 0x47
		};

		private int count = 0;
		boolean connected = false;

		@Override
		public void connect () throws IOException
		{
			// System.out.println("OutBound: connect");

			String host = getHost ();
			int port = getPort ();

			String uri = "http://" + host + ":" + port + "/index.html?crap=1"
					+ "&count=" + count;
			if (sessionid != null)
			{
				uri = uri + "&SESSIONID=" + sessionid;
			}
			// System.out.println("uri: "+uri);
			URL url = new URL (uri);
			con = (HttpURLConnection) url.openConnection ();
			count++;
			con.setRequestMethod ("POST");
			out = con.getOutputStream ();
			sendCount = getContentLength ();
		}

		@Override
		public synchronized void sendData (byte[] foo, int s, int l,
				boolean flush) throws IOException
		{
			// System.out.println("sendData: l="+l+" sendCount="+sendCount+" flush="+flush);
			if (foo != null && l <= 0) return;

			if (con == null)
			{
				connect ();
			}

			if (sendCount <= 0)
			{
				connect ();
			}

			int retry = 2;
			while (retry > 0)
			{
				try
				{
					if (l > 0) out.write (foo, s, l);
					sendCount -= l;

					// if(flush){
					out.close ();
					out = null;
					try
					{
						con.connect ();
					}
					catch (ConnectException e)
					{
						con.disconnect ();
						con = null;
						if (foo == null)
						{ // data retrieve
							connect ();
							retry--;
							continue;
						}
						ibdj.connected = false;
						return;
					}

					sessionid = con.getHeaderField ("x-SESSIONID");
					// System.out.println("sessionid: "+sessionid);
					in = con.getInputStream ();
					readData ();
					// sendCount=0;

					// return;
					// }

					return;
				}
				catch (IOException e)
				{
					connect ();
				}
				retry--;
			}
		}

		private void readData () throws IOException
		{
			// System.out.println("readData: "+this+" con="+con+" in="+in);
			if (con != null)
			{
				if (out != null)
				{
					try
					{
						out.close ();
						out = null;
					}
					catch (IOException e)
					{
					}
				}
				long datalen = con.getContentLengthLong ();
				// System.out.println("datalen: "+datalen);
				if (in != null)
				{
					try
					{
						while (true)
						{
							// System.out.println("now read");
							int c = in.read ();
							// System.out.println("c="+c);
							if (c == -1) break;
							while (true)
							{
								if (ibdj.space () >= 1)
								{
									break;
								}
								try
								{
									Thread.sleep (1000);
								}
								catch (Exception e)
								{
								}
							}
							ibdj.push (c);
						}
						in.close ();
						in = null;
					}
					catch (IOException e)
					{
					}
				}
				con.disconnect ();;
				con = null;
			}
			// System.out.println("close() done");
		}

		@Override
		public void close () throws IOException
		{
			connected = false;
		}
	}

	public class InBoundDoJa extends InBound
	{
		private final InputStream in = null;
		private final HttpURLConnection con = null;

		boolean connected = false;

		@Override
		public void connect () throws IOException
		{
			connected = true;
		}

		@Override
		public int receiveData (byte[] buf, int s, int l) throws IOException
		{
			// System.out.println("receiveData: buf="+buf+" l="+l);
			if (l <= 0)
			{
				return -1;
			}
			int retry = 2;
			while (connected)
			{
				synchronized (this)
				{
					int bl = be - bs;
					// System.out.println(" connected="+connected+" bl="+bl);
					if (bl > 0)
					{
						if (buf == null)
						{
							if (bl > l)
							{
								bl = l;
							}
							bs += bl;
							System.arraycopy (this.buf, bs, this.buf, 0, be
									- bs);
							be = be - bs;
							bs = 0;
							if (bl == l)
							{
								return -1; // ??
							}
							l -= bl;
							continue;
						}
						if (bl > l) bl = l;
						System.arraycopy (this.buf, bs, buf, s, bl);
						bs += bl;
						System.arraycopy (this.buf, bs, this.buf, 0, be - bs);
						be = be - bs;
						bs = 0;
						return bl;
					}
				}
				if (retry > 0)
				{
					retry--;
					obdj.sendData (null, 0, 0, true);
					obdj.readData ();
					// System.out.println("be-bs="+(be-bs));
					if (be - bs > 0)
					{
						continue;
					}

					/*if(blockToRead>0){ try{ Thread.sleep(blockToRead); }
					 * catch(Exception e){ } continue; } else
					 * if(blockToRead==0){ // non block return 0; } else{ try{
					 * Thread.sleep(10000); } // block foreaver catch(Exception
					 * e){ } retry=1; continue; } */

					try
					{
						Thread.sleep (5000);
					}
					catch (Exception e)
					{
					}
					continue;

				}
				else
				{
					return 0;
				}
				// return 0;
			}
			return -1;
		}

		// byte[] buf=new byte[1024];
		byte[] buf = new byte[4096];
		int bs = 0;
		int be = 0;

		public synchronized int space ()
		{
			return buf.length - be;
		}

		public synchronized void push (int c)
		{
			// System.out.println("push: "+c);
			buf[bs + be] = (byte) c;
			be++;
			// System.out.println(" be: "+be);
		}

		@Override
		public void close () throws IOException
		{
			connected = false;
		}
	}
}


text:
static struct {
    TIME_T      Seconds;                            // Seconds since init
    uint16_t    MS;                                 // MS within second
    uint16_t    Countdown;                          // Interrupt count
    bool        Changed;                            // Set TRUE at each tick
    } Timer NOINIT;

//////////////////////////////////////////////////////////////////////////////////////////
//
// Setup some port designations
//
#define PRTIMx      _PRTIM(TIMER_ID)
#define TIMER_ISR   _TCOMPA_VECT(TIMER_ID)

#define TCNTx       _TCNT(TIMER_ID)
#define TCCRAx      _TCCRA(TIMER_ID)
#define TCCRBx      _TCCRB(TIMER_ID)
#define TIMSKx      _TIMSK(TIMER_ID)
#define OCRAx       _OCRA(TIMER_ID)
#define OCIEAx      _OCIEA(TIMER_ID)

#define DISABLE_INT _CLR_BIT(TIMSKx,OCIEAx)
#define ENABLE_INT  _SET_BIT(TIMSKx,OCIEAx)

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//
// TimerInit - Initialize timer system
//
// Inputs:      None.
//
// Outputs:     None.
//
void TimerInit(void) {

    memset(&Timer,0,sizeof(Timer));

    _CLR_BIT(PRR,PRTIMx);           // Powerup the clock

    //
    // Setup the timer as free running, with OCRA as top value
    //
    TCCRAx = CTC_MODE;              // No output compare functions
    TCCRBx = CLOCK_BITS;            // Set appropriate clock
    TCNTx  = 0;
    OCRAx  = CLOCK_COUNT-1;         // And clock count for ticks

    Timer.Countdown = TIMER_COUNT;

    ENABLE_INT;                     // Allow interrupts
    }

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//
// TimerUpdate - Update timer, tell if tick has passed
//
// Inputs:      None.
//
// Outputs:     TRUE  if tick has elapsed since last call
//              FALSE otherwise
//
bool TimerUpdate(void) {

    //
    // Return immediately if tick hasn't expired.
    //
    if( !Timer.Changed )
        return(false);

    //
    // Otherwise, update the timer and inform the caller
    //
    Timer.MS += MS_PER_TICK;

    if( Timer.MS >= 1000 ) {
        Timer.MS -= 1000;
        Timer.Seconds++;
        }

    Timer.Changed = false;

    //
    // Call the user's function
    //
#ifdef CALL_TimerISR
    TimerISR();
#endif

    return true;
    }

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//
// TimerGetSeconds - Return seconds since TimerBInit()
// TimerGetMS      - Get milliseconds since previous second
//
// Inputs:      None.
//
// Outputs:     The value specified.
//
TIME_T TimerGetSeconds(void) {
    TIME_T Rtnval;

    DISABLE_INT;                    // Disable interrupts
    Rtnval = Timer.Seconds;
    ENABLE_INT;                     // Allow interrupts

    return Rtnval;
    }

uint16_t TimerGetMS(void) {
    TIME_T Rtnval;

    DISABLE_INT;                    // Disable interrupts
    Rtnval = Timer.MS;
    ENABLE_INT;                     // Allow interrupts

    return Rtnval;
    }

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//
// TIMERx_COMPA_vect - Compare A causes a timer tick
//
// This defines the "tick" of the system clock. Increment the global
//   clock counter, call the user's function (if defined) and return.
//
// Inputs:      None. (ISR)
//
// Outputs:     None.
//
ISR(TIMER_ISR,ISR_NOBLOCK) {

    if( --Timer.Countdown != 0 )
        return;

    Timer.Countdown = TIMER_COUNT;
    Timer.Changed   = true;
    }


text:
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="android:background">#C2C2C2</item>
    </style>

</resources>


text:
class Users::RegistrationsController < Devise::RegistrationsController

  before_action :configure_permitted_parameters

  def show
    @user = User.find(params[:id])
  end

  protected

  # my custom fields are :name, :last_name
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up) do |u|
      u.permit(:name, :last_name,
        :email, :password, :password_confirmation)
    end
    devise_parameter_sanitizer.permit(:account_update) do |u|
      u.permit(:name, :last_name,
        :email, :password, :password_confirmation, :current_password)
    end
  end

  def after_update_path_for(resource)
    user_path(resource)
  end
end


text:
function data = prepareDataForPaths(imgRoot, imgPaths)
% Converts paths into data format used by the codebase.
%
% Author: saurabh.me@gmail.com (Saurabh Singh).

for i = 1 : length(imgPaths)
  item = [];
  item.filename = imgPaths{i};
  item.folder = '';

  imInfo = imfinfo([imgRoot imgPaths{i}]);
  item.imagesize.nrows = imInfo.Height;
  item.imagesize.ncols = imInfo.Width;

  data(i).annotation = item;

end
end


text:
#include <exception>
#include <functional>
#include <iostream>

#include <mapmap/header/dynamic_programming.h>

NS_MAPMAP_BEGIN

/**
 * *****************************************************************************
 * *********************** DynamicProgrammingTableEntry ************************
 * *****************************************************************************
 */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
DynamicProgrammingTableEntry<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
DynamicProgrammingTableEntry(
    const TreeNode<COSTTYPE>& node,
    _s_t<COSTTYPE, SIMDWIDTH> * tbl_opt_values,
    _iv_st<COSTTYPE, SIMDWIDTH> * tbl_opt_labels)
: m_node(node),
  m_opt_values(tbl_opt_values),
  m_opt_labels(tbl_opt_labels)
{

}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
DynamicProgrammingTableEntry<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
~DynamicProgrammingTableEntry()
{

}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
const luint_t&
DynamicProgrammingTableEntry<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
node_id()
{
    return m_node.node_id;
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
const luint_t&
DynamicProgrammingTableEntry<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
parent_id()
{
    return m_node.parent_id;
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
void
DynamicProgrammingTableEntry<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
optimize_entry(
    const DPBundle<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>& costs)
{
    /* determine if we are optimizing a root node */
    const bool is_root = (node_id() == parent_id());

    /* optimize a single node - if it's a root, assume an artificial parent */
    const _iv_st<COSTTYPE, SIMDWIDTH> num_parent_labels = is_root ? 1 :
        costs.c_labels->label_set_size(parent_id());
    const _iv_st<COSTTYPE, SIMDWIDTH> num_node_labels =
        costs.c_labels->label_set_size(node_id());

    /* initialize running minimum */
    _v_t<COSTTYPE, SIMDWIDTH> min_costs = v_init<COSTTYPE, SIMDWIDTH>(
        std::numeric_limits<_s_t<COSTTYPE, SIMDWIDTH>>::max());
    _iv_t<COSTTYPE, SIMDWIDTH> min_labels = iv_init<COSTTYPE, SIMDWIDTH>(
        std::numeric_limits<_iv_st<COSTTYPE, SIMDWIDTH>>::max());

    /* space for final reduction */
    _s_t<COSTTYPE, SIMDWIDTH> r_cost[SIMDWIDTH];
    _iv_st<COSTTYPE, SIMDWIDTH> r_label[SIMDWIDTH];

    /* mask for excluding invalid labels */
    _iv_t<COSTTYPE, SIMDWIDTH> valid_labels;

    /* label to substitute for exceeding label indices */
    const _iv_st<COSTTYPE, SIMDWIDTH> exceed_l = costs.c_labels->
        label_from_offset(node_id(), 0);

    /* one DP table entry per iteration of this loop is created */
    for(_iv_st<COSTTYPE, SIMDWIDTH> l_p_i = 0; l_p_i < num_parent_labels;
        ++l_p_i)
    {
        min_costs = v_init<COSTTYPE, SIMDWIDTH>(
            std::numeric_limits<_s_t<COSTTYPE, SIMDWIDTH>>::max());
        min_labels = iv_init<COSTTYPE, SIMDWIDTH>(
            std::numeric_limits<_iv_st<COSTTYPE, SIMDWIDTH>>::max());

        /* retrieve label for parent's index */
        _iv_t<COSTTYPE, SIMDWIDTH> l_p = iv_init<COSTTYPE, SIMDWIDTH>(
            costs.c_labels->label_from_offset(m_node.parent_id, l_p_i));

        /* handle all this node's labels */
        for(_iv_st<COSTTYPE, SIMDWIDTH> l_i = 0; l_i < num_node_labels;
            l_i += SIMDWIDTH)
        {
            /* vector holding costs */
            _v_t<COSTTYPE, SIMDWIDTH> cost = v_init<COSTTYPE, SIMDWIDTH>();

            /* retrieve label index vector for this offset */
            const _iv_t<COSTTYPE, SIMDWIDTH> v_l_i =
                iv_sequence<COSTTYPE, SIMDWIDTH>(l_i);

            /* retrieve label vector for this offset */
            _iv_t<COSTTYPE, SIMDWIDTH> l = costs.c_labels->
                labels_from_offset(node_id(), l_i);

            /* mask out label indices exceeding num_node_labels */
            valid_labels = iv_le<COSTTYPE, SIMDWIDTH>
                (v_l_i, iv_init<COSTTYPE, SIMDWIDTH>(num_node_labels - 1));
            l = iv_blend<COSTTYPE, SIMDWIDTH>(
                iv_init<COSTTYPE, SIMDWIDTH>(exceed_l), l, valid_labels);

            /* determine weight to parent */
            _v_t<COSTTYPE, SIMDWIDTH> w_p = v_init<COSTTYPE, SIMDWIDTH>(
                m_node.to_parent_weight);

            /* add pairwise costs to parent (multiplied by weight) */
            if(!is_root)
            {
                if(costs.c_binary->node_dependent())
                    cost = v_add<COSTTYPE, SIMDWIDTH>(
                        v_mult<COSTTYPE, SIMDWIDTH>(w_p,
                        costs.c_binary->get_binary_costs(parent_id(),
                        l_p, node_id(), l)), cost);
                else
                    cost = v_add<COSTTYPE, SIMDWIDTH>(
                        v_mult<COSTTYPE, SIMDWIDTH>(w_p,
                        costs.c_binary->get_binary_costs(l_p, l)), cost);
            }

            /* add unary cost for node */
            if(costs.c_unary->supports_enumerable_costs())
                cost = v_add<COSTTYPE, SIMDWIDTH>(cost, costs.c_unary->
                    get_unary_costs_enum_offset(node_id(), l_i));
            else
                cost = v_add<COSTTYPE, SIMDWIDTH>(cost, costs.c_unary->
                    get_unary_costs(node_id(), l));

            /* add pairwise costs for dependencies (if applicable) */
            for(luint_t d_i = 0; costs.respect_dependencies &&
                (d_i < m_node.dependency_degree); ++d_i)
            {
                const luint_t d = m_node.dependency_ids[d_i];
                const _s_t<COSTTYPE, SIMDWIDTH> w =
                    m_node.dependency_weights[d_i];

                /* fetch dependency label index */
                _iv_st<COSTTYPE, SIMDWIDTH> l_d_i = (*costs.c_assignment)[d];
                _iv_t<COSTTYPE, SIMDWIDTH> l_d = iv_init<COSTTYPE, SIMDWIDTH>(
                    costs.c_labels->label_from_offset(d, l_d_i));

                /* add pairwise cost to dependency (multiplied by weight) */
                if(costs.c_binary->node_dependent())
                {
                    const _v_t<COSTTYPE, SIMDWIDTH> d_c =
                        costs.c_binary->get_binary_costs(d, l_d, node_id(), l);

                    cost = (w != 1.0) ?
                        v_add<COSTTYPE, SIMDWIDTH>(cost,
                        v_mult<COSTTYPE, SIMDWIDTH>(d_c,
                        v_init<COSTTYPE, SIMDWIDTH>(w))) :
                        v_add<COSTTYPE, SIMDWIDTH>(cost, d_c);
                }
                else
                {
                    const _v_t<COSTTYPE, SIMDWIDTH> d_c =
                        costs.c_binary->get_binary_costs(l_d, l);

                    cost = (w != 1.0) ?
                        v_add<COSTTYPE, SIMDWIDTH>(cost,
                        v_mult<COSTTYPE, SIMDWIDTH>(d_c,
                        v_init<COSTTYPE, SIMDWIDTH>(w))) :
                        v_add<COSTTYPE, SIMDWIDTH>(cost, d_c);
                }
            }

            /* add children's table entries */
            for(luint_t i = 0; i < m_node.degree; ++i)
            {
                const _s_t<COSTTYPE, SIMDWIDTH> * c_vals =
                    (*costs.c_child_values)[m_node.children_ids[i]];

                /* load corresponding optima from c's table */
                _v_t<COSTTYPE, SIMDWIDTH> c_dp = v_load<COSTTYPE, SIMDWIDTH>(
                    &c_vals[l_i]);

                cost = v_add<COSTTYPE, SIMDWIDTH>(cost, c_dp);
            }

            /**
             * SSE quirk: doing cmple (v_le) results in 0xff... if the first
             * operand is smaller, whereas blendv (v_blend) would copy
             * the second operand given 0xff....
             * Hence, in v_blend, we flip the arguments.
             *
             * Here, mask out costs for labels not in this node's table.
             */
            cost = v_blend<COSTTYPE, SIMDWIDTH>(
                v_init<COSTTYPE, SIMDWIDTH>(std::numeric_limits<
                _s_t<COSTTYPE, SIMDWIDTH>>::max()), cost,
                iv_reinterpret_v<COSTTYPE, SIMDWIDTH>(valid_labels));

            /* for a root, just save costs */
            if(is_root)
            {
                v_store<COSTTYPE, SIMDWIDTH>(cost, &m_opt_values[l_i]);
                iv_store<COSTTYPE, SIMDWIDTH>(v_l_i, &m_opt_labels[l_i]);
            }
            else
            {
                /* determine componentwise minimum */
                _v_t<COSTTYPE, SIMDWIDTH> min_mask =
                    v_le<COSTTYPE, SIMDWIDTH>(cost, min_costs);

                /* update componentwise minimas (values + label indices) */
                min_costs = v_blend<COSTTYPE, SIMDWIDTH>(min_costs, cost,
                    min_mask);
                min_labels = iv_blend<COSTTYPE, SIMDWIDTH>(min_labels, v_l_i,
                    v_reinterpret_iv<COSTTYPE, SIMDWIDTH>(min_mask));
            }
        }

        /**
         * From the loop above, we have a vector of SIMDWIDTH minimum
         * candidates, now need to reduce it to find the minimum and
         * save it.
         */
        if(!is_root)
        {
            /* reduce the componentwise minimum */
            v_store<COSTTYPE, SIMDWIDTH>(min_costs, r_cost);
            iv_store<COSTTYPE, SIMDWIDTH>(min_labels, r_label);

            uint_t min_ix = 0;

            for(uint_t ix = 0; ix < SIMDWIDTH; ++ix)
                if(r_cost[ix] < r_cost[min_ix])
                    min_ix = ix;

            /* save DP table entry */
            m_opt_values[l_p_i] = r_cost[min_ix];

            /* save minimum label (index) */
            m_opt_labels[l_p_i] = r_label[min_ix];
        }
    }
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
const _s_t<COSTTYPE, SIMDWIDTH> *
DynamicProgrammingTableEntry<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
optimal_value()
{
    return m_opt_values;
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
const _iv_st<COSTTYPE, SIMDWIDTH> *
DynamicProgrammingTableEntry<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
optimal_labels()
{
    return m_opt_labels;
}

/**
 * *****************************************************************************
 * *********************** CombinatorialDynamicProgramming *********************
 * *****************************************************************************
 */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
CombinatorialDynamicProgramming()
: m_level(0),
  m_level_size(0),
  m_value_allocator((tbb::tbb_allocator<_s_t<COSTTYPE, SIMDWIDTH>>*)
    (new tbb::cache_aligned_allocator<_s_t<COSTTYPE, SIMDWIDTH>>))
{

}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
~CombinatorialDynamicProgramming()
{
    /* free all node optimization spaces */
#if defined(BUILD_MEMORY_SAVE)
    for(const luint_t r : m_root_ids)
        m_value_allocator->deallocate(m_opt_value_nodes[r],
            m_opt_value_sizes[r]);
#endif
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
_s_t<COSTTYPE, SIMDWIDTH>
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
optimize(
    std::vector<_iv_st<COSTTYPE, SIMDWIDTH>>& solution)
throw()
{
    if(!this->data_complete())
        throw std::domain_error("Data for optimization problem "
            "incomplete!");

    /* search for leafs as initial nodes to optimize */
    this->discover_leaves();

    /* allocate required memory */
    this->allocate_memory();

    /* bottom-up pass: create table */
    bottom_up_opt();

    /* top-down pass: assign labels for minimum solution */
    top_down_opt(solution);

    return this->objective(solution);
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
void
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
discover_leaves()
{
    tbb::blocked_range<luint_t> tree_range(0, this->m_tree->num_graph_nodes());
    std::vector<luint_t> leaf_list(this->m_tree->num_graph_nodes(),
        (luint_t) 0);
    std::vector<luint_t> leaf_offsets(this->m_tree->num_graph_nodes(),
        (luint_t) 0);

    /* Leaf = node without children, count offsets */
    tbb::parallel_for(tree_range,
        [&](const tbb::blocked_range<luint_t>& r)
        {
            for(luint_t i = r.begin(); i != r.end(); ++i)
                leaf_list[i] = (this->m_tree->node(i).is_in_tree &&
                    this->m_tree->node(i).degree == 0);
        });

    PlusScan<luint_t, luint_t> p_scan(&leaf_list[0], &leaf_offsets[0]);
    tbb::parallel_scan(tree_range, p_scan);
    const luint_t num_leaves = leaf_offsets.back() + leaf_list.back();

    /* save leaf IDs in vector */
    m_leaf_ids = std::vector<luint_t>(num_leaves, invalid_luint_t);

    tbb::parallel_for(tree_range,
        [&](const tbb::blocked_range<luint_t>& r)
        {
            for(luint_t i = r.begin(); i != r.end(); ++i)
                if(leaf_list[i] > 0)
                    m_leaf_ids[leaf_offsets[i]] = i;
        });
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
void
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
allocate_memory()
{
    tbb::blocked_range<luint_t> leaf_range(0, m_leaf_ids.size(), 32u);
    tbb::blocked_range<luint_t> node_range(0, this->m_tree->num_graph_nodes(),
        32u);

    /* create pointer table for nodes' value tables (and their sizes) */
    m_opt_value_nodes = std::vector<_s_t<COSTTYPE, SIMDWIDTH>*>(
        this->m_tree->num_graph_nodes());
    m_opt_value_sizes = std::vector<_iv_st<COSTTYPE, SIMDWIDTH>>(
        this->m_tree->num_graph_nodes());

    /* allocate memory to hold the DP table for indices for all nodes */
    std::vector<luint_t> lbl_set_sizes(this->m_tree->num_graph_nodes(),
        (luint_t) 0);
    std::vector<luint_t> lbl_set_offsets(this->m_tree->num_graph_nodes(),
        (luint_t) 0);

    tbb::parallel_for(node_range,
        [&](const tbb::blocked_range<luint_t>& r)
        {
            for(luint_t i = r.begin(); i != r.end(); ++i)
            {
                /* root nodes (= self-parented) are included here */
                if(this->m_tree->node(i).parent_id != invalid_luint_t)
                    lbl_set_sizes[i] = SIMDWIDTH * DIV_UP(
                        this->m_label_set->label_set_size(
                        this->m_tree->node(i).parent_id), SIMDWIDTH);
            }
        });

    PlusScan<luint_t, luint_t> p_scan(&lbl_set_sizes[0], &lbl_set_offsets[0]);
    tbb::parallel_scan(node_range, p_scan);
    const luint_t total_mem_req = lbl_set_offsets.back() + lbl_set_sizes.back();

    /* index table for all nodes */
    m_opt_labels = std::vector<_iv_st<COSTTYPE, SIMDWIDTH>>(total_mem_req,
        (uint_t) invalid_luint_t);

#ifndef BUILD_MEMORY_SAVE
    /* value table for all nodes */
    m_opt_values = std::vector<_s_t<COSTTYPE, SIMDWIDTH>>(total_mem_req);
#endif

    /* create pointer tables for indices for all nodes */
    m_opt_label_nodes = std::vector<_iv_st<COSTTYPE, SIMDWIDTH>*>(
        this->m_tree->num_graph_nodes());

    /* save offsets into index table for all nodes */
    tbb::parallel_for(node_range,
        [&](const tbb::blocked_range<luint_t>& r)
        {
            for(luint_t i = r.begin(); i != r.end(); ++i)
                if(this->m_tree->node(i).parent_id != invalid_luint_t)
                {
                    m_opt_label_nodes[i] = &m_opt_labels[0] +
                        lbl_set_offsets[i];
#ifndef BUILD_MEMORY_SAVE
                    m_opt_value_nodes[i] = &m_opt_values[0] +
                        lbl_set_offsets[i];
#endif
                }
        });
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
void
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
node_memory_allocate(
    const luint_t node_id)
{
    /* determine number of needed storage spaces */
    const _iv_st<COSTTYPE, SIMDWIDTH> entry_size = SIMDWIDTH *
        DIV_UP(this->m_label_set->label_set_size(
        this->m_tree->node(node_id).parent_id), SIMDWIDTH);

    /* allocate memory */
    m_opt_value_nodes[node_id] = m_value_allocator->allocate(entry_size);
    m_opt_value_sizes[node_id] = entry_size;
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
void
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
node_memory_clean_children(
    const luint_t node_id)
{
    /* deallocate children's value tables */
    const TreeNode<COSTTYPE> tree_n = this->m_tree->node(node_id);
    const luint_t degree = tree_n.degree;
    const luint_t * children = tree_n.children_ids;

    for(luint_t d = 0; d < degree; ++d)
    {
        const luint_t c = children[d];
        m_value_allocator->deallocate(m_opt_value_nodes[c],
            m_opt_value_sizes[c]);
    }
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
void
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
bottom_up_opt()
{
    /* mark the number of unprocessed children atomically per node */
    std::vector<std::atomic<luint_t>> unproc_children(
        this->m_tree->num_graph_nodes(), 0);

    /* fill child counter for all node's parents */
    tbb::blocked_range<luint_t> node_range(0, this->m_graph->num_nodes());
    tbb::parallel_for(node_range,
        [&](const tbb::blocked_range<luint_t>& r)
        {
            for(luint_t i = r.begin(); i != r.end(); ++i)
                unproc_children[i] = this->m_tree->node(i).degree;
        });

    /* create a bundle with all necessary information for DP */
    DPBundle<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE> dpb;
    dpb.c_labels = this->m_label_set;
    dpb.c_unary = this->m_unaries;
    dpb.c_binary = this->m_pairwise;
    dpb.c_child_values = &m_opt_value_nodes;
    dpb.c_child_labels = &m_opt_label_nodes;
    dpb.c_assignment = &this->m_current_assignment;
    dpb.respect_dependencies = this->m_uses_dependencies;

    /* use feeder instead of level-wise queue */
    tbb::concurrent_vector<luint_t> queue;
    queue.assign(m_leaf_ids.begin(), m_leaf_ids.end());

    int processed = 0;
    tbb::parallel_for_each(queue.begin(), queue.end(),
        [&](const luint_t n, tbb::feeder<luint_t>& feeder)
        {
                /* allocate memory */
#if defined(BUILD_MEMORY_SAVE)
                node_memory_allocate(n);
#endif

                /* create one table entry per node */
                DynamicProgrammingTableEntry<COSTTYPE, SIMDWIDTH, UNARY,
                    PAIRWISE> dpe(this->m_tree->node(n), m_opt_value_nodes[n],
                        m_opt_label_nodes[n]);

                /* start DP for this node */
                dpe.optimize_entry(dpb);

                /* decrement parent's unprocessed children counter */
                const luint_t parent_id = this->m_tree->node(n).parent_id;
                if(parent_id != n && unproc_children[parent_id].
                    fetch_and_decrement() == (luint_t) 1)
                {
                    /* last child processed: push parent into next level */
                    feeder.add(parent_id);
                }

                /* free children's memory */
#if defined(BUILD_MEMORY_SAVE)
                node_memory_clean_children(n);
#endif

                /* for roots - record for top-down pass */
                if(parent_id == n)
                    m_root_ids.push_back(n);

                ++processed;
        });
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
void
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
top_down_opt(
    std::vector<_iv_st<COSTTYPE, SIMDWIDTH>>& solution)
{
    /* find minimum label (index) for each root */
    tbb::concurrent_vector<luint_t> queue;
    queue.reserve(this->m_graph->num_nodes());
    tbb::blocked_range<luint_t> root_range(0, m_root_ids.size());

    tbb::parallel_for(root_range,
        [&](const tbb::blocked_range<luint_t>& r)
        {
            for(luint_t i = r.begin(); i != r.end(); ++i)
            {
                const luint_t root = m_root_ids[i];
                const uint_t r_label_set_size = this->m_label_set->
                    label_set_size(root);

                const _s_t<COSTTYPE, SIMDWIDTH> * my_costs =
                    m_opt_value_nodes[root];
                const _iv_st<COSTTYPE, SIMDWIDTH> * my_labels =
                    m_opt_label_nodes[root];

                _s_t<COSTTYPE, SIMDWIDTH> min_costs = my_costs[0];
                _iv_st<COSTTYPE, SIMDWIDTH> min_label = my_labels[0];
                for(uint_t l_i = 0; l_i < r_label_set_size; ++l_i)
                {
                    if(my_costs[l_i] < min_costs)
                    {
                        min_costs = my_costs[l_i];
                        min_label = my_labels[l_i];
                    }
                }

                solution[root] = min_label;

                /* add children to queue */
                for(luint_t i = 0; i < this->m_tree->node(root).degree; ++i)
                    queue.push_back(this->m_tree->node(root).children_ids[i]);
            }
        });

    /* continue traversal */
    tbb::parallel_for_each(queue.begin(), queue.end(),
        [&](const luint_t n, tbb::feeder<luint_t>& feeder)
        {
            /* retrieve current node */
            const TreeNode<COSTTYPE>& node =
                this->m_tree->node(n);

            /* retrieve parent's label (index) */
            const _iv_st<COSTTYPE, SIMDWIDTH> p_label =
                solution[node.parent_id];

            /* set n's label (index) */
            const _iv_st<COSTTYPE, SIMDWIDTH> * my_labels =
                m_opt_label_nodes[n];
            solution[n] = my_labels[p_label];

            /* add children to queue */
            for(luint_t i = 0; i < node.degree; ++i)
                feeder.add(node.children_ids[i]);
        });
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
_iv_st<COSTTYPE, SIMDWIDTH>*
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
index_ptr()
{
    return &m_opt_labels[0];
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
std::vector<luint_t> *
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
current_level_queue_ptr()
{
    /* _a for even levels, _b else */
    return ((m_level & 0x1) ? &m_queue_b : &m_queue_a);
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
std::vector<luint_t> *
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
next_level_queue_ptr()
{
    /* _b for even levels, _a else */
    return ((m_level & 0x1) ? &m_queue_a : &m_queue_b);
}

/* ************************************************************************** */

template<typename COSTTYPE, uint_t SIMDWIDTH, typename UNARY, typename PAIRWISE>
FORCEINLINE
void
CombinatorialDynamicProgramming<COSTTYPE, SIMDWIDTH, UNARY, PAIRWISE>::
next_level()
{
    ++m_level;
}

NS_MAPMAP_END