text:
import optparse
import os
import sys
import shlex
import logging

from chrome_remote_control import browser_finder
from chrome_remote_control import wpr_modes

class BrowserOptions(optparse.Values):
  """Options to be used for discovering and launching a browser."""

  def __init__(self, browser_type=None):
    optparse.Values.__init__(self)

    self.browser_type = browser_type
    self.browser_executable = None
    self.chrome_root = None
    self.android_device = None
    self.cros_ssh_identity = None

    self.dont_override_profile = False
    self.extra_browser_args = []
    self.show_stdout = False

    self.cros_remote = None
    self.wpr_mode = wpr_modes.WPR_OFF

    self.verbosity = 0

  def Copy(self):
    other = BrowserOptions()
    other.__dict__.update(self.__dict__)
    return other

  def CreateParser(self, *args, **kwargs):
    parser = optparse.OptionParser(*args, **kwargs)

    # Selection group
    group = optparse.OptionGroup(parser, 'Which browser to use')
    group.add_option('--browser',
        dest='browser_type',
        default=None,
        help='Browser type to run, '
             'in order of priority. Supported values: list,%s' %
             browser_finder.ALL_BROWSER_TYPES)
    group.add_option('--browser-executable',
        dest='browser_executable',
        help='The exact browser to run.')
    group.add_option('--chrome-root',
        dest='chrome_root',
        help='Where to look for chrome builds.'
             'Defaults to searching parent dirs by default.')
    group.add_option('--device',
        dest='android_device',
        help='The android device ID to use'
             'If not specified, only 0 or 1 connected devcies are supported.')
    group.add_option(
        '--remote',
        dest='cros_remote',
        default=os.getenv('REMOTE'),
        help='The IP address of a remote ChromeOS device to use. ' +
             'Defaults to $REMOTE from environment variable if set.')
    group.add_option('--identity',
        dest='cros_ssh_identity',
        default=None,
        help='The identity file to use when ssh\'ing into the ChromeOS device')
    parser.add_option_group(group)

    # Browser options
    group = optparse.OptionGroup(parser, 'Browser options')
    group.add_option('--dont-override-profile', action='store_true',
        dest='dont_override_profile',
        help='Uses the regular user profile instead of a clean one')
    group.add_option('--extra-browser-args',
        dest='extra_browser_args_as_string',
        help='Additional arguments to pass to the browser when it starts')
    group.add_option('--show-stdout',
        action='store_true',
        help='When possible, will display the stdout of the process')
    parser.add_option_group(group)

    # Page set options
    group = optparse.OptionGroup(parser, 'Page set options')
    group.add_option('--record', action='store_const',
        dest='wpr_mode', const=wpr_modes.WPR_RECORD,
        help='Record to the page set archive')
    group.add_option('--page-repeat', dest='page_repeat', default=1,
        help='Number of times to repeat each individual ' +
        'page in the pageset before proceeding.')
    group.add_option('--pageset-repeat', dest='pageset_repeat', default=1,
        help='Number of times to repeat the entire pageset ' +
        'before finishing.')
    group.add_option('--test-shuffle', action='store_true', dest='test_shuffle',
        help='Shuffle the order of pages within a pageset.')
    group.add_option('--test-shuffle-order-file',
        dest='test_shuffle_order_file', default=None,
        help='Filename of an output of a previously run test on the current ' +
        'pageset. The tests will run in the same order again, overriding ' +
        'what is specified by --page-repeat and --pageset-repeat.')
    parser.add_option_group(group)

    # Debugging options
    group = optparse.OptionGroup(parser, 'When things go wrong')
    group.add_option(
      '-v', '--verbose', action='count', dest='verbosity',
      help='Increase verbosity level (repeat as needed)')
    parser.add_option_group(group)

    real_parse = parser.parse_args
    def ParseArgs(args=None):
      defaults = parser.get_default_values()
      for k, v in defaults.__dict__.items():
        if k in self.__dict__ and self.__dict__[k] != None:
          continue
        self.__dict__[k] = v
      ret = real_parse(args, self) # pylint: disable=E1121

      if self.verbosity >= 2:
        logging.basicConfig(level=logging.DEBUG)
      elif self.verbosity:
        logging.basicConfig(level=logging.INFO)
      else:
        logging.basicConfig(level=logging.WARNING)

      if self.browser_executable and not self.browser_type:
        self.browser_type = 'exact'
      if not self.browser_executable and not self.browser_type:
        sys.stderr.write('Must provide --browser=<type>. ' +
                         'Use --browser=list for valid options.\n')
        sys.exit(1)
      if self.browser_type == 'list':
        types = browser_finder.GetAllAvailableBrowserTypes(self)
        sys.stderr.write('Available browsers:\n')
        sys.stdout.write('  %s\n' % '\n  '.join(types))
        sys.exit(1)
      if self.extra_browser_args_as_string: # pylint: disable=E1101
        tmp = shlex.split(
          self.extra_browser_args_as_string) # pylint: disable=E1101
        self.extra_browser_args.extend(tmp)
        delattr(self, 'extra_browser_args_as_string')
      return ret
    parser.parse_args = ParseArgs
    return parser


text:
package com.questionnaire.ssm.module.global.service;

import com.questionnaire.ssm.module.generated.pojo.Questionnaire;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by 郑晓辉 on 2017/4/3.
 * Description:
 */
public interface Add2LibraryService {

    /**
     * 从数据库获取正在分享的问卷信息
     *
     * @param questionnaireId
     * @return
     * @throws Exception
     */
    @Transactional
    Questionnaire getSharingQesPaperFromDB(Long questionnaireId) throws Exception;

    /**
     *复制问卷信息并且重新组织问卷-题目对应关系
     *
     * @param questionnaireId 被操作问卷id
     * @param copiedQesPaper  复制的问卷
     * @return 新生成的问卷id
     * @throws Exception
     */
    @Transactional
    Long copiedQesPaperId(Long questionnaireId, Questionnaire copiedQesPaper) throws Exception;
}

redpajama_set_name: RedPajamaGithub


text:
#include "string.h"
#include "esp_gatt_defs.h"
#include "esp_gatts_api.h"
#include "esp_bt_main.h"
#include "btc/btc_manage.h"
#include "btc_gatts.h"
#include "btc_gatt_util.h"
#include "common/bt_target.h"
#include "stack/l2cdefs.h"
#include "stack/l2c_api.h"
#include "gatt_int.h"

#if (GATTS_INCLUDED == TRUE)
#define COPY_TO_GATTS_ARGS(_gatt_args, _arg, _arg_type) memcpy(_gatt_args, _arg, sizeof(_arg_type))

static esp_err_t esp_ble_gatts_add_char_desc_param_check(esp_attr_value_t *char_val, esp_attr_control_t *control);

esp_err_t esp_ble_gatts_register_callback(esp_gatts_cb_t callback)
{
    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    return (btc_profile_cb_set(BTC_PID_GATTS, callback) == 0 ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_app_register(uint16_t app_id)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    //if (app_id < ESP_APP_ID_MIN || app_id > ESP_APP_ID_MAX) {
    if (app_id > ESP_APP_ID_MAX) {
        return ESP_ERR_INVALID_ARG;
    }

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_APP_REGISTER;
    arg.app_reg.app_id = app_id;

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_app_unregister(esp_gatt_if_t gatts_if)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_APP_UNREGISTER;
    arg.app_unreg.gatts_if = gatts_if;

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_create_service(esp_gatt_if_t gatts_if,
                                       esp_gatt_srvc_id_t *service_id, uint16_t num_handle)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_CREATE_SERVICE;
    arg.create_srvc.gatts_if = gatts_if;
    arg.create_srvc.num_handle = num_handle;
    memcpy(&arg.create_srvc.service_id, service_id, sizeof(esp_gatt_srvc_id_t));

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_create_attr_tab(const esp_gatts_attr_db_t *gatts_attr_db,
                                        esp_gatt_if_t gatts_if,
                                        uint16_t max_nb_attr,
                                        uint8_t srvc_inst_id)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    if (max_nb_attr > ESP_GATT_ATTR_HANDLE_MAX) {
        LOG_ERROR("The number of attribute should not be greater than CONFIG_BT_GATT_MAX_SR_ATTRIBUTES\n");
        return ESP_ERR_INVALID_ARG;
    }

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_CREATE_ATTR_TAB;
    arg.create_attr_tab.gatts_if = gatts_if;
    arg.create_attr_tab.max_nb_attr = max_nb_attr;
    arg.create_attr_tab.srvc_inst_id = srvc_inst_id;
    arg.create_attr_tab.gatts_attr_db = (esp_gatts_attr_db_t *)gatts_attr_db;

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), btc_gatts_arg_deep_copy)
            == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_add_included_service(uint16_t service_handle, uint16_t included_service_handle)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_ADD_INCLUDE_SERVICE;
    arg.add_incl_srvc.service_handle = service_handle;
    arg.add_incl_srvc.included_service_handle = included_service_handle;

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_add_char(uint16_t service_handle,  esp_bt_uuid_t  *char_uuid,
                                 esp_gatt_perm_t perm, esp_gatt_char_prop_t property, esp_attr_value_t *char_val,
                                 esp_attr_control_t *control)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;
    esp_err_t status;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    /* parameter validation check */
    status = esp_ble_gatts_add_char_desc_param_check(char_val, control);
    if (status != ESP_OK){
        return status;
    }

    memset(&arg, 0, sizeof(btc_ble_gatts_args_t));
    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_ADD_CHAR;
    arg.add_char.service_handle = service_handle;
    arg.add_char.perm = perm;
    arg.add_char.property = property;
    if (char_val != NULL) {
        arg.add_char.char_val.attr_max_len = char_val->attr_max_len;
        arg.add_char.char_val.attr_len = char_val->attr_len;
        arg.add_char.char_val.attr_value = char_val->attr_value;
    }

    if (control != NULL) {
        arg.add_char.attr_control.auto_rsp = control->auto_rsp;
    }
    memcpy(&arg.add_char.char_uuid, char_uuid, sizeof(esp_bt_uuid_t));

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), btc_gatts_arg_deep_copy) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_add_char_descr (uint16_t service_handle,
                                        esp_bt_uuid_t   *descr_uuid,
                                        esp_gatt_perm_t perm, esp_attr_value_t *char_descr_val,
                                        esp_attr_control_t *control)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;
    esp_err_t status;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    /* parameter validation check */
    status = esp_ble_gatts_add_char_desc_param_check(char_descr_val, control);
    if (status != ESP_OK){
        return status;
    }

    memset(&arg, 0, sizeof(btc_ble_gatts_args_t));
    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_ADD_CHAR_DESCR;
    arg.add_descr.service_handle = service_handle;
    arg.add_descr.perm = perm;

    if (char_descr_val != NULL) {
        arg.add_descr.descr_val.attr_max_len = char_descr_val->attr_max_len;
        arg.add_descr.descr_val.attr_len = char_descr_val->attr_len;
        arg.add_descr.descr_val.attr_value = char_descr_val->attr_value;
    }

    if (control != NULL) {
        arg.add_descr.attr_control.auto_rsp = control->auto_rsp;
    }
    memcpy(&arg.add_descr.descr_uuid, descr_uuid, sizeof(esp_bt_uuid_t));

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), btc_gatts_arg_deep_copy) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_delete_service(uint16_t service_handle)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_DELETE_SERVICE;
    arg.delete_srvc.service_handle = service_handle;

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_start_service(uint16_t service_handle)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_START_SERVICE;
    arg.start_srvc.service_handle = service_handle;

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_stop_service(uint16_t service_handle)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_STOP_SERVICE;
    arg.stop_srvc.service_handle = service_handle;

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_send_indicate(esp_gatt_if_t gatts_if, uint16_t conn_id, uint16_t attr_handle,
                                      uint16_t value_len, uint8_t *value, bool need_confirm)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    tGATT_TCB       *p_tcb = gatt_get_tcb_by_idx(conn_id);
    if (!gatt_check_connection_state_by_tcb(p_tcb)) {
        LOG_WARN("%s, The connection not created.", __func__);
        return ESP_ERR_INVALID_STATE;
    }

    if (L2CA_CheckIsCongest(L2CAP_ATT_CID, p_tcb->peer_bda)) {
        LOG_DEBUG("%s, the l2cap chanel is congest.", __func__);
        return ESP_FAIL;
    }

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_SEND_INDICATE;
    arg.send_ind.conn_id = BTC_GATT_CREATE_CONN_ID(gatts_if, conn_id);
    arg.send_ind.attr_handle = attr_handle;
    arg.send_ind.need_confirm = need_confirm;
    arg.send_ind.value_len = value_len;
    arg.send_ind.value = value;
    if(need_confirm == false){
        l2ble_update_att_acl_pkt_num(L2CA_ADD_BTC_NUM, NULL);
    }
    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t),
                                 btc_gatts_arg_deep_copy) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_send_response(esp_gatt_if_t gatts_if, uint16_t conn_id, uint32_t trans_id,
                                      esp_gatt_status_t status, esp_gatt_rsp_t *rsp)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    tGATT_TCB       *p_tcb = gatt_get_tcb_by_idx(conn_id);
    if (!gatt_check_connection_state_by_tcb(p_tcb)) {
        LOG_WARN("%s, The connection not created.", __func__);
        return ESP_ERR_INVALID_STATE;
    }

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_SEND_RESPONSE;
    arg.send_rsp.conn_id = BTC_GATT_CREATE_CONN_ID(gatts_if, conn_id);
    arg.send_rsp.trans_id = trans_id;
    arg.send_rsp.status = status;
    arg.send_rsp.rsp = rsp;

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t),
                                 btc_gatts_arg_deep_copy) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_set_attr_value(uint16_t attr_handle, uint16_t length, const uint8_t *value)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_SET_ATTR_VALUE;
    arg.set_attr_val.handle = attr_handle;
    arg.set_attr_val.length = length;
    arg.set_attr_val.value  = (uint8_t *)value;

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t),
                                 btc_gatts_arg_deep_copy) == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_gatt_status_t esp_ble_gatts_get_attr_value(uint16_t attr_handle, uint16_t *length, const uint8_t **value)
{
    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    if (attr_handle == ESP_GATT_ILLEGAL_HANDLE) {
        *length = 0;
        return ESP_GATT_INVALID_HANDLE;
    }

    return btc_gatts_get_attr_value(attr_handle, length, (uint8_t **)value);
}

