text:
package com.glaf.matrix.combination.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.glaf.core.util.LowerLinkedMap;
import com.glaf.core.context.ContextFactory;
import com.glaf.core.domain.ColumnDefinition;
import com.glaf.core.domain.Database;
import com.glaf.core.domain.TableDefinition;
import com.glaf.core.jdbc.BulkInsertBean;
import com.glaf.core.jdbc.DBConnectionFactory;
import com.glaf.core.jdbc.QueryConnectionFactory;
import com.glaf.core.jdbc.QueryHelper;
import com.glaf.core.service.IDatabaseService;
import com.glaf.core.util.DBUtils;
import com.glaf.core.util.JdbcUtils;
import com.glaf.core.util.ParamUtils;
import com.glaf.core.util.QueryUtils;
import com.glaf.core.util.StringTools;
import com.glaf.core.util.UUID32;
import com.glaf.matrix.combination.domain.CombinationApp;
import com.glaf.matrix.combination.domain.CombinationItem;
import com.glaf.matrix.combination.service.CombinationAppService;
import com.glaf.matrix.data.domain.TableColumn;
import com.glaf.matrix.data.query.TableColumnQuery;
import com.glaf.matrix.data.service.ITableService;
import com.glaf.matrix.util.SysParams;

public class SqlToCombinationTableBean {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	public boolean execute(long srcDatabaseId, long targetDatabaseId, long syncId, Map<String, Object> params) {
		IDatabaseService databaseService = ContextFactory.getBean("databaseService");
		ITableService tableService = ContextFactory.getBean("tableService");
		CombinationAppService combinationAppService = ContextFactory
				.getBean("com.glaf.matrix.combination.service.combinationAppService");
		CombinationApp combinationApp = combinationAppService.getCombinationApp(syncId);
		if (combinationApp == null || !StringUtils.equals(combinationApp.getActive(), "Y")) {
			return false;
		}

		/**
		 * 严禁系统表被修改,系统表的维护只能通过特定界面操作!!!
		 */
		if (StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_role")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_user_role")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_user")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "login_module")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_key")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_property")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_server")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_dictory")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_scheduler")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_application")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_access")
				|| StringUtils.equalsIgnoreCase(combinationApp.getTargetTableName(), "sys_database")) {
			throw new RuntimeException(combinationApp.getTargetTableName() + " is update deny. ");
		}

		QueryHelper helper = new QueryHelper();

		Map<String, Object> parameter = new HashMap<String, Object>();
		if (params != null && !params.isEmpty()) {
			parameter.putAll(params);
		}

		Map<String, Map<String, Object>> dataListMap = new HashMap<String, Map<String, Object>>();
		List<Map<String, Object>> insertList = new ArrayList<Map<String, Object>>();

		SysParams.putInternalParams(parameter);
		Database srcDatabase = null;
		Database targetDatabase = null;
		Connection srcConn = null;
		Connection targetConn = null;
		PreparedStatement srcPsmt = null;
		PreparedStatement psmt = null;
		ResultSet srcRs = null;
		ResultSet rs = null;
		long ts = 0;
		try {
			srcDatabase = databaseService.getDatabaseById(srcDatabaseId);
			targetDatabase = databaseService.getDatabaseById(targetDatabaseId);

			if (srcDatabase != null) {
				srcConn = DBConnectionFactory.getConnection(srcDatabase.getName());
				logger.debug("srcConn:" + srcConn);
			} else {
				srcConn = DBConnectionFactory.getConnection();
			}

			if (targetDatabase != null) {
				targetConn = DBConnectionFactory.getConnection(targetDatabase.getName());
				logger.debug("targetConn:" + targetConn);
			} else {
				targetConn = DBConnectionFactory.getConnection();
			}

			if (srcConn != null && targetConn != null) {

				ts = System.currentTimeMillis();
				QueryConnectionFactory.getInstance().register(ts, srcConn);

				List<ColumnDefinition> columns = null;
				boolean tableExists = false;
				if (DBUtils.tableExists(targetConn, combinationApp.getTargetTableName())) {
					tableExists = true;
					columns = DBUtils.getColumnDefinitions(targetConn, combinationApp.getTargetTableName());
				} else {
					columns = new ArrayList<ColumnDefinition>();
				}
				Set<String> columnNames = new HashSet<String>();
				for (ColumnDefinition col : columns) {
					columnNames.add(col.getColumnName().trim().toLowerCase());
				}

				/**
				 * 优先使用外部定义的列信息
				 */
				if (StringUtils.equals(combinationApp.getExternalColumnsFlag(), "Y")) {
					TableColumnQuery query = new TableColumnQuery();
					query.tableId("combination_app_" + syncId);
					List<TableColumn> tblColumns = tableService.getTableColumns(query);
					if (tblColumns != null && !tblColumns.isEmpty()) {
						Map<String, ColumnDefinition> colMap = new HashMap<String, ColumnDefinition>();
						for (ColumnDefinition column : columns) {
							colMap.put(column.getColumnName().trim().toLowerCase(), column);
						}
						for (TableColumn tblCol : tblColumns) {
							ColumnDefinition column = colMap.get(tblCol.getColumnName().trim().toLowerCase());
							if (column != null) {
								column.setJavaType(tblCol.getJavaType());
								column.setLength(tblCol.getLength());
							} else {
								column = new ColumnDefinition();
								column.setColumnName(tblCol.getColumnName());
								column.setJavaType(tblCol.getJavaType());
								column.setLength(tblCol.getLength());
								columns.add(column);
								columnNames.add(column.getColumnName().trim().toLowerCase());
								logger.debug(tblCol.getColumnName() + " length:" + column.getLength());
							}
						}
					}
				}

				TableDefinition tableDefinition = new TableDefinition();
				tableDefinition.setTableName(combinationApp.getTargetTableName());
				tableDefinition.setColumns(columns);

				ColumnDefinition idColumn = new ColumnDefinition();
				idColumn.setColumnName("EX_ID_");// 主键
				idColumn.setJavaType("String");
				idColumn.setLength(200);
				tableDefinition.setIdColumn(idColumn);

				ColumnDefinition syncIdColumn = new ColumnDefinition();
				syncIdColumn.setColumnName("EX_SYNCID_");// syncId
				syncIdColumn.setJavaType("Long");
				tableDefinition.addColumn(syncIdColumn);

				ColumnDefinition complexIdColumn = new ColumnDefinition();
				complexIdColumn.setColumnName("EX_COMPLEX_KEY_");// 原始组合主键
				complexIdColumn.setJavaType("String");
				complexIdColumn.setLength(500);
				tableDefinition.addColumn(complexIdColumn);

				List<ColumnDefinition> cols = null;
				List<CombinationItem> items = combinationApp.getItems();
				for (CombinationItem item : items) {
					if (item.getLocked() == 1) {
						continue;
					}
					String sql = item.getSql();
					if (!DBUtils.isLegalQuerySql(sql)) {
						throw new RuntimeException(" SQL statement illegal ");
					}

					if (StringUtils.isNotEmpty(item.getRecursionSql())) {
						if (!DBUtils.isLegalQuerySql(item.getRecursionSql())) {
							throw new RuntimeException(" SQL statement illegal ");
						}
						List<String> recursionKeys = StringTools.splitLowerCase(item.getRecursionColumns(), ",");
						if (recursionKeys != null && !recursionKeys.isEmpty()) {
							String recursionSql = item.getRecursionSql();
							recursionSql = QueryUtils.replaceSQLVars(recursionSql, parameter);
							cols = helper.getColumnList(srcConn, recursionSql, parameter);
							if (cols != null && !cols.isEmpty()) {
								for (ColumnDefinition col : cols) {
									if (!columnNames.contains(col.getColumnName().toLowerCase())) {
										if (recursionKeys.contains(col.getColumnName().toLowerCase())) {
											columns.add(col);
											columnNames.add(col.getColumnName().trim().toLowerCase());
										}
									}
								}
							}
						}
					}

					sql = QueryUtils.replaceSQLVars(sql, parameter);
					cols = helper.getColumnList(srcConn, sql, parameter);
					if (cols != null && !cols.isEmpty()) {
						for (ColumnDefinition col : cols) {
							if (!columnNames.contains(col.getColumnName().toLowerCase())) {
								columns.add(col);
								columnNames.add(col.getColumnName().trim().toLowerCase());
							}
						}
					}
				}

				targetConn.setAutoCommit(false);
				if (!tableExists) {
					DBUtils.createTable(targetConn, tableDefinition);
					for (ColumnDefinition col : cols) {
						TableColumn tbCol = new TableColumn();
						tbCol.setTitle(col.getTitle());
						tbCol.setColumnName(col.getColumnName());
						tbCol.setJavaType(col.getJavaType());
						tbCol.setLength(col.getLength());
						tbCol.setTableId("combination_app_" + syncId);
						tbCol.setId("combination_app_" + syncId + "_" + col.getColumnName());
						tableService.saveTargetColumn("combination_app_" + syncId, tbCol);
					}
				} else {
					DBUtils.alterTable(targetConn, tableDefinition);
					for (ColumnDefinition col : cols) {
						TableColumn tbCol = new TableColumn();
						tbCol.setTitle(col.getTitle());
						tbCol.setColumnName(col.getColumnName());
						tbCol.setJavaType(col.getJavaType());
						tbCol.setLength(col.getLength());
						tbCol.setTableId("combination_app_" + syncId);
						tbCol.setId("combination_app_" + syncId + "_" + col.getColumnName());
						tableService.saveTargetColumn("combination_app_" + syncId, tbCol);
					}
				}
				targetConn.commit();

				logger.debug("columns:" + columns);

				int totalSize = 0;
				Object value = null;
				String idValue = null;
				StringBuilder keyBuffer = new StringBuilder();
				List<Map<String, Object>> sourceResultList = null;
				SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());

				for (CombinationItem item : items) {
					if (item.getLocked() == 1) {
						continue;
					}

					// StringBuilder buff = new StringBuilder();
					String sql = item.getSql();
					sql = QueryUtils.replaceSQLVars(sql, parameter);

					final List<String> recursionKeys = StringTools.splitLowerCase(item.getRecursionColumns(), ",");
					boolean recursionKeyExists = false;
					if (recursionKeys != null && !recursionKeys.isEmpty()) {
						recursionKeyExists = true;
					}

					if (recursionKeyExists && StringUtils.isNotEmpty(item.getRecursionSql())) {
						if (!DBUtils.isLegalQuerySql(item.getRecursionSql())) {
							throw new RuntimeException(" SQL statement illegal ");
						}

						String recursionSql = item.getRecursionSql();
						recursionSql = QueryUtils.replaceSQLVars(recursionSql, parameter);
						List<Map<String, Object>> recursionResultList = helper.getResultList(srcConn, recursionSql,
								parameter, 5000);
						if (recursionResultList != null && !recursionResultList.isEmpty()) {
							LowerLinkedMap params2 = new LowerLinkedMap();
							final List<String> keys = StringTools.splitLowerCase(item.getPrimaryKey(), ",");

							int index = 0;
							logger.debug("recursionKeys:" + recursionKeys);
							for (Map<String, Object> paramMap : recursionResultList) {
								params2.clear();// 清空条件
								params2.putAll(parameter);// 放入外部输入条件
								params2.putAll(paramMap);// 放入循环输入条件
								// logger.debug(" paramMap:" + paramMap);
								index++;
								// logger.debug(index + " ->params:" + paramMap);
								/**
								 * 通过新的参数获取每次循环的结果集
								 */
								sourceResultList = helper.getResultList(srcConn, sql, params2, SysParams.MAX_SIZE);
								if (sourceResultList != null && !sourceResultList.isEmpty()) {
									for (Map<String, Object> rowMap : sourceResultList) {
										Map<String, Object> dataMap2 = new LowerLinkedMap();
										dataMap2.putAll(rowMap);

										keyBuffer.delete(0, keyBuffer.length());

										for (String key : keys) {
											value = ParamUtils.getObject(dataMap2, key);
											if (value == null) {
												value = ParamUtils.getObject(params2, key);
											}
											if (value != null) {
												if (value instanceof Date) {
													keyBuffer.append(formatter.format((Date) value)).append("_");
												} else {
													keyBuffer.append(value).append("_");
												}
											} else {
												keyBuffer.append("null").append("_");
											}
										}

										keyBuffer.delete(keyBuffer.length() - 1, keyBuffer.length());

										idValue = DigestUtils.md5Hex(keyBuffer.toString());
										// idValue = keyBuffer.toString();
										if (idValue != null) {
											Map<String, Object> dataMap = dataListMap.get(idValue);
											if (dataMap == null) {
												dataMap = new LowerLinkedMap();
												dataMap.put("ex_id_", idValue);
												dataMap.put("ex_complex_key_", keyBuffer.toString());
												if (recursionKeyExists) {
													for (String recursionKey : recursionKeys) {
														dataMap.put(recursionKey,
																ParamUtils.getObject(paramMap, recursionKey));
														if (index == 1) {
															// logger.debug(
															// recursionKey + " = " + paramMap.get(recursionKey));
														}
													}
												}
											}
											// if (recursionKeyExists) {
											// for (String recursionKey : recursionKeys) {
											// dataMap.put(recursionKey,
											// ParamUtils.getObject(paramMap, recursionKey));
											// }
											// }
											dataMap.putAll(dataMap2);
											dataMap.put("ex_syncid_", syncId);
											dataListMap.put(idValue, dataMap);
										}
									}
									totalSize = dataListMap.size();
									if (totalSize > SysParams.MAX_SIZE) {
										logger.warn("totalSize:" + totalSize);
										throw new RuntimeException(
												"data list too large, please split small condition.");
									}
								}
							}
						}
					} else {
						sourceResultList = helper.getResultList(srcConn, sql, parameter, SysParams.MAX_SIZE);
						if (sourceResultList != null && !sourceResultList.isEmpty()) {
							List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
							for (Map<String, Object> rowMap : sourceResultList) {
								LowerLinkedMap dataMap2 = new LowerLinkedMap();
								dataMap2.putAll(rowMap);
								dataList.add(dataMap2);
							}
							sourceResultList.clear();

							List<String> keys = StringTools.splitLowerCase(item.getPrimaryKey(), ",");
							if (keys != null && !keys.isEmpty()) {
								for (Map<String, Object> rowMap : dataList) {
									keyBuffer.delete(0, keyBuffer.length());
									for (String key : keys) {
										value = rowMap.get(key);
										if (value == null) {
											value = ParamUtils.getObject(parameter, key);
										}
										if (value != null) {
											if (value instanceof Date) {
												keyBuffer.append(formatter.format((Date) value)).append("_");
											} else {
												keyBuffer.append(value).append("_");
											}
										} else {
											keyBuffer.append("null").append("_");
										}
									}
									keyBuffer.delete(keyBuffer.length() - 1, keyBuffer.length());

									idValue = DigestUtils.md5Hex(keyBuffer.toString());
									// idValue = keyBuffer.toString();
									if (idValue != null) {
										Map<String, Object> dataMap = dataListMap.get(idValue);
										if (dataMap == null) {
											dataMap = new LowerLinkedMap();
											dataMap.put("ex_id_", idValue);
											dataMap.put("ex_complex_key_", keyBuffer.toString());
										}
										dataMap.putAll(rowMap);
										dataMap.put("ex_syncid_", syncId);
										dataListMap.put(idValue, dataMap);
									}
								}
							} else {
								for (Map<String, Object> rowMap : dataList) {
									String uuid = UUID32.getUUID();
									rowMap.put("ex_id_", uuid);
									rowMap.put("ex_syncid_", syncId);
									dataListMap.put(uuid, rowMap);
								}
							}
						}
					}
					totalSize = dataListMap.size();
					if (totalSize > SysParams.MAX_SIZE) {
						logger.warn("totalSize:" + totalSize);
						throw new RuntimeException("data list too large, please split small condition.");
					}
				}

				insertList.addAll(dataListMap.values());

				if (insertList.size() > 0) {
					BulkInsertBean insertBean = new BulkInsertBean();
					targetConn.setAutoCommit(false);
					if (combinationApp.getDeleteFetch() == null
							|| StringUtils.equals(combinationApp.getDeleteFetch(), "Y")) {
						DBUtils.executeSchemaResource(targetConn, " delete from " + combinationApp.getTargetTableName()
								+ " where ex_syncid_ = " + combinationApp.getId());
					}
					insertBean.bulkInsert(null, targetConn, tableDefinition, insertList);
					targetConn.commit();
				}

				insertList.clear();
				dataListMap.clear();
				insertList = null;
				dataListMap = null;

			}

			return true;
		} catch (Exception ex) {
			// ex.printStackTrace();
			logger.error("execute sync error", ex);
			// logger.error("[insertList]:" + insertList);
			throw new RuntimeException(ex);
		} finally {

			if (srcConn != null) {
				QueryConnectionFactory.getInstance().unregister(ts, srcConn);
			}

			insertList = null;
			dataListMap = null;

			JdbcUtils.close(srcRs);
			JdbcUtils.close(srcPsmt);
			JdbcUtils.close(srcConn);

			JdbcUtils.close(rs);
			JdbcUtils.close(psmt);
			JdbcUtils.close(targetConn);
		}
	}

}


