text:
package com.mossle.humantask.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.mossle.api.form.FormConnector;
import com.mossle.api.form.FormDTO;
import com.mossle.api.humantask.HumanTaskConnector;
import com.mossle.api.humantask.HumanTaskConstants;
import com.mossle.api.humantask.HumanTaskDTO;
import com.mossle.api.humantask.HumanTaskDefinition;
import com.mossle.api.humantask.ParticipantDTO;

import com.mossle.core.mapper.BeanMapper;
import com.mossle.core.page.Page;

import com.mossle.humantask.listener.HumanTaskListener;
import com.mossle.humantask.persistence.domain.TaskConfUser;
import com.mossle.humantask.persistence.domain.TaskDeadline;
import com.mossle.humantask.persistence.domain.TaskInfo;
import com.mossle.humantask.persistence.domain.TaskParticipant;
import com.mossle.humantask.persistence.manager.TaskConfUserManager;
import com.mossle.humantask.persistence.manager.TaskDeadlineManager;
import com.mossle.humantask.persistence.manager.TaskInfoManager;
import com.mossle.humantask.persistence.manager.TaskParticipantManager;

import com.mossle.spi.humantask.TaskDefinitionConnector;
import com.mossle.spi.process.InternalProcessConnector;
import com.mossle.spi.process.ProcessTaskDefinition;

import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.util.Assert;

public class HumanTaskConnectorImpl implements HumanTaskConnector {
    private Logger logger = LoggerFactory
            .getLogger(HumanTaskConnectorImpl.class);
    private JdbcTemplate jdbcTemplate;
    private TaskInfoManager taskInfoManager;
    private TaskParticipantManager taskParticipantManager;
    private TaskConfUserManager taskConfUserManager;
    private TaskDeadlineManager taskDeadlineManager;
    private InternalProcessConnector internalProcessConnector;
    private TaskDefinitionConnector taskDefinitionConnector;
    private FormConnector formConnector;
    private BeanMapper beanMapper = new BeanMapper();
    private List<HumanTaskListener> humanTaskListeners;

    // ~
    /**
     * 创建一个任务.
     */
    public HumanTaskDTO createHumanTask() {
        return new HumanTaskBuilder().create();
    }

    // ~

    /**
     * 删除任务.
     */
    public void removeHumanTask(String humanTaskId) {
        TaskInfo taskInfo = taskInfoManager.get(Long.parseLong(humanTaskId));
        this.removeHumanTask(taskInfo);
    }

    public void removeHumanTaskByTaskId(String taskId) {
        TaskInfo taskInfo = taskInfoManager.findUniqueBy("taskId", taskId);
        this.removeHumanTask(taskInfo);
    }

    public void removeHumanTaskByProcessInstanceId(String processInstanceId) {
        String hql = "from TaskInfo where status='active' and processInstanceId=?";
        List<TaskInfo> taskInfos = taskInfoManager.find(hql, processInstanceId);

        for (TaskInfo taskInfo : taskInfos) {
            this.removeHumanTask(taskInfo);
        }
    }

    public void removeHumanTask(TaskInfo taskInfo) {
        taskInfoManager.removeAll(taskInfo.getTaskDeadlines());
        taskInfoManager.removeAll(taskInfo.getTaskLogs());
        taskInfoManager.remove(taskInfo);
    }

    // ~
    /**
     * 保存任务.
     */
    public HumanTaskDTO saveHumanTask(HumanTaskDTO humanTaskDto) {
        return this.saveHumanTask(humanTaskDto, true);
    }