esp_err_t esp_ble_gatts_open(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda, bool is_direct)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_OPEN;
    arg.open.gatts_if = gatts_if;
    arg.open.is_direct = is_direct;
    memcpy(&arg.open.remote_bda, remote_bda, sizeof(esp_bd_addr_t));

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL)
            == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_close(esp_gatt_if_t gatts_if, uint16_t conn_id)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_CLOSE;
    arg.close.conn_id = BTC_GATT_CREATE_CONN_ID(gatts_if, conn_id);

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL)
            == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

esp_err_t esp_ble_gatts_send_service_change_indication(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda)
{
    btc_msg_t msg = {0};
    btc_ble_gatts_args_t arg;

    ESP_BLUEDROID_STATUS_CHECK(ESP_BLUEDROID_STATUS_ENABLED);

    msg.sig = BTC_SIG_API_CALL;
    msg.pid = BTC_PID_GATTS;
    msg.act = BTC_GATTS_ACT_SEND_SERVICE_CHANGE;
    arg.send_service_change.gatts_if = gatts_if;
    if(remote_bda) {
        memcpy(&arg.send_service_change.remote_bda, remote_bda, sizeof(esp_bd_addr_t));
    } else {
        memset(arg.send_service_change.remote_bda, 0, sizeof(esp_bd_addr_t));
    }

    return (btc_transfer_context(&msg, &arg, sizeof(btc_ble_gatts_args_t), NULL)
            == BT_STATUS_SUCCESS ? ESP_OK : ESP_FAIL);
}

static esp_err_t esp_ble_gatts_add_char_desc_param_check(esp_attr_value_t *char_val, esp_attr_control_t *control)
{
    if ((control != NULL) && ((control->auto_rsp != ESP_GATT_AUTO_RSP) && (control->auto_rsp != ESP_GATT_RSP_BY_APP))){
            LOG_ERROR("Error in %s, line=%d, control->auto_rsp should be set to ESP_GATT_AUTO_RSP or ESP_GATT_RSP_BY_APP\n",\
                            __func__, __LINE__);
            return ESP_ERR_INVALID_ARG;
    }

    if ((control != NULL) && (control->auto_rsp == ESP_GATT_AUTO_RSP)){
        if (char_val == NULL){
            LOG_ERROR("Error in %s, line=%d, for stack respond attribute, char_val should not be NULL here\n",\
                            __func__, __LINE__);
            return ESP_ERR_INVALID_ARG;
        } else if (char_val->attr_max_len == 0){
            LOG_ERROR("Error in %s, line=%d, for stack respond attribute,  attribute max length should not be 0\n",\
                            __func__, __LINE__);
            return ESP_ERR_INVALID_ARG;
        }
    }

    return ESP_OK;
}

#endif  ///GATTS_INCLUDED


text:
Learning Python with a coding kata and TDD

## Running the tests

This uses the Python nose testing framework.

To run:

```nosetests mars-rover -v```

## Mars Rover Kata

https://technologyconversations.com/2013/12/29/learning-a-new-programming-language-through-katas-tdd-and-cyberdojo/

```
Mars Rover Kata.
Taken from http://amirrajan.net/Blog/code-katas-mars-rover

– Develop an api that moves a rover around a grid.
– You are given the initial starting point (x,y) of a rover and the direction (N,S,E,W) it is facing.
– The rover receives a character array of commands.
– Implement commands that move the rover forward/backward (f,b).
– Implement commands that turn the rover left/right (l,r).
– The only commands you can give the rover are f,b,l, and r.
– Implement wrapping from one edge of the grid to another. (planets are spheres after all)
– Implement obstacle detection before each move to a new square. If a given sequence of commands encounters an obstacle, the rover moves up to the last possible point and reports the obstacle.

Here is an example:
– Let's say that the rover is located at 0,0 facing North on a 100×100 grid.
– Given the command "ffrff" would put the rover at 2,2 facing East.
```

## Learnings

This was my first serious Python project.
I've done katas and TDD before in other languages.
So although I expected to learn some more about TDD and doing katas, the focus was on Python and its TDD framework.

### Python is easy

Although I was originally a bit skeptical about Python, the documentation is pretty solid and the syntax is straightforward.
It's not as fussy as Perl and Ruby. What I mean is, it avoids Perl's variable type sigils, '$', '%', etc.,
and it also avoids Ruby's similar global/local variable scoping sigils.
It's more like JavaScript in terms of being loosely typed.

I did actually get used to the colon-indent structure.

### Rich data structures

Support for the common data structures is built into the language.
I was quite impressed that even the set data structure is present.
This is like Ruby and Perl, but very much unlike Java and C++ where libraries need to be explicitly imported to support data structures.
This is admittedly only a first impression, due to the limited language scope required for this kata.

### Python TDD support is good

The unittest/nose framework even supports proper exception testing.

What I do miss is rspec-like test method structure which I've gotten used to in JavaScript (Jasmine, Mocha).
There was some project that tried to address this, but I didn't check it out.

### What is Python's 'with'?

The 'with' keyword was used in the tests for exceptions.
I just followed the example code, without fully understanding it.

I'm still noodling on the docs (TL;DR).

### Formatted strings

I think Python's approach to formatted strings - or templates - is unique.
There are various ways to do it, but the one I chose is like this:

```"template with substitution commands".format(arg1, arg2, ...)```

This is actually kind of neat - I think it looks more like a transform pattern.
It's very unlike the variable/expression interpolation of Ruby, PHP, bash, etc.
I used it to add descriptive content to exception messages.

### Object oriented programming

This Kata didn't provide an opportunity to dive into OOP with Python.
The only thing I can mention, is the language relies on the explict 'self' variable in all method signatures.
The need for 'self' is greatly eased by IDE support - IntelliJ automatically adds it for you.

### IDE support

I used IntelliJ in developing this kata.
The Python plugin seems to provide all the usual language support - although for this kata I used only a bit of the features.

### What I haven't learned

Python has a 'yield' keyword. Sounds similar to Ruby's, but don't know since I haven't tried Python's.

Python packaging and distribution, except for a little pip and easy_install.

## Tech debt

Here's the tech debt I deliberately took on:

- Rover depends on Planet. Rover should depend on Position, which depends on Planet.

## Links and references

https://www.youtube.com/watch?v=Qw2vczm4m2c&feature=youtu.be

### Nose home page

http://nose.readthedocs.io/en/latest/index.html

Note: nose is a superset of Python unittest

This gives three options for installing: easy_setup, pip, download.

On OS X El Capitan and later, SIP issues arise because the installers want to install in the pre-installed
Python directory, /Library/Python/2.7/. SIP won't allow even sudo install there.

Well, ``sudo easy_install nose`` eventually worked.
The test runner is at /usr/local/bin/nosetests.

### Nose testing manual

http://nose.readthedocs.io/en/latest/testing.html

### Konira

Since one of my complaints was the desire for rspec-likee tests, check out Konira: https://github.com/alfredodeza/konira

## FAQ

Here are some issues I encountered in getting this to work.

## nosetests file not found

After installing nose with pip, cannot find the executable in the path.

Executable should be in /usr/local/bin

Actually the problem is SIP on OS X El Capitan

http://apple.stackexchange.com/questions/209572/how-to-use-pip-after-the-os-x-el-capitan-upgrade

## IntelliJ

The Python plugin includes PyCharm

Preferences > Tools > Python Integrated Tools
switch from unittests to nosetests


text:
var ash = require('ash');

module.exports = new ash.Action('destroyTodo');


text:
package pl.shockah.jay;

import pl.shockah.util.func.Action0;
import pl.shockah.util.func.Action1;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

public class JSONObject extends LinkedHashMap<String, Object> {
	private static final long serialVersionUID = -8548703026353148866L;

	@Nonnull
	public static JSONObject of(Object... values) {
		if (values.length % 2 != 0)
			throw new IllegalArgumentException();
		JSONObject j = new JSONObject();
		for (int i = 0; i < values.length; i += 2) {
			if (!(values[i] instanceof String))
				throw new IllegalArgumentException();
			j.put((String)values[i], values[i + 1]);
		}
		return j;
	}