text:
from menpo.base import Vectorizable
from menpo.landmark import Landmarkable
from menpo.transform.base import Transformable
from menpo.visualize import LandmarkableViewable, Viewable

class Shape(Vectorizable, Transformable, Landmarkable, LandmarkableViewable, Viewable):
    """
    Abstract representation of shape. Shapes are :map:`Transformable`,
    :map:`Vectorizable`, :map:`Landmarkable`, :map:`LandmarkableViewable` and
    :map:`Viewable`. This base class handles transforming landmarks when the
    shape is transformed. Therefore, implementations of :map:`Shape` have to
    implement the abstract :meth:`_transform_self_inplace` method that handles
    transforming the :map:`Shape` itself.
    """

    def _transform_inplace(self, transform):
        """
        Transform the landmarks and the shape itself.

        Parameters
        ----------
        transform : `function`
            A function to transform the spatial data with.

        Returns
        -------
        self : `type(self)`
            A pointer to `self` (the result of :meth:`_transform_self_inplace`).
        """
        if self.has_landmarks:
            self.landmarks._transform_inplace(transform)
        return self._transform_self_inplace(transform)

    def _transform_self_inplace(self, transform):
        """
        Implement this method to transform the concrete implementation of a
        shape. This is then called by the Shape's :meth:`_transform_inplace`
        method, which will have updated the landmarks beforehand.

        Parameters
        ----------
        transform : `function`
            A function to transform the spatial data with.

        Returns
        -------
        self : `type(self)`
            A pointer to `self`.
        """
        pass

redpajama_set_name: RedPajamaGithub


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Range connect handler requirements</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="Protocol.html" title="Protocol requirements">
<link rel="next" href="ReadHandler.html" title="Read handler requirements">

Home
Libraries
People
FAQ
More