    public HumanTaskDTO saveHumanTask(HumanTaskDTO humanTaskDto,
            boolean triggerListener) {
        // process first
        Long id = null;

        if (humanTaskDto.getId() != null) {
            try {
                id = Long.parseLong(humanTaskDto.getId());
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }

        TaskInfo taskInfo = new TaskInfo();

        if (id != null) {
            taskInfo = taskInfoManager.get(id);
        }

        beanMapper.copy(humanTaskDto, taskInfo, HumanTaskDTO.class,
                TaskInfo.class);
        logger.debug("action : {}", humanTaskDto.getAction());
        logger.debug("comment : {}", humanTaskDto.getComment());
        logger.debug("action : {}", taskInfo.getAction());
        logger.debug("comment : {}", taskInfo.getComment());

        if (humanTaskDto.getParentId() != null) {
            taskInfo.setTaskInfo(taskInfoManager.get(Long
                    .parseLong(humanTaskDto.getParentId())));
        }

        taskInfoManager.save(taskInfo);

        if (triggerListener) {
            // create
            if ((id == null) && (humanTaskListeners != null)) {
                for (HumanTaskListener humanTaskListener : humanTaskListeners) {
                    try {
                        humanTaskListener.onCreate(taskInfo);
                    } catch (Exception ex) {
                        logger.error(ex.getMessage(), ex);
                    }
                }
            }

            humanTaskDto.setAssignee(taskInfo.getAssignee());
            humanTaskDto.setOwner(taskInfo.getOwner());
        }

        humanTaskDto.setId(Long.toString(taskInfo.getId()));

        return humanTaskDto;
    }

    /**
     * 保存任务,并处理参与者.
     */
    public HumanTaskDTO saveHumanTaskAndProcess(HumanTaskDTO humanTaskDto) {
        return this.saveHumanTask(humanTaskDto, true);
    }

    public HumanTaskDTO findHumanTaskByTaskId(String taskId) {
        TaskInfo taskInfo = taskInfoManager.findUniqueBy("taskId", taskId);
        HumanTaskDTO humanTaskDto = new HumanTaskDTO();
        humanTaskDto = convertHumanTaskDto(taskInfo);

        return humanTaskDto;
    }

    public List<HumanTaskDTO> findHumanTasksByProcessInstanceId(
            String processInstanceId) {
        List<TaskInfo> taskInfos = taskInfoManager
                .find("from TaskInfo where processInstanceId=? order by createTime asc",
                        processInstanceId);

        return this.convertHumanTaskDtos(taskInfos);
    }

    public HumanTaskDTO findHumanTask(String humanTaskId) {
        Assert.hasText(humanTaskId, "humanTaskId不能为空");

        TaskInfo taskInfo = taskInfoManager.get(Long.parseLong(humanTaskId));

        return this.convertHumanTaskDto(taskInfo);
    }

    public List<HumanTaskDTO> findSubTasks(String parentTaskId) {
        List<TaskInfo> taskInfos = taskInfoManager.findBy("taskInfo.id",
                Long.parseLong(parentTaskId));

        return this.convertHumanTaskDtos(taskInfos);
    }

    /**
     * 获取任务表单.
     */
    public FormDTO findTaskForm(String humanTaskId) {
        HumanTaskDTO humanTaskDto = this.findHumanTask(humanTaskId);

        FormDTO formDto = null;

        if (humanTaskDto.getTaskId() != null) {
            // formDto = internalProcessConnector.findTaskForm(humanTaskDto
            // .getTaskId());
            com.mossle.spi.humantask.FormDTO taskFormDto = taskDefinitionConnector
                    .findForm(humanTaskDto.getCode(),
                            humanTaskDto.getProcessDefinitionId());

            if (taskFormDto == null) {
                logger.info(
                        "cannot find form by code : {}, processDefinition : {}",
                        humanTaskDto.getCode(),
                        humanTaskDto.getProcessDefinitionId());
            } else {
                formDto = new FormDTO();
                formDto.setCode(taskFormDto.getKey());

                List<String> operations = taskDefinitionConnector
                        .findOperations(humanTaskDto.getCode(),
                                humanTaskDto.getProcessDefinitionId());
                formDto.getButtons().addAll(operations);
                formDto.setActivityId(humanTaskDto.getCode());
                formDto.setProcessDefinitionId(humanTaskDto
                        .getProcessDefinitionId());
            }
        } else {
            formDto = new FormDTO();
            formDto.setCode(humanTaskDto.getForm());
            formDto.setActivityId(humanTaskDto.getCode());
            formDto.setProcessDefinitionId(humanTaskDto
                    .getProcessDefinitionId());
        }

        if (formDto == null) {
            logger.error("cannot find form : {}", humanTaskId);

            return new FormDTO();
        }

        formDto.setTaskId(humanTaskId);

        FormDTO contentFormDto = formConnector.findForm(formDto.getCode(),
                humanTaskDto.getTenantId());

        if (contentFormDto == null) {
            logger.error("cannot find form : {}", formDto.getCode());

            return formDto;
        }

        formDto.setRedirect(contentFormDto.isRedirect());
        formDto.setUrl(contentFormDto.getUrl());
        formDto.setContent(contentFormDto.getContent());

        return formDto;
    }

    /**
     * 根据流程定义获得所有任务定义.
     */
    public List<HumanTaskDefinition> findHumanTaskDefinitions(
            String processDefinitionId) {
        List<ProcessTaskDefinition> processTaskDefinitions = internalProcessConnector
                .findTaskDefinitions(processDefinitionId);

        List<HumanTaskDefinition> humanTaskDefinitions = new ArrayList<HumanTaskDefinition>();

        for (ProcessTaskDefinition processTaskDefinition : processTaskDefinitions) {
            HumanTaskDefinition humanTaskDefinition = new HumanTaskDefinition();
            beanMapper.copy(processTaskDefinition, humanTaskDefinition);
            humanTaskDefinitions.add(humanTaskDefinition);
        }

        return humanTaskDefinitions;
    }

    /**
     * 流程发起之前,配置每个任务的负责人.
     */
    public void configTaskDefinitions(String businessKey,
            List<String> taskDefinitionKeys, List<String> taskAssignees) {
        if (taskDefinitionKeys == null) {
            return;
        }

        int index = 0;

        for (String taskDefinitionKey : taskDefinitionKeys) {
            String taskAssignee = taskAssignees.get(index++);
            String hql = "from TaskConfUser where businessKey=? and code=?";
            TaskConfUser taskConfUser = taskConfUserManager.findUnique(hql,
                    businessKey, taskDefinitionKey);

            if (taskConfUser == null) {
                taskConfUser = new TaskConfUser();
            }

            taskConfUser.setBusinessKey(businessKey);
            taskConfUser.setCode(taskDefinitionKey);
            taskConfUser.setValue(taskAssignee);
            taskConfUserManager.save(taskConfUser);
        }
    }

    /**
     * 完成任务.
     */
    public void completeTask(String humanTaskId, String userId, String action,
            String comment, Map<String, Object> taskParameters) {
        Assert.hasText(humanTaskId, "humanTaskId不能为空");
        logger.info("completeTask humanTaskId : {}, userId : {}, comment: {}",
                humanTaskId, userId, comment);

        HumanTaskDTO humanTaskDto = this.findHumanTask(humanTaskId);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        humanTaskDto.setStatus("complete");
        humanTaskDto.setCompleteTime(new Date());
        humanTaskDto.setAction("完成");

        if (StringUtils.isNotBlank(action)) {
            humanTaskDto.setAction(action);
        }

        if (StringUtils.isNotBlank(comment)) {
            humanTaskDto.setComment(comment);
        }

        Long longTaskId = Long.parseLong(humanTaskDto.getId());
        List<TaskDeadline> taskDeadlines = taskDeadlineManager.find(
                "from TaskDeadline where taskInfo.id=?", longTaskId);

        for (TaskDeadline taskDeadline : taskDeadlines) {
            taskDeadlineManager.remove(taskDeadline);
        }

        // 处理抄送任务
        if ("copy".equals(humanTaskDto.getCategory())) {
            humanTaskDto.setStatus("complete");
            humanTaskDto.setCompleteTime(new Date());
            humanTaskDto.setAction("完成");
            this.saveHumanTask(humanTaskDto, false);

            return;
        }

        // 处理startEvent任务
        if ("startEvent".equals(humanTaskDto.getCategory())) {
            humanTaskDto.setStatus("complete");
            humanTaskDto.setAction("提交");
            humanTaskDto.setCompleteTime(new Date());
            this.saveHumanTask(humanTaskDto, false);
            internalProcessConnector.signalExecution(humanTaskDto
                    .getExecutionId());

            return;
        }

        logger.debug("{}", humanTaskDto.getDelegateStatus());

        // 处理协办任务
        if ("pending".equals(humanTaskDto.getDelegateStatus())) {
            humanTaskDto.setStatus("active");
            humanTaskDto.setDelegateStatus("resolved");
            humanTaskDto.setAssignee(humanTaskDto.getOwner());
            humanTaskDto.setAction("完成");
            this.saveHumanTask(humanTaskDto, false);
            internalProcessConnector.resolveTask(humanTaskDto.getTaskId());

            return;
        }

        // 处理协办链式任务
        if ("pendingCreate".equals(humanTaskDto.getDelegateStatus())) {
            humanTaskDto.setCompleteTime(new Date());
            humanTaskDto.setDelegateStatus("resolved");
            humanTaskDto.setStatus("complete");
            humanTaskDto.setAction("完成");
            this.saveHumanTask(humanTaskDto, false);

            if (humanTaskDto.getParentId() != null) {
                HumanTaskDTO targetHumanTaskDto = this
                        .findHumanTask(humanTaskDto.getParentId());
                targetHumanTaskDto.setStatus("active");

                if (targetHumanTaskDto.getParentId() == null) {
                    targetHumanTaskDto.setDelegateStatus("resolved");
                }

                this.saveHumanTask(targetHumanTaskDto, false);
            }

            return;
        }

        this.saveHumanTask(humanTaskDto, false);

        // 判断加签
        if ("vote".equals(humanTaskDto.getCatalog())
                && (humanTaskDto.getParentId() != null)) {
            HumanTaskDTO parentTask = this.findHumanTask(humanTaskDto
                    .getParentId());
            boolean completed = true;

            for (HumanTaskDTO childTask : parentTask.getChildren()) {
                if (!"complete".equals(childTask.getStatus())) {
                    completed = false;

                    break;
                }
            }

            if (completed) {
                parentTask.setAssignee(parentTask.getOwner());
                parentTask.setOwner("");
                parentTask.setStatus("complete");
                parentTask.setCompleteTime(new Date());
                parentTask.setAction("完成");
                this.saveHumanTask(parentTask, false);
                internalProcessConnector.completeTask(humanTaskDto.getTaskId(),
                        userId, taskParameters);
            }
        } else {
            internalProcessConnector.completeTask(humanTaskDto.getTaskId(),
                    userId, taskParameters);
        }

        if (humanTaskListeners != null) {
            Long id = null;

            try {
                id = Long.parseLong(humanTaskDto.getId());
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }

            if (id == null) {
                return;
            }

            TaskInfo taskInfo = taskInfoManager.get(id);

            for (HumanTaskListener humanTaskListener : humanTaskListeners) {
                try {
                    humanTaskListener.onComplete(taskInfo);
                } catch (Exception ex) {
                    logger.error(ex.getMessage(), ex);
                }
            }
        }
    }

    /**
     * 待办任务.
     */
    public Page findPersonalTasks(String userId, String tenantId, int pageNo,
            int pageSize) {
        String hql = "from TaskInfo where assignee=? and tenantId=? and status='active' order by id desc";
        Page page = taskInfoManager.pagedQuery(hql, pageNo, pageSize, userId,
                tenantId);
        List<TaskInfo> taskInfos = (List<TaskInfo>) page.getResult();
        List<HumanTaskDTO> humanTaskDtos = this.convertHumanTaskDtos(taskInfos);
        page.setResult(humanTaskDtos);

        return page;
    }

    /**
     * 已办任务.
     */
    public Page findFinishedTasks(String userId, String tenantId, int pageNo,
            int pageSize) {
        String hql = "from TaskInfo where assignee=? and tenantId=? and status='complete' order by id desc";
        Page page = taskInfoManager.pagedQuery(hql, pageNo, pageSize, userId,
                tenantId);
        List<TaskInfo> taskInfos = (List<TaskInfo>) page.getResult();
        List<HumanTaskDTO> humanTaskDtos = this.convertHumanTaskDtos(taskInfos);
        page.setResult(humanTaskDtos);

        return page;
    }

    /**
     * 待领任务.
     */
    public Page findGroupTasks(String userId, String tenantId, int pageNo,
            int pageSize) {
        List<String> partyIds = new ArrayList<String>();
        partyIds.addAll(this.findGroupIds(userId));
        partyIds.addAll(this.findUserIds(userId));

        logger.debug("party ids : {}", partyIds);

        if (partyIds.isEmpty()) {
            return new Page();
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("partyIds", partyIds);
        map.put("tenantId", tenantId);

        String hql = "select distinct t from TaskInfo t join t.taskParticipants p "
                + "with p.ref in (:partyIds) where t.tenantId=:tenantId and t.assignee=null and t.status='active' "
                + "order by id desc";
        Page page = taskInfoManager.pagedQuery(hql, pageNo, pageSize, map);

        // List<PropertyFilter> propertyFilters = PropertyFilter
        // .buildFromMap(parameterMap);
        // propertyFilters.add(new PropertyFilter("EQS_status", "active"));
        // propertyFilters.add(new PropertyFilter("INLS_assignee", null));
        List<TaskInfo> taskInfos = (List<TaskInfo>) page.getResult();
        List<HumanTaskDTO> humanTaskDtos = this.convertHumanTaskDtos(taskInfos);
        page.setResult(humanTaskDtos);

        return page;
    }

    /**
     * 经手任务.
     */
    public Page findDelegateTasks(String userId, String tenantId, int pageNo,
            int pageSize) {
        String hql = "from TaskInfo where owner=? and tenantId=? and status='active' order by id desc";
        Page page = taskInfoManager.pagedQuery(hql, pageNo, pageSize, userId,
                tenantId);
        List<TaskInfo> taskInfos = (List<TaskInfo>) page.getResult();
        List<HumanTaskDTO> humanTaskDtos = this.convertHumanTaskDtos(taskInfos);
        page.setResult(humanTaskDtos);

        return page;
    }

    /**
     * 领取任务.
     */
    public void claimTask(String humanTaskId, String userId) {
        TaskInfo taskInfo = taskInfoManager.get(Integer.parseInt(humanTaskId));

        if (taskInfo.getAssignee() != null) {
            throw new IllegalStateException("task " + humanTaskId
                    + " already be claimed by " + taskInfo.getAssignee());
        }

        taskInfo.setAssignee(userId);
        taskInfoManager.save(taskInfo);
    }

    /**
     * 释放任务.
     */
    public void releaseTask(String humanTaskId, String comment) {
        TaskInfo taskInfo = taskInfoManager.get(Integer.parseInt(humanTaskId));

        taskInfo.setAssignee(null);
        taskInfoManager.save(taskInfo);
    }

    /**
     * 转办.
     */
    public void transfer(String humanTaskId, String userId, String comment) {
        HumanTaskDTO humanTaskDto = this.findHumanTask(humanTaskId);
        humanTaskDto.setOwner(humanTaskDto.getAssignee());
        humanTaskDto.setAssignee(userId);
        this.saveHumanTask(humanTaskDto, false);

        internalProcessConnector.transfer(humanTaskDto.getTaskId(),
                humanTaskDto.getAssignee(), humanTaskDto.getOwner());
    }

    /**
     * 取消转办.
     */
    public void cancel(String humanTaskId, String userId, String comment) {
        HumanTaskDTO humanTaskDto = this.findHumanTask(humanTaskId);
        humanTaskDto.setAssignee(humanTaskDto.getOwner());
        humanTaskDto.setOwner("");
        this.saveHumanTask(humanTaskDto, false);
    }

    /**
     * 回退,指定节点,重新分配.
     */
    public void rollbackActivity(String humanTaskId, String activityId,
            String comment) {
        HumanTaskDTO humanTaskDto = findHumanTask(humanTaskId);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        String taskId = humanTaskDto.getTaskId();
        internalProcessConnector.rollback(taskId, activityId, null);
    }

    /**
     * 回退,指定节点,上个执行人.
     */
    public void rollbackActivityLast(String humanTaskId, String activityId,
            String comment) {
        HumanTaskDTO humanTaskDto = findHumanTask(humanTaskId);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        String taskId = humanTaskDto.getTaskId();
        internalProcessConnector.rollbackAuto(taskId, activityId);
    }

    /**
     * 回退,指定节点,指定执行人.
     */
    public void rollbackActivityAssignee(String humanTaskId, String activityId,
            String userId, String comment) {
        HumanTaskDTO humanTaskDto = findHumanTask(humanTaskId);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        String taskId = humanTaskDto.getTaskId();
        internalProcessConnector.rollback(taskId, activityId, userId);
    }

    /**
     * 回退,上个节点,重新分配.
     */
    public void rollbackPrevious(String humanTaskId, String comment) {
        HumanTaskDTO humanTaskDto = findHumanTask(humanTaskId);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        String taskId = humanTaskDto.getTaskId();
        internalProcessConnector.rollback(taskId, null, null);
    }

    /**
     * 回退,上个节点,上个执行人.
     */
    public void rollbackPreviousLast(String humanTaskId, String comment) {
        HumanTaskDTO humanTaskDto = findHumanTask(humanTaskId);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        String taskId = humanTaskDto.getTaskId();
        internalProcessConnector.rollbackAuto(taskId, null);
    }

    /**
     * 回退,上个节点,指定执行人.
     */
    public void rollbackPreviousAssignee(String humanTaskId, String userId,
            String comment) {
        HumanTaskDTO humanTaskDto = findHumanTask(humanTaskId);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        String taskId = humanTaskDto.getTaskId();
        internalProcessConnector.rollback(taskId, null, userId);
    }

    /**
     * 回退,开始事件,流程发起人.
     */
    public void rollbackStart(String humanTaskId, String comment) {
        HumanTaskDTO humanTaskDto = findHumanTask(humanTaskId);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        String taskId = humanTaskDto.getTaskId();
        String processDefinitionId = humanTaskDto.getProcessDefinitionId();
        String processInstanceId = humanTaskDto.getProcessInstanceId();
        String activityId = this.internalProcessConnector
                .findInitialActivityId(processDefinitionId);
        String initiator = this.internalProcessConnector
                .findInitiator(processInstanceId);
        internalProcessConnector.rollback(taskId, activityId, initiator);
    }

    /**
     * 回退,流程发起人.
     */
    public void rollbackInitiator(String humanTaskId, String comment) {
        HumanTaskDTO humanTaskDto = findHumanTask(humanTaskId);
        humanTaskDto.setAction("回退(发起人)");
        humanTaskDto.setComment(comment);
        this.saveHumanTask(humanTaskDto, false);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        String taskId = humanTaskDto.getTaskId();
        String processDefinitionId = humanTaskDto.getProcessDefinitionId();
        String processInstanceId = humanTaskDto.getProcessInstanceId();
        String initiator = this.internalProcessConnector
                .findInitiator(processInstanceId);
        String activityId = this.internalProcessConnector
                .findFirstUserTaskActivityId(processDefinitionId, initiator);
        internalProcessConnector.rollback(taskId, activityId, initiator);
    }

    /**
     * 撤销.
     */
    public void withdraw(String humanTaskId, String comment) {
        HumanTaskDTO humanTaskDto = findHumanTask(humanTaskId);

        if (humanTaskDto == null) {
            throw new IllegalStateException("任务不存在");
        }

        internalProcessConnector.withdrawTask(humanTaskDto.getTaskId());
    }

    /**
     * 协办.
     */
    public void delegateTask(String humanTaskId, String userId, String comment) {
        HumanTaskDTO humanTaskDto = this.findHumanTask(humanTaskId);
        humanTaskDto.setOwner(humanTaskDto.getAssignee());
        humanTaskDto.setAssignee(userId);
        humanTaskDto.setDelegateStatus("pending");
        this.saveHumanTask(humanTaskDto, false);
        internalProcessConnector.delegateTask(humanTaskDto.getTaskId(), userId);
    }

    /**
     * 协办,链状.
     */
    public void delegateTaskCreate(String humanTaskId, String userId,
            String comment) {
        HumanTaskDTO humanTaskDto = this.findHumanTask(humanTaskId);
        humanTaskDto.setDelegateStatus("pendingCreate");
        humanTaskDto.setStatus("pending");
        this.saveHumanTask(humanTaskDto, false);

        HumanTaskDTO targetHumanTaskDto = this.createHumanTask();
        beanMapper.copy(humanTaskDto, targetHumanTaskDto);
        targetHumanTaskDto.setStatus("active");
        targetHumanTaskDto.setParentId(humanTaskDto.getId());
        targetHumanTaskDto.setId(null);
        targetHumanTaskDto.setOwner(humanTaskDto.getAssignee());
        targetHumanTaskDto.setAssignee(userId);

        this.saveHumanTask(targetHumanTaskDto, false);

        if (humanTaskDto.getParentId() == null) {
            humanTaskDto.setOwner(humanTaskDto.getAssignee());
            humanTaskDto.setAssignee(userId);
            // 只有第一次协办才更新bpm的历史
            internalProcessConnector.delegateTask(humanTaskDto.getTaskId(),
                    userId);
            humanTaskDto.setAssignee(humanTaskDto.getOwner());
            humanTaskDto.setOwner(null);
            this.saveHumanTask(humanTaskDto, false);
        }
    }

    /**
     * 沟通.
     */
    public void communicate(String humanTaskId, String userId, String comment) {
        HumanTaskDTO humanTaskDto = this.findHumanTask(humanTaskId);
        HumanTaskDTO target = new HumanTaskDTO();
        beanMapper.copy(humanTaskDto, target);
        target.setId(null);
        target.setCatalog(HumanTaskConstants.CATALOG_COMMUNICATE);
        target.setAssignee(userId);
        target.setParentId(humanTaskId);
        target.setMessage(comment);

        this.saveHumanTask(target, false);
    }

    /**
     * 反馈.
     */
    public void callback(String humanTaskId, String userId, String comment) {
        HumanTaskDTO humanTaskDto = this.findHumanTask(humanTaskId);
        humanTaskDto.setStatus("complete");
        humanTaskDto.setCompleteTime(new Date());
        humanTaskDto.setAction("反馈");
        humanTaskDto.setComment(comment);
        this.saveHumanTask(humanTaskDto, false);
    }

    /**
     * 跳过.
     */
    public void skip(String humanTaskId, String userId, String comment) {
        HumanTaskDTO humanTaskDto = this.findHumanTask(humanTaskId);
        humanTaskDto.setStatus("complete");
        humanTaskDto.setCompleteTime(new Date());
        humanTaskDto.setAction("跳过");
        humanTaskDto.setComment(comment);
        humanTaskDto.setOwner(humanTaskDto.getAssignee());
        humanTaskDto.setAssignee(userId);
        this.saveHumanTask(humanTaskDto, false);
        internalProcessConnector.completeTask(humanTaskDto.getTaskId(), userId,
                Collections.<String, Object> emptyMap());
    }

    public List<String> findGroupIds(String userId) {
        String groupSql = "select ps.PARENT_ENTITY_ID as ID from PARTY_STRUCT ps,PARTY_ENTITY child,PARTY_TYPE type"
                + " where ps.CHILD_ENTITY_ID=child.ID and child.TYPE_ID=type.ID and type.TYPE='1' and child.REF=?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(groupSql,
                userId);
        List<String> partyIds = new ArrayList<String>();

        for (Map<String, Object> map : list) {
            partyIds.add(map.get("ID").toString());
        }

        return partyIds;
    }

    public List<String> findUserIds(String userId) {
        String userSql = "select pe.ID as ID from PARTY_ENTITY pe,PARTY_TYPE type"
                + " where pe.TYPE_ID=type.ID and type.TYPE='1' and pe.REF=?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(userSql,
                userId);
        List<String> partyIds = new ArrayList<String>();

        for (Map<String, Object> map : list) {
            partyIds.add(map.get("ID").toString());
        }

        return partyIds;
    }