	@SuppressWarnings("unchecked")
	@Nullable
	protected static Object prepareObject(@Nullable Object o) {
		if (o == null)
			return null;
		else if (o instanceof Boolean || o instanceof BigInteger || o instanceof BigDecimal
			|| o instanceof String || o instanceof JSONObject || o instanceof JSONList<?>)
			return o;
		else if (o instanceof Integer)
			return BigInteger.valueOf((Integer)o);
		else if (o instanceof Long)
			return BigInteger.valueOf((Long)o);
		else if (o instanceof Float)
			return BigDecimal.valueOf((Float)o);
		else if (o instanceof Double)
			return BigDecimal.valueOf((Double)o);
		else if (o instanceof Map<?, ?>)
			return new JSONObject((Map<String, Object>)o);
		else if (o instanceof List<?>)
			return new JSONList<>((List<Object>) o);
		else
			throw new ClassCastException();
	}

	@Nonnull
	protected static Map<String, Object> prepareObjects(@Nonnull Map<? extends String, ?> map) {
		Map<String, Object> ret = new TreeMap<>();
		for (Map.Entry<? extends String, ?> entry : map.entrySet())
			ret.put(entry.getKey(), prepareObject(entry.getValue()));
		return ret;
	}

	@Nullable protected Map<String, String> comments;

	public JSONObject() {
		super();
	}

	public JSONObject(@Nonnull Map<String, Object> map) {
		super();
		putAll(map);
	}

	@Override
	@Nonnull
	public String toString() {
		return new JSONPrettyPrinter().toString(this);
	}

	public boolean isNull(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		return get(key) == null;
	}

	public boolean isBool(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		return o instanceof Boolean;
	}

	public boolean getBool(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		if (o instanceof Boolean)
			return (Boolean)o;
		throw new ClassCastException();
	}

	public boolean getBool(@Nonnull String key, boolean def) {
		return containsKey(key) ? getBool(key) : def;
	}

	@Nullable
	public Boolean getOptionalBool(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getBool(key) : null;
	}

	public void onBool(@Nonnull String key, @Nonnull Action1<Boolean> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getBool(key));
	}

	public void onBool(@Nonnull String key, @Nonnull Action1<Boolean> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getBool(key));
		else
			orElse.call();
	}

	public boolean isInteger(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		return o instanceof BigInteger;
	}

	@Nonnull
	public BigInteger getBigInt(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		if (o instanceof BigInteger)
			return (BigInteger)o;
		throw new ClassCastException();
	}

	@Nonnull
	public BigInteger getBigInt(@Nonnull String key, @Nonnull BigInteger def) {
		return containsKey(key) ? getBigInt(key) : def;
	}

	@Nullable
	public BigInteger getOptionalBigInt(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getBigInt(key) : null;
	}

	public void onBigInt(@Nonnull String key, @Nonnull Action1<BigInteger> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getBigInt(key));
	}

	public void onBigInt(@Nonnull String key, @Nonnull Action1<BigInteger> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getBigInt(key));
		else
			orElse.call();
	}

	public int getInt(@Nonnull String key) {
		return getBigInt(key).intValueExact();
	}

	public int getInt(@Nonnull String key, int def) {
		return containsKey(key) ? getInt(key) : def;
	}

	@Nullable
	public Integer getOptionalInt(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getInt(key) : null;
	}

	public void onInt(@Nonnull String key, @Nonnull Action1<Integer> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getInt(key));
	}

	public void onInt(@Nonnull String key, @Nonnull Action1<Integer> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getInt(key));
		else
			orElse.call();
	}

	public long getLong(@Nonnull String key) {
		return getBigInt(key).longValueExact();
	}

	public long getLong(@Nonnull String key, long def) {
		return containsKey(key) ? getLong(key) : def;
	}

	@Nullable
	public Long getOptionalLong(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getLong(key) : null;
	}

	public void onLong(@Nonnull String key, @Nonnull Action1<Long> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getLong(key));
	}

	public void onLong(@Nonnull String key, @Nonnull Action1<Long> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getLong(key));
		else
			orElse.call();
	}

	public boolean isDecimal(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		return o instanceof BigDecimal;
	}

	@Nonnull
	public BigDecimal getBigDecimal(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		if (o instanceof BigDecimal)
			return (BigDecimal)o;
		else if (o instanceof BigInteger)
			return new BigDecimal((BigInteger)o);
		throw new ClassCastException();
	}

	@Nonnull
	public BigDecimal getBigDecimal(@Nonnull String key, @Nonnull BigDecimal def) {
		return containsKey(key) ? getBigDecimal(key) : def;
	}

	@Nullable
	public BigDecimal getOptionalBigDecimal(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getBigDecimal(key) : null;
	}

	public void onBigDecimal(@Nonnull String key, @Nonnull Action1<BigDecimal> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getBigDecimal(key));
	}

	public void onBigDecimal(@Nonnull String key, @Nonnull Action1<BigDecimal> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getBigDecimal(key));
		else
			orElse.call();
	}

	public float getFloat(@Nonnull String key) {
		return getBigDecimal(key).floatValue();
	}

	public float getFloat(@Nonnull String key, float def) {
		return containsKey(key) ? getFloat(key) : def;
	}

	@Nullable
	public Float getOptionalFloat(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getFloat(key) : null;
	}

	public void onFloat(@Nonnull String key, @Nonnull Action1<Float> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getFloat(key));
	}

	public void onFloat(@Nonnull String key, @Nonnull Action1<Float> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getFloat(key));
		else
			orElse.call();
	}

	public double getDouble(@Nonnull String key) {
		return getBigDecimal(key).doubleValue();
	}

	public double getDouble(@Nonnull String key, double def) {
		return containsKey(key) ? getDouble(key) : def;
	}

	@Nullable
	public Double getOptionalDouble(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getDouble(key) : null;
	}

	public void onDouble(@Nonnull String key, @Nonnull Action1<Double> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getDouble(key));
	}

	public void onDouble(@Nonnull String key, @Nonnull Action1<Double> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getDouble(key));
		else
			orElse.call();
	}

	public boolean isString(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		return o instanceof String;
	}

	@Nonnull
	public String getString(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		if (o instanceof String)
			return (String)o;
		throw new ClassCastException();
	}

	@Nonnull
	public String getString(@Nonnull String key, @Nonnull String def) {
		return containsKey(key) ? getString(key) : def;
	}

	@Nullable
	public String getOptionalString(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getString(key) : null;
	}

	public void onString(@Nonnull String key, @Nonnull Action1<String> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getString(key));
	}

	public void onString(@Nonnull String key, @Nonnull Action1<String> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getString(key));
		else
			orElse.call();
	}

	public boolean isObject(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		return o instanceof JSONObject;
	}

	@Nonnull
	public JSONObject getObject(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		if (o instanceof JSONObject)
			return (JSONObject)o;
		throw new ClassCastException();
	}

	@Nonnull
	public JSONObject getObject(@Nonnull String key, @Nonnull JSONObject def) {
		return containsKey(key) ? getObject(key) : def;
	}

	@Nonnull
	public JSONObject getObjectOrEmpty(@Nonnull String key) {
		return containsKey(key) ? getObject(key) : new JSONObject();
	}

	@Nonnull
	public JSONObject getObjectOrNew(@Nonnull String key) {
		if (containsKey(key)) {
			return getObject(key);
		} else {
			JSONObject j = new JSONObject();
			put(key, j);
			return j;
		}
	}

	@Nullable
	public JSONObject getOptionalObject(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getObject(key) : null;
	}

	public void onObject(@Nonnull String key, @Nonnull Action1<JSONObject> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getObject(key));
	}

	public void onObject(@Nonnull String key, @Nonnull Action1<JSONObject> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getObject(key));
		else
			orElse.call();
	}

	public boolean isList(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		return o instanceof JSONList<?>;
	}

	@Nonnull
	public JSONList<?> getList(@Nonnull String key) {
		if (!containsKey(key))
			throw new NullPointerException();
		Object o = get(key);
		if (o instanceof JSONList<?>)
			return (JSONList<?>)o;
		throw new ClassCastException();
	}

	@Nonnull
	public JSONList<?> getList(@Nonnull String key, @Nonnull JSONList<?> def) {
		return containsKey(key) ? getList(key) : def;
	}

	@Nonnull
	public JSONList<?> getListOrEmpty(@Nonnull String key) {
		return containsKey(key) ? getList(key) : new JSONList<>();
	}

	@Nonnull
	public JSONList<?> getListOrNew(@Nonnull String key) {
		if (containsKey(key)) {
			return getList(key);
		} else {
			JSONList<?> j = new JSONList<>();
			put(key, j);
			return j;
		}
	}

	@Nullable
	public JSONList<?> getOptionalList(@Nonnull String key) {
		return containsKey(key) && !isNull(key) ? getList(key) : null;
	}

	public void onList(@Nonnull String key, @Nonnull Action1<JSONList<?>> f) {
		if (containsKey(key) && !isNull(key))
			f.call(getList(key));
	}

	public void onList(@Nonnull String key, @Nonnull Action1<JSONList<?>> f, @Nonnull Action0 orElse) {
		if (containsKey(key) && !isNull(key))
			f.call(getList(key));
		else
			orElse.call();
	}

	public boolean putDefault(@Nonnull String key, @Nullable Object value) {
		if (containsKey(key)) {
			return false;
		} else {
			put(key, value);
			return true;
		}
	}

	@Nonnull
	public JSONObject putNewObject(@Nonnull String key) {
		JSONObject j = new JSONObject();
		put(key, j);
		return j;
	}

	@Nonnull
	public JSONList<?> putNewList(@Nonnull String key) {
		JSONList<Object> j = new JSONList<>();
		put(key, j);
		return j;
	}

	public void clearComments() {
		comments = null;
	}

	public void setComment(@Nonnull String key, @Nullable String comment) {
		if (comment == null) {
			if (comments != null && comments.containsKey(key))
				comments.remove(key);
		} else {
			if (comments == null)
				comments = new HashMap<>();
			comments.put(key, comment);
		}
	}

	public String getComment(@Nonnull String key) {
		if (comments == null)
			return null;
		return comments.get(key);
	}

	@Override
	public Object put(@Nonnull String key, @Nullable Object value) {
		return super.put(key, prepareObject(value));
	}

	@Override
	public void putAll(@Nonnull Map<? extends String, ?> map) {
		super.putAll(prepareObjects(map));
	}

	public boolean isNumber(@Nonnull String key) {
		return isInteger(key) || isDecimal(key);
	}
}


text:
HOST_TRIPLET=i386-apple-darwin10.3.1
PACKAGE_VERSION=1.0.21
LIB_VERSION=`echo $PACKAGE_VERSION | sed "s/[a-z].*//"`

if test -f tests/sfversion ; then
	cd tests
	fi

if test ! -f sfversion ; then
	echo "Not able to find test executables."
	exit 1
	fi

if test -f libsndfile.so.$LIB_VERSION ; then
	# This will work on Linux, but not on Mac.
	# Windows is already sorted out.
	export LD_LIBRARY_PATH=`pwd`
	if test ! -f libsndfile.so.1 ; then
		ln -s libsndfile.so.$LIB_VERSION libsndfile.so.1
		fi
	fi

sfversion=`./sfversion`

if test $sfversion != libsndfile-$PACKAGE_VERSION ; then
	echo "Error : sfversion ($sfversion) and PACKAGE_VERSION ($PACKAGE_VERSION) don't match."
	exit 1
	fi