Range connect
      handler requirements

        A range connect handler must meet the requirements for a handler.
        A value h of a range connect handler class should work correctly
        in the expression h(ec, ep), where ec is an lvalue
        of type const error_code and ep is an lvalue of
        the type Protocol::endpoint for the Protocol type
        in the corresponding connect() or async_connect()` function.

        Examples

        A free function as a range connect handler:

void connect_handler(
    const boost::system::error_code& ec,
    const boost::asio::ip::tcp::endpoint& endpoint)
{
  ...
}

        A range connect handler function object:

struct connect_handler
{
  ...
  template <typename Range>
  void operator()(
      const boost::system::error_code& ec,
      const boost::asio::ip::tcp::endpoint& endpoint)
  {
    ...
  }
  ...
};

        A lambda as a range connect handler:

boost::asio::async_connect(...,
    [](const boost::system::error_code& ec,
      const boost::asio::ip::tcp::endpoint& endpoint)
    {
      ...
    });

        A non-static class member function adapted to a range connect handler using
        std::bind():

void my_class::connect_handler(
    const boost::system::error_code& ec,
    const boost::asio::ip::tcp::endpoint& endpoint)
{
  ...
}
...
boost::asio::async_connect(...,
    std::bind(&my_class::connect_handler,
      this, std::placeholders::_1,
      std::placeholders::_2));

        A non-static class member function adapted to a range connect handler using
        boost::bind():

void my_class::connect_handler(
    const boost::system::error_code& ec,
    const boost::asio::ip::tcp::endpoint& endpoint)
{
  ...
}
...
boost::asio::async_connect(...,
    boost::bind(&my_class::connect_handler,
      this, boost::asio::placeholders::error,
      boost::asio::placeholders::endpoint));

Copyright © 2003-2021 Christopher
      M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
"""Support for lights."""
from __future__ import annotations

from typing import Any

from fjaraskupan import COMMAND_LIGHT_ON_OFF

from homeassistant.components.light import ATTR_BRIGHTNESS, ColorMode, LightEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo, Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import Coordinator, async_setup_entry_platform

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up tuya sensors dynamically through tuya discovery."""

    def _constructor(coordinator: Coordinator) -> list[Entity]:
        return [Light(coordinator, coordinator.device_info)]

    async_setup_entry_platform(hass, config_entry, async_add_entities, _constructor)

class Light(CoordinatorEntity[Coordinator], LightEntity):
    """Light device."""

    _attr_has_entity_name = True

    def __init__(
        self,
        coordinator: Coordinator,
        device_info: DeviceInfo,
    ) -> None:
        """Init light entity."""
        super().__init__(coordinator)
        self._attr_color_mode = ColorMode.BRIGHTNESS
        self._attr_supported_color_modes = {ColorMode.BRIGHTNESS}
        self._attr_unique_id = coordinator.device.address
        self._attr_device_info = device_info

    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn the light on."""
        async with self.coordinator.async_connect_and_update() as device:
            if ATTR_BRIGHTNESS in kwargs:
                await device.send_dim(int(kwargs[ATTR_BRIGHTNESS] * (100.0 / 255.0)))
            else:
                if not self.is_on:
                    await device.send_command(COMMAND_LIGHT_ON_OFF)

    async def async_turn_off(self, **kwargs: Any) -> None:
        """Turn the entity off."""
        if self.is_on:
            async with self.coordinator.async_connect_and_update() as device:
                await device.send_command(COMMAND_LIGHT_ON_OFF)

    @property
    def is_on(self) -> bool:
        """Return True if entity is on."""
        if data := self.coordinator.data:
            return data.light_on
        return False

    @property
    def brightness(self) -> int | None:
        """Return the brightness of this light between 0..255."""
        if data := self.coordinator.data:
            return int(data.dim_level * (255.0 / 100.0))
        return None


text:
ApproveHoursController.$inject = [ 'TbUtils', 'hours' ];

function ApproveHoursController(TbUtils, hours) {
    const vm = this;

    vm.model = undefined;
    vm.toTitleCase = TbUtils.toTitleCase;
    vm.getPeriod = getPeriod;
    vm.approveHours = approveHours;

    vm.placeholder = 'Buscar por código del reporte.';
    vm.search = searchInfo;

    vm.loading = false;

    function getPeriod(period) {
        return period ? period.Number + period.Year : "";
    }

    function searchInfo (term) {
        vm.loading = true;

        hours.getHoursInfoSectionProjects(term, getHoursInfoSectionProjects,
            getHoursInfoSectionProjectsFail, () => { vm.loading = false; });
    }

    function getHoursInfoSectionProjects(response) {
        vm.model = response.data;
        if(vm.model.IsApproved)
        	TbUtils.displayNotification('warning', 'Advertencia',
            'Estas horas ya fueron Aprobadas');
    }

    function getHoursInfoSectionProjectsFail(response) {
        TbUtils.showErrorMessage(response);
    }

    function approveHours() {
        vm.loading = true;
        hours.putSectionProjectsApprove(vm.model.Id, putSectionProjectsApproveSuccess,
            putSectionProjectsApproveFail, () => { vm.loading = false; });
    }

    function putSectionProjectsApproveSuccess(){
    	TbUtils.displayNotification('success', 'Exitoso',
            'Horas aprobadas correctamente.');
    	TbUtils.reload()
    }

    function putSectionProjectsApproveFail(resp){
    	TbUtils.showErrorMessage(resp);
    }
}

module.exports = {
    name: 'ApproveHoursController',
    ctrl: ApproveHoursController
};


text:
namespace doris {

class RuntimeState;

class EsPredicateTest : public testing::Test {
public:
    EsPredicateTest() : _runtime_state("EsPredicateTest") {
        _runtime_state._instance_mem_tracker.reset(new MemTracker());
        TDescriptorTable t_desc_table;

        // table descriptors
        TTableDescriptor t_table_desc;
        t_table_desc.id = 0;
        t_table_desc.tableType = TTableType::ES_TABLE;
        t_table_desc.numCols = 1;
        t_table_desc.numClusteringCols = 0;
        t_table_desc.__isset.esTable = true;
        t_desc_table.tableDescriptors.push_back(t_table_desc);
        t_desc_table.__isset.tableDescriptors = true;

        // TSlotDescriptor
        int offset = 1;
        int i = 0;
        // id
        {
            TSlotDescriptor t_slot_desc;
            t_slot_desc.__set_slotType(TypeDescriptor(TYPE_INT).to_thrift());
            t_slot_desc.__set_columnPos(i);
            t_slot_desc.__set_byteOffset(offset);
            t_slot_desc.__set_nullIndicatorByte(0);
            t_slot_desc.__set_nullIndicatorBit(-1);
            t_slot_desc.__set_slotIdx(i);
            t_slot_desc.__set_isMaterialized(true);
            t_slot_desc.colName = "id";
            t_desc_table.slotDescriptors.push_back(t_slot_desc);
            offset += sizeof(int);
        }

        TTupleDescriptor t_tuple_desc;
        t_tuple_desc.id = 0;
        t_tuple_desc.byteSize = offset;
        t_tuple_desc.numNullBytes = 1;
        t_tuple_desc.tableId = 0;
        t_tuple_desc.__isset.tableId = true;
        t_desc_table.__isset.slotDescriptors = true;
        t_desc_table.tupleDescriptors.push_back(t_tuple_desc);

        DescriptorTbl::create(&_obj_pool, t_desc_table, &_desc_tbl);
        _runtime_state.set_desc_tbl(_desc_tbl);
    }

    Status build_expr_context_list(std::vector<ExprContext*>& conjunct_ctxs);
    void init();
    void SetUp() override {}
    void TearDown() override {}

private:

    ObjectPool _obj_pool;
    DescriptorTbl* _desc_tbl;
    RuntimeState _runtime_state;
};

Status EsPredicateTest::build_expr_context_list(std::vector<ExprContext*>& conjunct_ctxs) {

    TExpr texpr;
    {
        TExprNode node0;
        node0.opcode = TExprOpcode::GT;
        node0.child_type = TPrimitiveType::BIGINT;
        node0.node_type = TExprNodeType::BINARY_PRED;
        node0.num_children = 2;
        node0.__isset.opcode = true;
        node0.__isset.child_type = true;
        node0.type = gen_type_desc(TPrimitiveType::BOOLEAN);
        texpr.nodes.emplace_back(node0);

        TExprNode node1;
        node1.node_type = TExprNodeType::SLOT_REF;
        node1.type = gen_type_desc(TPrimitiveType::INT);
        node1.__isset.slot_ref = true;
        node1.num_children = 0;
        node1.slot_ref.slot_id = 0;
        node1.slot_ref.tuple_id = 0;
        node1.output_column = true;
        node1.__isset.output_column = true;
        texpr.nodes.emplace_back(node1);

        TExprNode node2;
        TIntLiteral intLiteral;
        intLiteral.value = 10;
        node2.node_type = TExprNodeType::INT_LITERAL;
        node2.type = gen_type_desc(TPrimitiveType::BIGINT);
        node2.__isset.int_literal = true;
        node2.int_literal = intLiteral;
        texpr.nodes.emplace_back(node2);
    }

    std::vector<TExpr> conjuncts;
    conjuncts.emplace_back(texpr);
    Status status = Expr::create_expr_trees(&_obj_pool, conjuncts, &conjunct_ctxs);

    return status;
}

TEST_F(EsPredicateTest, normal) {
    std::vector<ExprContext*> conjunct_ctxs;
    Status status = build_expr_context_list(conjunct_ctxs);

    TupleDescriptor *tuple_desc = _desc_tbl->get_tuple_descriptor(0);
    std::vector<EsPredicate*> predicates;
    for (int i = 0; i < conjunct_ctxs.size(); ++i) {
        EsPredicate* predicate = new EsPredicate(conjunct_ctxs[i], tuple_desc);
        if (predicate->build_disjuncts_list().ok()) {
            predicates.push_back(predicate);
        }
    }

    rapidjson::Document document;
    rapidjson::Value compound_bool_value(rapidjson::kObjectType);
    compound_bool_value.SetObject();
    BooleanQueryBuilder::to_query(predicates, &document, &compound_bool_value);
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    compound_bool_value.Accept(writer);
    std::string actual_bool_json = buffer.GetString();
    std::string expected_json = "{\"bool\":{\"filter\":[{\"bool\":{\"should\":[{\"range\":{\"id\":{\"gt\":\"10\"}}}]}}]}}";
    LOG(INFO) << "compound bool query" << actual_bool_json;
    ASSERT_STREQ(expected_json.c_str(), actual_bool_json.c_str());
}

} // end namespace doris

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
var id         = 'dist',
	gulp       = require('gulp'),
	pump       = require('pump'),
	del        = require('del'),
	path       = require('path'),
	plugins    = require('gulp-load-plugins')(),
	livereload = require('gulp-livereload'),
	config     = require('../config'),
	settings   = config.tasks[id];

function watch() {
	livereload.listen();

	return gulp.watch(settings.watch, gulp.series(id + ':lint', id + ':build'))
		.on('unlink', function(file) {
			/*
			var relpath  = path.relative(path.resolve('src'), file),
				resolved = path.resolve('build', relpath);

			console.log(file, relpath, resolved);
			*/
			//del.sync(resolved);
		});
}

function lint() {
	return gulp.src(settings.watch)
		.pipe(plugins.eslint())
		.pipe(plugins.eslint.format())
		.pipe(plugins.eslint.failAfterError())
		.pipe(plugins.size(config.settings.size));
}

function clean() {
	return del(settings.clean, { force: true });
}

function build(done) {
	pump([
		gulp.src(settings.process || settings.watch),
		// beautify
		plugins.include(config.settings.include),
		plugins.injectVersion({ prepend: '', replace: '{{package.version}}' }),
		// generate minified
		plugins.sourcemaps.init({ largeFile: true }),
		plugins.terser({
			ecma: 5,
			compress: {
				'passes':  5,
				'typeofs': false
			}
		}),
		plugins.header(config.banner),
		plugins.chmod(config.permissions),
		plugins.size(config.settings.size),
		plugins.sourcemaps.write('.'),
		gulp.dest(settings.dest),
		plugins.touchFd()
	], function() {
		livereload.reload();
		done();
	});
}

gulp.task(id + ':watch', watch);
gulp.task(id + ':lint', lint);
gulp.task(id + ':clean', clean);
gulp.task(id + ':build', build);
gulp.task(id, gulp.series(id + ':lint', id + ':clean', id + ':build'));


text:
#pragma once
#include <aws/elasticmapreduce/EMR_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/elasticmapreduce/model/PortRange.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace EMR
{
namespace Model
{

  /**
   *
A configuration for Amazon EMR block public access. When
   * BlockPublicSecurityGroupRules is set to true, Amazon
   * EMR prevents cluster creation if one of the cluster's security groups has a rule
   * that allows inbound traffic from 0.0.0.0/0 or ::/0 on a port, unless the port is
   * specified as an exception using
   * PermittedPublicSecurityGroupRuleRanges.

See Also:

   * AWS
   * API Reference

   */
  class AWS_EMR_API BlockPublicAccessConfiguration
  {
  public:
    BlockPublicAccessConfiguration();
    BlockPublicAccessConfiguration(Aws::Utils::Json::JsonView jsonValue);
    BlockPublicAccessConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Indicates whether Amazon EMR block public access is enabled
     * (true) or disabled (false). By default, the value is
     * false for accounts that have created EMR clusters before July 2019.
     * For accounts created after this, the default is true.

     */
    inline bool GetBlockPublicSecurityGroupRules() const{ return m_blockPublicSecurityGroupRules; }

    /**
     *
Indicates whether Amazon EMR block public access is enabled
     * (true) or disabled (false). By default, the value is
     * false for accounts that have created EMR clusters before July 2019.
     * For accounts created after this, the default is true.

     */
    inline bool BlockPublicSecurityGroupRulesHasBeenSet() const { return m_blockPublicSecurityGroupRulesHasBeenSet; }

    /**
     *
Indicates whether Amazon EMR block public access is enabled
     * (true) or disabled (false). By default, the value is
     * false for accounts that have created EMR clusters before July 2019.
     * For accounts created after this, the default is true.

     */
    inline void SetBlockPublicSecurityGroupRules(bool value) { m_blockPublicSecurityGroupRulesHasBeenSet = true; m_blockPublicSecurityGroupRules = value; }

    /**
     *
Indicates whether Amazon EMR block public access is enabled
     * (true) or disabled (false). By default, the value is
     * false for accounts that have created EMR clusters before July 2019.
     * For accounts created after this, the default is true.

     */
    inline BlockPublicAccessConfiguration& WithBlockPublicSecurityGroupRules(bool value) { SetBlockPublicSecurityGroupRules(value); return *this;}

    /**
     *
Specifies ports and port ranges that are permitted to have security group
     * rules that allow inbound traffic from all public sources. For example, if Port
     * 23 (Telnet) is specified for
     * PermittedPublicSecurityGroupRuleRanges, Amazon EMR allows cluster
     * creation if a security group associated with the cluster has a rule that allows
     * inbound traffic on Port 23 from IPv4 0.0.0.0/0 or IPv6 port ::/0 as the
     * source.

By default, Port 22, which is used for SSH access to the cluster
     * EC2 instances, is in the list of
     * PermittedPublicSecurityGroupRuleRanges.

     */
    inline const Aws::Vector<PortRange>& GetPermittedPublicSecurityGroupRuleRanges() const{ return m_permittedPublicSecurityGroupRuleRanges; }

    /**
     *
Specifies ports and port ranges that are permitted to have security group
     * rules that allow inbound traffic from all public sources. For example, if Port
     * 23 (Telnet) is specified for
     * PermittedPublicSecurityGroupRuleRanges, Amazon EMR allows cluster
     * creation if a security group associated with the cluster has a rule that allows
     * inbound traffic on Port 23 from IPv4 0.0.0.0/0 or IPv6 port ::/0 as the
     * source.

By default, Port 22, which is used for SSH access to the cluster
     * EC2 instances, is in the list of
     * PermittedPublicSecurityGroupRuleRanges.

     */
    inline bool PermittedPublicSecurityGroupRuleRangesHasBeenSet() const { return m_permittedPublicSecurityGroupRuleRangesHasBeenSet; }

    /**
     *
Specifies ports and port ranges that are permitted to have security group
     * rules that allow inbound traffic from all public sources. For example, if Port
     * 23 (Telnet) is specified for
     * PermittedPublicSecurityGroupRuleRanges, Amazon EMR allows cluster
     * creation if a security group associated with the cluster has a rule that allows
     * inbound traffic on Port 23 from IPv4 0.0.0.0/0 or IPv6 port ::/0 as the
     * source.

By default, Port 22, which is used for SSH access to the cluster
     * EC2 instances, is in the list of
     * PermittedPublicSecurityGroupRuleRanges.

     */
    inline void SetPermittedPublicSecurityGroupRuleRanges(const Aws::Vector<PortRange>& value) { m_permittedPublicSecurityGroupRuleRangesHasBeenSet = true; m_permittedPublicSecurityGroupRuleRanges = value; }

    /**
     *
Specifies ports and port ranges that are permitted to have security group
     * rules that allow inbound traffic from all public sources. For example, if Port
     * 23 (Telnet) is specified for
     * PermittedPublicSecurityGroupRuleRanges, Amazon EMR allows cluster
     * creation if a security group associated with the cluster has a rule that allows
     * inbound traffic on Port 23 from IPv4 0.0.0.0/0 or IPv6 port ::/0 as the
     * source.

By default, Port 22, which is used for SSH access to the cluster
     * EC2 instances, is in the list of
     * PermittedPublicSecurityGroupRuleRanges.

     */
    inline void SetPermittedPublicSecurityGroupRuleRanges(Aws::Vector<PortRange>&& value) { m_permittedPublicSecurityGroupRuleRangesHasBeenSet = true; m_permittedPublicSecurityGroupRuleRanges = std::move(value); }

    /**
     *
Specifies ports and port ranges that are permitted to have security group
     * rules that allow inbound traffic from all public sources. For example, if Port
     * 23 (Telnet) is specified for
     * PermittedPublicSecurityGroupRuleRanges, Amazon EMR allows cluster
     * creation if a security group associated with the cluster has a rule that allows
     * inbound traffic on Port 23 from IPv4 0.0.0.0/0 or IPv6 port ::/0 as the
     * source.

By default, Port 22, which is used for SSH access to the cluster
     * EC2 instances, is in the list of
     * PermittedPublicSecurityGroupRuleRanges.

     */
    inline BlockPublicAccessConfiguration& WithPermittedPublicSecurityGroupRuleRanges(const Aws::Vector<PortRange>& value) { SetPermittedPublicSecurityGroupRuleRanges(value); return *this;}

    /**
     *
Specifies ports and port ranges that are permitted to have security group
     * rules that allow inbound traffic from all public sources. For example, if Port
     * 23 (Telnet) is specified for
     * PermittedPublicSecurityGroupRuleRanges, Amazon EMR allows cluster
     * creation if a security group associated with the cluster has a rule that allows
     * inbound traffic on Port 23 from IPv4 0.0.0.0/0 or IPv6 port ::/0 as the
     * source.

By default, Port 22, which is used for SSH access to the cluster
     * EC2 instances, is in the list of
     * PermittedPublicSecurityGroupRuleRanges.

     */
    inline BlockPublicAccessConfiguration& WithPermittedPublicSecurityGroupRuleRanges(Aws::Vector<PortRange>&& value) { SetPermittedPublicSecurityGroupRuleRanges(std::move(value)); return *this;}

    /**
     *
Specifies ports and port ranges that are permitted to have security group
     * rules that allow inbound traffic from all public sources. For example, if Port
     * 23 (Telnet) is specified for
     * PermittedPublicSecurityGroupRuleRanges, Amazon EMR allows cluster
     * creation if a security group associated with the cluster has a rule that allows
     * inbound traffic on Port 23 from IPv4 0.0.0.0/0 or IPv6 port ::/0 as the
     * source.

By default, Port 22, which is used for SSH access to the cluster
     * EC2 instances, is in the list of
     * PermittedPublicSecurityGroupRuleRanges.

     */
    inline BlockPublicAccessConfiguration& AddPermittedPublicSecurityGroupRuleRanges(const PortRange& value) { m_permittedPublicSecurityGroupRuleRangesHasBeenSet = true; m_permittedPublicSecurityGroupRuleRanges.push_back(value); return *this; }

    /**
     *
Specifies ports and port ranges that are permitted to have security group
     * rules that allow inbound traffic from all public sources. For example, if Port
     * 23 (Telnet) is specified for
     * PermittedPublicSecurityGroupRuleRanges, Amazon EMR allows cluster
     * creation if a security group associated with the cluster has a rule that allows
     * inbound traffic on Port 23 from IPv4 0.0.0.0/0 or IPv6 port ::/0 as the
     * source.

By default, Port 22, which is used for SSH access to the cluster
     * EC2 instances, is in the list of
     * PermittedPublicSecurityGroupRuleRanges.

     */
    inline BlockPublicAccessConfiguration& AddPermittedPublicSecurityGroupRuleRanges(PortRange&& value) { m_permittedPublicSecurityGroupRuleRangesHasBeenSet = true; m_permittedPublicSecurityGroupRuleRanges.push_back(std::move(value)); return *this; }

  private:

    bool m_blockPublicSecurityGroupRules;
    bool m_blockPublicSecurityGroupRulesHasBeenSet = false;

    Aws::Vector<PortRange> m_permittedPublicSecurityGroupRuleRanges;
    bool m_permittedPublicSecurityGroupRuleRangesHasBeenSet = false;
  };

} // namespace Model
} // namespace EMR
} // namespace Aws


text:
<?php
namespace Wargame\Mollwitz\Ferozesha;

/**
 * Created by JetBrains PhpStorm.
 * User: markarianr
 * Date: 5/7/13
 * Time: 7:06 PM
 * To change this template use File | Settings | File Templates.
 */

class ferozesha2VictoryCore extends \Wargame\Mollwitz\IndiaVictoryCore
{

    public function specialHexChange($args)
    {
        $battle = \Wargame\Battle::getBattle();
        if (!empty($battle->scenario->dayTwo)) {
            list($mapHexName, $forceId) = $args;

            if ($forceId == FerozeshaDayTwo::SIKH_FORCE) {
                $this->victoryPoints[FerozeshaDayTwo::SIKH_FORCE] += 5;
                $battle->mapData->specialHexesVictory->$mapHexName = "+5 Sikh  vp";
            }
            if ($forceId == FerozeshaDayTwo::BRITISH_FORCE) {
                $this->victoryPoints[FerozeshaDayTwo::SIKH_FORCE] -= 5;
                $battle->mapData->specialHexesVictory->$mapHexName = "-5 Sikh  vp";
            }
        } else {

            list($mapHexName, $forceId) = $args;
            if ($mapHexName == $battle->moodkee) {
                if ($forceId == FerozeshaDayTwo::SIKH_FORCE) {
                    $this->victoryPoints[FerozeshaDayTwo::SIKH_FORCE] += 20;
                    $battle->mapData->specialHexesVictory->$mapHexName = "+5 Sikh  vp";
                }
                if ($forceId == FerozeshaDayTwo::BRITISH_FORCE) {
                    $this->victoryPoints[FerozeshaDayTwo::SIKH_FORCE] -= 20;
                    $battle->mapData->specialHexesVictory->$mapHexName = "-5 Sikh  vp";
                }

            } else {
                if ($forceId == FerozeshaDayTwo::BRITISH_FORCE) {
                    $this->victoryPoints[FerozeshaDayTwo::BRITISH_FORCE] += 5;
                    $battle->mapData->specialHexesVictory->$mapHexName = "+5 British  vp";
                }
                if ($forceId == FerozeshaDayTwo::SIKH_FORCE) {
                    $this->victoryPoints[FerozeshaDayTwo::BRITISH_FORCE] -= 5;
                    $battle->mapData->specialHexesVictory->$mapHexName = "-5 British  vp";
                }
            }
        }
    }

    protected function checkVictory( $battle)
    {
        $gameRules = $battle->gameRules;
        $scenario = $battle->scenario;
        $turn = $gameRules->turn;
        $britishWin = $sikhWin = false;

        if (!$this->gameOver) {
            $specialHexes = $battle->mapData->specialHexes;
            $sikhVic = 35;
            $britLead = 10;
            if ($this->victoryPoints[FerozeshaDayTwo::SIKH_FORCE] >= $sikhVic ) {
                $sikhWin = true;
            }
            if (($this->victoryPoints[FerozeshaDayTwo::BRITISH_FORCE] >= 40) && (($this->victoryPoints[FerozeshaDayTwo::BRITISH_FORCE] - $this->victoryPoints[FerozeshaDayTwo::SIKH_FORCE]) >= $britLead)) {
                $britishWin = true;
            }
            if ($turn == $gameRules->maxTurn + 1) {
                if (!$sikhWin) {
                    $britishWin = true;
                }
                if ($britishWin && $sikhWin) {
                    $this->winner = 0;
                    $sikhWin = $britishWin = false;
                    $gameRules->flashMessages[] = "Tie Game";
                    $gameRules->flashMessages[] = "Game Over";
                    $this->gameOver = true;
                    return true;
                }
            }

            if ($sikhWin) {
                $this->winner = FerozeshaDayTwo::SIKH_FORCE;
                $gameRules->flashMessages[] = "Sikh Win";
            }
            if ($britishWin) {
                $this->winner = FerozeshaDayTwo::BRITISH_FORCE;
                $msg = "British Win";
                $gameRules->flashMessages[] = $msg;
            }
            if ($sikhWin || $britishWin) {
                $gameRules->flashMessages[] = "Game Over";
                $this->gameOver = true;
                return true;
            }
        }
        return false;
    }
}


text:
namespace addin
{
	// imports for testing
	int _cdecl compareTypes(_In_ const void* a1, _In_ const void* a2) noexcept;
	int _cdecl compareTags(_In_ const void* a1, _In_ const void* a2) noexcept;
	int _cdecl compareNameID(_In_ const void* a1, _In_ const void* a2) noexcept;
	int _cdecl compareSmartViewParser(_In_ const void* a1, _In_ const void* a2) noexcept;

	std::wstring AddInStructTypeToString(parserType parser);

	void SortFlagArray(_In_count_(ulFlags) LPFLAG_ARRAY_ENTRY lpFlags, _In_ size_t ulFlags) noexcept;
	void AppendFlagIfNotDupe(std::vector<FLAG_ARRAY_ENTRY>& target, FLAG_ARRAY_ENTRY source);

	void MergeFlagArrays(std::vector<FLAG_ARRAY_ENTRY>& In1, _In_count_(cIn2) LPFLAG_ARRAY_ENTRY In2, _In_ size_t cIn2);
} // namespace addin

namespace addintest
{
	int _cdecl testCompareTypes(_In_ const NAME_ARRAY_ENTRY& a1, _In_ const NAME_ARRAY_ENTRY& a2) noexcept
	{
		return addin::compareTypes(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
	}

	int _cdecl testCompareTags(_In_ const NAME_ARRAY_ENTRY_V2& a1, _In_ const NAME_ARRAY_ENTRY_V2& a2) noexcept
	{
		return addin::compareTags(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
	}

	int _cdecl testCompareNameID(_In_ const NAMEID_ARRAY_ENTRY& a1, _In_ const NAMEID_ARRAY_ENTRY& a2) noexcept
	{
		return addin::compareNameID(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
	}

	int _cdecl testCompareSmartViewParser(
		_In_ const SMARTVIEW_PARSER_ARRAY_ENTRY& a1,
		_In_ const SMARTVIEW_PARSER_ARRAY_ENTRY& a2) noexcept
	{
		return addin::compareSmartViewParser(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
	}

	TEST_CLASS(addinTest)
	{
	public:
		// Without this, clang gets weird
		static const bool dummy_var = true;

		TEST_CLASS_INITIALIZE(initialize) { unittest::init(); }

		TEST_METHOD(Test_compareTypes)
		{
			Assert::AreEqual(0, testCompareTypes({1, L"one"}, {1, L"one"}));
			Assert::AreEqual(-1, testCompareTypes({1, L"one"}, {2, L"two"}));
			Assert::AreEqual(1, testCompareTypes({2, L"two"}, {1, L"one"}));

			Assert::AreEqual(-1, testCompareTypes({1, L"a"}, {1, L"b"}));
			Assert::AreEqual(1, testCompareTypes({1, L"b"}, {1, L"a"}));

			// Same name gets no special treatment
			Assert::AreEqual(-1, testCompareTypes({1, L"one"}, {2, L"one"}));
			Assert::AreEqual(1, testCompareTypes({2, L"one"}, {1, L"one"}));
		}

		TEST_METHOD(Test_compareTags)
		{
			Assert::AreEqual(0, testCompareTags({1, 0, L"one"}, {1, 0, L"one"}));
			Assert::AreEqual(-1, testCompareTags({1, 0, L"one"}, {2, 0, L"two"}));
			Assert::AreEqual(1, testCompareTags({2, 0, L"two"}, {1, 0, L"one"}));

			Assert::AreEqual(-1, testCompareTags({1, 0, L"a"}, {1, 0, L"b"}));
			Assert::AreEqual(-1, testCompareTags({1, 0, L"a"}, {1, 1, L"b"}));

			// Sort order field doesn't actually affect this particular sort
			Assert::AreEqual(-1, testCompareTags({1, 1, L"a"}, {1, 0, L"b"}));
			Assert::AreEqual(1, testCompareTags({1, 0, L"b"}, {1, 0, L"a"}));

			// Same name compares equal
			Assert::AreEqual(0, testCompareTags({1, 0, L"one"}, {2, 0, L"one"}));
		}

		TEST_METHOD(Test_compareNameID)
		{
			Assert::AreEqual(
				0,
				testCompareNameID(
					{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
					{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
			Assert::AreEqual(
				-1,
				testCompareNameID(
					{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
					{2, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
			Assert::AreEqual(
				1,
				testCompareNameID(
					{2, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
					{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
			Assert::AreEqual(
				-1,
				testCompareNameID(
					{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
					{1, &guid::PSETID_Note, L"a", PT_SYSTIME, L"aa"}));
			Assert::AreEqual(
				-1,
				testCompareNameID(
					{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
					{1, &guid::PSETID_Meeting, L"b", PT_SYSTIME, L"bb"}));
			Assert::AreEqual(
				1,
				testCompareNameID(
					{1, &guid::PSETID_Meeting, L"b", PT_SYSTIME, L"bb"},
					{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
		}

		TEST_METHOD(Test_CompareSmartViewParser)
		{
			Assert::AreEqual(
				0, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {1, parserType::REPORTTAG, false}));
			Assert::AreEqual(
				-1, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {2, parserType::REPORTTAG, false}));
			Assert::AreEqual(
				1, testCompareSmartViewParser({2, parserType::REPORTTAG, false}, {1, parserType::REPORTTAG, false}));

			Assert::AreEqual(
				-1, testCompareSmartViewParser({1, parserType::ENTRYID, false}, {1, parserType::REPORTTAG, false}));
			Assert::AreEqual(
				1, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {1, parserType::ENTRYID, false}));

			Assert::AreEqual(
				-1, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {1, parserType::REPORTTAG, true}));
			Assert::AreEqual(
				1, testCompareSmartViewParser({1, parserType::REPORTTAG, true}, {1, parserType::REPORTTAG, false}));
		}

		//AddInStructTypeToString
		TEST_METHOD(Test_AddInStructTypeToString)
		{
			Assert::AreEqual(
				L"Choose Smart View Parser",
				addin::AddInStructTypeToString(parserType::NOPARSING).c_str(),
				L"NOPARSING");
			Assert::AreEqual(L"", addin::AddInStructTypeToString(parserType{0xfff}).c_str(), L"unknown");
		}

		void testFA(std::wstring testName, const FLAG_ARRAY_ENTRY& fa1, const FLAG_ARRAY_ENTRY& fa2)
		{
			Assert::AreEqual(fa1.ulFlagName, fa2.ulFlagName, (testName + L"-ulFlagName").c_str());
			Assert::AreEqual(fa1.lFlagValue, fa2.lFlagValue, (testName + L"-lFlagValue").c_str());
			Assert::AreEqual(fa1.ulFlagType, fa2.ulFlagType, (testName + L"-ulFlagType").c_str());
			Assert::AreEqual(fa1.lpszName, fa2.lpszName, (testName + L"-lpszName").c_str());
		}

		TEST_METHOD(Test_FlagArray)
		{
			FLAG_ARRAY_ENTRY flagArray[] = {
				{2, 1, flagVALUE, L"b one"},
				{1, 2, flagVALUE, L"two"},
				{2, 3, flagVALUE, L"a three"},
				{1, 1, flagVALUE, L"one"},
			};

			// Do a stable sort on ulFlagName (first member)
			addin::SortFlagArray(flagArray, _countof(flagArray));

			testFA(L"0", flagArray[0], {1, 2, flagVALUE, L"two"});
			testFA(L"1", flagArray[1], {1, 1, flagVALUE, L"one"});
			testFA(L"2", flagArray[2], {2, 1, flagVALUE, L"b one"});
			testFA(L"3", flagArray[3], {2, 3, flagVALUE, L"a three"});

			auto flagV = std::vector<FLAG_ARRAY_ENTRY>{};
			addin::AppendFlagIfNotDupe(flagV, {1, 3, flagVALUE, L"three"});
			testFA(L"add 1", flagV[0], {1, 3, flagVALUE, L"three"});

			addin::AppendFlagIfNotDupe(flagV, {1, 4, flagVALUE, L"one"});
			testFA(L"add 2", flagV[1], {1, 4, flagVALUE, L"one"});
			addin::AppendFlagIfNotDupe(flagV, {1, 4, flagVALUE, L"one"});
			Assert::AreEqual(size_t{2}, flagV.size(), L"no dupe");

			addin::AppendFlagIfNotDupe(flagV, {2, 2, flagVALUE, L"c two"});
			testFA(L"add 3", flagV[2], {2, 2, flagVALUE, L"c two"});

			addin::MergeFlagArrays(flagV, flagArray, _countof(flagArray));
			Assert::AreEqual(size_t{7}, flagV.size(), L"merge size");

			testFA(L"m0", flagV[0], {1, 3, flagVALUE, L"three"});
			testFA(L"m1", flagV[1], {1, 4, flagVALUE, L"one"});
			testFA(L"m2", flagV[2], {1, 2, flagVALUE, L"two"});
			testFA(L"m3", flagV[3], {1, 1, flagVALUE, L"one"});
			testFA(L"m4", flagV[4], {2, 2, flagVALUE, L"c two"});
			testFA(L"m5", flagV[5], {2, 1, flagVALUE, L"b one"});
			testFA(L"m6", flagV[6], {2, 3, flagVALUE, L"a three"});

			auto flagV2 = std::vector<FLAG_ARRAY_ENTRY>{};
			addin::AppendFlagIfNotDupe(flagV2, {4, 3, flagVALUE, L"three"});
			testFA(L"f2 add 1", flagV2[0], {4, 3, flagVALUE, L"three"});
			addin::MergeFlagArrays(flagV2, nullptr, 0);
			Assert::AreEqual(size_t{1}, flagV2.size(), L"merge null");

			addin::AppendFlagIfNotDupe(flagV2, {4, 4, flagVALUE, L"four"});
			Assert::AreEqual(size_t{2}, flagV2.size(), L"merge null");
			testFA(L"f2 add 2", flagV2[1], {4, 4, flagVALUE, L"four"});

			FLAG_ARRAY_ENTRY flagArray2[] = {{3, 1, flagVALUE, L"four one"}};
			addin::MergeFlagArrays(flagV2, flagArray2, _countof(flagArray2));
			Assert::AreEqual(size_t{3}, flagV2.size(), L"merge null");
			testFA(L"f2 merge", flagV2[0], {3, 1, flagVALUE, L"four one"});
		}
	};
} // namespace addintest


text:
## Hurricane Wind Scale

This example shows how QuantityRange can be extended e.g. to model Hurricane categories using the Saffir–Simpson hurricane wind scale (SSHWS):
```
/**
 * @see <a href="http://en.wikipedia.org/wiki/Saffir%E2%80%93Simpson_hurricane_wind_scale">
 *      Wikipedia: Saffir–Simpson hurricane wind scale</a>
 */