    // ~ ==================================================
    public List<HumanTaskDTO> convertHumanTaskDtos(
            Collection<TaskInfo> taskInfos) {
        List<HumanTaskDTO> humanTaskDtos = new ArrayList<HumanTaskDTO>();

        for (TaskInfo taskInfo : taskInfos) {
            humanTaskDtos.add(convertHumanTaskDto(taskInfo));
        }

        return humanTaskDtos;
    }

    public HumanTaskDTO convertHumanTaskDto(TaskInfo taskInfo) {
        if (taskInfo == null) {
            return null;
        }

        HumanTaskDTO humanTaskDto = new HumanTaskDTO();
        beanMapper.copy(taskInfo, humanTaskDto);

        if (taskInfo.getTaskInfo() != null) {
            humanTaskDto.setParentId(Long.toString(taskInfo.getTaskInfo()
                    .getId()));
        }

        if (!taskInfo.getTaskInfos().isEmpty()) {
            List<HumanTaskDTO> children = this.convertHumanTaskDtos(taskInfo
                    .getTaskInfos());
            humanTaskDto.setChildren(children);
        }

        return humanTaskDto;
    }

    public void saveParticipant(ParticipantDTO participantDto) {
        TaskParticipant taskParticipant = new TaskParticipant();
        taskParticipant.setRef(participantDto.getCode());
        taskParticipant.setType(participantDto.getType());
        taskParticipant.setTaskInfo(taskInfoManager.get(Long
                .parseLong(participantDto.getHumanTaskId())));
        taskParticipantManager.save(taskParticipant);
    }

    // ~ ==================================================
    @Resource
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Resource
    public void setTaskInfoManager(TaskInfoManager taskInfoManager) {
        this.taskInfoManager = taskInfoManager;
    }

    @Resource
    public void setTaskParticipantManager(
            TaskParticipantManager taskParticipantManager) {
        this.taskParticipantManager = taskParticipantManager;
    }

    @Resource
    public void setTaskConfUserManager(TaskConfUserManager taskConfUserManager) {
        this.taskConfUserManager = taskConfUserManager;
    }

    @Resource
    public void setTaskDeadlineManager(TaskDeadlineManager taskDeadlineManager) {
        this.taskDeadlineManager = taskDeadlineManager;
    }

    @Resource
    public void setInternalProcessConnector(
            InternalProcessConnector internalProcessConnector) {
        this.internalProcessConnector = internalProcessConnector;
    }

    @Resource
    public void setTaskDefinitionConnector(
            TaskDefinitionConnector taskDefinitionConnector) {
        this.taskDefinitionConnector = taskDefinitionConnector;
    }

    @Resource
    public void setFormConnector(FormConnector formConnector) {
        this.formConnector = formConnector;
    }