# Force exit on errors.
set -e

# Generic-tests
uname -a

# Need this for when we're running from files collected into the
# libsndfile-testsuite-1.0.21 tarball.
if test -x test_main ; then
	echo "Running unit tests from src/ directory of source code tree."
	./test_main
	echo
	echo "Running end-to-end tests from tests/ directory."
	fi

./error_test
./pcm_test
./ulaw_test
./alaw_test
./dwvw_test
./command_test ver
./command_test norm
./command_test format
./command_test peak
./command_test trunc
./command_test inst
./command_test current_sf_info
./command_test bext
./command_test bextch
./command_test chanmap
./floating_point_test
./checksum_test
./scale_clip_test
./headerless_test
./locale_test
./win32_ordinal_test
./external_libs_test

# The win64 G++ compiler requires an extra runtime DLL which
# we don't have, so skip the following test on win64.
if test "$HOST_TRIPLET" != "x86_64-w64-mingw32" ; then
	./cpp_test
	fi

echo "----------------------------------------------------------------------"
echo "  $sfversion passed common tests."
echo "----------------------------------------------------------------------"

# aiff-tests
./write_read_test aiff
./lossy_comp_test aiff_ulaw
./lossy_comp_test aiff_alaw
./lossy_comp_test aiff_gsm610
echo "=========================="
echo "./lossy_comp_test aiff_ima"
echo "=========================="
./peak_chunk_test aiff
./header_test aiff
./misc_test aiff
./string_test aiff
./multi_file_test aiff
./aiff_rw_test
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on AIFF files."
echo "----------------------------------------------------------------------"

# au-tests
./write_read_test au
./lossy_comp_test au_ulaw
./lossy_comp_test au_alaw
./lossy_comp_test au_g721
./lossy_comp_test au_g723
./header_test au
./misc_test au
./multi_file_test au
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on AU files."
echo "----------------------------------------------------------------------"

# caf-tests
./write_read_test caf
./lossy_comp_test caf_ulaw
./lossy_comp_test caf_alaw
./header_test caf
./peak_chunk_test caf
./misc_test caf
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on CAF files."
echo "----------------------------------------------------------------------"

# wav-tests
./write_read_test wav
./lossy_comp_test wav_pcm
./lossy_comp_test wav_ima
./lossy_comp_test wav_msadpcm
./lossy_comp_test wav_ulaw
./lossy_comp_test wav_alaw
./lossy_comp_test wav_gsm610
./lossy_comp_test wav_g721
./peak_chunk_test wav
./header_test wav
./misc_test wav
./string_test wav
./multi_file_test wav
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on WAV files."
echo "----------------------------------------------------------------------"

# w64-tests
./write_read_test w64
./lossy_comp_test w64_ima
./lossy_comp_test w64_msadpcm
./lossy_comp_test w64_ulaw
./lossy_comp_test w64_alaw
./lossy_comp_test w64_gsm610
./header_test w64
./misc_test w64
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on W64 files."
echo "----------------------------------------------------------------------"

# rf64-tests
./write_read_test rf64
./header_test rf64
./misc_test rf64
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on RF64 files."
echo "----------------------------------------------------------------------"

# raw-tests
./write_read_test raw
./lossy_comp_test raw_ulaw
./lossy_comp_test raw_alaw
./lossy_comp_test raw_gsm610
./lossy_comp_test vox_adpcm
./raw_test
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on RAW (header-less) files."
echo "----------------------------------------------------------------------"

# paf-tests
./write_read_test paf
./header_test paf
./misc_test paf
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on PAF files."
echo "----------------------------------------------------------------------"

# svx-tests
./write_read_test svx
./header_test svx
./misc_test svx
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on SVX files."
echo "----------------------------------------------------------------------"

# nist-tests
./write_read_test nist
./lossy_comp_test nist_ulaw
./lossy_comp_test nist_alaw
./header_test nist
./misc_test nist
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on NIST files."
echo "----------------------------------------------------------------------"

# ircam-tests
./write_read_test ircam
./lossy_comp_test ircam_ulaw
./lossy_comp_test ircam_alaw
./header_test ircam
./misc_test ircam
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on IRCAM files."
echo "----------------------------------------------------------------------"

# voc-tests
./write_read_test voc
./lossy_comp_test voc_ulaw
./lossy_comp_test voc_alaw
./header_test voc
./misc_test voc
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on VOC files."
echo "----------------------------------------------------------------------"

# mat4-tests
./write_read_test mat4
./header_test mat4
./misc_test mat4
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on MAT4 files."
echo "----------------------------------------------------------------------"

# mat5-tests
./write_read_test mat5
./header_test mat5
./misc_test mat5
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on MAT5 files."
echo "----------------------------------------------------------------------"

# pvf-tests
./write_read_test pvf
./header_test pvf
./misc_test pvf
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on PVF files."
echo "----------------------------------------------------------------------"

# xi-tests
./lossy_comp_test xi_dpcm
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on XI files."
echo "----------------------------------------------------------------------"

# htk-tests
./write_read_test htk
./header_test htk
./misc_test htk
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on HTK files."
echo "----------------------------------------------------------------------"

# avr-tests
./write_read_test avr
./header_test avr
./misc_test avr
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on AVR files."
echo "----------------------------------------------------------------------"

# sds-tests
./write_read_test sds
./header_test sds
./misc_test sds
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on SDS files."
echo "----------------------------------------------------------------------"

# sd2-tests
./write_read_test sd2
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on SD2 files."
echo "----------------------------------------------------------------------"

# wve-tests
./lossy_comp_test wve
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on WVE files."
echo "----------------------------------------------------------------------"

# mpc2k-tests
./write_read_test mpc2k
./header_test mpc2k
./misc_test mpc2k
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on MPC 2000 files."
echo "----------------------------------------------------------------------"

# flac-tests
./write_read_test flac
./string_test flac
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on FLAC files."
echo "----------------------------------------------------------------------"

# vorbis-tests
./ogg_test
./vorbis_test
./lossy_comp_test ogg_vorbis
./string_test ogg
./misc_test ogg
echo "----------------------------------------------------------------------"
echo "  $sfversion passed tests on OGG/VORBIS files."
echo "----------------------------------------------------------------------"

# io-tests
./stdio_test
./pipe_test
./virtual_io_test
echo "----------------------------------------------------------------------"
echo "  $sfversion passed stdio/pipe/vio tests."
echo "----------------------------------------------------------------------"


text:
'use strict';

// MODULES //

var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var format = require( '@stdlib/string/format' );
var isnan = require( '@stdlib/assert/is-nan' );

// MAIN //

/**
* Validates parameters.
*
* @private
* @param {number} a - minimum support
* @param {number} b - maximum support
* @param {number} c - mode
* @returns {(Error|null)} error or null
*
* @example
* var err = validate( 1.0, 2.0, 1.3 );
* if ( err ) {
*     throw err;
* }
*/
function validate( a, b, c ) {
	if ( !isNumber( a ) || isnan( a ) ) {
		return new TypeError( format( 'invalid argument. First argument must be a number and not NaN. Value: `%s`.', a ) );
	}
	if ( !isNumber( b ) || isnan( b ) ) {
		return new TypeError( format( 'invalid argument. Second argument must be a number and not NaN. Value: `%s`.', b ) );
	}
	if ( !isNumber( c ) || isnan( c ) ) {
		return new TypeError( format( 'invalid argument. Third argument must be a number and not NaN. Value: `%s`.', c ) );
	}
	if ( !(a <= c && c <= b) ) {
		return new RangeError( format( 'invalid arguments. Parameters must satisfy the following condition: %s. a: `%f`. b: `%f`. c: `%f`.', 'a <= c <= b', a, b, c ) );
	}
	return null;
}

// EXPORTS //

module.exports = validate;


text:
define(['require'], function(require) {

  var lessAPI = {};

  lessAPI.pluginBuilder = './less-builder';

  if (typeof window == 'undefined') {
    lessAPI.load = function(n, r, load) { load(); }
    return lessAPI;
  }

  lessAPI.normalize = function(name, normalize) {
    if (name.substr(name.length - 5, 5) == '.less')
      name = name.substr(0, name.length - 5);

    name = normalize(name);

    return name;
  }

  var head = document.getElementsByTagName('head')[0];

  var base = document.getElementsByTagName('base');
  base = base && base[0] && base[0] && base[0].href;
  var pagePath = (base || window.location.href.split('#')[0].split('?')[0]).split('/');
  pagePath[pagePath.length - 1] = '';
  pagePath = pagePath.join('/');

  // set initial default configuration
  window.less = window.less || {
    env: 'development'
  };

  var styleCnt = 0;
  var curStyle;
  lessAPI.inject = function(css) {
    if (styleCnt < 31) {
      curStyle = document.createElement('style');
      curStyle.type = 'text/css';
      head.appendChild(curStyle);
      styleCnt++;
    }
    if (curStyle.styleSheet)
      curStyle.styleSheet.cssText += css;
    else
      curStyle.appendChild(document.createTextNode(css));
  }

  lessAPI.load = function(lessId, req, load, config) {
    require(['./lessc', './normalize'], function(lessc, normalize) {

      var fileUrl = req.toUrl(lessId + '.less');
      fileUrl = normalize.absoluteURI(fileUrl, pagePath);

      var parser = new lessc.Parser(window.less);

      parser.parse('@import (multiple) "' + fileUrl + '";', function(err, tree) {
        if (err)
          return load.error(err);

        lessAPI.inject(normalize(tree.toCSS(config.less), fileUrl, pagePath));

        setTimeout(load, 7);
      });

    });
  }

  return lessAPI;
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Einführung - Zend Framework Manual</title>

                    Zend_Dojo

Zend_Dojo

                        Programmer's Reference Guide

Zend_Dojo_Data: dojo.data Envelopes

Einführung

        Zend Framework wird mit dem
        » Dojo Toolkit ausgeliefert um Out-Of-The-Box
        reiche Entwicklung von Internet Anwendungen zu unterstützen. Die Integrationspunkte mit Dojo
        enthalten:

<acronym class="acronym">JSON-RPC</acronym> Unterstützung

dojo.data Kompatibilität

View Helfer um beim Setup der Dojo Umgebung zu helfen

Dijit-spezifische Zend_View Helfer

Dijit-spezifische Zend_Form Elemente und Dekoratore

        Die Dojo Distribution selbst kann im <var class="filename">externals/dojo/</var> Verzeichnis der
        Zend Framework Distribution gefunden werden. Es ist eine Source Distribution, welche Dojo's
        kompletten Javascript Source enthält, Unit Tests und Build Tools. Man kann das ins eigene
        Javascript Verzeichnis symbolisch linken, es kopieren, oder das Build Tool verwenden um
        einen eigenen Build zu erstellen und ins eigene Projekt zu inkludieren. Alternativ kann
        eines der Content Delivery Networks verwendet werden die Dojo anbietet (Zend Framework
        unterstützt beide, den offiziellen <acronym class="acronym">AOL</acronym> <acronym class="acronym">CDN</acronym> sowie den
        Google <acronym class="acronym">CDN</acronym>).

                    Zend_Dojo

Zend_Dojo

                        Programmer's Reference Guide

Zend_Dojo_Data: dojo.data Envelopes

Programmer's Reference Guide

Programmer's Reference Guide

Zend Framework Reference

Zend_Dojo

Einführung

Zend_Dojo_Data: dojo.data Envelopes

Dojo View Helfer

Formular Elemente und Dekoratore für Dojo

Support für den Build Layer von Zend_Dojo


text:
export function Stack() {

    this.count = 0;
    this.storage = {};

    this.push = function (value) {
        this.storage[this.count] = value;
        this.count++;
    }

    this.pop = function () {
        if (this.count === 0) {
            return undefined;
        }

        this.count--;
        var result = this.storage[this.count];
        delete this.storage[this.count];
        return result;
    }

    this.size = function () {
        return this.count;
    }

    this.peek = function () {
        return this.storage[this.count - 1];
    }

    return this;
}


text:
#include "archive_platform.h"

__FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_compression_bzip2.c 201091 2009-12-28 02:22:41Z kientzle $");

#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#include <stdio.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_BZLIB_H
#include <bzlib.h>
#endif

#include "archive.h"
#include "archive_private.h"
#include "archive_write_private.h"

#if ARCHIVE_VERSION_NUMBER < 4000000
int
archive_write_set_compression_bzip2(struct archive *a)
{
	__archive_write_filters_free(a);
	return (archive_write_add_filter_bzip2(a));
}
#endif

struct private_data {
	int		 compression_level;
#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
	bz_stream	 stream;
	int64_t		 total_in;
	char		*compressed;
	size_t		 compressed_buffer_size;
#else
	struct archive_write_program_data *pdata;
#endif
};

static int archive_compressor_bzip2_close(struct archive_write_filter *);
static int archive_compressor_bzip2_free(struct archive_write_filter *);
static int archive_compressor_bzip2_open(struct archive_write_filter *);
static int archive_compressor_bzip2_options(struct archive_write_filter *,
		    const char *, const char *);
static int archive_compressor_bzip2_write(struct archive_write_filter *,
		    const void *, size_t);

/*
 * Add a bzip2 compression filter to this write handle.
 */
int
archive_write_add_filter_bzip2(struct archive *_a)
{
	struct archive_write *a = (struct archive_write *)_a;
	struct archive_write_filter *f = __archive_write_allocate_filter(_a);
	struct private_data *data;

	archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC,
	    ARCHIVE_STATE_NEW, "archive_write_add_filter_bzip2");

	data = calloc(1, sizeof(*data));
	if (data == NULL) {
		archive_set_error(&a->archive, ENOMEM, "Out of memory");
		return (ARCHIVE_FATAL);
	}
	data->compression_level = 9; /* default */

	f->data = data;
	f->options = &archive_compressor_bzip2_options;
	f->close = &archive_compressor_bzip2_close;
	f->free = &archive_compressor_bzip2_free;
	f->open = &archive_compressor_bzip2_open;
	f->code = ARCHIVE_FILTER_BZIP2;
	f->name = "bzip2";
#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
	return (ARCHIVE_OK);
#else
	data->pdata = __archive_write_program_allocate("bzip2");
	if (data->pdata == NULL) {
		free(data);
		archive_set_error(&a->archive, ENOMEM, "Out of memory");
		return (ARCHIVE_FATAL);
	}
	data->compression_level = 0;
	archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
	    "Using external bzip2 program");
	return (ARCHIVE_WARN);
#endif
}