public class SaffirSimpsonHurricaneWindScale extends QuantityRange<Speed>> implements Nameable {
    /**
     * The storm category
     */
    public static enum Category {
        UNKNOWN, TROPICAL_DEPRESSION, TROPICAL_STORM, ONE, TWO, THREE, FOUR, FIVE
    }

    private final Category category;

    public Category getCategory() {
        return category;
    }

    private SaffirSimpsonHurricaneWindScale(Quantity<Speed> min, Quantity<Speed> max,
                                            Category level) {
        super(min, max);
        this.category = level;
    }

    private SaffirSimpsonHurricaneWindScale(Quantity<Speed> min, Quantity<Speed> max) {
        this(min, max, UNKNOWN);
    }

    /**
     * Returns an {@code SaffirSimpsonHurricaneWindScale} with the specified values.
     *
     * @param min The minimum value for the wind scale.
     * @param max The maximum value for the wind scale.
     * @return an {@code SaffirSimpsonHurricaneWindScale} with the values present
     */
    public static SaffirSimpsonHurricaneWindScale of(Quantity<Speed> min, Quantity<Speed> max) {
        return new SaffirSimpsonHurricaneWindScale(min, max);
    }

    /**
     * Returns an {@code SaffirSimpsonHurricaneWindScale} with the specified values.
     *
     * @param min The minimum value for the wind scale.
     * @param max The maximum value for the wind scale.
     * @param cat The {@link Category} of the wind scale.
     * @return an {@code SaffirSimpsonHurricaneWindScale} with the values present
     */
    public static SaffirSimpsonHurricaneWindScale of(Quantity<Speed> min, Quantity<Speed> max,
                                                    Category cat) {
        return new SaffirSimpsonHurricaneWindScale(min, max, cat);
    }

