text:
#include <nrfx.h>

#if NRFX_CHECK(NRFX_PPI_ENABLED)

#include <nrfx_ppi.h>

#define NRFX_LOG_MODULE PPI
#include <nrfx_log.h>

static uint32_t         m_channels_allocated; /**< Bitmap representing channels availability. 1 when a channel is allocated, 0 otherwise. */
static uint8_t          m_groups_allocated;   /**< Bitmap representing groups availability. 1 when a group is allocated, 0 otherwise.*/

/**
 * @brief Compute a group mask (needed for driver internals, not used for NRF_PPI registers).
 *
 * @param[in] group Group number to transform to a mask.
 *
 * @retval Group mask.
 */
static uint32_t group_to_mask(nrf_ppi_channel_group_t group)
{
    return (1uL << (uint32_t) group);
}

/**
 * @brief Check whether a channel is a programmable channel and can be used by an application.
 *
 * @param[in] channel Channel to check.
 *
 * @retval true  The channel is a programmable application channel.
 * @retval false The channel is used by a stack (for example SoftDevice) or is preprogrammed.
 */
static bool is_programmable_app_channel(nrf_ppi_channel_t channel)
{
    return ((NRFX_PPI_PROG_APP_CHANNELS_MASK & nrfx_ppi_channel_to_mask(channel)) != 0);
}

/**
 * @brief Check whether channels can be used by an application.
 *
 * @param[in] channel_mask Channel mask to check.
 *
 * @retval true  All specified channels can be used by an application.
 * @retval false At least one specified channel is used by a stack (for example SoftDevice).
 */
static bool are_app_channels(uint32_t channel_mask)
{
    //lint -e(587)
    return ((~(NRFX_PPI_ALL_APP_CHANNELS_MASK) & channel_mask) == 0);
}

/**
 * @brief Check whether a channel can be used by an application.
 *
 * @param[in] channel Channel to check.
 *
 * @retval true  The channel can be used by an application.
 * @retval false The channel is used by a stack (for example SoftDevice).
 */
static bool is_app_channel(nrf_ppi_channel_t channel)
{
    return are_app_channels(nrfx_ppi_channel_to_mask(channel));
}

/**
 * @brief Check whether a channel group can be used by an application.
 *
 * @param[in] group Group to check.
 *
 * @retval true  The group is an application group.
 * @retval false The group is not an application group (this group either does not exist or
 *               it is used by a stack (for example SoftDevice)).
 */
static bool is_app_group(nrf_ppi_channel_group_t group)
{
    return ((NRFX_PPI_ALL_APP_GROUPS_MASK & group_to_mask(group)) != 0);
}

/**
 * @brief Check whether a channel is allocated.
 *
 * @param[in] channel_num  Channel number to check.
 *
 * @retval true  The channel is allocated.
 * @retval false The channel is not allocated.
 */
static bool is_allocated_channel(nrf_ppi_channel_t channel)
{
    return ((m_channels_allocated & nrfx_ppi_channel_to_mask(channel)) != 0);
}

/**
 * @brief Set channel allocated indication.
 *
 * @param[in] channel_num Specifies the channel to set the "allocated" indication.
 */
static void channel_allocated_set(nrf_ppi_channel_t channel)
{
    m_channels_allocated |= nrfx_ppi_channel_to_mask(channel);
}

/**
 * @brief Clear channel allocated indication.
 *
 * @param[in] channel_num Specifies the channel to clear the "allocated" indication.
 */
static void channel_allocated_clr(nrf_ppi_channel_t channel)
{
    m_channels_allocated &= ~nrfx_ppi_channel_to_mask(channel);
}

/**
 * @brief Clear all allocated channels.
 */
static void channel_allocated_clr_all(void)
{
    m_channels_allocated &= ~NRFX_PPI_ALL_APP_CHANNELS_MASK;
}

/**
 * @brief Check whether a group is allocated.
 *
 * @param[in] group_num Group number to check.
 *
 * @retval true  The group is allocated.
 *         false The group is not allocated.
 */
static bool is_allocated_group(nrf_ppi_channel_group_t group)
{
    return ((m_groups_allocated & group_to_mask(group)) != 0);
}

/**
 * @brief Set group allocated indication.
 *
 * @param[in] group_num Specifies the group to set the "allocated" indication.
 */
static void group_allocated_set(nrf_ppi_channel_group_t group)
{
    m_groups_allocated |= group_to_mask(group);
}

/**
 * @brief Clear group allocated indication.
 *
 * @param[in] group_num Specifies the group to clear the "allocated" indication.
 */
static void group_allocated_clr(nrf_ppi_channel_group_t group)
{
    m_groups_allocated &= ~group_to_mask(group);
}

/**
 * @brief Clear all allocated groups.
 */
static void group_allocated_clr_all()
{
    m_groups_allocated &= ~NRFX_PPI_ALL_APP_GROUPS_MASK;
}

void nrfx_ppi_free_all(void)
{
    uint32_t mask = NRFX_PPI_ALL_APP_GROUPS_MASK;
    nrf_ppi_channel_group_t group;

    // Disable all channels and groups
    nrf_ppi_channels_disable(NRF_PPI, NRFX_PPI_ALL_APP_CHANNELS_MASK);

    for (group = NRF_PPI_CHANNEL_GROUP0; mask != 0; mask &= ~group_to_mask(group), group++)
    {
        if (mask & group_to_mask(group))
        {
            nrf_ppi_group_clear(NRF_PPI, group);
        }
    }
    channel_allocated_clr_all();
    group_allocated_clr_all();
}