/*
 * Set write options.
 */
static int
archive_compressor_bzip2_options(struct archive_write_filter *f,
    const char *key, const char *value)
{
	struct private_data *data = (struct private_data *)f->data;

	if (strcmp(key, "compression-level") == 0) {
		if (value == NULL || !(value[0] >= '0' && value[0] <= '9') ||
		    value[1] != '\0')
			return (ARCHIVE_WARN);
		data->compression_level = value[0] - '0';
		/* Make '0' be a synonym for '1'. */
		/* This way, bzip2 compressor supports the same 0..9
		 * range of levels as gzip. */
		if (data->compression_level < 1)
			data->compression_level = 1;
		return (ARCHIVE_OK);
	}

	/* Note: The "warn" return is just to inform the options
	 * supervisor that we didn't handle it.  It will generate
	 * a suitable error if no one used this option. */
	return (ARCHIVE_WARN);
}

#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
/* Don't compile this if we don't have bzlib. */

/*
 * Yuck.  bzlib.h is not const-correct, so I need this one bit
 * of ugly hackery to convert a const * pointer to a non-const pointer.
 */
#define	SET_NEXT_IN(st,src)					\
	(st)->stream.next_in = (char *)(uintptr_t)(const void *)(src)
static int drive_compressor(struct archive_write_filter *,
		    struct private_data *, int finishing);

/*
 * Setup callback.
 */
static int
archive_compressor_bzip2_open(struct archive_write_filter *f)
{
	struct private_data *data = (struct private_data *)f->data;
	int ret;

	ret = __archive_write_open_filter(f->next_filter);
	if (ret != 0)
		return (ret);

	if (data->compressed == NULL) {
		size_t bs = 65536, bpb;
		if (f->archive->magic == ARCHIVE_WRITE_MAGIC) {
			/* Buffer size should be a multiple number of the of bytes
			 * per block for performance. */
			bpb = archive_write_get_bytes_per_block(f->archive);
			if (bpb > bs)
				bs = bpb;
			else if (bpb != 0)
				bs -= bs % bpb;
		}
		data->compressed_buffer_size = bs;
		data->compressed
		    = (char *)malloc(data->compressed_buffer_size);
		if (data->compressed == NULL) {
			archive_set_error(f->archive, ENOMEM,
			    "Can't allocate data for compression buffer");
			return (ARCHIVE_FATAL);
		}
	}

	memset(&data->stream, 0, sizeof(data->stream));
	data->stream.next_out = data->compressed;
	data->stream.avail_out = data->compressed_buffer_size;
	f->write = archive_compressor_bzip2_write;

	/* Initialize compression library */
	ret = BZ2_bzCompressInit(&(data->stream),
	    data->compression_level, 0, 30);
	if (ret == BZ_OK) {
		f->data = data;
		return (ARCHIVE_OK);
	}

	/* Library setup failed: clean up. */
	archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
	    "Internal error initializing compression library");

	/* Override the error message if we know what really went wrong. */
	switch (ret) {
	case BZ_PARAM_ERROR:
		archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
		    "Internal error initializing compression library: "
		    "invalid setup parameter");
		break;
	case BZ_MEM_ERROR:
		archive_set_error(f->archive, ENOMEM,
		    "Internal error initializing compression library: "
		    "out of memory");
		break;
	case BZ_CONFIG_ERROR:
		archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
		    "Internal error initializing compression library: "
		    "mis-compiled library");
		break;
	}

	return (ARCHIVE_FATAL);

}

/*
 * Write data to the compressed stream.
 *
 * Returns ARCHIVE_OK if all data written, error otherwise.
 */
static int
archive_compressor_bzip2_write(struct archive_write_filter *f,
    const void *buff, size_t length)
{
	struct private_data *data = (struct private_data *)f->data;

	/* Update statistics */
	data->total_in += length;

	/* Compress input data to output buffer */
	SET_NEXT_IN(data, buff);
	data->stream.avail_in = length;
	if (drive_compressor(f, data, 0))
		return (ARCHIVE_FATAL);
	return (ARCHIVE_OK);
}

/*
 * Finish the compression.
 */
static int
archive_compressor_bzip2_close(struct archive_write_filter *f)
{
	struct private_data *data = (struct private_data *)f->data;
	int ret, r1;

	/* Finish compression cycle. */
	ret = drive_compressor(f, data, 1);
	if (ret == ARCHIVE_OK) {
		/* Write the last block */
		ret = __archive_write_filter(f->next_filter,
		    data->compressed,
		    data->compressed_buffer_size - data->stream.avail_out);
	}

	switch (BZ2_bzCompressEnd(&(data->stream))) {
	case BZ_OK:
		break;
	default:
		archive_set_error(f->archive, ARCHIVE_ERRNO_PROGRAMMER,
		    "Failed to clean up compressor");
		ret = ARCHIVE_FATAL;
	}

	r1 = __archive_write_close_filter(f->next_filter);
	return (r1 < ret ? r1 : ret);
}

static int
archive_compressor_bzip2_free(struct archive_write_filter *f)
{
	struct private_data *data = (struct private_data *)f->data;
	free(data->compressed);
	free(data);
	f->data = NULL;
	return (ARCHIVE_OK);
}

/*
 * Utility function to push input data through compressor, writing
 * full output blocks as necessary.
 *
 * Note that this handles both the regular write case (finishing ==
 * false) and the end-of-archive case (finishing == true).
 */
static int
drive_compressor(struct archive_write_filter *f,
    struct private_data *data, int finishing)
{
	int ret;

	for (;;) {
		if (data->stream.avail_out == 0) {
			ret = __archive_write_filter(f->next_filter,
			    data->compressed,
			    data->compressed_buffer_size);
			if (ret != ARCHIVE_OK) {
				/* TODO: Handle this write failure */
				return (ARCHIVE_FATAL);
			}
			data->stream.next_out = data->compressed;
			data->stream.avail_out = data->compressed_buffer_size;
		}

		/* If there's nothing to do, we're done. */
		if (!finishing && data->stream.avail_in == 0)
			return (ARCHIVE_OK);

		ret = BZ2_bzCompress(&(data->stream),
		    finishing ? BZ_FINISH : BZ_RUN);

		switch (ret) {
		case BZ_RUN_OK:
			/* In non-finishing case, did compressor
			 * consume everything? */
			if (!finishing && data->stream.avail_in == 0)
				return (ARCHIVE_OK);
			break;
		case BZ_FINISH_OK:  /* Finishing: There's more work to do */
			break;
		case BZ_STREAM_END: /* Finishing: all done */
			/* Only occurs in finishing case */
			return (ARCHIVE_OK);
		default:
			/* Any other return value indicates an error */
			archive_set_error(f->archive,
			    ARCHIVE_ERRNO_PROGRAMMER,
			    "Bzip2 compression failed;"
			    " BZ2_bzCompress() returned %d",
			    ret);
			return (ARCHIVE_FATAL);
		}
	}
}

#else /* HAVE_BZLIB_H && BZ_CONFIG_ERROR */

static int
archive_compressor_bzip2_open(struct archive_write_filter *f)
{
	struct private_data *data = (struct private_data *)f->data;
	struct archive_string as;
	int r;

	archive_string_init(&as);
	archive_strcpy(&as, "bzip2");

	/* Specify compression level. */
	if (data->compression_level > 0) {
		archive_strcat(&as, " -");
		archive_strappend_char(&as, '0' + data->compression_level);
	}
	f->write = archive_compressor_bzip2_write;

	r = __archive_write_program_open(f, data->pdata, as.s);
	archive_string_free(&as);
	return (r);
}

static int
archive_compressor_bzip2_write(struct archive_write_filter *f, const void *buff,
    size_t length)
{
	struct private_data *data = (struct private_data *)f->data;

	return __archive_write_program_write(f, data->pdata, buff, length);
}

static int
archive_compressor_bzip2_close(struct archive_write_filter *f)
{
	struct private_data *data = (struct private_data *)f->data;

	return __archive_write_program_close(f, data->pdata);
}