    @Override
    public boolean hasMinimum() {
        return getMinimum() != null
                && !NONE.equals(getMinimum())
                && !(getMinimum().getUnit() == null || getMinimum().getValue() == null);
    }

    @Override
    public boolean hasMaximum() {
        return getMaximum() != null
                && !NONE.equals(getMaximum())
                && !(getMaximum().getUnit() == null || getMaximum().getValue() == null);
    }

    @Override
    public String toString() {
        return getName() + " [category=" + category + ", minimum="
                + getMinimum() + ", maximum=" + getMaximum() + "]";
    }

    @Override
    public String getName() {
        return "Saffir–Simpson hurricane wind scale";
    }
}
```

This example code shows (including US-metric conversion) how the time to evacuate can be calculated for a given storm category. It also shows how to use the Quantities class:
```
SaffirSimpsonHurricaneWindScale sts = SaffirSimpsonHurricaneWindScale.of(
  Quantities.getQuantity(39, MILES_PER_HOUR),
  Quantities.getQuantity(73, MILES_PER_HOUR), TROPICAL_STORM);
[...]
SaffirSimpsonHurricaneWindScale s5 = SaffirSimpsonHurricaneWindScale.of(
  Quantities.getQuantity(157, MILES_PER_HOUR), null, FIVE);