nrfx_err_t nrfx_ppi_channel_alloc(nrf_ppi_channel_t * p_channel)
{
    nrfx_err_t err_code = NRFX_SUCCESS;
    nrf_ppi_channel_t channel;
    uint32_t mask = 0;
    err_code = NRFX_ERROR_NO_MEM;

    mask = NRFX_PPI_PROG_APP_CHANNELS_MASK;
    for (channel = NRF_PPI_CHANNEL0;
         mask != 0;
         mask &= ~nrfx_ppi_channel_to_mask(channel), channel++)
    {
        NRFX_CRITICAL_SECTION_ENTER();
        if ((mask & nrfx_ppi_channel_to_mask(channel)) && (!is_allocated_channel(channel)))
        {
            channel_allocated_set(channel);
            *p_channel = channel;
            err_code   = NRFX_SUCCESS;
        }
        NRFX_CRITICAL_SECTION_EXIT();
        if (err_code == NRFX_SUCCESS)
        {
            NRFX_LOG_INFO("Allocated channel: %d.", channel);
            break;
        }
    }

    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_channel_free(nrf_ppi_channel_t channel)
{
    nrfx_err_t err_code = NRFX_SUCCESS;

    if (!is_programmable_app_channel(channel))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else
    {
        // First disable this channel
        nrf_ppi_channel_disable(NRF_PPI, channel);
        NRFX_CRITICAL_SECTION_ENTER();
        channel_allocated_clr(channel);
        NRFX_CRITICAL_SECTION_EXIT();
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_channel_assign(nrf_ppi_channel_t channel, uint32_t eep, uint32_t tep)
{
    if ((uint32_t *)eep == NULL || (uint32_t *)tep == NULL)
    {
        return NRFX_ERROR_NULL;
    }

    nrfx_err_t err_code = NRFX_SUCCESS;

    if (!is_programmable_app_channel(channel))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else if (!is_allocated_channel(channel))
    {
        err_code = NRFX_ERROR_INVALID_STATE;
    }
    else
    {
        nrf_ppi_channel_endpoint_setup(NRF_PPI, channel, eep, tep);
        NRFX_LOG_INFO("Assigned channel: %d, event end point: %x, task end point: %x.",
                      channel,
                      eep,
                      tep);
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_channel_fork_assign(nrf_ppi_channel_t channel, uint32_t fork_tep)
{
    nrfx_err_t err_code = NRFX_SUCCESS;
#ifdef PPI_FEATURE_FORKS_PRESENT
    if (!is_allocated_channel(channel))
    {
        err_code = NRFX_ERROR_INVALID_STATE;
    }
    else
    {
        nrf_ppi_fork_endpoint_setup(NRF_PPI, channel, fork_tep);
        NRFX_LOG_INFO("Fork assigned channel: %d, task end point: %d.", channel, fork_tep);
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
#else
    err_code = NRFX_ERROR_NOT_SUPPORTED;
    NRFX_LOG_WARNING("Function: %s, error code: %s.",
                     __func__,
                     NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
#endif
}

nrfx_err_t nrfx_ppi_channel_enable(nrf_ppi_channel_t channel)
{
    nrfx_err_t err_code = NRFX_SUCCESS;

    if (!is_app_channel(channel))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else if (is_programmable_app_channel(channel) && !is_allocated_channel(channel))
    {
        err_code = NRFX_ERROR_INVALID_STATE;
    }
    else
    {
        nrf_ppi_channel_enable(NRF_PPI, channel);
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_channel_disable(nrf_ppi_channel_t channel)
{
    nrfx_err_t err_code = NRFX_SUCCESS;

    if (!is_app_channel(channel))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else if (is_programmable_app_channel(channel) && !is_allocated_channel(channel))
    {
        err_code = NRFX_ERROR_INVALID_STATE;
    }
    else
    {
        nrf_ppi_channel_disable(NRF_PPI, channel);
        err_code = NRFX_SUCCESS;
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_group_alloc(nrf_ppi_channel_group_t * p_group)
{
    nrfx_err_t err_code;
    uint32_t mask = 0;
    nrf_ppi_channel_group_t group;

    err_code = NRFX_ERROR_NO_MEM;

    mask = NRFX_PPI_ALL_APP_GROUPS_MASK;
    for (group = NRF_PPI_CHANNEL_GROUP0; mask != 0; mask &= ~group_to_mask(group), group++)
    {
        NRFX_CRITICAL_SECTION_ENTER();
        if ((mask & group_to_mask(group)) && (!is_allocated_group(group)))
        {
            group_allocated_set(group);
            *p_group = group;
            err_code = NRFX_SUCCESS;
        }
        NRFX_CRITICAL_SECTION_EXIT();
        if (err_code == NRFX_SUCCESS)
        {
            NRFX_LOG_INFO("Allocated group: %d.", group);
            break;
        }
    }

    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_group_free(nrf_ppi_channel_group_t group)
{
    nrfx_err_t err_code = NRFX_SUCCESS;

    if (!is_app_group(group))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    if (!is_allocated_group(group))
    {
        err_code = NRFX_ERROR_INVALID_STATE;
    }
    else
    {
        nrf_ppi_group_disable(NRF_PPI, group);
        NRFX_CRITICAL_SECTION_ENTER();
        group_allocated_clr(group);
        NRFX_CRITICAL_SECTION_EXIT();
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_group_enable(nrf_ppi_channel_group_t group)
{
    nrfx_err_t err_code = NRFX_SUCCESS;

    if (!is_app_group(group))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else if (!is_allocated_group(group))
    {
        err_code = NRFX_ERROR_INVALID_STATE;
    }
    else
    {
        nrf_ppi_group_enable(NRF_PPI, group);
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_group_disable(nrf_ppi_channel_group_t group)
{
    nrfx_err_t err_code = NRFX_SUCCESS;

    if (!is_app_group(group))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else
    {
        nrf_ppi_group_disable(NRF_PPI, group);
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_channels_remove_from_group(uint32_t                channel_mask,
                                               nrf_ppi_channel_group_t group)
{
    nrfx_err_t err_code = NRFX_SUCCESS;

    if (!is_app_group(group))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else if (!is_allocated_group(group))
    {
        err_code = NRFX_ERROR_INVALID_STATE;
    }
    else if (!are_app_channels(channel_mask))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else
    {
        NRFX_CRITICAL_SECTION_ENTER();
        nrf_ppi_channels_remove_from_group(NRF_PPI, channel_mask, group);
        NRFX_CRITICAL_SECTION_EXIT();
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}

nrfx_err_t nrfx_ppi_channels_include_in_group(uint32_t                channel_mask,
                                              nrf_ppi_channel_group_t group)
{
    nrfx_err_t err_code = NRFX_SUCCESS;

    if (!is_app_group(group))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else if (!is_allocated_group(group))
    {
        err_code = NRFX_ERROR_INVALID_STATE;
    }
    else if (!are_app_channels(channel_mask))
    {
        err_code = NRFX_ERROR_INVALID_PARAM;
    }
    else
    {
        NRFX_CRITICAL_SECTION_ENTER();
        nrf_ppi_channels_include_in_group(NRF_PPI, channel_mask, group);
        NRFX_CRITICAL_SECTION_EXIT();
    }
    NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
    return err_code;
}
#endif // NRFX_CHECK(NRFX_PPI_ENABLED)


text:
__author__ = 'mehdibenchoufi'

from constants import Constants
import numpy as np

class Data:

    def get_rows(self):
        return self.rows

    def set_rows(self, value):
        self.rows = value

    def get_larger_rows(self):
        return self.larger_rows

    def set_larger_rows(self, value):
        self.larger_rows = value

    def get_cols(self):
        return self.cols

    def set_cols(self, value):
        self.cols = value

    def __init__(self, num_args=None):
        if num_args is None:
            self.set_rows(Constants.NUM_IMG_DATA)
            self.set_larger_rows(Constants.OPENCV_RELATIVE_ANGLE)
            self.set_cols(Constants.NUM_SAMPLES)
            self.set_dimension()
        else:
            self.set_rows(num_args[0])
            self.set_larger_rows(num_args[1])
            self.set_cols(num_args[2])
            self.set_dimension()

    def set_dimension(self):
        self.src_size = self.rows, self.cols
        self.intermediate_size = self.larger_rows, self.cols
        self.dest_size = self.larger_rows, self.cols

    def get_src(self):
        return np.zeros(self.src_size, dtype=np.uint8)

    def get_intermediate_src(self):
        return np.zeros(self.intermediate_size, dtype=np.uint8)

    def get_destination(self):
        return np.zeros(self.dest_size, dtype=np.uint8)

redpajama_set_name: RedPajamaGithub


text:
package jef.database.meta;

import java.io.BufferedReader;
import java.net.URL;

import jef.common.log.LogUtil;
import jef.database.IQueryableEntity;
import jef.database.annotation.PartitionTable;
import jef.database.annotation.PartitionTableImpl;
import jef.json.JsonUtil;
import jef.tools.IOUtils;
import jef.tools.StringUtils;

/**
 * 缺省分表规则加载器,首先查找xxx.xxx.xxx.clzname.partition文件,然后使用annotation。
 *
 * 扩展这可以继承此类实现自定义的配置加载方式
 *
 * 文件为json结构
 *
 * @author jiyi
 *
 */
public class DefaultPartitionStrategyLoader implements PartitionStrategyLoader {
	public PartitionTable get(Class<? extends IQueryableEntity> clz) {
		String data=getJsonDataConfig(clz);
		if(data!=null && data.length()>0){
			return parseJsonConfig(data);
		}
		URL url = getResource(clz);
		if (url != null) {
			return loadFromResourceUrl(url);
		}
		return loadFromClassAnnotation(clz);
	}

	/**
	 * 从URL中获取
	 * @param url
	 * @return
	 */
	protected PartitionTable loadFromResourceUrl(URL url) {
		BufferedReader reader = null;
		try {
			reader= IOUtils.getReader(url.openStream(), null);
			StringBuilder sb = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				if (StringUtils.isEmpty(line) || line.startsWith("--")) {
					continue;
				}
				sb.append(line);
				sb.append('\n');
			}
			String data = sb.toString();
			if (!data.startsWith("{")) {
				data = StringUtils.concat("{", data, "}");
			}
			LogUtil.info("Loading partition strategy from:{}", url.getPath());
			PartitionTableImpl table = JsonUtil.toObject(data, PartitionTableImpl.class);
			System.out.println(JsonUtil.toJson(table));
			return table;
		} catch (Exception e) {
			LogUtil.exception("The Partition rule load failure in file:" + url + ", it will be ignored!", e);
			return null;
		} finally {
			IOUtils.closeQuietly(reader);
		}
	}

	private PartitionTable loadFromClassAnnotation(Class<? extends IQueryableEntity> clz) {
		PartitionTable table = clz.getAnnotation(PartitionTable.class);
		if (table != null)
			LogUtil.info(StringUtils.concat("Loading the partition strategy from annotation.[", clz.getName(), "]", JsonUtil.toJsonWithoutQuot(PartitionTableImpl.create(table))));
		return table;
	}

	/**
	 * 解析Json配置
	 * @param data
	 * @return
	 */
	protected PartitionTable parseJsonConfig(String data) {
		PartitionTableImpl table = JsonUtil.toObject(data, PartitionTableImpl.class);
		return table;
	}

	/**
	 * 寻找配置资源并返回
	 * @param clz
	 * @return
	 */
	protected URL getResource(Class<? extends IQueryableEntity> clz){
		String fileName = "/" + clz.getName() + ".json";
		return clz.getResource(fileName);
	}

	/**
	 * 得到JSON的分区配置。继承此类可以扩展配置读取的方式
	 * @param clz
	 * @return
	 */
	protected String getJsonDataConfig(Class<? extends IQueryableEntity> clz) {
		return null;
	}
}


text:
package br.com.futusteps.survey.core.survey;

import java.io.Serializable;
import java.util.List;

public class Question implements Serializable {

    private int id;
    private int order;
    private String description;
    private String type;
    private List<Alternative> alternatives;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<Alternative> getAlternatives() {
        return alternatives;
    }

    public void setAlternatives(List<Alternative> alternatives) {
        this.alternatives = alternatives;
    }
}


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Preview\Understand\Assistant\FieldType;

use Twilio\Deserialize;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Values;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 *
 * @property string accountSid
 * @property \DateTime dateCreated
 * @property \DateTime dateUpdated
 * @property string fieldTypeSid
 * @property string language
 * @property string assistantSid
 * @property string sid
 * @property string value
 * @property string url
 * @property string synonymOf
 */
class FieldValueInstance extends InstanceResource {
    /**
     * Initialize the FieldValueInstance
     *
     * @param \Twilio\Version $version Version that contains the resource
     * @param mixed[] $payload The response payload
     * @param string $assistantSid The unique ID of the Assistant.
     * @param string $fieldTypeSid The unique ID of the Field Type associated with
     *                             this Field Value.
     * @param string $sid The sid
     * @return \Twilio\Rest\Preview\Understand\Assistant\FieldType\FieldValueInstance
     */
    public function __construct(Version $version, array $payload, $assistantSid, $fieldTypeSid, $sid = null) {
        parent::__construct($version);

        // Marshaled Properties
        $this->properties = array(
            'accountSid' => Values::array_get($payload, 'account_sid'),
            'dateCreated' => Deserialize::dateTime(Values::array_get($payload, 'date_created')),
            'dateUpdated' => Deserialize::dateTime(Values::array_get($payload, 'date_updated')),
            'fieldTypeSid' => Values::array_get($payload, 'field_type_sid'),
            'language' => Values::array_get($payload, 'language'),
            'assistantSid' => Values::array_get($payload, 'assistant_sid'),
            'sid' => Values::array_get($payload, 'sid'),
            'value' => Values::array_get($payload, 'value'),
            'url' => Values::array_get($payload, 'url'),
            'synonymOf' => Values::array_get($payload, 'synonym_of'),
        );

        $this->solution = array(
            'assistantSid' => $assistantSid,
            'fieldTypeSid' => $fieldTypeSid,
            'sid' => $sid ?: $this->properties['sid'],
        );
    }

    /**
     * Generate an instance context for the instance, the context is capable of
     * performing various actions.  All instance actions are proxied to the context
     *
     * @return \Twilio\Rest\Preview\Understand\Assistant\FieldType\FieldValueContext Context for this
     *                                                                               FieldValueInstance
     */
    protected function proxy() {
        if (!$this->context) {
            $this->context = new FieldValueContext(
                $this->version,
                $this->solution['assistantSid'],
                $this->solution['fieldTypeSid'],
                $this->solution['sid']
            );
        }

        return $this->context;
    }

    /**
     * Fetch a FieldValueInstance
     *
     * @return FieldValueInstance Fetched FieldValueInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch() {
        return $this->proxy()->fetch();
    }

    /**
     * Deletes the FieldValueInstance
     *
     * @return boolean True if delete succeeds, false otherwise
     * @throws TwilioException When an HTTP error occurs.
     */
    public function delete() {
        return $this->proxy()->delete();
    }

    /**
     * Magic getter to access properties
     *
     * @param string $name Property to access
     * @return mixed The requested property
     * @throws TwilioException For unknown properties
     */
    public function __get($name) {
        if (array_key_exists($name, $this->properties)) {
            return $this->properties[$name];
        }

        if (property_exists($this, '_' . $name)) {
            $method = 'get' . ucfirst($name);
            return $this->$method();
        }

        throw new TwilioException('Unknown property: ' . $name);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $context = array();
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Preview.Understand.FieldValueInstance ' . implode(' ', $context) . ']';
    }
}


text:
namespace Google.Cloud.AIPlatform.V1.Snippets
{
    // [START aiplatform_v1_generated_PipelineService_CreateTrainingPipeline_async_flattened_resourceNames]
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.AIPlatform.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedPipelineServiceClientSnippets
    {
        /// <summary>Snippet for CreateTrainingPipelineAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task CreateTrainingPipelineResourceNamesAsync()
        {
            // Create client
            PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync();
            // Initialize request argument(s)
            LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
            TrainingPipeline trainingPipeline = new TrainingPipeline();
            // Make the request
            TrainingPipeline response = await pipelineServiceClient.CreateTrainingPipelineAsync(parent, trainingPipeline);
        }
    }
    // [END aiplatform_v1_generated_PipelineService_CreateTrainingPipeline_async_flattened_resourceNames]
}


text:
import {RenderPass} from "../processing/render-pass";

export class Network {

	private net: RenderPass[] = [];

	constructor(sizeX: number, sizeY: number) {
		for (let i = 0; i < 1; ++i) {
			this.net.push(new RenderPass(sizeX, sizeY));
		}
	}

	public update() {
		for (let tex of this.net) {
			tex.process();
		}
	}

	get Textures() {
		let array = [];
		for (let tex of this.net) {
			array.push(tex.Output);
		}
		return array;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2016 Jorge Ruesga

     Licensed under the Apache License, ServerVersion 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.
 -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24"
        android:viewportHeight="24">
    <path
        android:pathData="m2.5,4 l0,3 5,0 0,12 3,0 0,-12 5,0 0,-3z"
        android:fillColor="#000000"/>
    <path
        android:pathData="m13.764,10.961 l7.622,0 0,2.205 -7.622,0z"
        android:fillColor="#000000"/>
</vector>


text:
#include "test_intrusive_michael_iterable_hp.h"

#include <cds/intrusive/iterable_list_dhp.h>
#include <cds/intrusive/michael_set.h>

namespace {
    namespace ci = cds::intrusive;
    typedef cds::gc::DHP gc_type;

    class IntrusiveMichaelIterableSet_DHP : public cds_test::intrusive_set_hp
    {
    protected:
        typedef cds_test::intrusive_set_hp base_class;

    protected:
        void SetUp()
        {
            struct list_traits : public ci::iterable_list::traits
            {};
            typedef ci::IterableList< gc_type, item_type, list_traits > list_type;
            typedef ci::MichaelHashSet< gc_type, list_type > set_type;

            cds::gc::dhp::GarbageCollector::Construct( 16, set_type::c_nHazardPtrCount );
            cds::threading::Manager::attachThread();
        }

        void TearDown()
        {
            cds::threading::Manager::detachThread();
            cds::gc::dhp::GarbageCollector::Destruct();
        }
    };

    TEST_F( IntrusiveMichaelIterableSet_DHP, cmp )
    {
        typedef ci::IterableList< gc_type
            , item_type
            ,ci::iterable_list::make_traits<
                ci::opt::compare< cmp<item_type> >
                ,ci::opt::disposer< mock_disposer >
            >::type
        > bucket_type;

        typedef ci::MichaelHashSet< gc_type, bucket_type,
            ci::michael_set::make_traits<
                ci::opt::hash< hash_int >
            >::type
        > set_type;

        set_type s( kSize, 2 );
        test( s );
    }

    TEST_F( IntrusiveMichaelIterableSet_DHP, less )
    {
        typedef ci::IterableList< gc_type
            , item_type
            ,ci::iterable_list::make_traits<
                ci::opt::less< less<item_type> >
                ,ci::opt::disposer< mock_disposer >
            >::type
        > bucket_type;

        typedef ci::MichaelHashSet< gc_type, bucket_type,
            ci::michael_set::make_traits<
                ci::opt::hash< hash_int >
            >::type
        > set_type;

        set_type s( kSize, 2 );
        test( s );
    }

    TEST_F( IntrusiveMichaelIterableSet_DHP, cmpmix )
    {
        struct list_traits : public ci::iterable_list::traits
        {
            typedef base_class::less<item_type> less;
            typedef cmp<item_type> compare;
            typedef mock_disposer disposer;
        };
        typedef ci::IterableList< gc_type, item_type, list_traits > bucket_type;

        struct set_traits : public ci::michael_set::traits
        {
            typedef hash_int hash;
            typedef simple_item_counter item_counter;
        };
        typedef ci::MichaelHashSet< gc_type, bucket_type, set_traits > set_type;

        set_type s( kSize, 2 );
        test( s );
    }

    TEST_F( IntrusiveMichaelIterableSet_DHP, stat )
    {
        struct list_traits: public ci::iterable_list::traits
        {
            typedef base_class::less<item_type> less;
            typedef mock_disposer disposer;
            typedef ci::iterable_list::stat<> stat;
        };
        typedef ci::IterableList< gc_type, item_type, list_traits > bucket_type;

        struct set_traits: public ci::michael_set::traits
        {
            typedef hash_int hash;
            typedef simple_item_counter item_counter;
        };
        typedef ci::MichaelHashSet< gc_type, bucket_type, set_traits > set_type;

        set_type s( kSize, 2 );
        test( s );
        EXPECT_GE( s.statistics().m_nInsertSuccess, 0u );
    }

    TEST_F( IntrusiveMichaelIterableSet_DHP, wrapped_stat )
    {
        struct list_traits: public ci::iterable_list::traits
        {
            typedef base_class::less<item_type> less;
            typedef mock_disposer disposer;
            typedef ci::iterable_list::wrapped_stat<> stat;
        };
        typedef ci::IterableList< gc_type, item_type, list_traits > bucket_type;

        struct set_traits: public ci::michael_set::traits
        {
            typedef hash_int hash;
            typedef simple_item_counter item_counter;
        };
        typedef ci::MichaelHashSet< gc_type, bucket_type, set_traits > set_type;

        set_type s( kSize, 2 );
        test( s );
        EXPECT_GE( s.statistics().m_nInsertSuccess, 0u );
    }

    TEST_F( IntrusiveMichaelIterableSet_DHP, derived_list )
    {
        class bucket_type: public ci::IterableList< gc_type
            , item_type
            ,ci::iterable_list::make_traits<
                ci::opt::compare< cmp<item_type> >
                ,ci::opt::disposer< mock_disposer >
            >::type
        >
        {};

        typedef ci::MichaelHashSet< gc_type, bucket_type,
            ci::michael_set::make_traits<
                ci::opt::hash< hash_int >
            >::type
        > set_type;

        set_type s( kSize, 2 );
        test( s );
    }

} // namespace


text:
class CreateShipmentTypes < ActiveRecord::Migration
  def self.up
    create_table :shipment_types do |t|
      t.string :name
      t.integer :user_id

      t.timestamps
    end
  end

  def self.down
    drop_table :shipment_types
  end
end


text:
from msrest.serialization import Model

class TrendingImagesCategory(Model):
    """Defines the category of trending images.

    :param title: The name of the image category. For example, Popular People
     Searches.
    :type title: str
    :param tiles: A list of images that are trending in the category. Each
     tile contains an image and a URL that returns more images of the subject.
     For example, if the category is Popular People Searches, the image is of a
     popular person and the URL would return more images of that person.
    :type tiles:
     list[~azure.cognitiveservices.search.imagesearch.models.TrendingImagesTile]
    """

    _validation = {
        'title': {'required': True},
        'tiles': {'required': True},
    }

    _attribute_map = {
        'title': {'key': 'title', 'type': 'str'},
        'tiles': {'key': 'tiles', 'type': '[TrendingImagesTile]'},
    }

    def __init__(self, title, tiles):
        super(TrendingImagesCategory, self).__init__()
        self.title = title
        self.tiles = tiles


text:
class CreateEnums < ActiveRecord::Migration
  def change
    create_table :enums do |t|
      t.string :name, null: false
      t.string :value
    end
    add_index :enums, :name
  end
end


text:
package edu.jhu.pacaya.hypergraph;

import edu.jhu.pacaya.util.semiring.Semiring;

public interface Hyperpotential {

    /** Gets the potential for an edge in a hypergraph. */
    double getScore(Hyperedge e, Semiring s);

}


text:
package org.tanc.collections;

import java.util.LinkedList;

/**
 * 使用 LinkedList 作为 Queue
 * Created by tanc on 17-4-18.
 */
public class MyQueue<E> {

    private LinkedList<E> queue;

    public MyQueue() {
        this.queue = new LinkedList<>();
    }

    public void push(E data) {
        queue.add(data);
    }

    public E pop() {
        return queue.removeFirst();
    }

    public int size() {
        return queue.size();
    }
}


text:
require 'spec_helper'

describe GSGraph::Connections::Activities, '#activities' do
  context 'when included by GSGraph::User' do
    context 'when no access_token given' do
      it 'should raise GSGraph::Unauthorized' do
        mock_graph :get, 'arjun/activities', 'users/activities/arjun_public', :status => [401, 'Unauthorized'] do
          lambda do
            GSGraph::User.new('arjun').activities
          end.should raise_exception(GSGraph::Unauthorized)
        end
      end
    end

    context 'when access_token is given' do
      it 'should return activities as GSGraph::Page' do
        mock_graph :get, 'arjun/activities', 'users/activities/arjun_private', :access_token => 'access_token' do
          activities = GSGraph::User.new('arjun', :access_token => 'access_token').activities
          activities.class.should == GSGraph::Connection
          activities.first.should == GSGraph::Page.new(
            '378209722137',
            :access_token => 'access_token',
            :name => 'Doing Things at the Last Minute',
            :category => '活動'
          )
          activities.each do |activity|
            activity.should be_instance_of(GSGraph::Page)
          end
        end
      end
    end
  end
end


text:
require 'httpclient'

class HTTPClient
  class SSPINegotiateAuth
    def get_with_rescue(*args)
      get_without_rescue(*args)
    rescue
      unless @warned
        @warned = true
        RHC::Helpers.warn "Could not enable Kerberos authentication"
        RHC::Helpers.warn $!.message.sub('gss_init_sec_context did not return GSS_S_COMPLETE: Unspecified GSS failure.  Minor code may provide more information', '').strip rescue nil
      end
      nil
    end

    alias_method :get_without_rescue, :get if method_defined? :get
    alias_method :get, :get_with_rescue
  end
end

module RHC
  module Rest
    #
    # An instance of HTTPClient that will support deferred
    # Basic credentials and allow token challenges.
    #
    class HTTPClient < ::HTTPClient
      def initialize(*args)
        super
        @www_auth = WWWAuth.new
        @request_filter = [proxy_auth, www_auth]
      end
    end

    #
    # Support three altered authentication behaviors
    #
    # * Allow a bearer token to be provided for a server
    # * Allow the user and password attributes to be lazily
    #   evaluated when the credentials are needed, rather than
    #   up front.
    # * If a BASIC auth request has been rejected, do not
    #   retry.
    #
    class WWWAuth < HTTPClient::WWWAuth
      attr_reader :oauth2
      def initialize
        super
        @oauth2 = OAuth2.new
        @authenticator.unshift(@oauth2)

        deferred = DeferredBasic.new
        @authenticator.map!{ |o| o == @basic_auth ? deferred : o }
        @basic_auth = deferred
      end

      class OAuth2
        include ::HTTPClient::Util
        attr_reader :scheme

        def initialize
          @cred = nil
          @auth = {}
          @set = false
          @scheme = "Bearer"
        end

        def reset_challenge
        end

        def set(uri, user, password)
          @set = true
          if uri.nil?
            @cred = password
          else
            @auth[urify(uri)] = password
          end
        end

        def set_token(uri, token)
          set(uri, nil, token)
        end

        def set?
          @set == true
        end

        def get(req)
          target_uri = req.header.request_uri
          return @cred if @cred
          hash_find_value(@auth) { |uri, cred|
            uri_part_of(target_uri, uri)
          }
        end

        def challenge(uri, param_str = nil)
          false
        end
      end

      class DeferredCredential
        def initialize(user, password)
          @user, @password = user, password
        end
        def user
          (@user.call if @user.respond_to?(:call)) or @user
        end
        def passwd
          (@password.call if @password.respond_to?(:call)) or @password
        end

        #
        # Pretend to be a string
        #
        def to_str
          ["#{user}:#{passwd}"].pack('m').tr("\n", '')
        end
        [:sub].each do |sym|
          define_method(sym) { |*args|; to_str.send(sym, *args); }
        end
      end

      class DeferredBasic < ::HTTPClient::BasicAuth
        # Set authentication credential.
        # uri == nil for generic purpose (allow to use user/password for any URL).
        def set(uri, user, passwd)
          @set = true
          if uri.nil?
            @cred = DeferredCredential.new(user, passwd)
          else
            uri = uri_dirname(urify(uri))
            @auth[uri] = DeferredCredential.new(user, passwd)
          end
        end
        def challenge(uri, param_str = nil)
          return false if caller.any?{ |s| s =~ /webmock.*httpclient_adapter.*build_request_signature/ }
          uri = urify(uri)
          # httpclient < 2.4.0 uses @challengeable, >= 2.4.0 uses @challenge
          challenges = @challenge || @challengeable
          challenged = challenges[uri]
          challenges[uri] = true
          !challenged
        end
      end
    end
  end
end


text:
package z.tool.web.session;

import javax.servlet.http.HttpSession;

import z.tool.web.Context;

public final class SessionService  {
    /** SessionModel */
    public static final String SESSION_NAME = "SessionModel";

    private SessionService() {}

    public static void clearCurrentSessionModel() {
        HttpSession session = getSession();
        if ( null != session ) {
            session.removeAttribute(SESSION_NAME);
        }
    }

    public static SessionModel getCurrentSessionModel() {
        HttpSession session = getSession();
        if ( null != session ) {
            return (SessionModel) session.getAttribute(SESSION_NAME);
        }
        return null;
    }

    public static void setCurrentSessionModel(SessionModel sessionModel) {
        HttpSession session = getSession();
        if ( null != session ) {
            session.setAttribute(SESSION_NAME, sessionModel);
        }
    }

    private static HttpSession getSession() {
        Context context = Context.get();
        return null != context ? context.getSession() : null;
    }

}


text:
<?php

namespace Biz\User\Impl;

use Biz\Common\BaseService;
use Biz\User\UserService;
use AppBundle\Common\ArrayToolkit;
use AppBundle\Common\Upload;
use AppBundle\Common\LdapProcesser;

class UserServiceImpl extends BaseService implements UserService
{
    public function createUser($fields)
    {
        $this->validate($fields);
        $userTableFields = $this->getDao('user_dao')->getTableFields();
        $user = ArrayToolkit::parts($fields['basic'], $userTableFields);
        $user['status'] = 'on';
        $user['roles'] = array('ROLE_USER');
        if (!empty($user['joinTime'])) {
            $user['joinTime'] = strtotime($user['joinTime']);
        }
        $user['password'] = 'kaifazhe';
        $user['username'] = $user['number'];
        $user['salt'] = md5(time().mt_rand(0, 1000));
        $user['password'] = $this->biz['password_encoder']->encodePassword($user['password'], $user['salt']);

        $lastInsertUser = $this->getDao('user_dao')->create($user);

        $otherTableFields = $this->getDao('other_info_dao')->getTableFields();
        $other = ArrayToolkit::parts($fields['other'], $otherTableFields);
        $other['userId'] = $lastInsertUser['id'];
        $this->getDao('other_info_dao')->create($other);

        $basicTableFields = $this->getDao('user_basic_dao')->getTableFields();
        $basic = ArrayToolkit::parts($fields['basic'], $basicTableFields);
        $basic['userId'] = $lastInsertUser['id'];

        if (!empty($basic['bornTime'])) {
            $basic['bornTime'] = strtotime($basic['bornTime']);
        }

        $affectedBasic = $this->getDao('user_basic_dao')->create($basic);
        $department = $this->getDepartmentService()->getDepartment($basic['departmentId']);
        $departmentCount = $department['amount'] + 1;
        $this->getDepartmentService()->updateDepartment($department['id'], array('amount'=>$departmentCount));

        $familyTableFields = $this->getDao('family_member_dao')->getTableFields();
        foreach ($fields['family'] as $member) {
            $member = ArrayToolkit::parts($member, $familyTableFields);
            $member['userId'] = $lastInsertUser['id'];
            $this->getDao('family_member_dao')->create($member);
        }

        $eduTableFields = $this->getDao('edu_experience_dao')->getTableFields();
        foreach ($fields['education'] as $education) {
            $education = ArrayToolkit::parts($education, $eduTableFields);
            $education['userId'] = $lastInsertUser['id'];
            if (!empty($education['startTime'])) {
                $education['startTime'] = strtotime($education['startTime']);
            }
            if (!empty($education['endTime'])) {
                $education['endTime'] = strtotime($education['endTime']);
            }
            $this->getDao('edu_experience_dao')->create($education);
        }

        $workTableFields = $this->getDao('work_experience_dao')->getTableFields();
        foreach ($fields['work'] as $work) {
            $work = ArrayToolkit::parts($work, $workTableFields);
            $work['userId'] = $lastInsertUser['id'];
            if (!empty($work['startTime'])) {
                $work['startTime'] = strtotime($work['startTime']);
            }
            if (!empty($work['endTime'])) {
                $work['endTime'] = strtotime($work['endTime']);
            }
            $this->getDao('work_experience_dao')->create($work);
        }

        $process = new LdapProcesser($this->biz);
        $process->updateUserLdapInfo($user['id']);
        return array_merge($affectedBasic, $lastInsertUser);
    }

    public function importUser($user)
    {
        $presentUser = $this->getUserByNumber($user['basic']['number']);
        if (!empty($presentUser)) {
            return null;
        }

        $department = $this->getDepartmentService()->getDepartmentByName($user['basic']['department']);

        if (empty($department)) {
            $user['basic']['departmentId'] = 1;
        } else {
            $user['basic']['departmentId'] = $department['id'];
        }

        return $this->createUser($user);
    }

    public function register($user)
    {
        $user['salt'] = md5(time().mt_rand(0, 1000));
        $user['password'] = $this->biz['password_encoder']->encodePassword($user['password'], $user['salt']);
        if (empty($user['roles'])) {
            $user['roles'] = array('ROLE_USER');
        }
        if (isset($user['trueName'])) {
            $trueName = $user['trueName'];
            unset($user['trueName']);
        }
        $email = '';
        if (isset($user['email'])) {
            $email = $user['email'];
        }
        unset($user['email']);

        $user = $this->getDao('user_dao')->create($user);
        $this->getDao('other_info_dao')->create(array('userId'=>$user['id']));
        if (isset($trueName)) {
            $this->getDao('user_basic_dao')->create(array('userId'=>$user['id'],'trueName'=>$trueName));
        } else {
            $this->getDao('user_basic_dao')->create(array('userId'=>$user['id'], 'email'=>$email));
        }
        $this->getDao('family_member_dao')->create(array('userId'=>$user['id']));
        $this->getDao('work_experience_dao')->create(array('userId'=>$user['id']));
        $this->getDao('edu_experience_dao')->create(array('userId'=>$user['id']));
        $process = new LdapProcesser($this->biz);
        $process->updateUserLdapInfo($user['id']);
        return $user;
    }

    public function updateAll($id, $fields)
    {
        $currentUser = $this->getCurrentUser();

        if (!$this->isAdmin($currentUser['id'])) {
            unset($fields['basic']['number']);
            unset($fields['basic']['email']);
            unset($fields['basic']['rank']);
            unset($fields['basic']['joinTime']);
            unset($fields['basic']['professionTitle']);
        }

        $this->getDao('family_member_dao')->deleteByUserId($id);
        $this->getDao('edu_experience_dao')->deleteByUserId($id);
        $this->getDao('work_experience_dao')->deleteByUserId($id);
        $currentBasic = $this->getDao('user_basic_dao')->getByUserId($id);

        $userTableFields = $this->getDao('user_dao')->getTableFields();
        $user = ArrayToolkit::parts($fields['basic'], $userTableFields);

        if (isset($user['joinTime'])) {
            $user['joinTime'] = strtotime($user['joinTime']);
        }

        $this->getDao('user_dao')->update($id, $user);

        $userBasicTableFields = $this->getDao('user_basic_dao')->getTableFields();
        $userBasic = ArrayToolkit::parts($fields['basic'], $userBasicTableFields);
        $userBasic['bornTime'] = strtotime($userBasic['bornTime']);

        if (isset($userBasic['departmentId']) && $userBasic['departmentId'] != $currentBasic['departmentId']) {
            $department = $this->getDepartmentService()->getDepartment($userBasic['departmentId']);
            $departmentCount = $department['amount'] + 1;
            $this->getDepartmentService()->updateDepartment($department['id'], array('amount'=>$departmentCount));
            $beforeDepartment = $this->getDepartmentService()->getDepartment($currentBasic['departmentId']);
            $beforeDepartmentCount = $beforeDepartment['amount'] - 1;
            $this->getDepartmentService()->updateDepartment($beforeDepartment['id'], array('amount'=>$beforeDepartmentCount));
        }
        unset($userBasic['id']);
        $this->getDao('user_basic_dao')->update($currentBasic['id'], $userBasic);

        $this->editHelper($id, $fields, 'family', 'family_member_dao');

        $this->editHelper($id, $fields, 'education', 'edu_experience_dao');

        $this->editHelper($id, $fields, 'work', 'work_experience_dao');

        $otherTableFields = $this->getDao('other_info_dao')->getTableFields();
        $other = ArrayToolkit::parts($fields['other'], $otherTableFields);

        $this->getDao('other_info_dao')->update($other['id'], $other);
        $process = new LdapProcesser($this->biz);
        $process->updateUserLdapInfo($user['id']);

        return $user;
    }

    protected function editHelper($id, $fields, $tableName, $daoName)
    {
        $tableFields = $this->getDao($daoName)->getTableFields();
        foreach ($fields[$tableName] as $tableData) {

            $tableData = ArrayToolkit::parts($tableData, $tableFields);
            $tableData = array_filter($tableData);

            if (empty($tableData)) {
                continue;
            }

            foreach ($tableData as $key => $data) {
                if (stripos($key, 'time') != false) {
                    $tableData[$key] = strtotime($data);
                }
            }

            unset($tableData['id']);
            $tableData['userId'] = $id;

            $this->getDao($daoName)->create($tableData);
        }
    }

    public function getCompleteinfo($id)
    {
        $data = array();

        $data['user'] =  $this->getUser($id);
        $data['basic'] = $this->getBasic($id);
        $data['familyMembers'] = $this->findFamilyMembers($id);
        $data['eduExperiences'] = $this->findEduExperiences($id);
        $data['workInfos'] = $this->findWorkExperiences($id);
        $data['otherInfo'] = $this->getOtherInfoByUserId($id);

        return $data;
    }

    public function searchAllUsers($conditions, $orderBy, $start, $limit)
    {
        return $this->getDao('user_search_dao')->searchAll($conditions, $orderBy, $start, $limit);
    }

    public function searchDepartmentUsers($conditions, $orderBy, $start, $limit)
    {
        return $this->getDao('user_search_dao')->searchDepartmentUsers($mysql, $orderBy, $start, $limit);
    }

    public function searchAllUserCounts($conditions)
    {
        return $this->getDao('user_search_dao')->searchAllCounts($conditions);
    }

    public function searchDepartmentUserCounts($conditions)
    {
        return $this->getDao('user_search_dao')->searchDepartmentUserCounts($conditions);
    }
    /**
     * roster表
     */
    public function getRoster($userId)
    {
        $basic = $this->getDao('user_basic_dao')->getByUserId($userId);
        $user = $this->getUser($userId);
        $roster = $this->getDao('roster_dao')->getByUserId($userId);
        $basic = array_merge($user, $basic);
        if (empty($roster)) {
            $roster = $basic;
        } else {
            $roster = array_merge($basic, $roster);
        }

        return $roster;
    }

    public function createRoster($fields)
    {
        $tableFields = $this->getDao('roster_dao')->getTableFields();
        $fields = ArrayToolkit::parts($fields, $tableFields);
        unset($fields['id']);

        return $this->getDao('roster_dao')->create($fields);
    }

    public function updateRoster($userId, $fields)
    {
        $basic = $this->getDao('user_basic_dao')->getByUserId($userId);
        $tableFields = $this->getDao('user_basic_dao')->getTableFields();
        $basicFields = ArrayToolkit::parts($fields, $tableFields);
        if (isset($basicFields['bornTime'])) {
            $basicFields['bornTime'] = strtotime($basicFields['bornTime']);
        }
        $this->getDao('user_basic_dao')->update($basic['id'], $basicFields);

        $roster = $this->getDao('roster_dao')->getByUserId($userId);
        $tableFields = $this->getDao('roster_dao')->getTableFields();
        $fields = ArrayToolkit::parts($fields, $tableFields);
        return $this->getDao('roster_dao')->update($roster['id'], $fields);
    }

    /**
     * user表
     */
    public function updateUser($userId, $fields)
    {
        return $this->getDao('user_dao')->update($userId, $fields);
    }

    public function getUser($userId)
    {
        return $this->getDao('user_dao')->get($userId);
    }

    public function getUserByUsername($username)
    {
        return $this->getDao('user_dao')->getByUsername($username);
    }

    public function getUserByNumber($number)
    {
        return $this->getDao('user_dao')->getByNumber($number);
    }

    public function searchUsers($conditions, $order, $start, $limit)
    {
        return $this->getDao('user_dao')->search($conditions, $order, $start, $limit);
    }

    public function uploadImage($userId, $image, $type)
    {
        $image = new Upload($image);
        $user = $this->getUser($userId);
        $oldPath = $user['img'.$type];
        $path = $image->moveToDirectory($userId, $oldPath, $type);
        $this->getDao('user_dao')->update($userId, array(
            'img'.$type => $path
        ));

        return $path;
    }

    /**
     * user_basic表
     */
    public function getBasic($userId)
    {
        $basic = $this->getDao('user_basic_dao')->getByUserId($userId);
        $user = $this->getDao('user_dao')->get($userId);
        $basic['joinTime'] = $user['joinTime'];

        return $basic;
    }

    /**
     * family_member表
     */
    public function findFamilyMembers($userId)
    {
        return $this->getDao('family_member_dao')->findFamilyMembers($userId);
    }

    /**
     * edu_experience表
     */
    public function findEduExperiences($userId)
    {
        return $this->getDao('edu_experience_dao')->findEduExperiences($userId);
    }

    /**
     * work_experience表
     */
    public function findWorkExperiences($userId)
    {
        return $this->getDao('work_experience_dao')->findWorkExperiences($userId);
    }

    /**
     * other_info表
     */
    public function getOtherInfoByUserId($userId)
    {
        return $this->getDao('other_info_dao')->getByUserId($userId);
    }

    protected function validate($user)
    {
        if(empty($user['basic']['number'])) {
            throw new \Exception("请输入工号");
        }

        $number = $this->getUserByNumber($user['basic']['number']);
        if (!empty($number) || !preg_match('/^\d{4}$/', $user['basic']['number'])) {
            throw new \Exception("工号已经存在或者输入格式不正确");
        }

        if(empty($user['basic']['trueName'])) {
            throw new \Exception("请输入姓名");
        }

        if(empty($user['basic']['rank'])) {
            throw new \Exception("请输入职级");
        }
        if(empty($user['basic']['phone']) || !preg_match("/^1[3|4|5|7|8]\d{9}$/", $user['basic']['phone'])) {
            throw new \Exception("手机号输入有误");
        }
        if(!preg_match("/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/", $user['basic']['email'])){
            throw new \Exception("邮箱格式不正确");
        }
        if(empty($user['basic']['professionTitle'])) {
            throw new \Exception("请输入职称");
        }

        if(empty($user['basic']['joinTime'])) {
            throw new \Exception("请输入入职时间");
        }
    }

    protected function editValidate($id, $user)
    {
        if ($this->isAdmin($id)) {
            if(empty($user['basic']['rank'])) {
                throw new \Exception("请输入职级");
            }

            if(empty($user['basic']['professionTitle'])) {
                throw new \Exception("请输入职称");
            }

            if(empty($user['basic']['joinTime'])) {
                throw new \Exception("请输入入职时间");
            }
        }

        if(empty($user['basic']['trueName'])) {
            throw new \Exception("请输入姓名");
        }

        if(empty($user['basic']['phone']) || !preg_match("/^1[3|4|5|7|8]\d{9}$/", $user['basic']['phone'])) {
            throw new \Exception("手机号输入有误");
        }

        if(!preg_match("/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/", $user['basic']['email'])){
            throw new \Exception("邮箱格式不正确");
        }
    }

    protected function isAdmin($id)
    {
        $userInfo = $this->getUser($id);
        if (in_array('ROLE_ADMIN', $userInfo['roles'])) {
            return true;
        }

        return false;
    }

    protected function checkIdCard($id)
    {
        $len = strlen($id);
        if ($len != 18) {
            return 0;
        }

        $a = str_split($id,1);
        $w = array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
        $c = array(1,0,'X',9,8,7,6,5,4,3,2);
        $sum = 0;
        for ($i=0;$i<17;$i++){
            $sum = $sum + $a[$i] * $w[$i];
        }

        $r = $sum%11;
        $res = $c[$r];

        if ($res == $a[17]) {
            return 1;
        } else {
            return 0;
        }
    }
    /**
     * user_dao,user_basic_dao,family_member_dao
     * work_experience_dao,confirm_person,edu_experience_dao
     * other_info
     */
    protected function getDepartmentService()
    {
        return $this->biz['department_service'];
    }

    protected function getDao($dao)
    {
        return $this->biz[$dao];
    }
}


text:
@interface PodsDummy_Pods_iOS_PLColors_Example : NSObject
@end
@implementation PodsDummy_Pods_iOS_PLColors_Example
@end


text:
<?php
namespace Kahlan\Plugin;

use InvalidArgumentException;
use Reflection;
use ReflectionMethod;
use ReflectionClass;
use Kahlan\Suite;
use Kahlan\IncompleteException;
use Kahlan\Analysis\Inspector;
use Kahlan\Plugin\Stub\Method;

class Stub
{
    /**
     * Class dependencies.
     *
     * @var array
     */
    protected static $_classes = [
        'parser'   => 'Kahlan\Jit\Parser',
        'pointcut' => 'Kahlan\Jit\Patcher\Pointcut',
        'call'     => 'Kahlan\Plugin\Call'
    ];

    /**
     * The pointcut patcher instance.
     *
     * @var object
     */
    protected static $_pointcut = null;

    /**
     * Registered stubbed instance/class methods.
     *
     * @var array
     */
    protected static $_registered = [];

    /**
     * Stubbed methods.
     *
     * @var Method[]
     */
    protected $_stubs = [];

    /**
     * Stub index counter.
     *
     * @var integer
     */
    protected static $_index = 0;

    /**
     * The Constructor.
     *
     * @param mixed $reference An instance or a fully-namespaced class name.
     */
    public function __construct($reference)
    {
        $this->_reference = $reference;
    }

    /**
     * Getd/Setd stubs for methods or get stubbed methods array.
     *
     * @param  array    $name An array of method names.
     * @return Method[]       Return the array of stubbed methods.
     */
    public function methods($name = [])
    {
        if (!func_num_args()) {
            return $this->_stubs;
        }
        foreach ($name as $method => $returns) {
            if (is_callable($returns)) {
                $this->method($method, $returns);
            } elseif (is_array($returns)) {
                $stub = $this->method($method);
                call_user_func_array([$stub, 'andReturn'], $returns);
            } else {
                $error = "Stubbed method definition for `{$method}` must be a closure or an array of returned value(s).";
                throw new InvalidArgumentException($error);
            }
        }
    }

    /**
     * Stubs a method.
     *
     * @param  string $name    Method name or array of stubs where key are method names and
     *                         values the stubs.
     * @param  string $closure The stub implementation.
     * @return Method          The stubbed method instance.
     */
    public function method($name, $closure = null)
    {
        $static = false;
        $reference = $this->_reference;
        if (preg_match('/^::.*/', $name)) {
            $static = true;
            $reference = is_object($reference) ? get_class($reference) : $reference;
            $name = substr($name, 2);
        }
        $hash = Suite::hash($reference);
        if (!isset(static::$_registered[$hash])) {
            static::$_registered[$hash] = new static($reference);
        }
        $instance = static::$_registered[$hash];
        if (is_object($reference)) {
            Suite::register(get_class($reference));
        } else {
            Suite::register($reference);
        }
        if (!isset($instance->_stubs[$name])) {
            $instance->_stubs[$name] = [];
        }
        $method = new Method(compact('name', 'static', 'closure'));
        array_unshift($instance->_stubs[$name], $method);
        return $method;
    }

    /**
     * Stubs class methods.
     *
     * @param  object|string $reference An instance or a fully-namespaced class name.
     * @return self                     The Stub instance.
     */
    public static function on($reference)
    {
        $hash = Suite::hash($reference);
        if (isset(static::$_registered[$hash])) {
            return static::$_registered[$hash];
        }
        return static::$_registered[$hash] = new static($reference);
    }

    /**
     * Finds a stub.
     *
     * @param  mixed       $references An instance or a fully namespaced class name.
     *                                 or an array of that.
     * @param  string      $method     The method name.
     * @param  array       $params     The required arguments.
     * @return object|null             Return the subbed method or `null` if not founded.
     */
    public static function find($references, $method = null, $params = [])
    {
        $references = (array) $references;
        $stub = null;
        $refs = [];
        foreach ($references as $reference) {
            $hash = Suite::hash($reference);
            if (!isset(static::$_registered[$hash])) {
                continue;
            }
            $stubs = static::$_registered[$hash]->methods();
            $static = false;
            if (preg_match('/^::.*/', $method)) {
                $static = true;
                $method = substr($method, 2);
            }
            if (!isset($stubs[$method])) {
                continue;
            }
            foreach ($stubs[$method] as $stub) {
                $call['name'] = $method;
                $call['static'] = $static;
                $call['params'] = $params;
                if ($stub->match($call)) {
                    return $stub;
                }
            }
        }
        return false;
    }

    /**
     * Creates a polyvalent instance.
     *
     * @param  array  $options Array of options. Options are:
     *                         - `'class'`  _string_: the fully-namespaced class name.
     *                         - `'extends'` _string_: the fully-namespaced parent class name.
     *                         - `'params'` _array_: params to pass to the constructor.
     *                         - `'methods'` _string_: override the method defined.
     * @return object          The created instance.
     */
    public static function create($options = [])
    {
        $class = static::classname($options);

        if (isset($options['params'])) {
            $refl = new ReflectionClass($class);
            $instance = $refl->newInstanceArgs($options['params']);
        } else {
            $instance = new $class();
        }
        $call = static::$_classes['call'];
        new $call($instance);
        return $instance;
    }

    /**
     * Creates a polyvalent static class.
     *
     * @param  array  $options Array of options. Options are:
     *                         - `'class'` : the fully-namespaced class name.
     *                         - `'extends'` : the fully-namespaced parent class name.
     * @return string          The created fully-namespaced class name.
     */
    public static function classname($options = [])
    {
        $defaults = ['class' => 'Kahlan\Spec\Plugin\Stub\Stub' . static::$_index++];
        $options += $defaults;

        if (!static::$_pointcut) {
            $pointcut = static::$_classes['pointcut'];
            static::$_pointcut = new $pointcut();
        }

        if (!class_exists($options['class'], false)) {
            $parser = static::$_classes['parser'];
            $code = static::generate($options);
            $nodes = $parser::parse($code);
            $code = $parser::unparse(static::$_pointcut->process($nodes));
            eval('?>' . $code);
        }
        $call = static::$_classes['call'];
        new $call($options['class']);
        return $options['class'];
    }

    /**
     * Creates a class definition.
     *
     * @param  array  $options Array of options. Options are:
     *                         - `'class'`      _string_ : the fully-namespaced class name.
     *                         - `'extends'`    _string_ : the fully-namespaced parent class name.
     *                         - `'implements'` _array_  : the implemented interfaces.
     *                         - `'uses'`       _array_  : the used traits.
     *                         - `'methods'`    _array_  : the methods to stubs.
     *                         - `'layer'`      _boolean_: indicate if public methods should be layered.
     * @return string          The generated class string content.
     */
    public static function generate($options = [])
    {
        $defaults = [
            'class'      => 'spec\plugin\stub\Stub' . static::$_index++,
            'extends'    => '',
            'implements' => [],
            'uses'       => [],
            'methods'    => [],
            'layer'      => false,
            'openTag'    => true,
            'closeTag'   => true
        ];
        $options += $defaults;

        if ($options['extends']) {
            $options += ['magicMethods' => false];
        } else {
            $options += ['magicMethods' => true];
        }

        $class = $options['class'];
        $namespace = '';
        if (($pos = strrpos($class, '\\')) !== false) {
            $namespace = substr($class, 0, $pos);
            $class = substr($class, $pos + 1);
        }

        if ($namespace) {
            $namespace = "namespace {$namespace};\n";
        }

        $uses = static::_generateUses($options['uses']);
        $extends = static::_generateExtends($options['extends']);
        $implements = static::_generateImplements($options['implements']);

        $methods = static::_generateMethodStubs($options['methods'], $options['magicMethods']);
        if ($options['extends']) {
            $methods += static::_generateClassMethods($options['extends'], $options['layer']);
        }
        $methods += static::_generateInterfaceMethods($options['implements']);

        $methods = $methods ? '    ' . join("\n    ", $methods) : '';

        $openTag = $options['openTag'] ? "<?php\n" : '';
        $closeTag = $options['closeTag'] ? "?>" : '';

return $openTag . $namespace . <<<EOT

class {$class}{$extends}{$implements} {

{$uses}{$methods}

}
$closeTag
EOT;

    }

    /**
     * Returns Magic Methods definitions.
     *
     * @return array
     */
    public static function _getMagicMethods()
    {
        return [
            '__construct'    =>  "public function __construct() {}",
            '__destruct'     =>  "public function __destruct() {}",
            '__call'         =>  "public function __call(\$name, \$params) { return new static(); }",
            '::__callStatic' =>  "public static function __callStatic(\$name, \$params) {}",
            '__get'          =>  "public function __get(\$key){ return new static(); }",
            '__set'          =>  "public function __set(\$key, \$value) { \$this->{\$key} = \$value; }",
            '__isset'        =>  "public function __isset(\$key) { return isset(\$this->{\$key}); }",
            '__unset'        =>  "public function __unset(\$key) { unset(\$this->{\$key}); }",
            '__sleep'        =>  "public function __sleep() { return []; }",
            '__wakeup'       =>  "public function __wakeup() {}",
            '__toString'     =>  "public function __toString() { return get_class(); }",
            '__invoke'       =>  "public function __invoke() {}",
            '__set_sate'     =>  "public function __set_sate(\$properties) {}",
            '__clone'        =>  "public function __clone() {}"
        ];
    }

    /**
     * Creates a `use` definition.
     *
     * @param  array  $uses An array of traits.
     * @return string       The generated `use` definition.
     */
    protected static function _generateUses($uses)
    {
        if (!$uses) {
            return '';
        }
        $traits = [];
        foreach ((array) $uses as $use) {
            if (!trait_exists($use)) {
                throw new IncompleteException("Unexisting trait `{$use}`");
            }
            $traits[] = '\\' . ltrim($use, '\\');
        }
        return '    use ' . join(', ', $traits) . ';';
    }

    /**
     * Creates an `extends` definition.
     *
     * @param  string $extends The parent class name.
     * @return string          The generated `extends` definition.
     */
    protected static function _generateExtends($extends)
    {
        if (!$extends) {
            return '';
        }
        return ' extends \\' . ltrim($extends, '\\');
    }

    /**
     * Creates an `implements` definition.
     *
     * @param  array  $uses An array of interfaces.
     * @return string       The generated `implements` definition.
     */
    protected static function _generateImplements($implements)
    {
        if (!$implements) {
            return '';
        }
        $classes = [];
        foreach ((array) $implements as $implement) {
            $classes[] = '\\' . ltrim($implement, '\\');
        }
        return ' implements ' . join(', ', $classes);
    }

    /**
     * Creates method stubs.
     *
     * @param  array   $methods  An array of method definitions.
     * @param  boolean $defaults If `true`, Magic Methods will be appended.
     * @return string            The generated method definitions.
     */
    protected static function _generateMethodStubs($methods, $defaults = true)
    {
        $result = [];
        $methods = $methods !== null ? (array) $methods : [];

        if ($defaults) {
            $methods = array_merge($methods, array_keys(static::_getMagicMethods()));
        }
        $methods = array_unique($methods);

        $magicMethods = static::_getMagicMethods();

        foreach ($methods as $name) {
            if (isset($magicMethods[$name])) {
                $result[$name] = $magicMethods[$name];
            } else {
                $static = $return = '';
                if ($name[0] === '&') {
                    $return = '$r = null; return $r;';
                }
                if (preg_match('/^&?::.*/', $name)) {
                    $static = 'static ';
                    $name = substr($name, 2);
                }
                $result[$name] = "public {$static}function {$name}() {{$return}}";
            }
        }

        return $result;
    }

    /**
     * Creates method definitions from a class name.
     *
     * @param  string  $class A class name.
     * @param  boolean $layer If `true`, all public methods are "overriden".
     * @return string         The generated methods.
     */
    protected static function _generateClassMethods($class, $layer = false)
    {
        $result = [];
        if (!class_exists($class)) {
            throw new IncompleteException("Unexisting parent class `{$class}`");
        }
        $result = static::_generateAbstractMethods($class);

        if (!$layer) {
            return $result;
        }
        $reflection = Inspector::inspect($class);
        $finals = $reflection->getMethods(ReflectionMethod::IS_FINAL);
        $methods = array_diff($reflection->getMethods(ReflectionMethod::IS_PUBLIC), $finals);
        foreach ($methods as $method) {
            $result[$method->getName()] = static::_generateMethod($method, true);
        }
        return $result;
    }

    /**
     * Creates method definitions from a class name.
     *
     * @param  string  $class A class name.
     * @param  integer $mask  The method mask to filter.
     * @return string         The generated methods.
     */
    protected static function _generateAbstractMethods($class)
    {
        $result = [];
        if (!class_exists($class)) {
            throw new IncompleteException("Unexisting parent class `{$class}`");
        }
        $reflection = Inspector::inspect($class);
        $methods = $reflection->getMethods(ReflectionMethod::IS_ABSTRACT);
        foreach ($methods as $method) {
            $result[$method->getName()] = static::_generateMethod($method);
        }
        return $result;
    }

    /**
     * Creates method definitions from an interface array.
     *
     * @param  array   $interfaces A array on interfaces.
     * @param  integer $mask       The method mask to filter.
     * @return string              The generated methods.
     */
    protected static function _generateInterfaceMethods($interfaces, $mask = 255)
    {
        if (!$interfaces) {
            return [];
        }
        $result = [];
        foreach ((array) $interfaces as $interface) {
            if (!interface_exists($interface)) {
                throw new IncompleteException("Unexisting interface `{$interface}`");
            }
            $reflection = Inspector::inspect($interface);
            $methods = $reflection->getMethods($mask);
            foreach ($methods as $method) {
                $result[$method->getName()] = static::_generateMethod($method);
            }
        }
        return $result;
    }

    /**
     * Creates a method definition from a `ReflectionMethod` instance.
     *
     * @param  objedct $method A instance of `ReflectionMethod`.
     * @return string          The generated method.
     */
    protected static function _generateMethod($method, $callParent = false)
    {
        $result = join(' ', Reflection::getModifierNames($method->getModifiers()));
        $result = preg_replace('/abstract\s*/', '', $result);
        $name = $method->getName();
        $parameters = static::_generateSignature($method);
        if (PHP_MAJOR_VERSION >= 7) {
            $type = $method->getReturnType();
            if ($type && !$type->isBuiltin()) {
                $type = '\\' . $type;
            }

            $type = $type ? ": {$type} " : '';
        } else {
            $type = '';
        }
        $body = "{$result} function {$name}({$parameters}) {$type}{";
        if ($callParent) {
            $parameters = static::_generateParameters($method);
            $body .= "return parent::{$name}({$parameters});";
        }
        return $body . "}";
    }

    /**
     * Creates a parameters signature of a `ReflectionMethod` instance.
     *
     * @param  object $method A instance of `ReflectionMethod`.
     * @return string         The parameters definition list.
     */
    protected static function _generateSignature($method)
    {
        $params = [];
        $isVariadic = PHP_MAJOR_VERSION >= 7 ? $method->isVariadic() : false;

        foreach ($method->getParameters() as $num => $parameter) {
            $typehint = Inspector::typehint($parameter);
            $typehint = $typehint ? $typehint . ' ' : $typehint;
            $name = $parameter->getName();
            $name = ($name && $name !== '...') ? $name : 'param' . $num;
            $reference = $parameter->isPassedByReference() ? '&' : '';
            $default = '';
            if ($parameter->isDefaultValueAvailable()) {
                $default = var_export($parameter->getDefaultValue(), true);
                $default = ' = ' . preg_replace('/\s+/', '', $default);
            } elseif ($parameter->isOptional()) {
                if ($isVariadic && $parameter->isVariadic()) {
                    $reference = '...';
                    $default = '';
                } else {
                    $default = ' = NULL';
                }
            }

            $params[] = "{$typehint}{$reference}\${$name}{$default}";
        }
        return join(', ', $params);
    }

    /**
     * Creates a parameters list from a `ReflectionMethod` instance.
     *
     * @param  object $method A instance of `ReflectionMethod`.
     * @return string         The parameters definition list.
     */
    protected static function _generateParameters($method)
    {
        $params = [];
        foreach ($method->getParameters() as $num => $parameter) {
            $name = $parameter->getName();
            $name = ($name && $name !== '...') ? $name : 'param' . $num;
            $params[] = "\${$name}";
        }
        return join(', ', $params);
    }

    /**
     * Checks if a stub has been registered for a hash
     *
     * @param  mixed         $hash An instance hash or a fully namespaced class name.
     * @return boolean|array
     */
    public static function registered($hash = null)
    {
        if ($hash === null) {
            return array_keys(static::$_registered);
        }
        return isset(static::$_registered[$hash]);
    }

    /**
     * Clears the registered references.
     *
     * @param string $reference An instance or a fully namespaced class name or `null` to clear all.
     */
    public static function reset($reference = null)
    {
        if ($reference === null) {
            static::$_registered = [];
            Suite::reset();
            return;
        }
        unset(static::$_registered[Suite::hash($reference)]);
    }
}


text:
using System.Collections.Concurrent;

namespace System.IO
{
    internal sealed class FileChannelHistory
    {
        private readonly ConcurrentDictionary<string, DateTime> _history
            = new ConcurrentDictionary<string, DateTime>();

        public bool IsChanged(string filePath)
        {
            var lastWriteTime = File.GetLastWriteTime(filePath);

            DateTime lastReadTime;

            if (_history.TryGetValue(filePath, out lastReadTime))
            {
                if (!DateTimeEquals(lastWriteTime, lastReadTime))
                {
                    _history.TryUpdate(filePath, lastWriteTime, lastReadTime);

                    return true;
                }
            }
            else
            {
                _history.TryAdd(filePath, lastWriteTime);

                return true;
            }

            return false;
        }

        private static bool DateTimeEquals(DateTime left, DateTime right)
        {
            return left.Year == right.Year
                   && left.Month == right.Month
                   && left.Hour == right.Hour
                   && left.Minute == right.Minute
                   && left.Second == right.Second;
        }
    }
}


text:
package com.infinities.skyport.util;

public class ExceptionUtil {

	private ExceptionUtil() {

	}

	public static Throwable getRootCause(Throwable t) {
		Throwable result = t;

		while (result.getCause() != null) {
			result = result.getCause();
		}

		return result;
	}

}


text:
package org.cordovastudio.editors.designer.propertyTable.actions;

/**
 * @author Alexander Lobas
 */
public interface IPropertyTableAction {
  void update();
}


text:
try:
    from ConfigParser import ConfigParser
except ImportError:
    from configparser import ConfigParser

import json
import os
import glob
import shutil
from numbers import Number

class Config(object):
    DEFAULT_FILENAMES = [
        "config.ini", ("..", "config.ini"), ("~", ".simcity_client")]

    def __init__(self, filenames=None, from_file=True):
        if from_file:
            if filenames is None:
                filenames = Config.DEFAULT_FILENAMES

            exp_filenames = expandfilenames(filenames)

            self.parser = ConfigParser()
            self.filename = self.parser.read(exp_filenames)
            if len(self.filename) == 0:
                raise ValueError(
                    "No valid configuration files could be found: tried " +
                    str(exp_filenames))
        else:
            self.parser = None
            self.filename = None

        self.sections = {}

    def add_section(self, name, keyvalue):
        self.sections[name] = dict_value_expandvar(keyvalue)

    def section(self, name):
        try:
            return self.sections[name]
        except KeyError:
            if self.parser is not None and (name == 'DEFAULT' or
                                            self.parser.has_section(name)):
                return dict_value_expandvar(dict(self.parser.items(name)))
            else:
                raise

def dict_value_expandvar(d):
    for key in d:
        try:
            d[key] = os.path.expandvars(d[key])
        except TypeError:
            pass  # d[key] is not a string
    return d

def get_truthy(value):
    truthy = ['1', 'true', 'yes', 'on']
    if isinstance(value, Number):
        return bool(value)
    else:
        return value.lower() in truthy

def issequence(obj):
    return isinstance(obj, (list, tuple))

def expandfilename(filename):
    if issequence(filename):
        filename = os.path.join(*filename)
    return os.path.expandvars(os.path.expanduser(filename))

def expandfilenames(filenames):
    if not issequence(filenames):
        filenames = [filenames]
    return [expandfilename(fname) for fname in filenames]

def write_json(fname, obj):
    with open(fname, 'w') as outfile:
        json.dump(obj, outfile)

def listfiles(mypath):
    return [f
            for f in os.listdir(mypath)
            if os.path.isfile(os.path.join(mypath, f))]

def listdirs(mypath):
    return [d
            for d in os.listdir(mypath)
            if os.path.isdir(os.path.join(mypath, d))]

def copyglob(srcglob, dstdir, prefix=""):
    if not os.path.isdir(dstdir):
        raise ValueError("Destination of copyglob must be a directory")

    for src in glob.glob(expandfilename(srcglob)):
        _, fname = os.path.split(src)
        shutil.copyfile(src, os.path.join(dstdir, prefix + fname))