static int
archive_compressor_bzip2_free(struct archive_write_filter *f)
{
	struct private_data *data = (struct private_data *)f->data;

	__archive_write_program_free(data->pdata);
	free(data);
	return (ARCHIVE_OK);
}

#endif /* HAVE_BZLIB_H && BZ_CONFIG_ERROR */


text:
/* etherfun.h */

/* constants */
/* ether header */
#define ETYPE_RARP 0x8035  /* ethertype is RARP */
#define ETYPE_IP   0x800   /* ethertype is IP   */

/* rev arp */
#define PTYPE_IP 0x800     /* Protocol type is IP      */
#define OPCODE_RARP 3      /* Optype is REVARP request */
#define OPCODE_REPLY 4     /* Optype is REVARP reply   */

/* ip header */
#define  IPP_UDP 17	/* IP Protocol is UDP       */
#define  IP_VERSION 4      /* IP version number	*/
#define  IP_HLEN 5	 /* IP header length is a fixed 50 bytes */
#define N 1536

/* tftp header */
#define FTPOP_ACKN 4      /* Opcode is acknowledge     */
#define FTPOP_ERR 5       /* Opcode is Error	       */
#define FTP_PORT 69       /* Standard TFTP port number */
#define MSG "\0\1xxxxxxxx.mvme68k\0octet\0" /* implicit NULL */

/* data structures */

struct  ether_header {
	u_char  ether_dhost[6];
	u_char  ether_shost[6];
	u_short ether_type;
};

struct  ether_arp {
	u_short ar_hrd;		/* format of hardware address */
	u_short ar_pro;		/* format of protocol address */
	u_char  ar_hln;		/* length of hardware address */
	u_char  ar_pln;		/* length of protocol address */
	u_short ar_op;
	u_char  arp_sha[6];	/* sender hardware address */
	u_char  arp_spa[4];	/* sender protocol address */
	u_char  arp_tha[6];	/* target hardware address */
	u_char  arp_tpa[4];	/* target protocol address */
};

struct ip {
	u_char  ip_v:4,		/* version */
		ip_hl:4;	/* header length */
	u_char  ip_tos;		/* type of service */
	short   ip_len;		/* total length */
	u_short ip_id;		/* identification */
	short   ip_off;		/* fragment offset field */
#define IP_DF 0x4000		/* dont fragment flag */
#define IP_MF 0x2000		/* more fragments flag */
#define IP_OFFMASK 0x1fff	/* mask for fragmenting bits */
	u_char  ip_ttl;		/* time to live */
	u_char  ip_p;		/* protocol */
	u_short ip_sum;		/* checksum */
	u_char  ip_src[4];
	u_char  ip_dst[4];	/* source and dest address */
};

struct udp {
	u_short uh_sport;
	u_short uh_dport;
	short uh_ulen;
	u_short uh_sum;
};

struct tftph {
	u_short	op_code;
	u_short	block;
};

struct tftphr {
	struct tftph info;
	char	data[1];
};

/* globals */
int last_ack;
char buf[N];
struct ether_header *eh = (struct ether_header *)buf;
struct ether_arp *rarp = (struct ether_arp *)
	(buf + sizeof(struct ether_header));
struct ip *iph = (struct ip *)(buf + sizeof(struct ether_header));
struct udp *udph = (struct udp *)
	(buf + sizeof(struct ether_header) + sizeof(struct ip));
char *tftp_r = buf + sizeof(struct ether_header) + sizeof(struct ip) +
	sizeof(struct udp);
struct tftph *tftp_a = (struct tftph *)(buf + sizeof(struct ether_header) +
	sizeof(struct ip) + sizeof(struct udp));
struct tftphr *tftp = (struct tftphr *)(buf + sizeof(struct ether_header) +
	sizeof(struct ip) + sizeof(struct udp));


text:
<?php

namespace Buzz\Test\Client;

use Buzz\Message;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideInvalidHosts
     */
    public function testSendToInvalidUrl($host, $client)
    {
        $this->setExpectedException('Buzz\\Exception\\ClientException');

        $request = new Message\Request();
        $request->fromUrl('http://'.$host.':12345');

        $response = new Message\Response();

        $client = new $client();
        $client->setTimeout(0.05);
        $client->send($request, $response);
    }

    public function provideInvalidHosts()
    {
        return array(
            array('invalid_domain', 'Buzz\\Client\\Curl'),
            array('invalid_domain.buzz', 'Buzz\\Client\\Curl'),

            array('invalid_domain', 'Buzz\\Client\\FileGetContents'),
            array('invalid_domain.buzz', 'Buzz\\Client\\FileGetContents'),
        );
    }
}


text:
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';

//set up testing environment to run like browser inthe command line

global.document = jsdom.jsdom('<!doctype html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);  // jquery be responsible for fake instance of dom we made (window)

// set up chai-jquery

chaiJquery(chai, chai.util, $);

// build 'renderComponent' helper that should render a given react class

function renderComponent(ComponentClass, props = {}, state = {}) {
  const componentInstance =  TestUtils.renderIntoDocument(
    <Provider store={createStore(reducers, state)}>
      <ComponentClass {...props} />
    </Provider>
  );

  return $(ReactDOM.findDOMNode(componentInstance)); // produces HTML
}

// build 'renderComponent' helper that should render a given react class
//.fn opens simulate to all jquery

$.fn.simulate = function(eventName, value) {
  if (value) {
    this.val(value);
  }
  TestUtils.Simulate[eventName](this[0]);
};

export {renderComponent, expect};


text:
{% extends "base.html" %}
{% block head %}
  <title>Chrome Performance Test Owners</title>

  <link rel="import" href="/third_party/polymer/components/polymer/polymer.html">
  <link rel="import" href="/dashboard/elements/editable-list.html">

{% endblock %}
{% block content %}

Chrome Performance Test Owners

    <editable-list id="edit-owner-list"
                   xsrfToken="{{xsrf_token | safe}}"></editable-list>

{% endblock %}
{% include 'analytics.html' %}


text:
module.exports = {
    // The key you want to use. It could be the master key, the device key
    // or the stream key, depending on the endpoints you plan to use.
    api_key: "<YOUR-API-KEY>",
    // The device you want to use. This is required for device related endpoints.
    device:  "<YOUR-DEVICE-ID>",
    // The collection you want to use. This is required for collection related endpoints.
    collectionId: "<YOUR-COLLECTION-ID>",
    // The distribution you want to use. This is required for distribution related endpoints.
    distributionId: "<YOUR-DISTRIBUTION-ID>"
};


text:
package org.reactivecouchbase.play.plugins

import play.api._
import scala.reflect.io.Directory
import play.api.libs.Codecs
import play.api.libs.json._
import scala.concurrent.{Future, Await, ExecutionContext}
import scala.concurrent.duration.Duration
import java.util.concurrent.TimeUnit
import org.reactivecouchbase.{Couchbase, CouchbaseBucket}
import org.reactivecouchbase.play.PlayCouchbase
import org.reactivecouchbase.client.OpResult

/**
 * @author Didier Bathily - https://github.com/dbathily
 */
case class DocumentDescription(fileName:String, bucket:CouchbaseBucket , bytes:Array[Byte]) {

  lazy val hash = Codecs.sha1(bytes)
  lazy val json = Json.parse(bytes)

  lazy val name = (json \ "name").asOpt[String].getOrElse(fileName)

  def put(dev:Boolean)(implicit ec:ExecutionContext):Future[OpResult] = {
    Couchbase.createDesignDoc(DocumentDescription.name(name, dev), json.as[JsObject])(bucket, ec)
  }

}

object DocumentDescription {
  def name(name:String, dev: Boolean):String = {
    if (dev) "dev_"+name else name
  }
}

object CouchbaseEvolutions {

  lazy val logger = Logger(classOf[CouchbaseEvolutionsPlugin])

  /*
  TODO : There is no way to list design documents of the bucket using the client
  See : http://www.couchbase.com/issues/browse/JCBC-306
   */
  def designDocuments(bucket: CouchbaseBucket)(implicit ec:ExecutionContext):List[String] = {
    List()
  }

  def perform(docs: Iterator[DocumentDescription], synchronise:Boolean, dev:Boolean = true)(implicit bucket:CouchbaseBucket, ec:ExecutionContext) = {

    if(synchronise)
      designDocuments(bucket).filterNot { name =>
        docs.exists(nd => DocumentDescription.name(nd.name, dev) == DocumentDescription.name(name, dev))
      }.foldLeft(List[OpResult]()) {
        (res, doc) => {
          val name = DocumentDescription.name(doc, dev)
          val status = Await.result(Couchbase.deleteDesignDoc(name), Duration(1, TimeUnit.SECONDS))
          if(!status.isSuccess)
            logger.warn(s"Fail to delete design document $name : ${status.getMessage}")
          res :+ status
        }
      }

    docs.foldLeft(List[OpResult]()) {
      (res, doc) => {
        val status = Await.result(doc.put(dev), Duration(1, TimeUnit.SECONDS))
        if(!status.isSuccess)
          logger.warn(s"Fail to create design document ${doc.name} : ${status.getMessage}")
        res :+ status
      }
    }

  }

}

class CouchbaseEvolutionsPlugin(app: Application) extends Plugin {

  import CouchbaseEvolutions._

  lazy val conf = app.configuration.getConfig("couchbase").getOrElse(Configuration.empty)
  lazy val evolutionConf = conf.getConfig("evolutions").getOrElse(Configuration.empty)

  lazy val docs = evolutionConf.getString("documents").getOrElse("conf/views")

  implicit val ec = PlayCouchbase.couchbaseExecutor(app)

  override lazy val enabled = !evolutionConf.getBoolean("disabled").exists(_ == true)

  /**
   * Checks the evolutions state.
   */
  override def onStart() {

    PlayCouchbase.buckets(app).foreach {
      case(name, bucket) => {
        implicit val b = bucket

        val bucketConf = evolutionConf.getConfig(name).getOrElse(Configuration.empty)
        val applyEvolutions = bucketConf.getBoolean("apply").exists(_ == true)
        val synchronise = bucketConf.getBoolean("synchronise").exists(_ == true)

        withLock() {
          Play.getExistingFile(s"$docs/$name")(app).map { folder =>
            logger.debug(s"Search couchbase documents for bucket $name in ${folder.getAbsolutePath}")
            val documents = new Directory(folder).files.filter(_.toFile.name.endsWith(".json")).map { path =>
              DocumentDescription(path.name.replaceAll("""\.[^.]*$""", ""), bucket, path.toFile.toByteArray()) //Resource.fromInputStream(path.toFile.inputStream()).byteArray)
            }

            if(!documents.isEmpty) {
              app.mode match {
                case Mode.Test => perform(documents, synchronise)
                case Mode.Dev if applyEvolutions => perform(documents, synchronise)
                case Mode.Prod if applyEvolutions => perform(documents, synchronise, false)
                case Mode.Prod => {
                  Logger("play").warn(s"Your production bucket $name needs couchbase design documents evolution!\n\n")
                  Logger("play").warn(s"Run with -Dcouchbase.evolutions.$name.apply=true if you want to run them automatically (be careful)")

                  throw new PlayException(s"Couchbase evolution should be applied, set couchbase.evolutions.$name.apply=true in application.conf", null)
                }
                case _ => new PlayException(s"Couchbase evolution should be applied, set couchbase.evolutions.$name.apply=true in application.conf", null)
              }
            }

          }
        }
      }
    }
  }

  def withLock()(block: => Unit)(implicit bucket: CouchbaseBucket, ec: ExecutionContext) {
    if (evolutionConf.getBoolean("use.locks").getOrElse(true)) {
      lock()
      try {
        block
      } finally {
        unlock()
      }
    } else {
      block
    }
  }

  def lock(attempts: Int = 5)(implicit bucket: CouchbaseBucket, ec:ExecutionContext) {
    try {
      logger.debug(s"Attempting to acquire lock for couchbase evolutions on bucket ${bucket.alias}...")

      val maybe = Await.result(Couchbase.get[JsValue]("couchbase_evolution_lock"), Duration(1, TimeUnit.SECONDS))

      if(maybe.map(json => (json \ "locked").as[Int]).getOrElse(0) == 1) throw new LockedEvolution(bucket)

      val status = Await.result(Couchbase.set("couchbase_evolution_lock", Json.obj("locked" -> JsNumber(1))), Duration(1, TimeUnit.SECONDS))

      if(!status.isSuccess) throw new LockedEvolution(bucket)
      logger.debug("locked!")

    } catch {
      case e:LockedEvolution =>
        if (attempts == 0) throw e
        else {
          logger.warn(e.content() + ", sleeping for 1 sec")
          Thread.sleep(1000)
          lock(attempts - 1)
        }
    }
  }

  def unlock()(implicit bucket: CouchbaseBucket, ec:ExecutionContext) {
    logger.debug(s"Attempting to release lock for couchbase evolutions on bucket ${bucket.alias}...")
    Await.result(Couchbase.delete("couchbase_evolution_lock"), Duration(1, TimeUnit.SECONDS))
    logger.debug("unlocked!")
  }
}

case class LockedEvolution(bucket:CouchbaseBucket) extends PlayException.RichDescription(
  s"Bucket ${bucket.alias} locked",
  "Exception while attempting to lock couchbase evolutions (other node probably has lock)"
  ) {

  def subTitle(): String = s"Bucket ${bucket.alias} locked"

  def content(): String = "Exception while attempting to lock couchbase evolutions (other node probably has lock)"

  def htmlDescription(): String = {

    Unable to run couchbase evolution on bucket {bucket.alias}

  }.mkString
}


text:
<?php
/**
 * Definition of the IsLessThanOrEqualToType type
 *
 * @author Michal Korzeniowski <mko_san@lafiel.net>
 */

class EWSType_IsLessThanOrEqualToType extends EWSType {
	/**
	 * SearchExpression property
	 *
	 * @var EWSType_TwoOperandExpressionType
	 */
	public $SearchExpression;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->schema = array(
			array(
				'name' => 'SearchExpression',
				'required' => false,
				'type' => 'TwoOperandExpressionType',
			),
		); // end $this->schema
	} // end function __construct()
} // end class IsLessThanOrEqualToType