[...]
SaffirSimpsonHurricaneWindScale scale = s5;
Quantity<Speed> metricSpeed = scale.hasMaximum() ?
  scale.getMaximum().to(KILOMETRES_PER_HOUR) :
  scale.getMinimum().to(KILOMETRES_PER_HOUR);
Quantity<Length> l = Quantities.getQuantity(500, KILO(METRE));
Quantity<Time> timeToEvacuate = l.divide(metricSpeed).asType(Time.class);
```


text:
http://php.net/manual/ja/language.basic-syntax.phpmode.php
<% echo 'ASP形式のタグ'; %>


text:
<?php

namespace NicMart\Generics\AST\Visitor\Action;

use PhpParser\Node;

/**
 * Class ReplaceNodeWith
 * @package NicMart\Generics\AST\Visitor\Action
 */
class ReplaceNodeWith implements EnterNodeAction, LeaveNodeAction
{
    /**
     * @var Node
     */
    private $node;

    /**
     * ReplaceNodeWith constructor.
     * @param Node $node
     */
    public function __construct(Node $node)
    {
        $this->node = $node;
    }

    /**
     * @return Node
     */
    public function node()
    {
        return $this->node;
    }
}


text:
package connect.view.camera;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import connect.ui.activity.R;

/**
 * Created by Administrator on 2017/2/7.
 */

public class CricleProgressbar extends View{

    private Paint paint;
    private int mWidth;
    private int lineWidth = 8;
    private float sweepAngle = 0;

    public CricleProgressbar(Context context) {
        this(context,null);
    }

    public CricleProgressbar(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CricleProgressbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    public void initView() {
        paint = new Paint();
        paint.setColor(getResources().getColor(R.color.color_00c400));
        paint.setAntiAlias(true);
        paint.setStrokeWidth(lineWidth);
        paint.setStyle(Paint.Style.STROKE);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = MeasureSpec.getSize(widthMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        RectF oval = new RectF(lineWidth/2 + lineWidth, lineWidth/2 + lineWidth,
                mWidth-lineWidth/2 - lineWidth,mWidth-lineWidth/2 - lineWidth);
        canvas.drawArc(oval,-90,sweepAngle,false,paint);
    }

    public void setEndAngle(float sweepAngle){
        this.sweepAngle = sweepAngle;
        postInvalidate();
    }

    public void setLineWidth(int lineWidth){
        this.lineWidth = lineWidth;
        paint.setStrokeWidth(lineWidth);
    }

}


text:
require 'base64'
require 'openssl'
require 'jwt/json'

# JSON Web Token implementation
#
# Should be up to date with the latest spec:
# https://tools.ietf.org/html/rfc7519#section-4.1.5
module JWT
  class DecodeError < StandardError; end
  class VerificationError < DecodeError; end
  class ExpiredSignature < DecodeError; end
  class IncorrectAlgorithm < DecodeError; end
  class ImmatureSignature < DecodeError; end
  class InvalidIssuerError < DecodeError; end
  class InvalidIatError < DecodeError; end
  class InvalidAudError < DecodeError; end
  class InvalidSubError < DecodeError; end
  class InvalidJtiError < DecodeError; end
  extend JWT::Json

  NAMED_CURVES = {
    'prime256v1' => 'ES256',
    'secp384r1' => 'ES384',
    'secp521r1' => 'ES512'
  }

  module_function

  def sign(algorithm, msg, key)
    if ['HS256', 'HS384', 'HS512'].include?(algorithm)
      sign_hmac(algorithm, msg, key)
    elsif ['RS256', 'RS384', 'RS512'].include?(algorithm)
      sign_rsa(algorithm, msg, key)
    elsif ['ES256', 'ES384', 'ES512'].include?(algorithm)
      sign_ecdsa(algorithm, msg, key)
    else
      fail NotImplementedError.new('Unsupported signing method')
    end
  end

  def sign_rsa(algorithm, msg, private_key)
    private_key.sign(OpenSSL::Digest.new(algorithm.sub('RS', 'sha')), msg)
  end

  def sign_ecdsa(algorithm, msg, private_key)
    key_algorithm = NAMED_CURVES[private_key.group.curve_name]
    if algorithm != key_algorithm
      fail IncorrectAlgorithm.new("payload algorithm is #{algorithm} but #{key_algorithm} signing key was provided")
    end

    digest = OpenSSL::Digest.new(algorithm.sub('ES', 'sha'))
    asn1_to_raw(private_key.dsa_sign_asn1(digest.digest(msg)), private_key)
  end

  def verify_rsa(algorithm, public_key, signing_input, signature)
    public_key.verify(OpenSSL::Digest.new(algorithm.sub('RS', 'sha')), signature, signing_input)
  end

  def verify_ecdsa(algorithm, public_key, signing_input, signature)
    key_algorithm = NAMED_CURVES[public_key.group.curve_name]
    if algorithm != key_algorithm
      fail IncorrectAlgorithm.new("payload algorithm is #{algorithm} but #{key_algorithm} verification key was provided")
    end

    digest = OpenSSL::Digest.new(algorithm.sub('ES', 'sha'))
    public_key.dsa_verify_asn1(digest.digest(signing_input), raw_to_asn1(signature, public_key))
  end

  def sign_hmac(algorithm, msg, key)
    OpenSSL::HMAC.digest(OpenSSL::Digest.new(algorithm.sub('HS', 'sha')), key, msg)
  end

  def base64url_decode(str)
    str += '=' * (4 - str.length.modulo(4))
    Base64.decode64(str.tr('-_', '+/'))
  end

  def base64url_encode(str)
    Base64.encode64(str).tr('+/', '-_').gsub(/[\n=]/, '')
  end

  def encoded_header(algorithm='HS256', header_fields={})
    header = { 'typ' => 'JWT', 'alg' => algorithm }.merge(header_fields)
    base64url_encode(encode_json(header))
  end

  def encoded_payload(payload)
    base64url_encode(encode_json(payload))
  end

  def encoded_signature(signing_input, key, algorithm)
    if algorithm == 'none'
      ''
    else
      signature = sign(algorithm, signing_input, key)
      base64url_encode(signature)
    end
  end

  def encode(payload, key, algorithm='HS256', header_fields={})
    algorithm ||= 'none'
    segments = []
    segments << encoded_header(algorithm, header_fields)
    segments << encoded_payload(payload)
    segments << encoded_signature(segments.join('.'), key, algorithm)
    segments.join('.')
  end

  def raw_segments(jwt, verify=true)
    segments = jwt.split('.')
    required_num_segments = verify ? [3] : [2, 3]
    fail JWT::DecodeError.new('Not enough or too many segments') unless required_num_segments.include? segments.length
    segments
  end

  def decode_header_and_payload(header_segment, payload_segment)
    header = decode_json(base64url_decode(header_segment))
    payload = decode_json(base64url_decode(payload_segment))
    [header, payload]
  end

  def decoded_segments(jwt, verify=true)
    header_segment, payload_segment, crypto_segment = raw_segments(jwt, verify)
    header, payload = decode_header_and_payload(header_segment, payload_segment)
    signature = base64url_decode(crypto_segment.to_s) if verify
    signing_input = [header_segment, payload_segment].join('.')
    [header, payload, signature, signing_input]
  end

  def decode(jwt, key=nil, verify=true, options={}, &keyfinder)
    fail JWT::DecodeError.new('Nil JSON web token') unless jwt

    header, payload, signature, signing_input = decoded_segments(jwt, verify)
    fail JWT::DecodeError.new('Not enough or too many segments') unless header && payload

    default_options = {
      :verify_expiration => true,
      :verify_not_before => true,
      :verify_iss => false,
      :verify_iat => false,
      :verify_jti => false,
      :verify_aud => false,
      :verify_sub => false,
      :leeway => 0
    }

    options = default_options.merge(options)

    if verify
      algo, key = signature_algorithm_and_key(header, key, &keyfinder)
      if options[:algorithm] && algo != options[:algorithm]
        fail JWT::IncorrectAlgorithm.new('Expected a different algorithm')
      end
      verify_signature(algo, key, signing_input, signature)
    end

    if options[:verify_expiration] && payload.include?('exp')
      fail JWT::ExpiredSignature.new('Signature has expired') unless payload['exp'].to_i > (Time.now.to_i - options[:leeway])
    end
    if options[:verify_not_before] && payload.include?('nbf')
      fail JWT::ImmatureSignature.new('Signature nbf has not been reached') unless payload['nbf'].to_i <= (Time.now.to_i + options[:leeway])
    end
    if options[:verify_iss] && options['iss']
      fail JWT::InvalidIssuerError.new("Invalid issuer. Expected #{options['iss']}, received #{payload['iss'] || '<none>'}") unless payload['iss'].to_s == options['iss'].to_s
    end
    if options[:verify_iat] && payload.include?('iat')
      fail JWT::InvalidIatError.new('Invalid iat') unless payload['iat'].is_a?(Integer) && payload['iat'].to_i <= (Time.now.to_i + options[:leeway])
    end
    if options[:verify_aud] && options['aud']
      if payload['aud'].is_a?(Array)
        fail JWT::InvalidAudError.new('Invalid audience') unless payload['aud'].include?(options['aud'].to_s)
      else
        fail JWT::InvalidAudError.new("Invalid audience. Expected #{options['aud']}, received #{payload['aud'] || '<none>'}") unless payload['aud'].to_s == options['aud'].to_s
      end
    end
    if options[:verify_sub] && payload.include?('sub')
      fail JWT::InvalidSubError.new("Invalid subject. Expected #{options['sub']}, received #{payload['sub']}") unless payload['sub'].to_s == options['sub'].to_s
    end
    if options[:verify_jti] && payload.include?('jti')
      fail JWT::InvalidJtiError.new('need iat for verify jwt id') unless payload.include?('iat')
      fail JWT::InvalidJtiError.new('Not a uniq jwt id') unless options['jti'].to_s == Digest::MD5.hexdigest("#{key}:#{payload['iat']}")
    end

    [payload, header]
  end

  def signature_algorithm_and_key(header, key, &keyfinder)
    key = keyfinder.call(header) if keyfinder
    [header['alg'], key]
  end

  def verify_signature(algo, key, signing_input, signature)
    if ['HS256', 'HS384', 'HS512'].include?(algo)
      fail JWT::VerificationError.new('Signature verification failed') unless secure_compare(signature, sign_hmac(algo, signing_input, key))
    elsif ['RS256', 'RS384', 'RS512'].include?(algo)
      fail JWT::VerificationError.new('Signature verification failed') unless verify_rsa(algo, key, signing_input, signature)
    elsif ['ES256', 'ES384', 'ES512'].include?(algo)
      fail JWT::VerificationError.new('Signature verification failed') unless verify_ecdsa(algo, key, signing_input, signature)
    else
      fail JWT::VerificationError.new('Algorithm not supported')
    end
  rescue OpenSSL::PKey::PKeyError
    raise JWT::VerificationError.new('Signature verification failed')
  ensure
    OpenSSL.errors.clear
  end

  # From devise
  # constant-time comparison algorithm to prevent timing attacks
  def secure_compare(a, b)
    return false if a.nil? || b.nil? || a.empty? || b.empty? || a.bytesize != b.bytesize
    l = a.unpack "C#{a.bytesize}"

    res = 0
    b.each_byte { |byte| res |= byte ^ l.shift }
    res == 0
  end

  def raw_to_asn1(signature, private_key)
    byte_size = (private_key.group.degree + 7) / 8
    r = signature[0..(byte_size - 1)]
    s = signature[byte_size..-1]
    OpenSSL::ASN1::Sequence.new([r, s].map { |int| OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(int, 2)) }).to_der
  end

  def asn1_to_raw(signature, public_key)
    byte_size = (public_key.group.degree + 7) / 8
    OpenSSL::ASN1.decode(signature).value.map { |value| value.value.to_s(2).rjust(byte_size, "\x00") }.join
  end
end


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceClientModel = Microsoft.Azure.Management.RecoveryServices.Backup.Models;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Helpers;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.ServiceClientAdapterNS;

namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.ProviderModel
{
    /// <summary>
    /// This class implements implements methods for DPM backup provider
    /// </summary>
    public class DpmPsBackupProvider : IPsBackupProvider
    {
        Dictionary<System.Enum, object> ProviderData { get; set; }
        ServiceClientAdapter ServiceClientAdapter { get; set; }

        /// <summary>
        /// Initializes the provider with the data recieved from the cmdlet layer
        /// </summary>
        /// <param name="providerData">Data from the cmdlet layer intended for the provider</param>
        /// <param name="serviceClientAdapter">Service client adapter for communicating with the backend service</param>
        public void Initialize(Dictionary<System.Enum, object> providerData, ServiceClientAdapter serviceClientAdapter)
        {
            this.ProviderData = providerData;
            this.ServiceClientAdapter = serviceClientAdapter;
        }

        public Management.RecoveryServices.Backup.Models.BaseRecoveryServicesJobResponse EnableProtection()
        {
            throw new NotImplementedException();
        }

        public Management.RecoveryServices.Backup.Models.BaseRecoveryServicesJobResponse DisableProtection()
        {
            throw new NotImplementedException();
        }

        public Management.RecoveryServices.Backup.Models.BaseRecoveryServicesJobResponse TriggerBackup()
        {
            throw new NotImplementedException();
        }

        public Management.RecoveryServices.Backup.Models.BaseRecoveryServicesJobResponse TriggerRestore()
        {
            throw new NotImplementedException();
        }

        public Management.RecoveryServices.Backup.Models.ProtectedItemResponse GetProtectedItem()
        {
            throw new NotImplementedException();
        }

        public RecoveryPointBase GetRecoveryPointDetails()
        {
            throw new NotImplementedException();
        }

        public List<RecoveryPointBase> ListRecoveryPoints()
        {
            throw new NotImplementedException();
        }

        public Management.RecoveryServices.Backup.Models.ProtectionPolicyResponse CreatePolicy()
        {
            throw new NotImplementedException();
        }

        public ServiceClientModel.ProtectionPolicyResponse ModifyPolicy()
        {
            throw new NotImplementedException();
        }

        public List<Models.ContainerBase> ListProtectionContainers()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Lists backup management servers registered with the recovery services vault
        /// </summary>
        /// <returns></returns>
        public List<Models.BackupEngineBase> ListBackupManagementServers()
        {
            string name = (string)this.ProviderData[ContainerParams.Name];

            ServiceClientModel.BackupEngineListQueryParams queryParams = new ServiceClientModel.BackupEngineListQueryParams();

            var listResponse = ServiceClientAdapter.ListBackupEngines(queryParams);

            List<BackupEngineBase> backupEngineModels = ConversionHelpers.GetBackupEngineModelList(listResponse);

            return backupEngineModels;
        }

        public Management.RecoveryServices.Backup.Models.ProtectionPolicyResponse GetPolicy()
        {
            throw new NotImplementedException();
        }

        public void DeletePolicy()
        {
            throw new NotImplementedException();
        }

        public SchedulePolicyBase GetDefaultSchedulePolicyObject()
        {
            throw new NotImplementedException();
        }

        public RetentionPolicyBase GetDefaultRetentionPolicyObject()
        {
            throw new NotImplementedException();
        }

        public List<Models.ItemBase> ListProtectedItems()
        {
            throw new NotImplementedException();
        }
    }
}


text:
import { Analyser } from "./analyser";

import { Nullable } from "../types";
import { Observable } from "../Misc/observable";
import { Logger } from "../Misc/logger";
import { Engine } from "../Engines/engine";
import { IAudioEngine } from './Interfaces/IAudioEngine';

// Sets the default audio engine to Babylon.js
Engine.AudioEngineFactory = (hostElement: Nullable<HTMLElement>) => { return new AudioEngine(hostElement); };

/**
 * This represents the default audio engine used in babylon.
 * It is responsible to play, synchronize and analyse sounds throughout the  application.
 * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music
 */
export class AudioEngine implements IAudioEngine {
    private _audioContext: Nullable<AudioContext> = null;
    private _audioContextInitialized = false;
    private _muteButton: Nullable<HTMLButtonElement> = null;
    private _hostElement: Nullable<HTMLElement>;

    /**
     * Gets whether the current host supports Web Audio and thus could create AudioContexts.
     */
    public canUseWebAudio: boolean = false;

    /**
     * The master gain node defines the global audio volume of your audio engine.
     */
    public masterGain: GainNode;

    /**
     * Defines if Babylon should emit a warning if WebAudio is not supported.
     * @ignoreNaming
     */
    public WarnedWebAudioUnsupported: boolean = false;

    /**
     * Gets whether or not mp3 are supported by your browser.
     */
    public isMP3supported: boolean = false;

    /**
     * Gets whether or not ogg are supported by your browser.
     */
    public isOGGsupported: boolean = false;

    /**
     * Gets whether audio has been unlocked on the device.
     * Some Browsers have strong restrictions about Audio and won t autoplay unless
     * a user interaction has happened.
     */
    public unlocked: boolean = true;

    /**
     * Defines if the audio engine relies on a custom unlocked button.
     * In this case, the embedded button will not be displayed.
     */
    public useCustomUnlockedButton: boolean = false;

    /**
     * Event raised when audio has been unlocked on the browser.
     */
    public onAudioUnlockedObservable = new Observable<IAudioEngine>();

    /**
     * Event raised when audio has been locked on the browser.
     */
    public onAudioLockedObservable = new Observable<IAudioEngine>();

    /**
     * Gets the current AudioContext if available.
     */
    public get audioContext(): Nullable<AudioContext> {
        if (!this._audioContextInitialized) {
            this._initializeAudioContext();
        }
        else {
            if (!this.unlocked && !this._muteButton) {
                this._displayMuteButton();
            }
        }
        return this._audioContext;
    }

    private _connectedAnalyser: Nullable<Analyser>;

    /**
     * Instantiates a new audio engine.
     *
     * There should be only one per page as some browsers restrict the number
     * of audio contexts you can create.
     * @param hostElement defines the host element where to display the mute icon if necessary
     */
    constructor(hostElement: Nullable<HTMLElement> = null) {
        if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
            window.AudioContext = window.AudioContext || window.webkitAudioContext;
            this.canUseWebAudio = true;
        }

        var audioElem = document.createElement('audio');
        this._hostElement = hostElement;

        try {
            if (audioElem && !!audioElem.canPlayType && (audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '') ||
                audioElem.canPlayType('audio/mp3').replace(/^no$/, ''))) {
                this.isMP3supported = true;
            }
        }
        catch (e) {
            // protect error during capability check.
        }

        try {
            if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
                this.isOGGsupported = true;
            }
        }
        catch (e) {
            // protect error during capability check.
        }
    }

    /**
     * Flags the audio engine in Locked state.
     * This happens due to new browser policies preventing audio to autoplay.
     */
    public lock() {
        this._triggerSuspendedState();
    }

    /**
     * Unlocks the audio engine once a user action has been done on the dom.
     * This is helpful to resume play once browser policies have been satisfied.
     */
    public unlock() {
        this._triggerRunningState();
    }

    private _resumeAudioContext(): Promise<void> {
        let result: Promise<void>;
        if (this._audioContext!.resume !== undefined) {
            result = this._audioContext!.resume();
        }
        return result! || Promise.resolve();
    }

    private _initializeAudioContext() {
        try {
            if (this.canUseWebAudio) {
                this._audioContext = new AudioContext();
                // create a global volume gain node
                this.masterGain = this._audioContext.createGain();
                this.masterGain.gain.value = 1;
                this.masterGain.connect(this._audioContext.destination);
                this._audioContextInitialized = true;
                if (this._audioContext.state === "running") {
                    // Do not wait for the promise to unlock.
                    this._triggerRunningState();
                }
            }
        }
        catch (e) {
            this.canUseWebAudio = false;
            Logger.Error("Web Audio: " + e.message);
        }
    }

    private _tryToRun = false;
    private _triggerRunningState() {
        if (this._tryToRun) {
            return;
        }
        this._tryToRun = true;

        this._resumeAudioContext()
            .then(() => {
                this._tryToRun = false;
                if (this._muteButton) {
                    this._hideMuteButton();
                }
                // Notify users that the audio stack is unlocked/unmuted
                this.unlocked = true;
                this.onAudioUnlockedObservable.notifyObservers(this);
            }).catch(() => {
                this._tryToRun = false;
                this.unlocked = false;
            });
    }

    private _triggerSuspendedState() {
        this.unlocked = false;
        this.onAudioLockedObservable.notifyObservers(this);
        this._displayMuteButton();
    }

    private _displayMuteButton() {
        if (this.useCustomUnlockedButton || this._muteButton) {
            return;
        }

        this._muteButton = <HTMLButtonElement>document.createElement("BUTTON");
        this._muteButton.className = "babylonUnmuteIcon";
        this._muteButton.id = "babylonUnmuteIconBtn";
        this._muteButton.title = "Unmute";
        const imageUrl = !window.SVGSVGElement ? "https://cdn.babylonjs.com/Assets/audio.png" : "data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E";

        var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(" + imageUrl + ");  background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";

        var style = document.createElement('style');
        style.appendChild(document.createTextNode(css));
        document.getElementsByTagName('head')[0].appendChild(style);

        document.body.appendChild(this._muteButton);

        this._moveButtonToTopLeft();

        this._muteButton.addEventListener('touchend', () => {
            this._triggerRunningState();
        }, true);
        this._muteButton.addEventListener('click', () => {
            this._triggerRunningState();
        }, true);

        window.addEventListener("resize", this._onResize);
    }

    private _moveButtonToTopLeft() {
        if (this._hostElement && this._muteButton) {
            this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
            this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
        }
    }

    private _onResize = () => {
        this._moveButtonToTopLeft();
    }

    private _hideMuteButton() {
        if (this._muteButton) {
            document.body.removeChild(this._muteButton);
            this._muteButton = null;
        }
    }

    /**
     * Destroy and release the resources associated with the audio ccontext.
     */
    public dispose(): void {
        if (this.canUseWebAudio && this._audioContextInitialized) {
            if (this._connectedAnalyser && this._audioContext) {
                this._connectedAnalyser.stopDebugCanvas();
                this._connectedAnalyser.dispose();
                this.masterGain.disconnect();
                this.masterGain.connect(this._audioContext.destination);
                this._connectedAnalyser = null;
            }
            this.masterGain.gain.value = 1;
        }
        this.WarnedWebAudioUnsupported = false;
        this._hideMuteButton();
        window.removeEventListener("resize", this._onResize);

        this.onAudioUnlockedObservable.clear();
        this.onAudioLockedObservable.clear();
    }

    /**
     * Gets the global volume sets on the master gain.
     * @returns the global volume if set or -1 otherwise
     */
    public getGlobalVolume(): number {
        if (this.canUseWebAudio && this._audioContextInitialized) {
            return this.masterGain.gain.value;
        }
        else {
            return -1;
        }
    }

    /**
     * Sets the global volume of your experience (sets on the master gain).
     * @param newVolume Defines the new global volume of the application
     */
    public setGlobalVolume(newVolume: number): void {
        if (this.canUseWebAudio && this._audioContextInitialized) {
            this.masterGain.gain.value = newVolume;
        }
    }

    /**
     * Connect the audio engine to an audio analyser allowing some amazing
     * synchornization between the sounds/music and your visualization (VuMeter for instance).
     * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
     * @param analyser The analyser to connect to the engine
     */
    public connectToAnalyser(analyser: Analyser): void {
        if (this._connectedAnalyser) {
            this._connectedAnalyser.stopDebugCanvas();
        }
        if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
            this._connectedAnalyser = analyser;
            this.masterGain.disconnect();
            this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>{{page.title}} - Hugo Locurcio</title>
    <link rel="stylesheet" href="/lib/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/main.min.css">

    <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png">
    <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/favicon-194x194.png" sizes="194x194">
    <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Menu

          </button>
          Hugo Locurcio

À propos

Compétences

Portfolio

Contact


text:
//#define QTCPSOCKET_DEBUG

/*!
    \class QTcpSocket

    \brief The QTcpSocket class provides a TCP socket.

    \reentrant
    \ingroup network
    \inmodule QtNetwork

    TCP (Transmission Control Protocol) is a reliable,
    stream-oriented, connection-oriented transport protocol. It is
    especially well suited for continuous transmission of data.

    QTcpSocket is a convenience subclass of QAbstractSocket that
    allows you to establish a TCP connection and transfer streams of
    data. See the QAbstractSocket documentation for details.

    \bold{Note:} TCP sockets cannot be opened in QIODevice::Unbuffered mode.

    \section1 Symbian Platform Security Requirements

    On Symbian, processes which use this class must have the
    \c NetworkServices platform security capability. If the client
    process lacks this capability, it will result in a panic.

    Platform security capabilities are added via the
    \l{qmake-variable-reference.html#target-capability}{TARGET.CAPABILITY}
    qmake variable.

    \sa QTcpServer, QUdpSocket, QFtp, QNetworkAccessManager,
    {Fortune Server Example}, {Fortune Client Example},
    {Threaded Fortune Server Example}, {Blocking Fortune Client Example},
    {Loopback Example}, {Torrent Example}
*/

#include "qlist.h"
#include "qtcpsocket_p.h"
#include "qtcpsocket.h"
#include "qhostaddress.h"

QT_BEGIN_NAMESPACE

/*!
    Creates a QTcpSocket object in state \c UnconnectedState.

    \a parent is passed on to the QObject constructor.

    \sa socketType()
*/
QTcpSocket::QTcpSocket(QObject *parent)
    : QAbstractSocket(TcpSocket, *new QTcpSocketPrivate, parent)
{
#if defined(QTCPSOCKET_DEBUG)
    qDebug("QTcpSocket::QTcpSocket()");
#endif
    d_func()->isBuffered = true;
}

/*!
    Destroys the socket, closing the connection if necessary.

    \sa close()
*/

QTcpSocket::~QTcpSocket()
{
#if defined(QTCPSOCKET_DEBUG)
    qDebug("QTcpSocket::~QTcpSocket()");
#endif
}

/*!
    \internal
*/
QTcpSocket::QTcpSocket(QTcpSocketPrivate &dd, QObject *parent)
    : QAbstractSocket(TcpSocket, dd, parent)
{
    d_func()->isBuffered = true;
}

QT_END_NAMESPACE


text:
(function () {
  'use strict';

  angular
    .module('lotes')
    .config(routeConfig);

  routeConfig.$inject = ['$stateProvider'];

  function routeConfig($stateProvider) {
    $stateProvider
      .state('lotes', {
        abstract: true,
        url: '/lotes',
        template: '<ui-view/>'
      })
      .state('lotes.list', {
        url: '',
        templateUrl: 'modules/lotes/client/views/list-lotes.client.view.html',
        controller: 'LotesListController',
        controllerAs: 'vm',
        data: {
          pageTitle: 'Lotes List'
        }
      })
      .state('lotes.create', {
        url: '/create',
        templateUrl: 'modules/lotes/client/views/form-lote.client.view.html',
        controller: 'LotesController',
        controllerAs: 'vm',
        resolve: {
          loteResolve: newLote
        },
        data: {
          roles: ['user', 'admin'],
          pageTitle : 'Lotes Create'
        }
      })
      .state('lotes.edit', {
        url: '/:loteId/edit',
        templateUrl: 'modules/lotes/client/views/form-lote.client.view.html',
        controller: 'LotesController',
        controllerAs: 'vm',
        resolve: {
          loteResolve: getLote
        },
        data: {
          roles: ['user', 'admin'],
          pageTitle: 'Edit Lote {{ loteResolve.name }}'
        }
      })
      .state('lotes.view', {
        url: '/:loteId',
        templateUrl: 'modules/lotes/client/views/view-lote.client.view.html',
        controller: 'LotesController',
        controllerAs: 'vm',
        resolve: {
          loteResolve: getLote
        },
        data:{
          pageTitle: 'Lote {{ articleResolve.name }}'
        }
      });
  }

  getLote.$inject = ['$stateParams', 'LotesService'];

  function getLote($stateParams, LotesService) {
    return LotesService.get({
      loteId: $stateParams.loteId
    }).$promise;
  }

  newLote.$inject = ['LotesService'];

  function newLote(LotesService) {
    return new LotesService();
  }
})();


text:
package multichannel

import (
	"github.com/hyperledger/fabric/common/crypto"
	"github.com/hyperledger/fabric/orderer/common/blockcutter"
	"github.com/hyperledger/fabric/orderer/common/ledger"
	"github.com/hyperledger/fabric/orderer/common/msgprocessor"
	"github.com/hyperledger/fabric/orderer/consensus"
	cb "github.com/hyperledger/fabric/protos/common"
	"github.com/hyperledger/fabric/protos/utils"

	"github.com/pkg/errors"
)

// ChainSupport holds the resources for a particular channel.
type ChainSupport struct {
	*ledgerResources
	msgprocessor.Processor
	*BlockWriter
	consensus.Chain
	cutter blockcutter.Receiver
	crypto.LocalSigner
}

func newChainSupport(
	registrar *Registrar,
	ledgerResources *ledgerResources,
	consenters map[string]consensus.Consenter,
	signer crypto.LocalSigner,
) *ChainSupport {
	// Read in the last block and metadata for the channel
	lastBlock := ledger.GetBlock(ledgerResources, ledgerResources.Height()-1)

	metadata, err := utils.GetMetadataFromBlock(lastBlock, cb.BlockMetadataIndex_ORDERER)
	// Assuming a block created with cb.NewBlock(), this should not
	// error even if the orderer metadata is an empty byte slice
	if err != nil {
		logger.Fatalf("[channel: %s] Error extracting orderer metadata: %s", ledgerResources.ConfigtxManager().ChainID(), err)
	}

	// Construct limited support needed as a parameter for additional support
	cs := &ChainSupport{
		ledgerResources: ledgerResources,
		LocalSigner:     signer,
		cutter:          blockcutter.NewReceiverImpl(ledgerResources.SharedConfig()),
	}

	// Set up the msgprocessor
	cs.Processor = msgprocessor.NewStandardChannel(cs, msgprocessor.CreateStandardChannelFilters(cs))

	// Set up the block writer
	cs.BlockWriter = newBlockWriter(lastBlock, registrar, cs)

	// Set up the consenter
	consenterType := ledgerResources.SharedConfig().ConsensusType()
	consenter, ok := consenters[consenterType]
	if !ok {
		logger.Panicf("Error retrieving consenter of type: %s", consenterType)
	}

	cs.Chain, err = consenter.HandleChain(cs, metadata)
	if err != nil {
		logger.Panicf("[channel: %s] Error creating consenter: %s", cs.ChainID(), err)
	}

	logger.Debugf("[channel: %s] Done creating channel support resources", cs.ChainID())

	return cs
}

func (cs *ChainSupport) Reader() ledger.Reader {
	return cs
}

// Signer returns the crypto.Localsigner for this channel.
func (cs *ChainSupport) Signer() crypto.LocalSigner {
	return cs
}

func (cs *ChainSupport) start() {
	cs.Chain.Start()
}

// BlockCutter returns the blockcutter.Receiver instance for this channel.
func (cs *ChainSupport) BlockCutter() blockcutter.Receiver {
	return cs.cutter
}

// Validate passes through to the underlying configtxapi.Manager
func (cs *ChainSupport) Validate(configEnv *cb.ConfigEnvelope) error {
	return cs.ConfigtxManager().Validate(configEnv)
}

// ProposeConfigUpdate passes through to the underlying configtxapi.Manager
func (cs *ChainSupport) ProposeConfigUpdate(configtx *cb.Envelope) (*cb.ConfigEnvelope, error) {
	env, err := cs.ConfigtxManager().ProposeConfigUpdate(configtx)
	if err != nil {
		return nil, err
	}

	bundle, err := cs.CreateBundle(cs.ChainID(), env.Config)
	if err != nil {
		return nil, err
	}

	if err = checkResources(bundle); err != nil {
		return nil, errors.Wrap(err, "config update is not compatible")
	}

	return env, cs.ValidateNew(bundle)
}

// ChainID passes through to the underlying configtxapi.Manager
func (cs *ChainSupport) ChainID() string {
	return cs.ConfigtxManager().ChainID()
}

// ConfigEnvelope passes through to the underlying configtxapi.Manager
func (cs *ChainSupport) ConfigEnvelope() *cb.ConfigEnvelope {
	return cs.ConfigtxManager().ConfigEnvelope()
}

// Sequence passes through to the underlying configtxapi.Manager
func (cs *ChainSupport) Sequence() uint64 {
	return cs.ConfigtxManager().Sequence()
}


text:
describe('Templates test suite', function () {
	var Templates = HotSausage.Templates;

	Templates.extend(function (Templates, _Templates_HS) {

	});

	it('should be added to HS', function () {
		expect(Templates.isModule()).toBe(true);
	});

	describe('When Templates is loaded', function () {
		var Clone = Templates.Clone;
		var instance0, purse, instanceBD, bootstrapBD;

		it('should have a function at Clone', function () {
			expect( Clone ).toBeDefined();
			expect( typeof Clone ).toBe( "function" );
		});

		it('should have a template object named Clone', function () {
			instance0 = Clone();

			expect( instance0 ).toBeDefined();
			expect( instance0.name() ).toBe( "Clone" );
			expect( instance0.template() ).toBe( null );
			expect( instance0.isTemplate() ).toBe( true );
		});

		it('should have a purse', function () {
			purse = instance0._purse;

			expect( purse ).toBeDefined();
			expect( purse._owner ).toBe( instance0 );
		});

		it('should have behavior data', function () {
			instanceBD = instance0._purse.__hsbd;

			expect( instanceBD ).toBeDefined();
			expect( instanceBD.name() ).toBe( "Clone_BD" );
		});

		it('should have a bootstrap behavior data object', function () {
			bootstrapBD = instance0._purse.__hsbd._delegateBD;

			expect( bootstrapBD ).toBeDefined();
			expect( bootstrapBD.name() ).toBe("_NULL__BD");
			expect( bootstrapBD._templateBD ).toBe( bootstrapBD );
		});

	});
});

/*
	var templateInstance0 = (function bootstrap() {
		var bootstrapInstance = _newObject();
		var bootstrapBD = __newBehavioralData(Object.prototype, null);
		__attachPurse(bootstrapInstance, bootstrapBD);
		__ensureMethodDictionary(bootstrapBD);
		bootstrapBD.templateBD = bootstrapBD;
		bootstrapBD.template = null;
		bootstrapBD.basicName = "_NULL_";
		// This function is very similar to _newTemplate but the
		// following functions and properties are not needed:
		//    __attachMethod_newInstance(), __copyMethods()
		//    snapshotId, delegateBD, instanceCount, snapshotCount
		bootstrapBD.name = function () {return __bdBasicName(this) + "-BD";};
		return _newTemplate(bootstrapInstance, "Clone");
	})();
*/