text:
package org.jbpm.kie.services.impl;

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

import org.drools.core.command.impl.ExecutableCommand;
import org.drools.core.command.impl.RegistryContext;
import org.drools.core.command.runtime.process.SetProcessInstanceVariablesCommand;
import org.drools.core.command.runtime.process.StartProcessCommand;
import org.drools.core.process.instance.WorkItemManager;
import org.jbpm.process.instance.impl.ProcessInstanceImpl;
import org.jbpm.process.instance.impl.util.VariableUtil;
import org.jbpm.services.api.DeploymentNotFoundException;
import org.jbpm.services.api.DeploymentService;
import org.jbpm.services.api.ProcessInstanceNotFoundException;
import org.jbpm.services.api.ProcessService;
import org.jbpm.services.api.RuntimeDataService;
import org.jbpm.services.api.WorkItemNotFoundException;
import org.jbpm.services.api.model.DeployedUnit;
import org.jbpm.services.api.model.NodeInstanceDesc;
import org.jbpm.services.api.model.ProcessInstanceDesc;
import org.jbpm.services.api.service.ServiceRegistry;
import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl;
import org.jbpm.workflow.instance.node.CompositeNodeInstance;
import org.jbpm.workflow.instance.node.EventNodeInstance;
import org.kie.api.command.Command;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.Context;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.process.NodeInstance;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkflowProcessInstance;
import org.kie.internal.process.CorrelationAwareProcessRuntime;
import org.kie.internal.process.CorrelationKey;
import org.kie.internal.runtime.manager.InternalRuntimeManager;
import org.kie.internal.runtime.manager.SessionNotFoundException;
import org.kie.internal.runtime.manager.context.CaseContext;
import org.kie.internal.runtime.manager.context.CorrelationKeyContext;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProcessServiceImpl implements ProcessService, VariablesAware {

	private static final Logger logger = LoggerFactory.getLogger(ProcessServiceImpl.class);

	protected DeploymentService deploymentService;
	protected RuntimeDataService dataService;

    public ProcessServiceImpl() {
        ServiceRegistry.get().register(ProcessService.class.getSimpleName(), this);
    }

	public void setDeploymentService(DeploymentService deploymentService) {
		this.deploymentService = deploymentService;
	}

	public void setDataService(RuntimeDataService dataService) {
		this.dataService = dataService;
	}

	@Override
	public Long startProcess(String deploymentId, String processId) {

		return startProcess(deploymentId, processId, new HashMap<>());
	}

	@Override
	public Long startProcess(String deploymentId, String processId, Map<String, Object> params) {
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deploymentId);
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + deploymentId);
		}
		if (!deployedUnit.isActive()) {
			throw new DeploymentNotFoundException("Deployments " + deploymentId + " is not active");
		}

		RuntimeManager manager = deployedUnit.getRuntimeManager();

		params = process(params, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
        RuntimeEngine engine = manager.getRuntimeEngine(getContext(params));
        KieSession ksession = engine.getKieSession();
        ProcessInstance pi;
        try {
            pi = ksession.startProcess(processId, params);
            return pi.getId();
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public Long startProcess(String deploymentId, String processId, CorrelationKey correlationKey) {
		return startProcess(deploymentId, processId, correlationKey, new HashMap<>());
	}

	@Override
	public Long startProcess(String deploymentId, String processId, CorrelationKey correlationKey, Map<String, Object> params) {
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deploymentId);
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + deploymentId);
		}
		if (!deployedUnit.isActive()) {
			throw new DeploymentNotFoundException("Deployments " + deploymentId + " is not active");
		}

		RuntimeManager manager = deployedUnit.getRuntimeManager();

		params = process(params, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
        RuntimeEngine engine = manager.getRuntimeEngine(getContext(params));
        KieSession ksession = engine.getKieSession();
        ProcessInstance pi;
        try {
            pi = ((CorrelationAwareProcessRuntime)ksession).startProcess(processId, correlationKey, params);
            return pi.getId();
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	protected Context<?> getContext(Map<String, Object> params) {
	    if (params == null) {
	        return ProcessInstanceIdContext.get();
	    }
	    String caseId = (String) params.get(EnvironmentName.CASE_ID);
	    if (caseId != null && !caseId.isEmpty()) {
	        return CaseContext.get(caseId);
	    }

	    return ProcessInstanceIdContext.get();
	}

	@Override
	public void abortProcessInstance(Long processInstanceId) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
		if (piDesc == null || piDesc.getState() != 1) {
			throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            ksession.abortProcessInstance(processInstanceId);
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public void abortProcessInstances(List<Long> processInstanceIds) {
		for (long processInstanceId : processInstanceIds) {
			abortProcessInstance(processInstanceId);
		}
	}

	@Override
	public void signalProcessInstance(Long processInstanceId, String signalName, Object event) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
		if (piDesc == null || piDesc.getState() != 1) {
			throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
		event = process(event, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            ksession.signalEvent(signalName, event, processInstanceId);
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public void signalProcessInstances(List<Long> processInstanceIds, String signalName, Object event) {
		for (Long processInstanceId : processInstanceIds) {
			signalProcessInstance(processInstanceId, signalName, event);
		}

	}

    @Override
    public void signalEvent(String deployment, String signalName, Object event) {
        DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deployment);
        if (deployedUnit == null) {
            throw new DeploymentNotFoundException("No deployments available for " + deployment);
        }
        RuntimeManager manager = deployedUnit.getRuntimeManager();
        event = process(event, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
        manager.signalEvent(signalName, event);
    }

	@Override
	public ProcessInstance getProcessInstance(Long processInstanceId) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
		if (piDesc == null) {
			return null;
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            return ksession.getProcessInstance(processInstanceId);
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public ProcessInstance getProcessInstance(CorrelationKey key) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceByCorrelationKey(key);
		if (piDesc == null) {
			return null;
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(CorrelationKeyContext.get(key));
        KieSession ksession = engine.getKieSession();
        try {
        	return ((CorrelationAwareProcessRuntime)ksession).getProcessInstance(key);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public void setProcessVariable(Long processInstanceId, String variableId, Object value) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
		if (piDesc == null || piDesc.getState() != 1) {
			throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
		value = process(value, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            ksession.execute(new SetProcessInstanceVariablesCommand(processInstanceId, Collections.singletonMap(variableId, value)));
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public void setProcessVariables(Long processInstanceId, Map<String, Object> variables) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
		if (piDesc == null || piDesc.getState() != 1) {
			throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
		variables = process(variables, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            ksession.execute(new SetProcessInstanceVariablesCommand(processInstanceId, variables));
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public Object getProcessInstanceVariable(Long processInstanceId, String variableName) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
		if (piDesc == null || piDesc.getState() != 1) {
			throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
           return ksession.execute(new ExecutableCommand<Object>() {

                private static final long serialVersionUID = -2693525229757876896L;

                @Override
                public Object execute(org.kie.api.runtime.Context context) {
                    KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
                    WorkflowProcessInstance pi = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId, true);
                    if (pi == null) {
                        throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
                    }
                    return pi.getVariable(variableName);
                }
            });
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public Map<String, Object> getProcessInstanceVariables(Long processInstanceId) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
		if (piDesc == null || piDesc.getState() != 1) {
			throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            WorkflowProcessInstanceImpl pi = (WorkflowProcessInstanceImpl) ksession.getProcessInstance(processInstanceId, true);

        	return pi.getVariables();
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public Collection<String> getAvailableSignals(Long processInstanceId) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
		if (piDesc == null) {
			throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId);
            Collection<String> activeSignals = new ArrayList<>();

            if (processInstance != null) {
                ((ProcessInstanceImpl) processInstance)
                        .setProcess(ksession.getKieBase().getProcess(processInstance.getProcessId()));
                Collection<NodeInstance> activeNodes = ((WorkflowProcessInstance) processInstance).getNodeInstances();

                activeSignals.addAll(collectActiveSignals(activeNodes));
            }

            return activeSignals;
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public void completeWorkItem(Long id, Map<String, Object> results) {
		NodeInstanceDesc nodeDesc = dataService.getNodeInstanceForWorkItem(id);
		if (nodeDesc == null) {
			throw new WorkItemNotFoundException("Work item with id " + id + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(nodeDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + nodeDesc.getDeploymentId());
		}
		Long processInstanceId = nodeDesc.getProcessInstanceId();
		RuntimeManager manager = deployedUnit.getRuntimeManager();
		results = process(results, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            ksession.getWorkItemManager().completeWorkItem(id, results);
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }

	}

	@Override
	public void abortWorkItem(Long id) {
		NodeInstanceDesc nodeDesc = dataService.getNodeInstanceForWorkItem(id);
		if (nodeDesc == null) {
			throw new WorkItemNotFoundException("Work item with id " + id + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(nodeDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + nodeDesc.getDeploymentId());
		}
		Long processInstanceId = nodeDesc.getProcessInstanceId();
		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            ksession.getWorkItemManager().abortWorkItem(id);
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public WorkItem getWorkItem(Long id) {
		NodeInstanceDesc nodeDesc = dataService.getNodeInstanceForWorkItem(id);
		if (nodeDesc == null) {
			throw new WorkItemNotFoundException("Work item with id " + id + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(nodeDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + nodeDesc.getDeploymentId());
		}
		Long processInstanceId = nodeDesc.getProcessInstanceId();
		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            return ((WorkItemManager)ksession.getWorkItemManager()).getWorkItem(id);
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public List<WorkItem> getWorkItemByProcessInstance(Long processInstanceId) {
		ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
		if (piDesc == null || piDesc.getState() != 1) {
			throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
		}
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
		}
		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            List<WorkItem> workItems = new ArrayList<>();

        	Collection<NodeInstanceDesc> nodes = dataService.getProcessInstanceHistoryActive(processInstanceId, null);

        	for (NodeInstanceDesc node : nodes) {
        		if (node.getWorkItemId() != null) {
        			workItems.add(((WorkItemManager)ksession.getWorkItemManager()).getWorkItem(node.getWorkItemId()));
        		}
        	}

        	return workItems;
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public <T> T execute(String deploymentId, Command<T> command) {
		Long processInstanceId = CommonUtils.getProcessInstanceId(command);
		logger.debug("Executing command {} with process instance id {} as contextual data", command, processInstanceId);

		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deploymentId);
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + deploymentId);
		}
		disallowWhenNotActive(deployedUnit, command);

		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
        try {
            KieSession ksession = engine.getKieSession();
            return ksession.execute(command);
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	@Override
	public <T> T execute(String deploymentId, Context<?> context, Command<T> command) {
		DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deploymentId);
		if (deployedUnit == null) {
			throw new DeploymentNotFoundException("No deployments available for " + deploymentId);
		}
		disallowWhenNotActive(deployedUnit, command);

		RuntimeManager manager = deployedUnit.getRuntimeManager();
        RuntimeEngine engine = manager.getRuntimeEngine(context);
        try {
            KieSession ksession = engine.getKieSession();
            return ksession.execute(command);
        } catch(SessionNotFoundException e) {
            throw new ProcessInstanceNotFoundException("Process instance with context id " + context.getContextId() + " was not found", e);
        } finally {
        	disposeRuntimeEngine(manager, engine);
        }
	}

	protected void disallowWhenNotActive(DeployedUnit deployedUnit, Command<?> cmd) {
		if (!deployedUnit.isActive() &&
				cmd instanceof StartProcessCommand) {
			throw new DeploymentNotFoundException("Deployments " + deployedUnit.getDeploymentUnit().getIdentifier() + " is not active");
		}
	}

	protected Collection<String> collectActiveSignals(
			Collection<NodeInstance> activeNodes) {
		Collection<String> activeNodesComposite = new ArrayList<>();
		for (NodeInstance nodeInstance : activeNodes) {
			if (nodeInstance instanceof EventNodeInstance) {
				String type = ((EventNodeInstance) nodeInstance).getEventNode().getType();
				if (type != null && !type.startsWith("Message-")) {
					activeNodesComposite.add(VariableUtil.resolveVariable(type, nodeInstance));
				}

			}
			if (nodeInstance instanceof CompositeNodeInstance) {
				Collection<NodeInstance> currentNodeInstances = ((CompositeNodeInstance) nodeInstance).getNodeInstances();

				// recursively check current nodes
				activeNodesComposite
						.addAll(collectActiveSignals(currentNodeInstances));
			}
		}

		return activeNodesComposite;
	}

	@Override
	public <T> T process(T variables, ClassLoader cl) {
		// do nothing here as there is no need to process variables
		return variables;
	}

	protected void disposeRuntimeEngine(RuntimeManager manager, RuntimeEngine engine) {
		manager.disposeRuntimeEngine(engine);
	}

}


text:
Group 6 TMDs
============

.. meta::
   :description: Collection of group 6 TMDs for pybinding

.. automodule:: pybinding.repository.group6_tmd

redpajama_set_name: RedPajamaGithub


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../orov-behaviors/orov-behavior.html">
<link rel="import" href="../iron-icon/iron-icon.html">
<dom-module name="orov-servo-tilt">

  <template>

      <iron-icon id="servoTiltImage"icon="av:videocam"></iron-icon>

  </template>

</dom-module>


text:
namespace ebuilder { class CodeGenerator; }

namespace erespacker
{

class NodeToLuaString
{
public:
	static int TransTime(float time);
	static int TransRadian(float r);
	static int TransFloat(float f);
	static int TransFloatX100(float f);
	static std::string TransBool(bool b);

	static void PackVertices(const CU_VEC<sm::vec2>& vertices, ebuilder::CodeGenerator& gen,
		const std::string& name, bool reverse_y = true, int scale = SCALE);

}; // NodeToLuaString

}

#endif // _EASYRESPACKER_NODE_TO_LUA_STRING_H_


text:
package  xmlcursor.detailed;

import junit.framework.*;

import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlString;
import org.apache.xmlbeans.XmlCursor.TokenType;
import xmlcursor.common.*;
import tools.util.JarUtil;

/**
 *
 *
 */
public class MultipleCursorSetTest extends TestCase {
    public MultipleCursorSetTest(String sName) {
        super(sName);
    }

    public static Test suite() {
        return new TestSuite(MultipleCursorSetTest.class);
    }

    public void testClassPath() throws Exception {
        String sClassPath = System.getProperty("java.class.path");
        int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR);
        assertTrue(i >= 0);
    }

    public void testMultipleCursorSet() throws Exception {
        XmlCursor xc = XmlObject.Factory.parse(JarUtil.getResourceFromJar(
                Common.TRANXML_FILE_CLM)).newCursor();
        xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT +
                      "$this//EquipmentNumber");
        xc.toNextSelection();
        XmlString xs = (XmlString) xc.getObject();
        assertEquals("123456", xs.getStringValue());
        assertEquals(TokenType.TEXT, xc.toNextToken());
        XmlCursor[] aCursors = new XmlCursor[6];
        for (int i = 0; i < 6; i++) {
            xc.toNextChar(1);
            aCursors[i] = xc.newCursor();
        }
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j != i && j < 6; j++) {
                assertEquals(false, aCursors[i].isAtSamePositionAs(aCursors[j]));
            }
        }
        xs.setStringValue("XYZ");
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                assertEquals(true, aCursors[i].isAtSamePositionAs(aCursors[j]));
            }
            // System.out.println(aCursors[i].currentTokenType());
            // assertEquals(null, aCursors[i].getTextValue());

            try {

                aCursors[i].getTextValue();
                fail("Expecting IllegalStateException");
            } catch (IllegalStateException e) {
            }

        }
        assertEquals("XYZ", xs.getStringValue());

    }

}


text:
"""
Processor for Hansard
"""
import logging
from raw.models import RawCouncilHansard, LANG_BOTH, LANG_EN, LANG_CN
from raw.processors.base import BaseProcessor, file_wrapper
from django.db.models import Count
from django.core.exceptions import *
from django.utils.timezone import now
import warnings
import re
from raw import utils

logger = logging.getLogger('legcowatch')

class LibraryHansardProcessor(BaseProcessor):
    """
    Class that handles the loading of Library Hansard scraped items
    into RawCouncilHansard table
    """
    def process(self, *args, **kwargs):
        logger.info("Processing file {}".format(self.items_file_path))
        counter = 0
        for item in file_wrapper(self.items_file_path):
            counter += 1
            if item['type'] == 'LibraryResultPage':
                # Ignore these entries
                continue
            if item['type'] == 'LibraryHansard':
                self._process_hansard_item(item)
        # After all downloaded hansards are created/updated, merge the ones that are parts of a hansard.
        self._merge_parts()
        logger.info("{} (raw) items processed, {} created, {} updated, {} warnings".format(counter, self._count_created, self._count_updated, self._count_warning))
        logger.info("{} merged items created/updated.".format(self._count_merged))

    def _process_hansard_item(self, item):
        # Usually generate three items, floor record and EN/CN formal records
        # but can be more or less
        # Ancient hansards may contain an English version and an image, probably not even an image
        # The first Chinese hansard seems to exist on 1985.10.30
        # Old harsards are bilingual (2 files), without floor version.
        # Floor version seems to exist since 1995.10.12

        # Loop over files in an item
        #print(u"Processing item: {}".format(item['title_en']))
        for i in range(len(item['links'])):
            # clear variables
            date_str = None
            lang = None
            language = None
            uid = None
            title = None
            url = None
            local_filename = None
            obj = None

            #Date always the same for an item
            date_str = self._get_date(item)
            if 'English' in item['links'][i][0]:
                #A formal, English record
                lang = u'e'
                language = LANG_EN
            elif u'中文' in item['links'][i][0]:
                lang = u'c'
                language = LANG_CN
            elif 'Floor' in item['links'][i][0]:
                lang = u'b'
                language = LANG_BOTH
            elif 'Image' in item['links'][i][0]:
                # we do not do images
                continue
            else:
                # Assume they are new Floor versions, log a warning just in case
                logger.warn(u'Unrecognised type: {}. Assume floor records.'.format(item['links'][i][0]))
                self._count_warning+=1
                lang = u'b'
                language = LANG_BOTH

            # Be careful of potential 'Parts' in title
            title = item['links'][i][0] #e.g. "H20150325 (Floor Version)"

            # Generate an uid
            uid = self._generate_base_hansard_uid(title,date_str,lang)
            if uid is None:
                logger.warn(u'Cannot generate uid for item with title: {}.'.format(title.strip()))
                self._count_warning+=1
                continue

            # Put items here for clarity
            #raw_date = date_str
            #language = language # 0,1 or 2
            url = item['links'][i][1]
            local_filename = self._get_local_filename(url, item) #"full/..."
            # Sometimes the file

            if local_filename is None:
                # Sometimes due to bandwidth/connection, file may fail to be downloaded
                logger.warn(u'Problem with local_filename of item: {}\nLink: {}'.format(title,url))
                self._count_warning+=1

            # Get/Create object from database
            #print(u'Building item: {}'.format(uid))
            # we allow non-unique UID for parts of Hansard, but title should be unique
            # we will merge parts of Hansard into one and create a new instance
            obj = self._get_or_create_hansard_record_by_title(title,uid)
            #if obj is not None:
            # at the moment we do not deal with floor recordings
            if obj is not None and language!=LANG_BOTH:
                obj = self._build_obj(obj, title, date_str, language, url, local_filename, item)
                obj.save()
            #End of for loop

    def _merge_parts(self):
        # Search for non-unique UIDs, merge their DOCXs into one HTML file, and make a new object for it.
        ## Remember to set the field CREATED_BY_PARTS to True
        # Get the list of duplicate UIDs
        dup_hansard_uid = RawCouncilHansard.objects.values('uid').annotate(uid_count=Count('uid')).exclude(uid_count=1)
        for item in dup_hansard_uid:
            # Firstly, check if we need to merge docs. Sometimes the parts are just appendices,
            # which we will ignore. In this case, there should be a normal UID for this object (without 'p').
            normal_uid = item['uid'].replace('p','')
            try:
                normal_han = RawCouncilHansard.objects.get(uid=normal_uid)
                #print normal_han
                if normal_han.created_by_parts is False:
                    # The parts are appendices. Do not process them.
                    # if this condition is not matched, the program will continue, as we will update the old object
                    continue
            except MultipleObjectsReturned:
                # Usually there should be no MultipleObjectsReturned exception.
                # This is for a very special case on 2012.06.14
                continue
            except ObjectDoesNotExist:
                # We need to create a new object
                pass

            self._count_merged += 1
            print(u'Merging Hansard Parts {}'.format(normal_uid))
            # We have to either create/update the Hansard
            # get a list of hansard objects
            han_part = RawCouncilHansard.objects.filter(uid=item['uid']).order_by('uid') #very weird, order by uid works but title does not
            # get their full local filepaths
            path_list = []
            for han in han_part:
                path_list.append(han.full_local_filename())
            # Make a name for output path, and create a full absolute path for saving
            html_name = han_part[0].uid + '-merge'
            out_htmlpath = han_part[0].full_local_filename().rsplit('/',1)[0] + '/' + html_name
            # Also make a relative path in same format as other normal objects
            local_filepath = '/'.join(out_htmlpath.rsplit('/',2)[1:])
            # Pass the list to merger, and let it write out a file
            html_str_or_None = utils.merge_docx(docx_list=path_list, out_htmlpath=out_htmlpath)
            # Sometimes the DOC/DOCX to HTML conversion fails.
            # In this case, we cannot parse the hansard anyway, so we leave the parts as is.
            if html_str_or_None is None:
                print(u'DOC/DOCX to HTML conversion failed for Hansard parts {}'.format(normal_uid))
            else:
                # Get/Create an object for merged file
                obj,_ = RawCouncilHansard.objects.get_or_create(uid=normal_uid)
                obj.raw_date = han_part[0].raw_date
                obj.language = han_part[0].language
                obj.url = ''
                obj.local_filename = local_filepath
                obj.crawled_from = ''
                obj.last_parsed = now()
                if han_part[0].language == LANG_CN:
                    obj.title = 'H'+ han_part[0].raw_date+' '+u'(中文版)'+u'MERGE'
                else:
                    obj.title = 'H'+ han_part[0].raw_date+' '+u'(English Version)'+u'MERGE'
                # Do not forget this
                obj.created_by_parts = True
                obj.save()

    def _build_obj(self, obj, title, raw_date, language, url, local_file, item):
        obj.title = title
        obj.raw_date = raw_date
        obj.language = language
        obj.url = url
        obj.local_filename = local_file
        obj.crawled_from = item['source_url']
        obj.last_parsed = now()
        if self.job:
            obj.last_crawled = self.job.completed
        return obj

    def _get_or_create_hansard_record_by_uid(self, uid):
        try:
            obj = RawCouncilHansard.objects.get(uid=uid)
            self._count_updated += 1
        except RawCouncilHansard.DoesNotExist:
            obj = RawCouncilHansard(uid=uid)
            self._count_created += 1
        except RawCouncilHansard.MultipleObjectsReturned:
            warnings.warn(u"Found more than one item with raw id {}".format(uid), RuntimeWarning)
            obj = None
        return obj

    def _get_or_create_hansard_record_by_title(self,title,uid):
        try:
            obj = RawCouncilHansard.objects.get(title=title)
            self._count_updated += 1
        except RawCouncilHansard.DoesNotExist:
            obj = RawCouncilHansard(title=title,uid=uid)
            self._count_created += 1
        return obj

    def _get_local_filename(self, link, item):
        """
        Given a link and an item to which the link belongs, get the local file path that
        matches the link
        """
        # Sanity check, in case of incorrect index order
        for f in item['files']:
            if link == f['url']:
                return f['path']
        return None

    def _generate_base_hansard_uid(self, title, date, lang):
        """
        Try to generate a unique id for a harsard item
        e.g.: council_hansard-19950110-e or council_hansard-20100110-b
        or : council_hansard-20120629-p2-e
        Basically council_hansard-<date: YYYYMMDD>-(optional:-p<d>-)<lang>
        e for English, c for Chinese, b for bilingual
        """
        # Handle Hansards divided into parts
        #part = None
        #part_pattern = ur'第(?P<part>.)部分' if lang==u'c' else r'Part (?P<part>.)'

        #match = re.match(part_pattern,title)
        #if match is not None:
        #    # this hansard is a part
        #    logger.info(u'Title "{}" is a part.'.format(title))
        #    part = match.group('part')
        #    if lang == u'c':
        #        if part == u'一':
        #            part = '1'
        #        elif part == u'二':
        #            part = '2'
        #        elif part == u'三':
        #            part = '3'
        #        else:
        #            logger.error(u"Unknown part character '{}' for hansard title: {}".format(part,title))
        #            part = None

        #if date and lang and part:
        #    return u'council_hansard-{}-p{}-{}'.format(date,part,lang)
        #elif date and lang:
        #    return u'council_hansard-{}-{}'.format(date,lang)
        #else:
        #    return None

        title_len_max = 16 if lang == u'c' else 28 #allow for 1 extra char
        if len(title.strip())>title_len_max:
            # This is a part file. Put a special char 'p' to indicate.
            return u'council_hansard-{}p-{}'.format(date,lang)
        elif date and lang:
            return u'council_hansard-{}-{}'.format(date,lang)
        else:
            return None

    def _get_date(self,item):
        """
        Returns the date string of an item in format YYYYMMDD
        """
        # Some rare cases the title e.g. H20070430 xxxxx is not in format,
        # so we get date from long title.
        return item['title_en'][-11:].replace('.', '')


text:
<?php
namespace Ticket\Controller;

use Ticket\Service\TicketServiceInterface;
use Zend\View\Model\ViewModel;
use Client\Controller\ClientBaseController;

class CloseController extends ClientBaseController
{

    /**
     *
     * @var TicketServiceInterface
     */
    protected $ticketService;

    /**
     *
     * @param TicketServiceInterface $ticketService
     */
    public function __construct(TicketServiceInterface $ticketService)
    {
        $this->ticketService = $ticketService;
    }

    /**
     *
     * {@inheritDoc}
     *
     * @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        parent::indexAction();

        $request = $this->getRequest();

        $ticketId = $this->params()->fromRoute('ticketId');

        // get ticket
        $ticketEntity = $this->GetTicket($this->clientId, $ticketId);

        // if post
        if ($request->isPost()) {

            $del = $request->getPost('delete_confirmation', 'no');

            // if yes delete
            if ($del === 'yes') {

                $ticketEntity->setTicketStatus('Closed');

                $ticketEntity->setTicketDateClose(time());

                $ticketEntity = $this->ticketService->save($ticketEntity);

                // trigger close event
                $this->getEventManager()->trigger('ticketClose', $this, array(
                    'ticketEntity' => $ticketEntity,
                    'authId' => $this->identity()
                        ->getAuthId(),
                    'historyUrl' => $this->getRequest()
                        ->getUri()
                ));

                // set flash messenger
                $this->flashMessenger()->addSuccessMessage('The ticket was closed');
            }

            // return to view ticket
            return $this->redirect()->toRoute('ticket-view', array(
                'clientId' => $ticketEntity->getClientId(),
                'ticketId' => $ticketEntity->getTicketId()
            ));
        }

        // return view model
        return new ViewModel(array(
            'clientId' => $this->clientId,
            'ticketId' => $ticketId,
            'clientEntity' => $this->clientEntity,
            'ticketEntity' => $ticketEntity
        ));
    }
}


text:
get '/choices/new' do
  survey = Survey.where(user_id: session[:user_id]).last
  @question = Question.where(survey_id: survey.id).last
  erb :'/choice/new'
end

post '/choices' do
  choice = Choice.new(params[:choices])
  @question = Question.find_by(id: choice.question_id)
  if choice.save
    if request.xhr?
      erb :'/choice/_new_partial', layout: false
    else
      redirect '/choices/new'
    end
  else
    @error = "Error creating choice"
    @question = Question.find_by(id: params[:choices][:question_id])
    erb :'/choice/new'
  end
end


text:
#ifndef UTILS_H
#define UTILS_H

#include <stdbool.h>
#include <stdint.h>
#include <sepol/policydb/avtab.h>
#include <sepol/policydb/policydb.h>

extern bool USAGE_ERROR;

void display_allow(policydb_t *policydb, avtab_key_t *key, int idx, uint32_t perms);

int load_policy(char *filename, policydb_t * policydb, struct policy_file *pf);

#endif /* UTILS_H */


text:
from uuid import uuid1
import collections
import datetime

from flask import current_app
from sqlalchemy import and_
from sqlalchemy import event
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import foreign
from sqlalchemy.orm import relationship
from sqlalchemy.orm import validates
from sqlalchemy.orm.session import Session

from ggrc import db
from ggrc.models import reflection
from ggrc.models.computed_property import computed_property
from ggrc.models.inflector import ModelInflectorDescriptor
from ggrc.models.reflection import AttributeInfo
from ggrc.utils import underscore_from_camelcase

"""Mixins to add common attributes and relationships. Note, all model classes
must also inherit from ``db.Model``. For example:

  ..

     class Market(BusinessObject, db.Model):
       __tablename__ = 'markets'

"""

def deferred(column, classname):
  """Defer column loading for basic properties, such as boolean or string, so
  that they are not loaded on joins. However, Identifiable provides an
  eager_query implementation that will specify undefer in the options so that
  when the resource is loaded itself, rather than through a join, it is
  completely loaded.

  In join tables, this function should not wrap foreign keys nor should it wrap
  type properties for polymorphic relations.
  """
  return db.deferred(column, group=classname + '_complete')

class Identifiable(object):

  """A model with an ``id`` property that is the primary key."""
  id = db.Column(db.Integer, primary_key=True)  # noqa

  # REST properties
  _publish_attrs = ['id', 'type']
  _update_attrs = []
  _stub_attrs = ['id', 'type']

  _inflector = ModelInflectorDescriptor()

  @computed_property
  def type(self):
    return self.__class__.__name__

  @classmethod
  def eager_query(cls):
    mapper_class = cls._sa_class_manager.mapper.base_mapper.class_
    return db.session.query(cls).options(
        db.Load(mapper_class).undefer_group(
            mapper_class.__name__ + '_complete'),
    )

  @classmethod
  def eager_inclusions(cls, query, include_links):
    options = []
    for include_link in include_links:
      inclusion_class = getattr(cls, include_link).property.mapper.class_
      options.append(
          orm.subqueryload(include_link)
          .undefer_group(inclusion_class.__name__ + '_complete'))
    return query.options(*options)

  @declared_attr
  def __table_args__(cls):
    extra_table_args = AttributeInfo.gather_attrs(cls, '_extra_table_args')
    table_args = []
    table_dict = {}
    for table_arg in extra_table_args:
      if callable(table_arg):
        table_arg = table_arg()
      if isinstance(table_arg, (list, tuple, set)):
        if isinstance(table_arg[-1], (dict,)):
          table_dict.update(table_arg[-1])
          table_args.extend(table_arg[:-1])
        else:
          table_args.extend(table_arg)
      elif isinstance(table_arg, (dict,)):
        table_dict.update(table_arg)
      else:
        table_args.append(table_arg)
    if len(table_dict) > 0:
      table_args.append(table_dict)
    return tuple(table_args,)

  # FIXME: This is not the right place, but there is no better common base
  # FIXME: class. I don't know what copy_into is used for. My guess would
  # FIXME: be cloning of some sort. I'm not sure that this code will work
  # FIXME: with custom attributes.
  def copy_into(self, _other, columns, **kwargs):
    target = _other or type(self)()

    columns = set(columns).union(kwargs.keys())
    for name in columns:
      if name in kwargs:
        value = kwargs[name]
      else:
        value = getattr(self, name)
      setattr(target, name, value)

    return target

def created_at_args():
  """Sqlite doesn't have a server, per se, so the server_* args are useless."""
  return {'default': db.text('current_timestamp'), }

def updated_at_args():
  """Sqlite doesn't have a server, per se, so the server_* args are useless."""
  return {
      'default': db.text('current_timestamp'),
      'onupdate': db.text('current_timestamp'),
  }

class ChangeTracked(object):

  """A model with fields to tracked the last user to modify the model, the
  creation time of the model, and the last time the model was updated.
  """
  # FIXME: change modified_by_id to nullable=False when there is an Account
  # model
  @declared_attr
  def modified_by_id(cls):
    return deferred(db.Column(db.Integer), cls.__name__)

  @declared_attr
  def created_at(cls):
    return deferred(db.Column(
        db.DateTime,
        **created_at_args()), cls.__name__)

  @declared_attr
  def updated_at(cls):
    return deferred(db.Column(
        db.DateTime,
        **updated_at_args()), cls.__name__)

  @declared_attr
  def modified_by(cls):
    return db.relationship(
        'Person',
        primaryjoin='{0}.modified_by_id == Person.id'.format(cls.__name__),
        foreign_keys='{0}.modified_by_id'.format(cls.__name__),
        uselist=False,
    )

  @staticmethod
  def _extra_table_args(cls):
    return (
        db.Index('ix_{}_updated_at'.format(cls.__tablename__), 'updated_at'),
    )

  # TODO Add a transaction id, this will be handy for generating etags
  # and for tracking the changes made to several resources together.
  # transaction_id = db.Column(db.Integer)

  # REST properties
  _publish_attrs = [
      'modified_by',
      'created_at',
      'updated_at',
  ]
  _update_attrs = []

class Titled(object):

  @declared_attr
  def title(cls):
    return deferred(db.Column(db.String, nullable=False), cls.__name__)

  @staticmethod
  def _extra_table_args(cls):
    if getattr(cls, '_title_uniqueness', True):
      return (
          db.UniqueConstraint(
              'title', name='uq_t_{}'.format(cls.__tablename__)),
      )
    return ()

  # REST properties
  _publish_attrs = ['title']
  _fulltext_attrs = ['title']
  _sanitize_html = ['title']
  _aliases = {"title": "Title"}

class Described(object):

  @declared_attr
  def description(cls):
    return deferred(db.Column(db.Text), cls.__name__)

  # REST properties
  _publish_attrs = ['description']
  _fulltext_attrs = ['description']
  _sanitize_html = ['description']
  _aliases = {"description": "Description"}

class Noted(object):

  @declared_attr
  def notes(cls):
    return deferred(db.Column(db.Text), cls.__name__)

  # REST properties
  _publish_attrs = ['notes']
  _fulltext_attrs = ['notes']
  _sanitize_html = ['notes']
  _aliases = {"notes": "Notes"}

class Hyperlinked(object):

  @declared_attr
  def url(cls):
    return deferred(db.Column(db.String), cls.__name__)

  @declared_attr
  def reference_url(cls):
    return deferred(db.Column(db.String), cls.__name__)

  # REST properties
  _publish_attrs = ['url', 'reference_url']

  _aliases = {
      "url": "Url",
      "reference_url": "Reference URL",
  }

class Hierarchical(object):

  @declared_attr
  def parent_id(cls):
    return deferred(db.Column(
        db.Integer, db.ForeignKey('{0}.id'.format(cls.__tablename__))),
        cls.__name__)

  @declared_attr
  def children(cls):
    return db.relationship(
        cls.__name__,
        backref=db.backref(
            'parent', remote_side='{0}.id'.format(cls.__name__)),
    )

  # REST properties
  _publish_attrs = [
      'children',
      'parent',
  ]

  @classmethod
  def eager_query(cls):
    query = super(Hierarchical, cls).eager_query()
    return query.options(
        orm.subqueryload('children'),
        # orm.joinedload('parent'),
    )

class Timeboxed(object):

  @declared_attr
  def start_date(cls):
    return deferred(db.Column(db.Date), cls.__name__)

  @declared_attr
  def end_date(cls):
    return deferred(db.Column(db.Date), cls.__name__)

  # REST properties
  _publish_attrs = ['start_date', 'end_date']

  _aliases = {
      "start_date": "Effective Date",
      "end_date": "Stop Date",
  }

class Stateful(object):

  @declared_attr
  def status(cls):
    return deferred(
        db.Column(db.String, default=cls.default_status), cls.__name__)

  _publish_attrs = ['status']
  _aliases = {"status": "State"}

  @classmethod
  def default_status(cls):
    return cls.valid_statuses()[0]

  @classmethod
  def valid_statuses(cls):
    return cls.VALID_STATES

  @validates('status')
  def validate_status(self, key, value):
    # Sqlalchemy only uses one validator per status (not neccessarily the
    # first) and ignores others. This enables cooperation between validators
    # since there are other mixins that want to touch 'status'.
    if hasattr(super(Stateful, self), "validate_status"):
      value = super(Stateful, self).validate_status(key, value)
    if value is None:
      value = self.default_status()
    if value not in self.valid_statuses():
      message = u"Invalid state '{}'".format(value)
      raise ValueError(message)
    return value

class FinishedDate(object):
  """Adds 'Finished Date' which is set when status is set to a finished state.

  Requires Stateful to be mixed in as well.
  """

  NOT_DONE_STATES = None
  DONE_STATES = {}

  # pylint: disable=method-hidden
  # because validator only sets date per model instance
  @declared_attr
  def finished_date(self):
    return deferred(
        db.Column(db.Date, nullable=True),
        self.__name__
    )

  _publish_attrs = [
      reflection.PublishOnly('finished_date')
  ]

  _aliases = {
      "finished_date": "Finished Date"
  }

  @validates('status')
  def validate_status(self, key, value):
    """Update finished_date given the right status change."""
    # Sqlalchemy only uses one validator per status (not neccessarily the
    # first) and ignores others. This enables cooperation between validators
    # since 'status' is not defined here.
    if hasattr(super(FinishedDate, self), "validate_status"):
      value = super(FinishedDate, self).validate_status(key, value)
    # pylint: disable=unsupported-membership-test
    # short circuit
    if (value in self.DONE_STATES and
       (self.NOT_DONE_STATES is None or
           self.status in self.NOT_DONE_STATES)):
      self.finished_date = datetime.datetime.now()
    elif ((self.NOT_DONE_STATES is None or
           value in self.NOT_DONE_STATES) and
            self.status in self.DONE_STATES):
      self.finished_date = None
    return value

class VerifiedDate(object):
  """Adds 'Verified Date' which is set when status is set to 'Verified'.

  When object is verified the status is overriden to 'Final' and the
  information about verification exposed as the 'verified' boolean.
  Requires Stateful to be mixed in as well.
  """

  VERIFIED_STATES = {u"Verified"}
  DONE_STATES = {}

  # pylint: disable=method-hidden
  # because validator only sets date per model instance
  @declared_attr
  def verified_date(self):
    return deferred(
        db.Column(db.Date, nullable=True),
        self.__name__
    )

  @hybrid_property
  def verified(self):
    return self.verified_date != None  # noqa

  _publish_attrs = [
      reflection.PublishOnly('verified'),
      reflection.PublishOnly('verified_date'),
  ]

  _aliases = {
      "verified_date": "Verified Date"
  }

  @validates('status')
  def validate_status(self, key, value):
    """Update verified_date on status change, make verified status final."""
    # Sqlalchemy only uses one validator per status (not neccessarily the
    # first) and ignores others. This enables cooperation between validators
    # since 'status' is not defined here.
    if hasattr(super(VerifiedDate, self), "validate_status"):
      value = super(VerifiedDate, self).validate_status(key, value)
    if (value in self.VERIFIED_STATES and
       self.status not in self.VERIFIED_STATES):
      self.verified_date = datetime.datetime.now()
      value = self.FINAL_STATE
    elif (value not in self.VERIFIED_STATES and
          value not in self.DONE_STATES and
          (self.status in self.VERIFIED_STATES or
           self.status in self.DONE_STATES)):
      self.verified_date = None
    return value

class ContextRBAC(object):

  @declared_attr
  def context_id(cls):
    return db.Column(db.Integer, db.ForeignKey('contexts.id'))

  @declared_attr
  def context(cls):
    return db.relationship('Context', uselist=False)

  @staticmethod
  def _extra_table_args(cls):
    return (
        db.Index('fk_{}_contexts'.format(cls.__tablename__), 'context_id'),
    )

  _publish_attrs = ['context']

  # @classmethod
  # def eager_query(cls):
  # from sqlalchemy import orm

  # query = super(ContextRBAC, cls).eager_query()
  # return query.options(
  # orm.subqueryload('context'))

class Base(ChangeTracked, ContextRBAC, Identifiable):

  """Several of the models use the same mixins. This class covers that common
  case.
  """

  def log_json(self):
    d = {}
    for column in self.__table__.columns:
      try:
        d[column.name] = getattr(self, column.name)
      except AttributeError:
        pass
    d['display_name'] = self.display_name
    return d

  @computed_property
  def display_name(self):
    try:
      return self._display_name()
    except:
      current_app.logger.warn(
          "display_name error in {}".format(type(self)), exc_info=True)
      return ""

  def _display_name(self):
    return getattr(self, "title", None) or getattr(self, "name", "")

class Slugged(Base):

  """Several classes make use of the common mixins and additional are
  "slugged" and have additional fields related to their publishing in the
  system.
  """

  @declared_attr
  def slug(cls):
    return deferred(db.Column(db.String, nullable=False), cls.__name__)

  @staticmethod
  def _extra_table_args(cls):
    if getattr(cls, '_slug_uniqueness', True):
      return (
          db.UniqueConstraint('slug', name='uq_{}'.format(cls.__tablename__)),
      )
    return ()

  # REST properties
  _publish_attrs = ['slug']
  _fulltext_attrs = ['slug']
  _sanitize_html = ['slug']
  _aliases = {
      "slug": {
          "display_name": "Code",
          "description": ("Must be unique. Can be left empty for "
                          "autogeneration. If updating or deleting, "
                          "code is required"),
      }
  }

  @classmethod
  def generate_slug_for(cls, obj):
    _id = getattr(obj, 'id', uuid1())
    obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id)
    # We need to make sure the generated slug is not already present in the
    # database. If it is, we increment the id until we find a slug that is
    # unique.
    # A better approach would be to query the database for slug uniqueness
    # only if the there was a conflict, but because we can't easily catch a
    # session rollback at this point we are sticking with a
    # suboptimal solution for now.
    INCREMENT = 1000
    while cls.query.filter(cls.slug == obj.slug).count():
      _id += INCREMENT
      obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id)

  @classmethod
  def generate_slug_prefix_for(cls, obj):
    return obj.__class__.__name__.upper()

  @classmethod
  def ensure_slug_before_flush(cls, session, flush_context, instances):
    """Set the slug to a default string so we don't run afoul of the NOT NULL
    constraint.
    """
    for o in session.new:
      if isinstance(o, Slugged) and (o.slug is None or o.slug == ''):
        o.slug = str(uuid1())
        o._replace_slug = True

  @classmethod
  def ensure_slug_after_flush_postexec(cls, session, flush_context):
    """Replace the placeholder slug with a real slug that will be set on the
    next flush/commit.
    """
    for o in session.identity_map.values():
      if isinstance(o, Slugged) and hasattr(o, '_replace_slug'):
        o.generate_slug_for(o)
        delattr(o, '_replace_slug')

event.listen(Session, 'before_flush', Slugged.ensure_slug_before_flush)
event.listen(
    Session, 'after_flush_postexec', Slugged.ensure_slug_after_flush_postexec)

class Mapping(Stateful, Base):
  VALID_STATES = (
      'Draft',
      'Final',
  )

class WithContact(object):

  @declared_attr
  def contact_id(cls):
    return deferred(
        db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__)

  @declared_attr
  def secondary_contact_id(cls):
    return deferred(
        db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__)

  @declared_attr
  def contact(cls):
    return db.relationship(
        'Person',
        uselist=False,
        foreign_keys='{}.contact_id'.format(cls.__name__))

  @declared_attr
  def secondary_contact(cls):
    return db.relationship(
        'Person',
        uselist=False,
        foreign_keys='{}.secondary_contact_id'.format(cls.__name__))

  @staticmethod
  def _extra_table_args(cls):
    return (
        db.Index('fk_{}_contact'.format(cls.__tablename__), 'contact_id'),
        db.Index('fk_{}_secondary_contact'.format(
            cls.__tablename__), 'secondary_contact_id'),
    )

  _publish_attrs = ['contact', 'secondary_contact']
  _aliases = {
      "contact": {
          "display_name": "Primary Contact",
          "filter_by": "_filter_by_contact",
      },
      "secondary_contact": {
          "display_name": "Secondary Contact",
          "filter_by": "_filter_by_secondary_contact",
      },
  }

  @classmethod
  def _filter_by_contact(cls, predicate):
    # dependency cycle mixins.py <~> person.py
    from ggrc.models.person import Person
    return Person.query.filter(
        (Person.id == cls.contact_id) &
        (predicate(Person.name) | predicate(Person.email))
    ).exists()

  @classmethod
  def _filter_by_secondary_contact(cls, predicate):
    # dependency cycle mixins.py <~> person.py
    from ggrc.models.person import Person
    return Person.query.filter(
        (Person.id == cls.secondary_contact_id) &
        (predicate(Person.name) | predicate(Person.email))
    ).exists()

class BusinessObject(Stateful, Noted, Described, Hyperlinked, WithContact,
                     Titled, Slugged):
  VALID_STATES = (
      'Draft',
      'Final',
      'Effective',
      'Ineffective',
      'Launched',
      'Not Launched',
      'In Scope',
      'Not in Scope',
      'Deprecated',
  )

# This class is just a marker interface/mixin to indicate that a model type
# supports custom attributes.

class CustomAttributable(object):

  @declared_attr
  def custom_attribute_values(cls):
    from ggrc.models.custom_attribute_value import CustomAttributeValue

    def join_function():
      return and_(
          foreign(CustomAttributeValue.attributable_id) == cls.id,
          foreign(CustomAttributeValue.attributable_type) == cls.__name__)
    return relationship(
        "CustomAttributeValue",
        primaryjoin=join_function,
        backref='{0}_custom_attributable'.format(cls.__name__),
        cascade='all, delete-orphan',
    )

  def custom_attributes(cls, attributes):
    from ggrc.fulltext.mysql import MysqlRecordProperty
    from ggrc.models.custom_attribute_value import CustomAttributeValue
    from ggrc.services import signals

    if 'custom_attributes' not in attributes:
      return

    attributes = attributes['custom_attributes']

    old_values = collections.defaultdict(list)
    last_values = dict()

    # attributes looks like this:
    #    [ {<id of attribute definition> : attribute value, ... }, ... ]

    # 1) Get all custom attribute values for the CustomAttributable instance
    attr_values = db.session.query(CustomAttributeValue).filter(and_(
        CustomAttributeValue.attributable_type == cls.__class__.__name__,
        CustomAttributeValue.attributable_id == cls.id)).all()

    attr_value_ids = [v.id for v in attr_values]
    ftrp_properties = [
        "attribute_value_{id}".format(id=_id) for _id in attr_value_ids]

    # Save previous value of custom attribute. This is a bit complicated by
    # the fact that imports can save multiple values at the time of writing.
    # old_values holds all previous values of attribute, last_values holds
    # chronologically last value.
    for v in attr_values:
      old_values[v.custom_attribute_id] += [(v.created_at, v.attribute_value)]

    last_values = {str(key): max(old_vals,
                                 key=lambda (created_at, _): created_at)
                   for key, old_vals in old_values.iteritems()}

    # 2) Delete all fulltext_record_properties for the list of values
    if len(attr_value_ids) > 0:
      db.session.query(MysqlRecordProperty)\
          .filter(
              and_(
                  MysqlRecordProperty.type == cls.__class__.__name__,
                  MysqlRecordProperty.property.in_(ftrp_properties)))\
          .delete(synchronize_session='fetch')

      # 3) Delete the list of custom attribute values
      db.session.query(CustomAttributeValue)\
          .filter(CustomAttributeValue.id.in_(attr_value_ids))\
          .delete(synchronize_session='fetch')

      db.session.commit()

    # 4) Instantiate custom attribute values for each of the definitions
    #    passed in (keys)
    # pylint: disable=not-an-iterable
    definitions = {d.id: d for d in cls.get_custom_attribute_definitions()}
    for ad_id in attributes.keys():
      obj_type = cls.__class__.__name__
      obj_id = cls.id
      new_value = CustomAttributeValue(
          custom_attribute_id=ad_id,
          attributable_id=obj_id,
          attributable_type=obj_type,
          attribute_value=attributes[ad_id],
      )
      if definitions[int(ad_id)].attribute_type.startswith("Map:"):
        obj_type, obj_id = new_value.attribute_value.split(":")
        new_value.attribute_value = obj_type
        new_value.attribute_object_id = obj_id
      # 5) Set the context_id for each custom attribute value to the context id
      #    of the custom attributable.
      # TODO: We are ignoring contexts for now
      # new_value.context_id = cls.context_id
      db.session.add(new_value)
      if ad_id in last_values:
        ca, pv = last_values[ad_id]  # created_at, previous_value
        if pv != attributes[ad_id]:
          signals.Signals.custom_attribute_changed.send(
              cls.__class__,
              obj=cls,
              src={
                  "type": obj_type,
                  "id": obj_id,
                  "operation": "UPDATE",
                  "value": new_value,
                  "old": pv
              }, service=cls.__class__.__name__)
      else:
        signals.Signals.custom_attribute_changed.send(
            cls.__class__,
            obj=cls,
            src={
                "type": obj_type,
                "id": obj_id,
                "operation": "INSERT",
                "value": new_value,
            }, service=cls.__class__.__name__)

  _publish_attrs = ['custom_attribute_values']
  _update_attrs = ['custom_attributes']
  _include_links = []

  @classmethod
  def get_custom_attribute_definitions(cls):
    from ggrc.models.custom_attribute_definition import \
        CustomAttributeDefinition
    return CustomAttributeDefinition.query.filter(
        CustomAttributeDefinition.definition_type ==
        underscore_from_camelcase(cls.__name__)).all()

  @classmethod
  def eager_query(cls):
    query = super(CustomAttributable, cls).eager_query()
    return query.options(
        orm.subqueryload('custom_attribute_values')
    )

class TestPlanned(object):

  @declared_attr
  def test_plan(cls):
    return deferred(db.Column(db.Text), cls.__name__)

  # REST properties
  _publish_attrs = ['test_plan']
  _fulltext_attrs = ['test_plan']
  _sanitize_html = ['test_plan']
  _aliases = {"test_plan": "Test Plan"}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Non focused states -->
    <item android:drawable="@drawable/vector_tabbar_unselected_background_light" android:state_focused="false" android:state_pressed="false" android:state_selected="false" />
    <item android:drawable="@drawable/vector_tabbar_selected_background_light" android:state_focused="false" android:state_pressed="false" android:state_selected="true" />

    <!-- Focused states -->
    <item android:drawable="@drawable/vector_tabbar_unselected_background_light" android:state_focused="true" android:state_pressed="false" android:state_selected="false" />
    <item android:drawable="@drawable/vector_tabbar_selected_background_light" android:state_focused="true" android:state_pressed="false" android:state_selected="true" />

    <!-- Pressed -->
    <!-- Non focused states -->
    <item android:drawable="@drawable/vector_tabbar_unselected_background_light" android:state_focused="false" android:state_pressed="true" android:state_selected="false" />
    <item android:drawable="@drawable/vector_tabbar_selected_background_light" android:state_focused="false" android:state_pressed="true" android:state_selected="true" />

    <!-- Focused states -->
    <item android:drawable="@drawable/vector_tabbar_unselected_background_light" android:state_focused="true" android:state_pressed="true" android:state_selected="false" />
    <item android:drawable="@drawable/vector_tabbar_selected_background_light" android:state_focused="true" android:state_pressed="true" android:state_selected="true" />

</selector>


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

namespace Piofthings.Data.Models
{
    public class Newsletter
    {
        public int Id { get; set; }
        public Guid Key { get; set; }
        public string EmailAddress { get; set; }
        public bool Validated { get; set; }
        public bool Unsubscribed { get; set; }
    }
}


text:
package org.springside.modules.utils.base;

import java.util.EnumSet;

import org.apache.commons.lang3.EnumUtils;

/**
 * 枚举工具集
 *
 * @author calvin
 *
 */
public class EnumUtil {

	/**
	 * 将若干个枚举值转换为long,用于使用long保存多个选项的情况.
	 */
	public static <E extends Enum<E>> long generateBits(final Class<E> enumClass, final Iterable<? extends E> values) {
		return EnumUtils.generateBitVector(enumClass, values);
	}

	/**
	 * 将若干个枚举值转换为long,用于使用long保存多个选项的情况.
	 */
	public static <E extends Enum<E>> long generateBits(final Class<E> enumClass, final E... values) {
		return EnumUtils.generateBitVector(enumClass, values);
	}

	/**
	 * long重新解析为若干个枚举值,用于使用long保存多个选项的情况.
	 */
	public static <E extends Enum<E>> EnumSet<E> processBits(final Class<E> enumClass, final long value) {
		return EnumUtils.processBitVector(enumClass, value);
	}

}


text:
package com.alibaba.otter.canal.parse.index;

import com.alibaba.otter.canal.common.CanalLifeCycle;
import com.alibaba.otter.canal.parse.exception.CanalParseException;
import com.alibaba.otter.canal.protocol.position.LogPosition;

/**
 * Created by yinxiu on 17/3/17. Email: marklin.hz@gmail.com
 */
public interface CanalLogPositionManager extends CanalLifeCycle {

    LogPosition getLatestIndexBy(String destination);

    void persistLogPosition(String destination, LogPosition logPosition) throws CanalParseException;

}


text:
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Authorization.Models;

namespace Azure.ResourceManager.Authorization
{
    internal partial class ProviderOperationsMetadataRestOperations
    {
        private readonly TelemetryDetails _userAgent;
        private readonly HttpPipeline _pipeline;
        private readonly Uri _endpoint;
        private readonly string _apiVersion;

        /// <summary> Initializes a new instance of ProviderOperationsMetadataRestOperations. </summary>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="applicationId"> The application id to use for user agent. </param>
        /// <param name="endpoint"> server parameter. </param>
        /// <param name="apiVersion"> Api Version. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception>
        public ProviderOperationsMetadataRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
        {
            _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
            _endpoint = endpoint ?? new Uri("https://management.azure.com");
            _apiVersion = apiVersion ?? "2022-04-01";
            _userAgent = new TelemetryDetails(GetType().Assembly, applicationId);
        }

        internal HttpMessage CreateGetRequest(string resourceProviderNamespace, string expand)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/providers/Microsoft.Authorization/providerOperations/", false);
            uri.AppendPath(resourceProviderNamespace, false);
            uri.AppendQuery("api-version", _apiVersion, true);
            if (expand != null)
            {
                uri.AppendQuery("$expand", expand, true);
            }
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets provider operations metadata for the specified resource provider. </summary>
        /// <param name="resourceProviderNamespace"> The namespace of the resource provider. </param>
        /// <param name="expand"> Specifies whether to expand the values. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceProviderNamespace"/> is null. </exception>
        public async Task<Response<AuthorizationProviderOperationsMetadataData>> GetAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(resourceProviderNamespace, nameof(resourceProviderNamespace));

            using var message = CreateGetRequest(resourceProviderNamespace, expand);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        AuthorizationProviderOperationsMetadataData value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = AuthorizationProviderOperationsMetadataData.DeserializeAuthorizationProviderOperationsMetadataData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                case 404:
                    return Response.FromValue((AuthorizationProviderOperationsMetadataData)null, message.Response);
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets provider operations metadata for the specified resource provider. </summary>
        /// <param name="resourceProviderNamespace"> The namespace of the resource provider. </param>
        /// <param name="expand"> Specifies whether to expand the values. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="resourceProviderNamespace"/> is null. </exception>
        public Response<AuthorizationProviderOperationsMetadataData> Get(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(resourceProviderNamespace, nameof(resourceProviderNamespace));

            using var message = CreateGetRequest(resourceProviderNamespace, expand);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        AuthorizationProviderOperationsMetadataData value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = AuthorizationProviderOperationsMetadataData.DeserializeAuthorizationProviderOperationsMetadataData(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                case 404:
                    return Response.FromValue((AuthorizationProviderOperationsMetadataData)null, message.Response);
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListRequest(string expand)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendPath("/providers/Microsoft.Authorization/providerOperations", false);
            uri.AppendQuery("api-version", _apiVersion, true);
            if (expand != null)
            {
                uri.AppendQuery("$expand", expand, true);
            }
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets provider operations metadata for all resource providers. </summary>
        /// <param name="expand"> Specifies whether to expand the values. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public async Task<Response<AuthorizationProviderOperationsMetadataListResult>> ListAsync(string expand = null, CancellationToken cancellationToken = default)
        {
            using var message = CreateListRequest(expand);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        AuthorizationProviderOperationsMetadataListResult value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = AuthorizationProviderOperationsMetadataListResult.DeserializeAuthorizationProviderOperationsMetadataListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets provider operations metadata for all resource providers. </summary>
        /// <param name="expand"> Specifies whether to expand the values. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public Response<AuthorizationProviderOperationsMetadataListResult> List(string expand = null, CancellationToken cancellationToken = default)
        {
            using var message = CreateListRequest(expand);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        AuthorizationProviderOperationsMetadataListResult value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = AuthorizationProviderOperationsMetadataListResult.DeserializeAuthorizationProviderOperationsMetadataListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListNextPageRequest(string nextLink, string expand)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.Reset(_endpoint);
            uri.AppendRawNextLink(nextLink, false);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            _userAgent.Apply(message);
            return message;
        }

        /// <summary> Gets provider operations metadata for all resource providers. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="expand"> Specifies whether to expand the values. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
        public async Task<Response<AuthorizationProviderOperationsMetadataListResult>> ListNextPageAsync(string nextLink, string expand = null, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));

            using var message = CreateListNextPageRequest(nextLink, expand);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        AuthorizationProviderOperationsMetadataListResult value = default;
                        using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
                        value = AuthorizationProviderOperationsMetadataListResult.DeserializeAuthorizationProviderOperationsMetadataListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }

        /// <summary> Gets provider operations metadata for all resource providers. </summary>
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="expand"> Specifies whether to expand the values. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
        public Response<AuthorizationProviderOperationsMetadataListResult> ListNextPage(string nextLink, string expand = null, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(nextLink, nameof(nextLink));

            using var message = CreateListNextPageRequest(nextLink, expand);
            _pipeline.Send(message, cancellationToken);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        AuthorizationProviderOperationsMetadataListResult value = default;
                        using var document = JsonDocument.Parse(message.Response.ContentStream);
                        value = AuthorizationProviderOperationsMetadataListResult.DeserializeAuthorizationProviderOperationsMetadataListResult(document.RootElement);
                        return Response.FromValue(value, message.Response);
                    }
                default:
                    throw new RequestFailedException(message.Response);
            }
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class BedchambersTowerSegment : TowerSegment {
	public override float OnGetConstructionDuration() {
		return GameConstants.BEDCHAMBERS_TOWER_SEGMENT_BUILD_TIME;
	}
}