text:
package fbm

import "github.com/strongo/bots-framework/core"

// WebhookChat provides information about current FBM chat
type WebhookChat struct {
	ID string
}

var _ bots.WebhookChat = (*WebhookChat)(nil)

// GetID returns ID of current FBM chat
func (wh WebhookChat) GetID() string {
	return wh.ID
}

// GetType returns type of bot chat, always 'private' for FBM
func (wh WebhookChat) GetType() string {
	return "private"
}

// IsGroupChat indicates if current chat is a group one. Always false for FBM
func (wh WebhookChat) IsGroupChat() bool {
	return false
}

// NewFbmWebhookChat creates a new FBM chat instance
func NewFbmWebhookChat(id string) WebhookChat {
	return WebhookChat{
		ID: id,
	}
}


text:
class ContentStore
  def initialize
    @content = {}
  end

  def capture(key, value = nil)
    @content[key] = block_given? ? yield : value
    nil
  end

  def [](key)
    @content[key]
  end
end


text:
package config

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"time"
)

type Config struct {
	CacheDir            string          `json:"cachedir"`
	DiffDir             string          `json:"diffdir"`
	Connection          string          `json:"connection"`
	MappingFile         string          `json:"mapping"`
	LimitTo             string          `json:"limitto"`
	LimitToCacheBuffer  float64         `json:"limitto_cache_buffer"`
	Srid                int             `json:"srid"`
	Schemas             Schemas         `json:"schemas"`
	ExpireTilesDir      string          `json:"expiretiles_dir"`
	ExpireTilesZoom     int             `json:"expiretiles_zoom"`
	ReplicationUrl      string          `json:"replication_url"`
	ReplicationInterval MinutesInterval `json:"replication_interval"`
}

type Schemas struct {
	Import     string `json:"import"`
	Production string `json:"production"`
	Backup     string `json:"backup"`
}

const defaultSrid = 3857
const defaultCacheDir = "/tmp/imposm3"
const defaultSchemaImport = "import"
const defaultSchemaProduction = "public"
const defaultSchemaBackup = "backup"

var ImportFlags = flag.NewFlagSet("import", flag.ExitOnError)
var DiffFlags = flag.NewFlagSet("diff", flag.ExitOnError)
var RunFlags = flag.NewFlagSet("run", flag.ExitOnError)

type _BaseOptions struct {
	Connection          string
	CacheDir            string
	DiffDir             string
	MappingFile         string
	Srid                int
	LimitTo             string
	LimitToCacheBuffer  float64
	ConfigFile          string
	Httpprofile         string
	Quiet               bool
	Schemas             Schemas
	ExpireTilesDir      string
	ExpireTilesZoom     int
	ReplicationUrl      string
	ReplicationInterval time.Duration
}

func (o *_BaseOptions) updateFromConfig() error {
	conf := &Config{
		CacheDir: defaultCacheDir,
		Srid:     defaultSrid,
	}

	if o.ConfigFile != "" {
		f, err := os.Open(o.ConfigFile)
		if err != nil {
			return err
		}
		decoder := json.NewDecoder(f)

		err = decoder.Decode(&conf)
		if err != nil {
			return err
		}
	}

	if conf.Schemas.Import != "" && o.Schemas.Import == defaultSchemaImport {
		o.Schemas.Import = conf.Schemas.Import
	}
	if conf.Schemas.Production != "" && o.Schemas.Production == defaultSchemaProduction {
		o.Schemas.Production = conf.Schemas.Production
	}
	if conf.Schemas.Backup != "" && o.Schemas.Backup == defaultSchemaBackup {
		o.Schemas.Backup = conf.Schemas.Backup
	}

	if o.Connection == "" {
		o.Connection = conf.Connection
	}
	if conf.Srid == 0 {
		conf.Srid = defaultSrid
	}
	if o.Srid == defaultSrid {
		o.Srid = conf.Srid
	}
	if o.MappingFile == "" {
		o.MappingFile = conf.MappingFile
	}
	if o.LimitTo == "" {
		o.LimitTo = conf.LimitTo
	}
	if o.LimitTo == "NONE" {
		// allow overwrite from cmd line
		o.LimitTo = ""
	}
	if o.LimitToCacheBuffer == 0.0 {
		o.LimitToCacheBuffer = conf.LimitToCacheBuffer
	}
	if o.CacheDir == defaultCacheDir {
		o.CacheDir = conf.CacheDir
	}

	if o.ExpireTilesDir == "" {
		o.ExpireTilesDir = conf.ExpireTilesDir
	}
	if o.ExpireTilesZoom == 0 {
		o.ExpireTilesZoom = conf.ExpireTilesZoom
	}
	if o.ExpireTilesZoom < 6 || o.ExpireTilesZoom > 18 {
		o.ExpireTilesZoom = 14
	}

	if conf.ReplicationInterval.Duration != 0 && o.ReplicationInterval != time.Minute {
		o.ReplicationInterval = conf.ReplicationInterval.Duration
	}
	if o.ReplicationInterval < time.Minute {
		o.ReplicationInterval = time.Minute
	}
	o.ReplicationUrl = conf.ReplicationUrl

	if o.DiffDir == "" {
		if conf.DiffDir == "" {
			// use CacheDir for backwards compatibility
			o.DiffDir = o.CacheDir
		} else {
			o.DiffDir = conf.DiffDir
		}
	}
	return nil
}

func (o *_BaseOptions) check() []error {
	errs := []error{}
	if o.Srid != 3857 && o.Srid != 4326 {
		errs = append(errs, errors.New("only -srid=3857 or -srid=4326 are supported"))
	}
	if o.MappingFile == "" {
		errs = append(errs, errors.New("missing mapping"))
	}
	return errs
}

type _ImportOptions struct {
	Overwritecache   bool
	Appendcache      bool
	Read             string
	Write            bool
	Optimize         bool
	Diff             bool
	DeployProduction bool
	RevertDeploy     bool
	RemoveBackup     bool
	DiffStateBefore  time.Duration
}

var BaseOptions = _BaseOptions{}
var ImportOptions = _ImportOptions{}

func addBaseFlags(flags *flag.FlagSet) {
	flags.StringVar(&BaseOptions.Connection, "connection", "", "connection parameters")
	flags.StringVar(&BaseOptions.CacheDir, "cachedir", defaultCacheDir, "cache directory")
	flags.StringVar(&BaseOptions.DiffDir, "diffdir", "", "diff directory for last.state.txt")
	flags.StringVar(&BaseOptions.MappingFile, "mapping", "", "mapping file")
	flags.IntVar(&BaseOptions.Srid, "srid", defaultSrid, "srs id")
	flags.StringVar(&BaseOptions.LimitTo, "limitto", "", "limit to geometries")
	flags.Float64Var(&BaseOptions.LimitToCacheBuffer, "limittocachebuffer", 0.0, "limit to buffer for cache")
	flags.StringVar(&BaseOptions.ConfigFile, "config", "", "config (json)")
	flags.StringVar(&BaseOptions.Httpprofile, "httpprofile", "", "bind address for profile server")
	flags.BoolVar(&BaseOptions.Quiet, "quiet", false, "quiet log output")
	flags.StringVar(&BaseOptions.Schemas.Import, "dbschema-import", defaultSchemaImport, "db schema for imports")
	flags.StringVar(&BaseOptions.Schemas.Production, "dbschema-production", defaultSchemaProduction, "db schema for production")
	flags.StringVar(&BaseOptions.Schemas.Backup, "dbschema-backup", defaultSchemaBackup, "db schema for backups")
}

func UsageImport() {
	fmt.Fprintf(os.Stderr, "Usage: %s %s [args]\n\n", os.Args[0], os.Args[1])
	ImportFlags.PrintDefaults()
	os.Exit(2)
}

func UsageDiff() {
	fmt.Fprintf(os.Stderr, "Usage: %s %s [args] [.osc.gz, ...]\n\n", os.Args[0], os.Args[1])
	DiffFlags.PrintDefaults()
	os.Exit(2)
}

func UsageRun() {
	fmt.Fprintf(os.Stderr, "Usage: %s %s [args] [.osc.gz, ...]\n\n", os.Args[0], os.Args[1])
	DiffFlags.PrintDefaults()
	os.Exit(2)
}