    public void setHumanTaskListeners(List<HumanTaskListener> humanTaskListeners) {
        this.humanTaskListeners = humanTaskListeners;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE language SYSTEM "language.dtd">
<language version="2" kateversion="3.4" name="Gitolite" section="Configuration" extensions="gitolite.conf" author="Andor Dávid (david-andor@kozpontiagy.hu)" license="GPL">
  <highlighting>
    <list name="keywords">
      <item>repo</item>
    </list>

    <contexts>
      <context name="Normal Text" attribute="Normal Text" lineEndContext="#pop">
        <DetectChar                     context="SingleLineComment" char="#" />
        <keyword attribute="Keyword"    context="#stay"   String="keywords" />
        <RegExpr attribute="Group"      context="#stay"   String="\@[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" />
        <RegExpr attribute="Symbol"     context="Value"   String="=" />
      </context>

      <context name="SingleLineComment" attribute="Comment (Single)" lineEndContext="#pop" />

      <context name="Value" attribute="Normal Text" lineEndContext="#pop">
        <RegExpr attribute="Group"       context="#stay" String="\@[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" />
      </context>
    </contexts>

    <itemDatas>
      <itemData name="Normal Text"      defStyleNum="dsNormal"/>
      <itemData name="Comment (Single)" defStyleNum="dsComment" />
      <itemData name="Keyword"          defStyleNum="dsKeyword" spellChecking="false" />
      <itemData name="Group"            defStyleNum="dsKeyword" spellChecking="false" />
 <!-- <itemData name="Refs"             defStyleNum="dsKeyword" spellChecking="false" /> -->
      <itemData name="Symbol"           defStyleNum="dsString" />
    </itemDatas>
  </highlighting>

  <general>
    <keywords casesensitive="1" />

    <comments>
      <comment name="singleLine" start="#" />
    </comments>

  </general>

  <!-- kate: space-indent on indent-width 2 replace-tabs on indent-mode xml -->
</language>

redpajama_set_name: RedPajamaGithub


text:
/*
 * 	Name:BinaryImage.h
 *
 *  Created on: 13 Sep 2018
 *      Author: Olu Adebari
 *
 *  Description: Binary image class containing binary image and regions of interest extracted from a binary image
 */

#ifndef BINARYIMAGE_H_
#define BINARYIMAGE_H_

#include "RegionOfInterest.h"
#include <vector>
#include <memory>
#include <unordered_map>

class BinaryImage {
private:

	const uint32_t m_ID;
	const cv::Mat m_binary_image;
	std::unordered_map<uint32_t, std::shared_ptr<RegionOfInterest> > m_regions_of_interest;
	std::vector < std::shared_ptr<RegionOfInterest> >  m_all_regions_of_interest;

public:

/**	*****************************************************************************************
	 *  @name      BinaryImage
	 *
	 *  @brief     Constructor
	 *
	 *  @param     uint32_t: ID for binaryImage
	 *  @param     cv::Mat: binary image
	 ****************************************************************************************/
	BinaryImage(uint32_t ID, cv::Mat binaryImage);
	virtual ~BinaryImage() = default;

/**	*****************************************************************************************
	 *  @name      getID
	 *
	 *	@brief     get the ID for the region of interest.
	 *
	 *  @return    uint32_t: ID for the region of interest.
	 ****************************************************************************************/
	 uint32_t getID () const;

/**	*****************************************************************************************
	 *  @name      getBinaryImage
	 *
	 *  @brief     get Binary image.
	 *
	 *  @return    cv::Mat: get Binary image.
	 ****************************************************************************************/
	 cv::Mat getBinaryImage () const;

/**	*****************************************************************************************
	 *  @name      addRegionOfInterest
	 *
	 *  @brief     add a region of interest
	 *
	 *  @param     std::shared_ptr<RegionOfInterest>: region of interest
	 ****************************************************************************************/
	void addRegionOfInterest (std::shared_ptr<RegionOfInterest>  ROI);

/**	*****************************************************************************************
	 *  @name      addRegionOfInterest
	 *
	 *  @brief     add a region of interest
	 *
	 *  @param 	   uint32_t: region of interest unique ID
	 *  @param 	   cv::Mat: region of interest
	 *  @param     int: coordinate of the region of axis within the image along the x axis
	 *  @param     int: coordinate of the region of axis within the image along the y axis
	 *  @param     cv::Rec: bounded Box of the region of interest
	 ****************************************************************************************/
	void addRegionOfInterest ( uint32_t region_of_interests_ID, cv::Mat region_of_interest, int x_coordinate, int y_coordinate, cv::Rect boundedBox);

/**	*****************************************************************************************
	 *  @name      getRegionOfInterestByID
	 *
	 *  @brief	   get a region of interest based on its ID
	 *
	 *	@param	   uint32_t: ID of requested region of interest image
	 *
	 *  @return    std::shared_ptr<RegionOfInterest>: a region of interest
	 ****************************************************************************************/
	std::shared_ptr<RegionOfInterest> getRegionOfInterestByID (uint32_t ID) const;

/**	*****************************************************************************************
	 *  @name      getAllRegionsOfInterest
	 *
	 *  @brief     get all regions of interest images currently held
	 *
	 *  @return    std::vector< std::shared_ptr<RegionOfInterest> > : regions of interest
	 ****************************************************************************************/
	std::vector< std::shared_ptr<RegionOfInterest> > getAllRegionsOfInterest() const;
};

#endif /* BINARYIMAGE_H_ */


text:
<component name="CopyrightManager">
  <copyright>
    <option name="myName" value="TudorTUDelft" />
  </copyright>
</component>


text:
package org.apache.hadoop.hbase.mapreduce;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Tool used to copy a table to another one which can be on a different setup.
 * It is also configurable with a start and time as well as a specification
 * of the region server implementation if different from the local cluster.
 */
public class CopyTable extends Configured implements Tool {

  final static String NAME = "copytable";
  static long startTime = 0;
  static long endTime = 0;
  static int versions = -1;
  static String tableName = null;
  static String startRow = null;
  static String stopRow = null;
  static String newTableName = null;
  static String peerAddress = null;
  static String families = null;
  static boolean allCells = false;

  public CopyTable(Configuration conf) {
    super(conf);
  }
  /**
   * Sets up the actual job.
   *
   * @param conf  The current configuration.
   * @param args  The command line parameters.
   * @return The newly created job.
   * @throws IOException When setting up the job fails.
   */
  public static Job createSubmittableJob(Configuration conf, String[] args)
  throws IOException {
    if (!doCommandLine(args)) {
      return null;
    }
    Job job = new Job(conf, NAME + "_" + tableName);
    job.setJarByClass(CopyTable.class);
    Scan scan = new Scan();
    scan.setCacheBlocks(false);
    if (startTime != 0) {
      scan.setTimeRange(startTime,
          endTime == 0 ? HConstants.LATEST_TIMESTAMP : endTime);
    }
    if (allCells) {
      scan.setRaw(true);
    }
    if (versions >= 0) {
      scan.setMaxVersions(versions);
    }

    if (startRow != null) {
      scan.setStartRow(Bytes.toBytes(startRow));
    }

    if (stopRow != null) {
      scan.setStopRow(Bytes.toBytes(stopRow));
    }

    if(families != null) {
      String[] fams = families.split(",");
      Map<String,String> cfRenameMap = new HashMap<String,String>();
      for(String fam : fams) {
        String sourceCf;
        if(fam.contains(":")) {
            // fam looks like "sourceCfName:destCfName"
            String[] srcAndDest = fam.split(":", 2);
            sourceCf = srcAndDest[0];
            String destCf = srcAndDest[1];
            cfRenameMap.put(sourceCf, destCf);
        } else {
            // fam is just "sourceCf"
            sourceCf = fam;
        }
        scan.addFamily(Bytes.toBytes(sourceCf));
      }
      Import.configureCfRenaming(job.getConfiguration(), cfRenameMap);
    }
    TableMapReduceUtil.initTableMapperJob(tableName, scan,
        Import.Importer.class, null, null, job);
    TableMapReduceUtil.initTableReducerJob(
        newTableName == null ? tableName : newTableName, null, job,
        null, peerAddress, null, null);
    job.setNumReduceTasks(0);
    return job;
  }

  /*
   * @param errorMsg Error message.  Can be null.
   */
  private static void printUsage(final String errorMsg) {
    if (errorMsg != null && errorMsg.length() > 0) {
      System.err.println("ERROR: " + errorMsg);
    }
    System.err.println("Usage: CopyTable [general options] [--starttime=X] [--endtime=Y] " +
        "[--new.name=NEW] [--peer.adr=ADR] <tablename>");
    System.err.println();
    System.err.println("Options:");
    System.err.println(" rs.class     hbase.regionserver.class of the peer cluster");
    System.err.println("              specify if different from current cluster");
    System.err.println(" rs.impl      hbase.regionserver.impl of the peer cluster");
    System.err.println(" startrow     the start row");
    System.err.println(" stoprow      the stop row");
    System.err.println(" starttime    beginning of the time range (unixtime in millis)");
    System.err.println("              without endtime means from starttime to forever");
    System.err.println(" endtime      end of the time range.  Ignored if no starttime specified.");
    System.err.println(" versions     number of cell versions to copy");
    System.err.println(" new.name     new table's name");
    System.err.println(" peer.adr     Address of the peer cluster given in the format");
    System.err.println("              hbase.zookeeer.quorum:hbase.zookeeper.client.port:zookeeper.znode.parent");
    System.err.println(" families     comma-separated list of families to copy");
    System.err.println("              To copy from cf1 to cf2, give sourceCfName:destCfName. ");
    System.err.println("              To keep the same name, just give \"cfName\"");
    System.err.println(" all.cells    also copy delete markers and deleted cells");
    System.err.println();
    System.err.println("Args:");
    System.err.println(" tablename    Name of the table to copy");
    System.err.println();
    System.err.println("Examples:");
    System.err.println(" To copy 'TestTable' to a cluster that uses replication for a 1 hour window:");
    System.err.println(" $ bin/hbase " +
        "org.apache.hadoop.hbase.mapreduce.CopyTable --starttime=1265875194289 --endtime=1265878794289 " +
        "--peer.adr=server1,server2,server3:2181:/hbase --families=myOldCf:myNewCf,cf2,cf3 TestTable ");
    System.err.println("For performance consider the following general options:\n"
        + "-Dhbase.client.scanner.caching=100\n"
        + "-Dmapred.map.tasks.speculative.execution=false");
  }

  private static boolean doCommandLine(final String[] args) {
    // Process command-line args. TODO: Better cmd-line processing
    // (but hopefully something not as painful as cli options).
    if (args.length < 1) {
      printUsage(null);
      return false;
    }
    try {
      for (int i = 0; i < args.length; i++) {
        String cmd = args[i];
        if (cmd.equals("-h") || cmd.startsWith("--h")) {
          printUsage(null);
          return false;
        }

        final String startRowArgKey = "--startrow=";
        if (cmd.startsWith(startRowArgKey)) {
          startRow = cmd.substring(startRowArgKey.length());
          continue;
        }

        final String stopRowArgKey = "--stoprow=";
        if (cmd.startsWith(stopRowArgKey)) {
          stopRow = cmd.substring(stopRowArgKey.length());
          continue;
        }

        final String startTimeArgKey = "--starttime=";
        if (cmd.startsWith(startTimeArgKey)) {
          startTime = Long.parseLong(cmd.substring(startTimeArgKey.length()));
          continue;
        }

        final String endTimeArgKey = "--endtime=";
        if (cmd.startsWith(endTimeArgKey)) {
          endTime = Long.parseLong(cmd.substring(endTimeArgKey.length()));
          continue;
        }

        final String versionsArgKey = "--versions=";
        if (cmd.startsWith(versionsArgKey)) {
          versions = Integer.parseInt(cmd.substring(versionsArgKey.length()));
          continue;
        }

        final String newNameArgKey = "--new.name=";
        if (cmd.startsWith(newNameArgKey)) {
          newTableName = cmd.substring(newNameArgKey.length());
          continue;
        }

        final String peerAdrArgKey = "--peer.adr=";
        if (cmd.startsWith(peerAdrArgKey)) {
          peerAddress = cmd.substring(peerAdrArgKey.length());
          continue;
        }

        final String familiesArgKey = "--families=";
        if (cmd.startsWith(familiesArgKey)) {
          families = cmd.substring(familiesArgKey.length());
          continue;
        }

        if (cmd.startsWith("--all.cells")) {
          allCells = true;
          continue;
        }

        if (i == args.length-1) {
          tableName = cmd;
        } else {
          printUsage("Invalid argument '" + cmd + "'" );
          return false;
        }
      }
      if (newTableName == null && peerAddress == null) {
        printUsage("At least a new table name or a " +
            "peer address must be specified");
        return false;
      }
      if (startTime > endTime) {
        printUsage("Invalid time range filter: starttime=" + startTime + " >  endtime=" + endTime);
        return false;
      }
    } catch (Exception e) {
      e.printStackTrace();
      printUsage("Can't start because " + e.getMessage());
      return false;
    }
    return true;
  }

  /**
   * Main entry point.
   *
   * @param args  The command line parameters.
   * @throws Exception When running the job fails.
   */
  public static void main(String[] args) throws Exception {
    int ret = ToolRunner.run(new CopyTable(HBaseConfiguration.create()), args);
    System.exit(ret);
  }

  @Override
  public int run(String[] args) throws Exception {
    String[] otherArgs = new GenericOptionsParser(getConf(), args).getRemainingArgs();
    Job job = createSubmittableJob(getConf(), otherArgs);
    if (job == null) return 1;
    return job.waitForCompletion(true) ? 0 : 1;
  }
}


text:
class AddColsToCampus < ActiveRecord::Migration
  def change
    add_column :campuses, :city, :string
    add_column :campuses, :state, :string
    add_column :campuses, :zip, :string
    add_column :campuses, :picture_url, :string
  end
end


text:
<?php

namespace app\modules\factory\models;

use Yii;

/**
 * This is the model class for table "polyiigon_module_field".
 *
 * @property integer $id
 * @property string $title
 * @property integer $polyiigon_module_template_field_id
 * @property integer $polyiigon_module_id
 *
 * @property PolyiigonModule $polyiigonModule
 * @property PolyiigonModuleTemplateField $polyiigonModuleTemplateField
 */
class PolyiigonModuleField extends \yii\db\ActiveRecord implements yii\db\ActiveRecordInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'polyiigon_module_field';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'polyiigon_module_template_field_id', 'polyiigon_module_id'], 'required'],
            [['polyiigon_module_template_field_id', 'polyiigon_module_id'], 'integer'],
            [['title'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'polyiigon_module_template_field_id' => 'Polyiigon Module Template Field ID',
            'polyiigon_module_id' => 'Polyiigon Module ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPolyiigonModule()
    {
        return $this->hasOne(PolyiigonModule::className(), ['id' => 'polyiigon_module_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPolyiigonModuleTemplateField()
    {
        return $this->hasOne(PolyiigonModuleTemplateField::className(), ['id' => 'polyiigon_module_template_field_id']);
    }
}


text:
package com.ning.pummel.cli;

import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
import org.skife.cli.Arguments;
import org.skife.cli.Command;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.concurrent.Callable;

@Command(name="analyze", description = "generate some descriptive stats on a file of times, such as generated by benchmark")
public class Analyze  implements Callable<Void>
{

    @Arguments(title = "url-file", description = "Optional file to take times from, if not given will use stdin")
    public File urlFile;

    public Void call() throws Exception
    {
        final BufferedReader in ;
        if (urlFile != null) {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(urlFile)));
        }
        else {
            in = new BufferedReader(new InputStreamReader(System.in));
        }

        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (String line = in.readLine(); line != null; line = in.readLine()) {
            long val = Long.parseLong(line);
            stats.addValue(val);
        }

        System.out.printf("n\t%d\n", stats.getN());
        System.out.printf("max\t%f\n", stats.getMax());
        System.out.printf("mean\t%f\n", stats.getMean());
        System.out.printf("99.9%%\t%f\n", stats.getPercentile(99.9));
        System.out.printf("99%%\t%f\n", stats.getPercentile(99));
        System.out.printf("90%%\t%f\n", stats.getPercentile(90));
        System.out.printf("80%%\t%f\n", stats.getPercentile(80));
        System.out.printf("50%%\t%f\n", stats.getPercentile(50));
        return null;
    }
}


text:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import socket
import re
import requests
from ca import setup_certs
import settings
import random
from google_connection import setup_google_connection
from multiprocessing import Process
from threading import Thread, Semaphore, Lock
import time
from enum import Enum

class RangeRequestStatus(Enum):
    ready = 0
    retrying = 1
    succeeded = 2
    failed = 3

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    pass

class HopeAppRequestHandler(BaseHTTPRequestHandler):
    TARGET_SCHEME = None

    def do_GET(self):
        self.do("GET")
        return None

    def do_HEAD(self):
        self.do("HEAD")
        return None

    def do_DELETE(self):
        self.do("DELETE")
        return None

    def do_PUT(self):
        self.do("PUT")
        return None

    def do_POST(self):
        self.do("POST")
        return None

    # It breaks when started without console, so make it silent.
    def log_message(self, message, *args):
        try:
            settings.logger.info(('"Host: %s" ' + message) % ((self.headers['host'],) + args))
        except RuntimeError:
            pass
        return

    def do(self, method):
        host = self.headers['host']
        if host.startswith('127.0.0.1') or host.startswith('localhost'):
            self.send_response(200)
            self.end_headers()
            self.wfile.write("Hope app server")
            return None

        headers = {key: value for key, value in self.headers.items()}
        url = self.setup_google_headers(headers)

        if 'content-length' in self.headers:
            body = self.rfile.read(int(self.headers['content-length']))
        else:
            body = None

        if method == "GET" and self.guess_range_required(headers):
            r = requests.head(url=url, data=body, headers=headers, allow_redirects=False)
            size = int(r.headers['Source-Content-Length']) if 'Source-Content-Length' in r.headers else 0
            if str(r.status_code).startswith('2') and size > settings.range_required_size:
                if "range" in headers:
                    range_bytes = headers["range"].split('=')[1].split('-')
                    start = int(range_bytes[0])
                    target = int(range_bytes[1]) if range_bytes[1] else start + size - 1
                else:
                    start = 0
                    target = size - 1
                self.make_range_requests(headers, start, target, r)
            else:
                self.make_normal_requests(method, url, body, headers)

        else:
            self.make_normal_requests(method, url, body, headers)

        return None

    def setup_google_headers(self, headers):
        host = self.headers['host']
        app_id = self.get_app_id()
        if self.TARGET_SCHEME == 'http':
            target_url = self.path.replace("http", self.TARGET_SCHEME)
        else:
            target_url = "https://" + host + self.path

        headers['target_url'] = target_url
        headers["host"] = app_id + ".appspot.com"

        if settings.using_dev_app_engine:
            url = "http://localhost:9000/hope/"
        else:
            url = "https://%s.appspot.com/hope/" % app_id
            setup_google_connection()

        return url

    def get_app_id(self):
        for key, value in settings.domain_use_specific_app.items():
            if key in self.headers['host']:
                return value

        return random.choice(settings.app_ids)

    def send_common_headers(self, response):
        self.send_response(response.status_code)
        self.pass_headers(response)
        self.send_header('content-length', len(response.content))
        self.end_headers()

    def make_normal_requests(self, method, url, body, headers):
        try:
            r = requests.request(method=method, url=url, data=body, headers=headers,
                                 allow_redirects=False, timeout=settings.timeout)
            self.send_common_headers(r)
            self.wfile.write(r.content)
            self.wfile.close()
        except requests.exceptions.RequestException, socket.error:
            self.wfile.close()

    def make_range_requests(self, headers, start, target, head_response):
        try:
            is_original_range_request = True if 'range' in headers else False
            headers.pop('if_modified_since', None)
            range_bytes = "bytes=%s-%s" % (start, start + settings.range_split_size - 1)
            headers['range'] = range_bytes

            # first request
            url = self.setup_google_headers(headers)  # reset google app to avoid OverQuotaError
            r = requests.get(url=url, headers=headers, allow_redirects=False)
            if r.status_code == 206:
                if is_original_range_request:
                    self.send_response(206)
                    self.pass_headers(r, ignore={'content-range'})
                    self.send_header('content-range', 'bytes %s-%s/*' % (start, target))
                else:
                    self.send_response(200)
                    self.pass_headers(head_response)

                self.send_header('content-length', target - start + 1)
                self.end_headers()
                self.wfile.write(r.content)
            else:
                self.send_error(500)
                self.end_headers()
                self.wfile.close()
            start += settings.range_split_size

            # the rest range requests
            requests_left, size_left = divmod(target - start + 1, settings.range_split_size)
            total_requests = requests_left if size_left == 0 else requests_left + 1
            data_splits = [RangeRequestStatus.ready] * total_requests
            data_lock = Lock()
            threads = []
            semaphore = Semaphore(settings.range_concurrent_requests)
            for index in range(total_requests):
                range_bytes = "bytes=%s-%s" % (start, min(start + settings.range_split_size - 1, target))
                headers_copy = dict(headers)
                headers_copy['range'] = range_bytes
                threads.append(Thread(target=self.fetch_range_data, args=(semaphore, headers_copy, data_splits,
                                                                          data_lock, index)))
                start += settings.range_split_size

            threads.append(Thread(target=self.write_range_data, args=(data_splits, data_lock)))
            for thread in threads:
                thread.start()
            for thread in threads:
                thread.join()

            self.wfile.close()
        except requests.exceptions.RequestException, socket.error:
            self.wfile.close()

    @staticmethod
    def range_progress_inspect(data_splits):
        inspect = []
        for item in data_splits:
            if isinstance(item, RangeRequestStatus):
                inspect.append(item.name)
            else:
                inspect.append(len(item))
        sent_count = 0
        for item in inspect:
            if item == RangeRequestStatus.succeeded.name:
                sent_count += 1
            else:
                break
        print(['sent * %s' % sent_count] + inspect[sent_count:])

    def write_range_data(self, data_splits, data_lock):
        for index in range(len(data_splits)):
            while True:
                data_lock.acquire()

                # self.range_progress_inspect(data_splits)

                content = data_splits[index]
                if content is RangeRequestStatus.ready or content is RangeRequestStatus.retrying:
                    data_lock.release()
                    if RangeRequestStatus.failed in data_splits:
                        self.wfile.close()
                        return
                    else:
                        time.sleep(0.5)
                else:
                    try:
                        self.wfile.write(content)
                        data_splits[index] = RangeRequestStatus.succeeded
                        # if index == len(data_splits) - 1:
                        #     self.range_progress_inspect(data_splits)
                        data_lock.release()
                        break
                    except socket.error:
                        data_lock.release()
                        self.wfile.close()
                        return None

    def fetch_range_data(self, semaphore, headers, data, data_lock, index):
        semaphore.acquire()
        if self.wfile.closed:
            data_lock.acquire()
            data[index] = RangeRequestStatus.failed
            data_lock.release()
            semaphore.release()
            return None

        for _ in range(5):
            url = self.setup_google_headers(headers)  # reset google app to avoid OverQuotaError
            try:
                r = requests.get(url=url, headers=headers, allow_redirects=False, timeout=settings.timeout)
            except requests.exceptions.RequestException:
                data_lock.acquire()
                data[index] = RangeRequestStatus.retrying
                data_lock.release()
                continue

            data_lock.acquire()
            if r.status_code == 206:
                data[index] = r.content
                data_lock.release()
                break
            else:
                data[index] = RangeRequestStatus.retrying
                data_lock.release()

        data_lock.acquire()
        if data[index] is RangeRequestStatus.retrying:
            data[index] = RangeRequestStatus.failed
        data_lock.release()

        semaphore.release()

    @staticmethod
    def guess_range_required(headers):
        url = re.sub(r'\?.*', '', headers['target_url']).lower()
        for extension in settings.large_file_extensions:
            if url.endswith(extension):
                return True

        if 'range' in headers:
            return True

        return False

    def pass_headers(self, response, ignore=None):
        headers_to_ignore = {'content-encoding', 'content-length', 'transfer-encoding',
                             'connection', 'source-content-length'}
        if ignore:
            headers_to_ignore.update(ignore)
        for header in response.headers:
            if header not in headers_to_ignore:
                if header.startswith('set-cookie-'):
                    self.send_header('set-cookie', response.headers[header])
                else:
                    self.send_header(header, response.headers[header])

class HopeAppHttpRequestHandler(HopeAppRequestHandler):
    TARGET_SCHEME = 'http'

class HopeAppHttpsRequestHandler(HopeAppRequestHandler):
    TARGET_SCHEME = 'https'

def run_app_http_server():
    server = ThreadingHTTPServer(settings.app_http_server_address, HopeAppHttpRequestHandler)
    server.serve_forever()

def run_app_https_server():
    server = ThreadingHTTPServer(settings.app_https_server_address, HopeAppHttpsRequestHandler)
    server.serve_forever()

if __name__ == '__main__':
    setup_certs()
    processes = [
        Process(target=run_app_http_server),
        Process(target=run_app_https_server)
    ]

    for process in processes:
        process.start()
    for process in processes:
        process.join()


text:
package org.sagebionetworks.table.cluster.view.filter;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.jdo.KeyFactory;
import org.sagebionetworks.repo.model.message.ChangeMessage;
import org.sagebionetworks.repo.model.table.ReplicationType;
import org.sagebionetworks.repo.model.table.SubType;
import org.sagebionetworks.util.ValidateArgument;

/**
 * ViewFilter for a scope defined by a hierarchy of parentIds
 *
 */
public class HierarchicaFilter extends AbstractViewFilter {

	protected final Set<Long> parentIds;

	public HierarchicaFilter(ReplicationType mainType, Set<SubType> subTypes, Set<Long> scope) {
		this(mainType, subTypes, null, null, scope, false);
	}

	public HierarchicaFilter(ReplicationType mainType, Set<SubType> subTypes, Set<Long> limitObjectIds,
			Set<String> excludeKeys, Set<Long> scope, boolean excludeDerivedKeys) {
		super(mainType, subTypes, limitObjectIds, excludeKeys, excludeDerivedKeys);
		ValidateArgument.required(scope, "scope");
		this.parentIds = scope;
		this.params.put("parentIds", scope);
	}

	@Override
	public boolean isEmpty() {
		return this.parentIds.isEmpty();
	}

	@Override
	public String getFilterSql() {
		return super.getFilterSql() + " AND R.PARENT_ID IN (:parentIds) AND R.OBJECT_VERSION = R.CURRENT_VERSION";
	}

	@Override
	public String getObjectIdFilterSql() {
		// this filter includes all versions of each object.
		return super.getFilterSql() + " AND R.PARENT_ID IN (:parentIds)";
	}

	public Set<Long> getParentIds() {
		return parentIds;
	}

	@Override
	public Builder newBuilder() {
		return new Builder(mainType, subTypes, limitObjectIds, excludeKeys, parentIds, excludeDerivedKeys);
	}

	@Override
	public Optional<List<ChangeMessage>> getSubViews() {
		if (ReplicationType.ENTITY.equals(mainType) && parentIds.size() > 1) {
			return Optional.of(parentIds.stream().map(p -> new ChangeMessage().setObjectId(KeyFactory.keyToString(p))
					.setObjectType(ObjectType.ENTITY_CONTAINER)).collect(Collectors.toList()));
		} else {
			return Optional.empty();
		}
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + Objects.hash(parentIds);
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (!(obj instanceof HierarchicaFilter)) {
			return false;
		}
		HierarchicaFilter other = (HierarchicaFilter) obj;
		return Objects.equals(parentIds, other.parentIds);
	}

	@Override
	public String toString() {
		return "HierarchyFilter [scope=" + parentIds + ", mainType=" + mainType + ", subTypes=" + subTypes
				+ ", limitObjectIds=" + limitObjectIds + ", excludeKeys=" + excludeKeys + ", params=" + params + "]";
	}

	public static class Builder extends AbstractBuilder {

		Set<Long> scope;

		public Builder(ReplicationType mainType, Set<SubType> subTypes, Set<Long> limitObjectIds,
				Set<String> excludeKeys, Set<Long> scope, boolean excludeDerivedKeys) {
			super(mainType, subTypes, limitObjectIds, excludeKeys, excludeDerivedKeys);
			this.scope = scope;
		}

		@Override
		public ViewFilter build() {
			return new HierarchicaFilter(mainType, subTypes, limitObjectIds, excludeKeys, scope, excludeDerivedKeys);
		}

	}

}


text:
<LINK REL="stylesheet" HREF="../static/styles.css">

<TITLE>System::setSoftwareFormat</TITLE>

Firelight Technologies FMOD Studio API

System::setSoftwareFormat

Sets the output format for the software mixer.

If loading Studio banks, this must be called with speakermode corresponding to the project's output format if there is a possibility
of the output audio device not matching the project's format.  Any differences between the project format and the system's speakermode
will cause the mix to sound wrong.

If not loading Studio banks, do not call this unless you explicity want to change a setting from the default.
FMOD will default to the speaker mode and sample rate that the OS / output prefers.

C++ Syntax

FMOD_RESULT System::setSoftwareFormat(
  int samplerate,
  FMOD_SPEAKERMODE speakermode,
  int numrawspeakers
);

C Syntax

FMOD_RESULT FMOD_System_SetSoftwareFormat(
  FMOD_SYSTEM *system,
  int samplerate,
  FMOD_SPEAKERMODE speakermode,
  int numrawspeakers
);

C# Syntax

RESULT System.setSoftwareFormat(
  int samplerate,
  SPEAKERMODE speakermode,
  int numrawspeakers
);

Parameters

samplerate

Sample rate in Hz, that the software mixer will run at.  Specify values between 8000 and 192000.

speakermode

Speaker setup for the software mixer.

numrawspeakers

Number of output channels / speakers to initialize the sound card to in FMOD_SPEAKERMODE_RAW mode.  Optional.  Specify 0 to ignore.  Maximum of FMOD_MAX_CHANNEL_WIDTH.

Return Values

If the function succeeds then the return value is FMOD_OK.

If the function fails then the return value will be one of the values defined in the FMOD_RESULT enumeration.

Remarks

This function cannot be called after FMOD is already activated, it must be called before System::init, or after
System::close.

See Also

System::getSoftwareFormat

FMOD_SPEAKERMODE

System::init

System::close

FMOD_MAX_CHANNEL_WIDTH

Version 1.08.02 Built on Apr 14, 2016


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>FSDirectory.OpenInput Method (String, Int32)</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache Lucene.Net 2.4.0 Class Library API

FSDirectory.OpenInput Method (String, Int32)

public override IndexInput OpenInput(
   string name,
   int bufferSize
);

See Also

        FSDirectory Class | Lucene.Net.Store Namespace | FSDirectory.OpenInput Overload List

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="OpenInput method">
        </param>
        <param name="Keyword" value="OpenInput method, FSDirectory class">
        </param>
        <param name="Keyword" value="FSDirectory.OpenInput method">
        </param>
      </object>

Generated from assembly Lucene.Net [2.4.0.2]


text:
void GenerateAssetEntropy(uint256& entropy, const COutPoint& prevout, const uint256& contracthash)
{
    // E : entropy
    // I : prevout
    // C : contract
    // E = H( H(I) || H(C) )
    std::vector<uint256> leaves;
    leaves.reserve(2);
    leaves.push_back(SerializeHash(prevout, SER_GETHASH, 0));
    leaves.push_back(contracthash);
    entropy = ComputeFastMerkleRoot(leaves);
}

void CalculateAsset(CAsset& asset, const uint256& entropy)
{
    static const uint256 kZero = uint256S("0x0000000000000000000000000000000000000000000000000000000000000000");
    // H_a : asset tag
    // E   : entropy
    // H_a = H( E || 0 )
    std::vector<uint256> leaves;
    leaves.reserve(2);
    leaves.push_back(entropy);
    leaves.push_back(kZero);
    asset = CAsset(ComputeFastMerkleRoot(leaves));
}

void CalculateReissuanceToken(CAsset& reissuanceToken, const uint256& entropy, bool fConfidential)
{
    static const uint256 kOne = uint256S("0x0000000000000000000000000000000000000000000000000000000000000001");
    static const uint256 kTwo = uint256S("0x0000000000000000000000000000000000000000000000000000000000000002");
    // H_a : asset reissuance tag
    // E   : entropy
    // if not fConfidential:
    //     H_a = H( E || 1 )
    // else
    //     H_a = H( E || 2 )
    std::vector<uint256> leaves;
    leaves.reserve(2);
    leaves.push_back(entropy);
    leaves.push_back(fConfidential? kTwo: kOne);
    reissuanceToken = CAsset(ComputeFastMerkleRoot(leaves));
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>My first post | Make Coding Easier</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<link rel="stylesheet" href="/css/main.css">

	<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">

	<link rel="canonical" href="http://example.com/2015/01/24/my_post.html">

	<link rel="alternate" type="application/atom+xml" title="Make Coding Easier" href="http://example.com/feed.xml" />

	<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

	<link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,700italic,400italic" rel="stylesheet" type="text/css">

			Make Coding Easier

					About

My first post

    January 24, 2015

Powered by Jekyll with Type Theme


text:
FbfDias

{{ HTML::ul($errors->all()) }}

{{ Form::open(array('url' => 'fbf_dias')) }}

{{ Form::label('dia', 'Dia') }}
{{ Form::text('dia', Input::old('dia'), array('class' => 'form-control', 'required')) }}

{{ Form::label('descricao', 'Descricao') }}
{{ Form::text('descricao', Input::old('descricao'), array('class' => 'form-control', '')) }}

	{{ Form::submit('Cadastrar!', array('class' => 'btn btn-primary')) }}

{{ Form::close() }}


text:
layout: compress
---
<!DOCTYPE html>
<html>
  {% include head.html %}
  <body>
    <main class="wrapper">
      {% include header.html %}
      {{ content }}
      {% include footer.html %}
      {% include googleanalytics.html %}
    </main>
  </body>
</html>


text:
<?php

namespace ZfTable\Decorator;

use Zend\ServiceManager\AbstractPluginManager;

class DecoratorPluginManager extends AbstractPluginManager
{

    /**
     * Default set of helpers
     *
     * @var array
     */
    protected $invokableClasses = array(

        'cellattr' => '\ZfTable\Decorator\Cell\AttrDecorator',
        'cellvarattr' => '\ZfTable\Decorator\Cell\VarAttrDecorator',
        'cellclass' => '\ZfTable\Decorator\Cell\ClassDecorator',
        'cellicon' => '\ZfTable\Decorator\Cell\Icon',
        'cellmapper' => '\ZfTable\Decorator\Cell\Mapper',
        'celllink' => '\ZfTable\Decorator\Cell\Link',
        'celltemplate' => '\ZfTable\Decorator\Cell\Template',
        'celleditable' => '\ZfTable\Decorator\Cell\Editable',
        'cellcallable' => '\ZfTable\Decorator\Cell\CallableDecorator',

        'rowclass' => '\ZfTable\Decorator\Row\ClassDecorator',
        'rowvarattr' => '\ZfTable\Decorator\Row\VarAttr',
        'rowseparatable' => '\ZfTable\Decorator\Row\Separatable',
    );

    /**
     * Don't share header by default
     *
     * @var bool
     */
    protected $shareByDefault = false;

    /**
     * @param mixed $plugin
     */
    public function validatePlugin($plugin)
    {
        if ($plugin instanceof AbstractDecorator) {
            return;
        }
        throw new \DomainException('Invalid Decorator Implementation');
    }
}


text:
  La Chapelle-Saint-Laud est
       un village
       localisé dans le département de Maine-et-Loire en Pays de la Loire. Elle comptait 583 habitants en 2008.

Si vous pensez emmenager à La Chapelle-Saint-Laud, vous pourrez facilement trouver une maison à vendre.

À proximité de La Chapelle-Saint-Laud sont situées les communes de
Seiches-sur-le-Loir à 5 km, 3 019 habitants,
Montreuil-sur-Loir située à 7 km, 450 habitants,
Beauvau localisée à 5 km, 238 habitants,
Jarzé située à 8 km, 1 489 habitants,
Corzé à 8 km, 1 581 habitants,
Lézigné localisée à 3 km, 700 habitants,
 entre autres. De plus, La Chapelle-Saint-Laud est située à seulement 23 km de Angers.

À La Chapelle-Saint-Laud, la valorisation moyenne à la vente d'un appartement se situe à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 701 € du m². À la location le prix moyen se situe à 19,23 € du m² mensuel.

La commune compte quelques  équipements, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.

Le nombre d'habitations, à La Chapelle-Saint-Laud, était réparti en 2011 en trois appartements et 267 maisons soit
 un marché relativement équilibré.


text:
package org.libx4j.xsb.compiler.processor.model.element;

import java.util.Arrays;
import java.util.Collection;

import org.libx4j.xsb.compiler.lang.UniqueQName;
import org.libx4j.xsb.compiler.processor.model.Model;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public final class ListModel extends SimpleTypeModel<SimpleTypeModel<?>> {
  private SimpleTypeModel<?> itemType = null;
  private UnionModel unionType = null;

  protected ListModel(final Node node, final Model parent) {
    super(node, parent);
    final NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
      final Node attribute = attributes.item(i);
      if ("itemType".equals(attribute.getLocalName()))
        setItemType(SimpleTypeModel.Reference.parseSimpleType(UniqueQName.getInstance(parseQNameValue(attribute.getNodeValue(), node))));
    }
  }

  public final void setItemType(final SimpleTypeModel<?> itemType) {
    this.itemType = itemType;
  }

  public final void setItemType(final UnionModel unionType) {
    this.unionType = unionType;
  }

  public final Collection<SimpleTypeModel<?>> getItemType() {
    if (unionType != null)
      return unionType.getNormalizedMemberTypes();

    if (itemType != null)
      return Arrays.<SimpleTypeModel<?>>asList(itemType);

    return null;
  }
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace OpenRiaServices.DomainServices.Tools.Test
{
    /// <summary>
    /// Summary description for NamingTests
    /// </summary>
    [TestClass]
    public class NamingTests
    {
        // Singular and expected plural forms for plural test below
        private static string[] _plurals =
        {
            "Product", "Products",
            "Entity", "Entities",
            "Unix", "Unixes",
            "Munch", "Munches",
            "Progress", "Progresses",
            "Marsh", "Marshes",
            "Funny", "Funnies",
            "Money", "Moneys",
            "Today", "Todays",
            "Toy", "Toys",
            "Products", "Products"      // already plural
        };

        public NamingTests()
        {
        }

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        [TestMethod]
        [Description("Tests all edge cases of Naming.MakePluralName")]
        public void TestPlurals()
        {
            for (int i = 0; i < _plurals.Length; i += 2)
            {
                string singular = _plurals[i];
                string expectedPlural = _plurals[i+1];
                string generatedPlural = Naming.MakePluralName(singular);
                Assert.AreEqual(expectedPlural, generatedPlural);
            }
        }
    }
}


text:
import _ from "lodash";

let styleTypeHandlers = {
    isArray(entity) {
        return merge(entity);
    },
    isObject(entity) {
        return entity;
    },
    isFunction(entity, collector) {
        return entity(new StylerObject(collector));
    },
    isStyler(entity) {
        return entity();
    }
}

let determineType = entity => {
    if(_.isArray(entity)) {return "isArray"}
    if(entity._isStyler) {return "isStyler"}
    else if (_.isFunction(entity)) {return "isFunction"}
    else if (_.isObject(entity)) {return "isObject"}
    else if(_.isString(entity)) {return "isString"}
    return null;
}

let merge = (stylesArr) => {
    return _.chain(stylesArr)
            .map(entity => styleTypeHandlers[determineType(entity)].bind(null, entity))
            .reduce((outputObj, argFunc) => {
                _.assign(outputObj, argFunc(outputObj));

                return outputObj;
            }, {})
            .value();
}

let functionalMethods = {
    merge(...args) {
        let newArgs = [_.assign({}, this), ...args];

        return new StylerObject(merge(newArgs), this);
    },
    map(mapFunc) {
       let data = this instanceof StylerObject ? this : this._getStyles(),
           result = _.mapValues(data, mapFunc);

        return new StylerObject(result, this);
    },
    reduce(reduceFunc) {
        let data = this instanceof StylerObject ? this : this._getStyles(),
            result = _.reduce(data, reduceFunc, {});

        return new StylerObject(result, this);
    },
    filter(filterFunc) {
        let data = this instanceof StylerObject ? this : this._getStyles();
        let result = _.reduce(data, (accum, val, key) => {
            if(filterFunc(val, key)) {
                accum[key] = val;
            }
            return accum;
        }, {});

        return new StylerObject(result, this);
    },
    get(keysArr) {
        let currentStyles = this instanceof StylerObject ? this : this._getStyles(),
            accum = {};

        for(let i = 0, l = keysArr.length; i<l; i++) {
            if(currentStyles[keysArr[i]]) {
                accum[keysArr[i]] = currentStyles[keysArr[i]];
            }
        }

        return new StylerObject(accum, this);
    },
    forIn(iteratee) {
        let data = this instanceof StylerObject ? this : this._getStyles();

        _.forIn(data, iteratee);

        return data;
    },
    update(...args) {
        let data = this instanceof StylerObject ? this : this._getStyles(),
            mergedArgs = merge(args),
            styles = {};

        for(let prop in data) {
            if(data[prop]) {
                if(mergedArgs.hasOwnProperty(prop)) {
                    if(!Object.is(mergedArgs[prop], null)) {
                        styles[prop] = mergedArgs[prop];
                    }
                } else {
                    styles[prop] = data[prop];
                }
            }
        }

        return new StylerObject(styles, this);
    }
}

class StylerObject {
    constructor(result) {
        for (let prop in result) {
            this[prop] = result[prop];
        }
    }
    map(mapFunc) {
        return functionalMethods.map.call(this, mapFunc);
    }
    filter(filterFunc) {
        return functionalMethods.filter.call(this, filterFunc);
    }
    get(keysArr) {
        return functionalMethods.get.call(this, keysArr);
    }
    merge(...args) {
        return functionalMethods.merge.call(this, ...args);
    }
    reduce(reduceFunc) {
        return functionalMethods.reduce.call(this, reduceFunc);
    }
    forIn(iteratee) {
        return functionalMethods.forIn.call(this, iteratee);
    }
    update(...args) {
        return functionalMethods.update.call(this, ...args);
    }
    toStyler() {
        return new Styler().create(this);
    }
}

class StandardStyler {
    constructor(stylerInstance, ...initStyles) {
        Object.defineProperty(this, "_initStyles", { value: initStyles});
        Object.defineProperty(this, "_stylerInstance", { value: stylerInstance});
    }
    _getStyles(...args) {
        let stylesArr = this._initStyles.concat(args);

        return new StylerObject(merge(stylesArr), this);
    }
}

class Styler {
    constructor(initConfig) {
    }
    create(...initStyles) {
        let styler = new StandardStyler(this, ...initStyles),
            stylerFunc = styler._getStyles.bind(styler);

        _.forEach(functionalMethods, (propVal, propName) => {
            Object.defineProperty(stylerFunc, propName, {
                value: typeof propVal === "function" ? propVal.bind(styler) : propVal
            });
        });

        Object.defineProperty(stylerFunc, "_isStyler", {value: true});

        return stylerFunc;
    }
}

export default {
    Styler: new Styler(),
    StylerObject: StylerObject
}


text:
/// <autosync enabled="true" />
/// <reference path="bootstrap.js" />
/// <reference path="html5shiv.js" />
/// <reference path="jquery.tagsinput.js" />
/// <reference path="jquery.unobtrusive-ajax.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
/// <reference path="jquery-1.11.2.js" />
/// <reference path="markdown.js" />
/// <reference path="modernizr-2.8.3.js" />
/// <reference path="highlight/highlight.pack.js" />
/// <reference path="editor/Gruntfile.js" />
/// <reference path="editor/kindeditor-all-min.js" />
/// <reference path="editor/kindeditor-all.js" />
/// <reference path="editor/lang/ar.js" />
/// <reference path="editor/lang/en.js" />
/// <reference path="editor/lang/ko.js" />
/// <reference path="editor/lang/ru.js" />
/// <reference path="editor/lang/zh-CN.js" />
/// <reference path="editor/lang/zh-TW.js" />
/// <reference path="editor/lib/jquery.min.js" />
/// <reference path="editor/lib/firebug-lite/build/firebug-lite-beta.js" />
/// <reference path="editor/lib/firebug-lite/build/firebug-lite-debug.js" />
/// <reference path="editor/lib/firebug-lite/build/firebug-lite.js" />
/// <reference path="editor/lib/firebug-lite/build/chrome-extension/contentScript.js" />
/// <reference path="editor/lib/firebug-lite/build/chrome-extension/firebug-lite.js" />
/// <reference path="editor/lib/firebug-lite/build/chrome-extension/googleChrome.js" />
/// <reference path="editor/lib/firebug-lite/build/chrome-extension-beta/contentScript.js" />
/// <reference path="editor/lib/firebug-lite/build/chrome-extension-beta/firebug-lite-beta.js" />
/// <reference path="editor/lib/firebug-lite/build/chrome-extension-beta/googleChrome.js" />
/// <reference path="editor/lib/qunit/qunit.js" />
/// <reference path="editor/plugins/anchor/anchor.js" />
/// <reference path="editor/plugins/autoheight/autoheight.js" />
/// <reference path="editor/plugins/baidumap/baidumap.js" />
/// <reference path="editor/plugins/clearhtml/clearhtml.js" />
/// <reference path="editor/plugins/code/code.js" />
/// <reference path="editor/plugins/code/prettify.js" />
/// <reference path="editor/plugins/emoticons/emoticons.js" />
/// <reference path="editor/plugins/filemanager/filemanager.js" />
/// <reference path="editor/plugins/fixtoolbar/fixtoolbar.js" />
/// <reference path="editor/plugins/flash/flash.js" />
/// <reference path="editor/plugins/image/image.js" />
/// <reference path="editor/plugins/insertfile/insertfile.js" />
/// <reference path="editor/plugins/lineheight/lineheight.js" />
/// <reference path="editor/plugins/link/link.js" />
/// <reference path="editor/plugins/map/map.js" />
/// <reference path="editor/plugins/media/media.js" />
/// <reference path="editor/plugins/multiimage/multiimage.js" />
/// <reference path="editor/plugins/pagebreak/pagebreak.js" />
/// <reference path="editor/plugins/plainpaste/plainpaste.js" />
/// <reference path="editor/plugins/preview/preview.js" />
/// <reference path="editor/plugins/quickformat/quickformat.js" />
/// <reference path="editor/plugins/table/table.js" />
/// <reference path="editor/plugins/template/template.js" />
/// <reference path="editor/plugins/wordpaste/wordpaste.js" />
/// <reference path="editor/src/ajax.js" />
/// <reference path="editor/src/cmd.js" />
/// <reference path="editor/src/colorpicker.js" />
/// <reference path="editor/src/config.js" />
/// <reference path="editor/src/core.js" />
/// <reference path="editor/src/dialog.js" />
/// <reference path="editor/src/edit.js" />
/// <reference path="editor/src/event.js" />
/// <reference path="editor/src/footer.js" />
/// <reference path="editor/src/header.js" />
/// <reference path="editor/src/html.js" />
/// <reference path="editor/src/main.js" />
/// <reference path="editor/src/menu.js" />
/// <reference path="editor/src/node.js" />
/// <reference path="editor/src/range.js" />
/// <reference path="editor/src/selector.js" />
/// <reference path="editor/src/tabs.js" />
/// <reference path="editor/src/toolbar.js" />
/// <reference path="editor/src/uploadbutton.js" />
/// <reference path="editor/src/widget.js" />
/// <reference path="editor/test/cmd.js" />
/// <reference path="editor/test/core.js" />
/// <reference path="editor/test/edit.js" />
/// <reference path="editor/test/editor.js" />
/// <reference path="editor/test/event.js" />
/// <reference path="editor/test/html.js" />
/// <reference path="editor/test/menu.js" />
/// <reference path="editor/test/node.js" />
/// <reference path="editor/test/range.js" />
/// <reference path="editor/test/selector.js" />


text:
package net.zomis.spring.games.messages;

public class CreateGameRequest {

    private String playerName;
    private String password;
    private Object playerConfig;
    private Object gameConfig;

    public String getPassword() {
        return password;
    }

    public String getPlayerName() {
        return playerName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setPlayerName(String playerName) {
        this.playerName = playerName;
    }

    public Object getGameConfig() {
        return gameConfig;
    }

    public Object getPlayerConfig() {
        return playerConfig;
    }

    public void setGameConfig(Object gameConfig) {
        this.gameConfig = gameConfig;
    }

    public void setPlayerConfig(Object playerConfig) {
        this.playerConfig = playerConfig;
    }

    @Override
    public String toString() {
        return "StartGameRequest{" +
                "playerName='" + playerName + '\'' +
                ", password='" + password + '\'' +
                ", playerConfig=" + playerConfig +
                ", gameConfig=" + gameConfig +
                '}';
    }

}


text:
""" Implementation of WaterFrame.drop(parameters) """

def drop(self, parameters, inplace=True):
    """
    Remove input parameters from WaterFrame.data.

    Parameters
    ----------
        parameters: str, list of str
            Parameters of WaterFrame.data.
        inplace: bool
            If True, Drop in place and return 'True', If False, return a copy of the WaterFrame
            without the input parameters.

    Returns
    -------
        new_wf: WaterFrame
    """
    keys = []
    if isinstance(parameters, str):
        keys.append(parameters)
        keys.append(parameters + '_QC')
    elif isinstance(keys, list):
        for parameter in parameters:
            keys.append(parameter)
            keys.append(parameter + '_QC')

    if inplace:
        self.data.drop(keys, axis=1, inplace=True)
        for key in keys:
            self.vocabulary.pop(key)
        return True
    else:
        new_wf = self.copy()
        new_wf.vocabulary = self.vocabulary.copy()
        new_wf.metadata = self.metadata.copy()
        new_wf.data = self.data.drop(keys, axis=1)
        for key in keys:
            new_wf.vocabulary.pop(key)

        return new_wf


text:
package org.apache.sling.replication.agent;

import java.util.Collection;
import java.util.SortedSet;
import org.apache.sling.replication.communication.ReplicationActionType;

/**
 * A manager for {@link ReplicationAgent}s
 */
public interface ReplicationAgentsManager {

    /**
     * get agents which can handle the given action on the given paths
     *
     * @param action a {@link ReplicationActionType}
     * @param paths  the paths such agents should be able to handle
     * @return a {@link SortedSet} of {@link ReplicationAgent}s
     */
    SortedSet<ReplicationAgent> getAgentsFor(ReplicationActionType action, String... paths);

    /**
     * get all the agents registered and active in the system
     *
     * @return a Collection of {@link ReplicationAgent}s
     */
    Collection<ReplicationAgent> getAllAvailableAgents();
}


text:
// Package eureka provides a Eureka registry
package eureka

/*
	Eureka is a plugin for Netflix Eureka service discovery
*/

import (
	"net/http"
	"time"

	"golang.org/x/net/context"

	"github.com/hudl/fargo"
	"github.com/micro/go-micro/cmd"
	"github.com/micro/go-micro/registry"
	"github.com/op/go-logging"
)

type fargoConnection interface {
	RegisterInstance(*fargo.Instance) error
	DeregisterInstance(*fargo.Instance) error
	HeartBeatInstance(*fargo.Instance) error
	GetInstance(string, string) (*fargo.Instance, error)
	GetApp(string) (*fargo.Application, error)
	GetApps() (map[string]*fargo.Application, error)
	ScheduleAppUpdates(string, bool, <-chan struct{}) <-chan fargo.AppUpdate
}

type eurekaRegistry struct {
	conn fargoConnection
	opts registry.Options
}

func init() {
	cmd.DefaultRegistries["eureka"] = NewRegistry
	logging.SetLevel(logging.ERROR, "fargo")
}

func newRegistry(opts ...registry.Option) registry.Registry {
	options := registry.Options{
		Context: context.Background(),
	}

	for _, o := range opts {
		o(&options)
	}

	var cAddrs []string
	for _, addr := range options.Addrs {
		if len(addr) == 0 {
			continue
		}
		cAddrs = append(cAddrs, addr)
	}

	if len(cAddrs) == 0 {
		cAddrs = []string{"http://localhost:8080/eureka/v2"}
	}

	if c, ok := options.Context.Value(contextHttpClient{}).(*http.Client); ok {
		fargo.HttpClient = c
	}

	conn := fargo.NewConn(cAddrs...)
	conn.PollInterval = time.Second * 5

	return &eurekaRegistry{
		conn: &conn,
		opts: options,
	}
}

func (e *eurekaRegistry) Register(s *registry.Service, opts ...registry.RegisterOption) error {
	instance, err := serviceToInstance(s)
	if err != nil {
		return err
	}

	if e.instanceRegistered(instance) {
		return e.conn.HeartBeatInstance(instance)
	}

	return e.conn.RegisterInstance(instance)
}

func (e *eurekaRegistry) Deregister(s *registry.Service) error {
	instance, err := serviceToInstance(s)
	if err != nil {
		return err
	}
	return e.conn.DeregisterInstance(instance)
}

func (e *eurekaRegistry) GetService(name string) ([]*registry.Service, error) {
	app, err := e.conn.GetApp(name)
	if err != nil {
		return nil, err
	}
	return appToService(app), nil
}

func (e *eurekaRegistry) ListServices() ([]*registry.Service, error) {
	var services []*registry.Service

	apps, err := e.conn.GetApps()
	if err != nil {
		return nil, err
	}

	for _, app := range apps {
		services = append(services, appToService(app)...)
	}

	return services, nil
}

func (e *eurekaRegistry) Watch() (registry.Watcher, error) {
	return newWatcher(e.conn), nil
}

func (e *eurekaRegistry) String() string {
	return "eureka"
}

func (e *eurekaRegistry) instanceRegistered(instance *fargo.Instance) bool {
	_, err := e.conn.GetInstance(instance.App, instance.UniqueID(*instance))
	return err == nil
}

func NewRegistry(opts ...registry.Option) registry.Registry {
	return newRegistry(opts...)
}


text:
package me.predatorray.bud.lisp.lexer;

public class RightParenthesis extends ConstantToken {

    public RightParenthesis(TextLocation location) {
        super(location, ")");
    }

    @Override
    public void accept(TokenVisitor visitor) {
        visitor.visit(this);
    }
}


text:
<?php

final class PhabricatorHelpEditorProtocolController
  extends PhabricatorHelpController {

  public function shouldAllowPublic() {
    return true;
  }

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();

    $dialog = id(new AphrontDialogView())
      ->setUser($viewer)
      ->setMethod('GET')
      ->setSubmitURI('/settings/panel/display/')
      ->setTitle(pht('Unsupported Editor Protocol'))
      ->appendParagraph(
        pht(
          'Your configured editor URI uses an unsupported protocol. Change '.
          'your settings to use a supported protocol, or ask your '.
          'administrator to add support for the chosen protocol by '.
          'configuring: %s',
          phutil_tag('tt', array(), 'uri.allowed-editor-protocols')))
      ->addSubmitButton(pht('Change Settings'))
      ->addCancelButton('/');

    return id(new AphrontDialogResponse())
      ->setDialog($dialog);
  }

  public static function hasAllowedProtocol($uri) {
    $uri = new PhutilURI($uri);
    $editor_protocol = $uri->getProtocol();
    if (!$editor_protocol) {
      // The URI must have a protocol.
      return false;
    }

    $allowed_key = 'uri.allowed-editor-protocols';
    $allowed_protocols = PhabricatorEnv::getEnvConfig($allowed_key);
    if (empty($allowed_protocols[$editor_protocol])) {
      // The protocol must be on the allowed protocol whitelist.
      return false;
    }

    return true;
  }

}


text:
var ng = angular;
(function() {
  "use strict";
  ng.module('CListApp',['ngRoute'])

  .factory('helloFactory', function() {
    return function(name) {
      this.name = name;
      this.hello = function() {
        return "Hello " + this.name;
      };
    };
  });
  .factory ('searchFactory', function(){
    var factory = {};
    var anyWord = "hope";

    factory.searchAgain= function(searchKey){
      //var newData = [];
      var theWord = searchKey;
      var url = 'http://search.3taps.com?auth_token=11a2ac1d6fd4d8a9dcbd221445790888&retvals=images,price,heading,location&heading='+theWord+'&rpp=20&has_image1'
      function getJSONP(url, cbName){
        var $script = document.createElement('script');
        document.body.appendChild($script);
      }
      $http.get(url)
      .success(function(data){

        console.log(data);
        /*$scope.newData = data;
        $scope.newData.keyword = $scope.NewSearch;
        myDataRef.push($scope.newData);
        console.log($scope.newData);*/
      })
      .error(function(err){
        console.log(err);
      });
      return data;
    };

    return factory;
  })

}());


text:
package com.squarespace.less;

import static com.squarespace.less.model.PropertyMergeMode.COMMA;
import static com.squarespace.less.model.PropertyMergeMode.SPACE;
import static com.squarespace.less.parse.Parselets.RULE_PROPERTY;
import static org.testng.Assert.assertEquals;

import org.testng.annotations.Test;

import com.squarespace.less.core.LessHarness;
import com.squarespace.less.core.LessTestBase;
import com.squarespace.less.model.Node;
import com.squarespace.less.model.CompositeProperty;

public class CompositePropertyTest extends LessTestBase {

  @Test
  public void testEquals() throws LessException {
    assertEquals(prop(list(prop("x"), var("@y"))), prop(list(prop("x"), var("@y"))));
  }

  @Test
  public void testParse() throws LessException {
    LessHarness h = new LessHarness(RULE_PROPERTY);

    Node expected = prop(list(prop("foo-"), var("@var1", true), prop("-bar-"), var("@var2", true)));
    h.parseEquals("foo-@{var1}-bar-@{var2}  :", expected);
  }

  @Test
  public void testRepr() throws LessException {
    CompositeProperty actual = prop(list(prop("x-"), var("@y", true)), SPACE);
    assertEquals(actual.repr(), "x-@{y}+_");

    actual.mergeMode(COMMA);
    assertEquals(actual.repr(), "x-@{y}+");
  }

}


text:
@interface JSONModel : NSObject

-(instancetype)initWithDictionary:(NSMutableDictionary *)jsonObject;

@end


text:
<?php

namespace Plugins\Content\Formathtml\Macros;

use Plugins\Content\Formathtml\Macro;

/**
 * Macro class for anchors
 */
class Anchor extends Macro
{
	/**
	 * Allow macro in partial parsing?
	 *
	 * @var string
	 */
	public $allowPartial = true;

	/**
	 * Returns description of macro, use, and accepted arguments
	 *
	 * @return     array
	 */
	public function description()
	{
		$txt = array();
		$txt['wiki'] = 'Inserts an anchor into a page.';
		$txt['html'] = '
Inserts an anchor into a page.
';
		return $txt['html'];
	}

	/**
	 * Generate macro output
	 *
	 * @return     string
	 */
	public function render()
	{
		$name = $this->args;

		// Did we get a result from the database?
		if ($name)
		{
			// Build and return the link
			return '';
		}
	}
}


text:
package javax.faces.component.html;

import javax.faces.component.UIInput;

import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFComponent;

/**
 * Renders a HTML textarea element.
 *
 */
@JSFComponent
(name = "h:inputTextarea",
clazz = "javax.faces.component.html.HtmlInputTextarea",template=true,
tagClass = "org.apache.myfaces.taglib.html.HtmlInputTextareaTag",
defaultRendererType = "javax.faces.Textarea",
implementz = "javax.faces.component.behavior.ClientBehaviorHolder",
defaultEventName = "valueChange"
)
abstract class _HtmlInputTextarea extends UIInput implements _AccesskeyProperty,
    _UniversalProperties, _FocusBlurProperties, _ChangeSelectProperties,
    _EventProperties, _StyleProperties, _TabindexProperty,
    _DisabledReadonlyProperties, _LabelProperty, _RoleProperty
{

  static public final String COMPONENT_FAMILY =
    "javax.faces.Input";
  static public final String COMPONENT_TYPE =
    "javax.faces.HtmlInputTextarea";

  /**
   * HTML: The width of this element, in characters.
   *
   * @JSFProperty
   *   defaultValue = "Integer.MIN_VALUE"
   */
  public abstract int getCols();

  /**
   * HTML: The height of this element, in characters.
   *
   * @JSFProperty
   *   defaultValue = "Integer.MIN_VALUE"
   */
  public abstract int getRows();

}