func init() {
	ImportFlags.Usage = UsageImport
	DiffFlags.Usage = UsageDiff
	RunFlags.Usage = UsageRun

	addBaseFlags(DiffFlags)
	addBaseFlags(ImportFlags)
	addBaseFlags(RunFlags)
	ImportFlags.BoolVar(&ImportOptions.Overwritecache, "overwritecache", false, "overwritecache")
	ImportFlags.BoolVar(&ImportOptions.Appendcache, "appendcache", false, "append cache")
	ImportFlags.StringVar(&ImportOptions.Read, "read", "", "read")
	ImportFlags.BoolVar(&ImportOptions.Write, "write", false, "write")
	ImportFlags.BoolVar(&ImportOptions.Optimize, "optimize", false, "optimize")
	ImportFlags.BoolVar(&ImportOptions.Diff, "diff", false, "enable diff support")
	ImportFlags.BoolVar(&ImportOptions.DeployProduction, "deployproduction", false, "deploy production")
	ImportFlags.BoolVar(&ImportOptions.RevertDeploy, "revertdeploy", false, "revert deploy to production")
	ImportFlags.BoolVar(&ImportOptions.RemoveBackup, "removebackup", false, "remove backups from deploy")
	ImportFlags.DurationVar(&ImportOptions.DiffStateBefore, "diff-state-before", 2*time.Hour, "set initial diff sequence before")

	DiffFlags.StringVar(&BaseOptions.ExpireTilesDir, "expiretiles-dir", "", "write expire tiles into dir")
	DiffFlags.IntVar(&BaseOptions.ExpireTilesZoom, "expiretiles-zoom", 14, "write expire tiles in this zoom level")

	RunFlags.StringVar(&BaseOptions.ExpireTilesDir, "expiretiles-dir", "", "write expire tiles into dir")
	RunFlags.IntVar(&BaseOptions.ExpireTilesZoom, "expiretiles-zoom", 14, "write expire tiles in this zoom level")
	RunFlags.DurationVar(&BaseOptions.ReplicationInterval, "replication-interval", time.Minute, "replication interval as duration (1m, 1h, 24h)")
}

func ParseImport(args []string) {
	if len(args) == 0 {
		UsageImport()
	}
	err := ImportFlags.Parse(args)
	if err != nil {
		log.Fatal(err)
	}
	err = BaseOptions.updateFromConfig()
	if err != nil {
		log.Fatal(err)
	}
	errs := BaseOptions.check()
	if len(errs) != 0 {
		reportErrors(errs)
		UsageImport()
	}
}

func ParseDiffImport(args []string) {
	if len(args) == 0 {
		UsageDiff()
	}
	err := DiffFlags.Parse(args)
	if err != nil {
		log.Fatal(err)
	}

	err = BaseOptions.updateFromConfig()
	if err != nil {
		log.Fatal(err)
	}

	errs := BaseOptions.check()
	if len(errs) != 0 {
		reportErrors(errs)
		UsageDiff()
	}
}

func ParseRunImport(args []string) {
	if len(args) == 0 {
		UsageRun()
	}
	err := RunFlags.Parse(args)
	if err != nil {
		log.Fatal(err)
	}

	err = BaseOptions.updateFromConfig()
	if err != nil {
		log.Fatal(err)
	}

	errs := BaseOptions.check()
	if len(errs) != 0 {
		reportErrors(errs)
		UsageRun()
	}
}

func reportErrors(errs []error) {
	fmt.Println("errors in config/options:")
	for _, err := range errs {
		fmt.Printf("\t%s\n", err)
	}
	os.Exit(1)
}

type MinutesInterval struct {
	time.Duration
}

func (d *MinutesInterval) UnmarshalJSON(b []byte) (err error) {
	if b[0] == '"' {
		sd := string(b[1 : len(b)-1])
		d.Duration, err = time.ParseDuration(sd)
		return
	}

	var id int64
	id, err = json.Number(string(b)).Int64()
	d.Duration = time.Duration(id) * time.Minute

	return
}


text:
#ifndef HK_VISUALIZE_PROCESS_CONTEXT_H
#define HK_VISUALIZE_PROCESS_CONTEXT_H

class hkVisualDebugger;
class hkThreadPool;

	/// hkProcessContext provides a way to get information to Visual Debugger processes e.g., viewers, in a
	/// non physics-specific way. Note that the hkProcessContext itself is not Havok memory managed. It is just
	/// an interface so that you can use your own container classes for whatever data you want to expose to
	/// processes you create and use with the Visual Debugger.
class HK_EXPORT_COMMON hkProcessContext
{
	public:

		HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_BASE,hkProcessContext);

		hkProcessContext() : m_owner(HK_NULL) { }

		virtual ~hkProcessContext();

			/// Get the type of context. Common ones are 'Physics' or 'Animation'. Leave it open as a generic
			/// string so that users can make their own contexts for Processes.
		virtual const char* getType() = 0;

			/// Set the owner.
		virtual void setOwner( hkVisualDebugger* vdb ) { m_owner = vdb; }

			/// This function must be called once per frame.
			/// It prepares timer data for sending to the VDB. If you are using a thread pool you can optionally pass it in here.
		void syncTimers( hkThreadPool* threadPool = HK_NULL );

			/// Add timers from an additional thread pool
		void addThreadPoolTimers( hkThreadPool* threadPool );

	public:

			/// hkProcessContext owner.
		hkVisualDebugger* m_owner;

			/// Used by the stats viewer, the current start and end of the threads being timed.
			/// If they are empty arrays, will use the static hkMonitorStream::begin() and
			/// hkMonitorStream::end() pointers directly instead.
		hkInplaceArray<const char*, 6> m_monitorStreamBegins;
			/// See m_monitorStreamBegins comment.
		hkInplaceArray<const char*, 6> m_monitorStreamEnds;
};

#endif // HK_VISUALIZE_PROCESS_CONTEXT_H

/*
 * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907)
 *
 * Confidential Information of Havok.  (C) Copyright 1999-2014
 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
 * Logo, and the Havok buzzsaw logo are trademarks of Havok.  Title, ownership
 * rights, and intellectual property rights in the Havok software remain in
 * Havok and/or its suppliers.
 *
 * Use of this software for evaluation purposes is subject to and indicates
 * acceptance of the End User licence Agreement for this product. A copy of
 * the license is included with this software and is also available at www.havok.com/tryhavok.
 *
 */


text:
package pgtype_test

import (
	"testing"

	"github.com/jackc/pgx/pgtype"
	"github.com/jackc/pgx/pgtype/testutil"
)

func TestInt4rangeTranscode(t *testing.T) {
	testutil.TestSuccessfulTranscode(t, "int4range", []interface{}{
		&pgtype.Int4range{LowerType: pgtype.Empty, UpperType: pgtype.Empty, Status: pgtype.Present},
		&pgtype.Int4range{Lower: pgtype.Int4{Int: 1, Status: pgtype.Present}, Upper: pgtype.Int4{Int: 10, Status: pgtype.Present}, LowerType: pgtype.Inclusive, UpperType: pgtype.Exclusive, Status: pgtype.Present},
		&pgtype.Int4range{Lower: pgtype.Int4{Int: -42, Status: pgtype.Present}, Upper: pgtype.Int4{Int: -5, Status: pgtype.Present}, LowerType: pgtype.Inclusive, UpperType: pgtype.Exclusive, Status: pgtype.Present},
		&pgtype.Int4range{Status: pgtype.Null},
	})
}

func TestInt4rangeNormalize(t *testing.T) {
	testutil.TestSuccessfulNormalize(t, []testutil.NormalizeTest{
		{
			SQL:   "select int4range(1, 10, '(]')",
			Value: pgtype.Int4range{Lower: pgtype.Int4{Int: 2, Status: pgtype.Present}, Upper: pgtype.Int4{Int: 11, Status: pgtype.Present}, LowerType: pgtype.Inclusive, UpperType: pgtype.Exclusive, Status: pgtype.Present},
		},
	})
}


text:
const fs = require('fs')

function render( page ) {

  return new Promise(( resolve, reject ) => {

    let viewUrl = `./view/${page}`
    fs.readFile(viewUrl, "binary", ( err, data ) => {
      if ( err ) {
        reject( err )
      } else {
        resolve( data )
      }
    })
  })

}

module.exports = render


text:
//
//  DDAddMemberToGroupAPI.m
//  Duoduo
//
//  Created by 独嘉 on 14-5-8.
//  Copyright (c) 2015年 MoguIM All rights reserved.
//

#import "DDAddMemberToGroupAPI.h"
#import "DDGroupModule.h"
#import "MTTGroupEntity.h"
#import "RuntimeStatus.h"
#import "IMGroup.pb.h"
@implementation DDAddMemberToGroupAPI
/**
 *  请求超时时间
 *
 *  @return 超时时间
 */
- (int)requestTimeOutTimeInterval
{
    return TimeOutTimeInterval;
}

/**
 *  请求的serviceID
 *
 *  @return 对应的serviceID
 */
- (int)requestServiceID
{
    return SID_GROUP;
}

/**
 *  请求返回的serviceID
 *
 *  @return 对应的serviceID
 */
- (int)responseServiceID
{
    return SID_GROUP;
}

/**
 *  请求的commendID
 *
 *  @return 对应的commendID
 */
- (int)requestCommendID
{
    return IM_GROUP_CHANGE_MEMBER_REQ;
}

/**
 *  请求返回的commendID
 *
 *  @return 对应的commendID
 */
- (int)responseCommendID
{
    return IM_GROUP_CHANGE_MEMBER_RES;
}

/**
 *  解析数据的block
 *
 *  @return 解析数据的block
 */
- (Analysis)analysisReturnData
{
    Analysis analysis = (id)^(NSData* data)
    {

        IMGroupChangeMemberRsp *rsp = [IMGroupChangeMemberRsp parseFromData:data];

        uint32_t result =rsp.resultCode;
    NSMutableArray *array = [NSMutableArray new];
        if (result != 0)
        {
            return array;
        }

        NSUInteger userCnt = [[rsp curUserIdList] count];

        for (NSUInteger i = 0; i < userCnt; i++) {
                NSString* userId = [MTTUtil changeOriginalToLocalID:[[rsp curUserIdList][i] integerValue] SessionType:SessionTypeSessionTypeSingle];
                [array addObject:userId];
            }
        return array;

    };
    return analysis;
}

/**
 *  打包数据的block
 *
 *  @return 打包数据的block
 */
- (Package)packageRequestObject
{
    Package package = (id)^(id object,uint16_t seqNo)
    {
        NSArray* array = (NSArray*)object;
        NSString* groupId = array[0];
        NSArray* userList = array[1];
        NSMutableArray *users = [NSMutableArray new];
        for (NSString *user in userList) {
            [users addObject:@([MTTUtil changeIDToOriginal:user])];
        }
        IMGroupChangeMemberReqBuilder *memberChange = [IMGroupChangeMemberReq builder];
        [memberChange setUserId:0];
        [memberChange setChangeType:GroupModifyTypeGroupModifyTypeAdd];
        [memberChange setGroupId:[MTTUtil changeIDToOriginal:groupId]];
        [memberChange setMemberIdListArray:users];
        DDDataOutputStream *dataout = [[DDDataOutputStream alloc] init];
        [dataout writeInt:0];
        [dataout writeTcpProtocolHeader:SID_GROUP cId:IM_GROUP_CHANGE_MEMBER_REQ seqNo:seqNo];
        [dataout directWriteBytes:[memberChange build].data];
        [dataout writeDataCount];
        return [dataout toByteArray];
    };
    return package;
}
@end