text:
package org.camunda.bpm.engine.test.api.runtime;

import static org.junit.Assert.*;
import static org.camunda.bpm.engine.test.api.runtime.migration.models.ConditionalModels.*;
import static org.hamcrest.CoreMatchers.containsString;

import java.io.File;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.engine.history.HistoricVariableInstance;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.runtime.VariableInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.TaskQuery;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.engine.test.api.runtime.migration.models.ProcessModels;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.RuleChain;

@RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_AUDIT)
public class TransientVariableTest {

  private static final int OUTPUT_VALUE = 2;
  protected ProcessEngineRule engineRule = new ProvidedProcessEngineRule();
  protected ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule);

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Rule
  public RuleChain ruleChain = RuleChain.outerRule(engineRule).around(testRule);

  protected RuntimeService runtimeService;
  protected HistoryService historyService;
  protected TaskService taskService;

  @Before
  public void init() {
    this.runtimeService = engineRule.getRuntimeService();
    this.historyService = engineRule.getHistoryService();
    this.taskService = engineRule.getTaskService();
  }

  @Test
  public void createTransientTypedVariablesUsingVariableMap() throws URISyntaxException {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess("Process")
      .startEvent()
      .serviceTask()
        .camundaClass(ReadTransientVariablesOfAllTypesDelegate.class.getName())
      .userTask("user")
      .endEvent()
      .done();

    testRule.deploy(instance);

    // when
    runtimeService.startProcessInstanceByKey("Process",
        Variables.createVariables()
            .putValueTyped("a", Variables.stringValue("bar", true))
            .putValueTyped("b", Variables.booleanValue(true, true))
            .putValueTyped("c", Variables.byteArrayValue("test".getBytes(), true))
            .putValueTyped("d", Variables.dateValue(new Date(), true))
            .putValueTyped("e", Variables.doubleValue(20., true))
            .putValueTyped("f", Variables.integerValue(10, true))
            .putValueTyped("g", Variables.longValue((long) 10, true))
            .putValueTyped("h", Variables.shortValue((short) 10, true))
            .putValueTyped("i", Variables.objectValue(new Integer(100), true).create())
            .putValueTyped("j", Variables.untypedValue(null, true))
            .putValueTyped("k", Variables.untypedValue(Variables.booleanValue(true), true))
            .putValueTyped("l", Variables.fileValue(new File(this.getClass().getClassLoader()
                .getResource("org/camunda/bpm/engine/test/standalone/variables/simpleFile.txt").toURI()), true)));

    // then
    List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery().list();
    List<VariableInstance> variableInstances = runtimeService.createVariableInstanceQuery().list();
    assertEquals(0, historicVariableInstances.size());
    assertEquals(0, variableInstances.size());
  }

  @Test
  public void createTransientVariablesUsingVariableMap() throws URISyntaxException {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess("Process")
      .startEvent()
      .serviceTask()
        .camundaClass(ReadTransientVariablesOfAllTypesDelegate.class.getName())
      .userTask("user")
      .endEvent()
      .done();

    testRule.deploy(instance);

    // when
    runtimeService.startProcessInstanceByKey("Process",
        Variables.createVariables().putValue("a", Variables.stringValue("bar", true))
        .putValue("b", Variables.booleanValue(true, true))
        .putValue("c", Variables.byteArrayValue("test".getBytes(), true))
        .putValue("d", Variables.dateValue(new Date(), true))
        .putValue("e", Variables.doubleValue(20., true))
        .putValue("f", Variables.integerValue(10, true))
        .putValue("g", Variables.longValue((long) 10, true))
        .putValue("h", Variables.shortValue((short) 10, true))
        .putValue("i", Variables.objectValue(new Integer(100), true).create())
        .putValue("j", Variables.untypedValue(null, true))
        .putValue("k", Variables.untypedValue(Variables.booleanValue(true), true))
        .putValue("l", Variables.fileValue(new File(this.getClass().getClassLoader()
            .getResource("org/camunda/bpm/engine/test/standalone/variables/simpleFile.txt").toURI()), true)));

    // then
    List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery().list();
    List<VariableInstance> variableInstances = runtimeService.createVariableInstanceQuery().list();
    assertEquals(0, historicVariableInstances.size());
    assertEquals(0, variableInstances.size());
  }

  @Test
  public void createTransientVariablesUsingFluentBuilder() {
    // given
    BpmnModelInstance simpleInstanceWithListener = Bpmn.createExecutableProcess("Process")
        .startEvent()
          .camundaExecutionListenerClass(ExecutionListener.EVENTNAME_END, ReadTransientVariableExecutionListener.class)
        .userTask()
        .endEvent()
        .done();
    testRule.deploy(simpleInstanceWithListener);

    // when
    runtimeService.createProcessInstanceByKey("Process")
      .setVariables(Variables.createVariables().putValue(VARIABLE_NAME, Variables.stringValue("dlsd", true)))
      .execute();

    // then
    List<VariableInstance> variableInstances = runtimeService.createVariableInstanceQuery().list();
    List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery().list();
    assertEquals(0, variableInstances.size());
    assertEquals(0, historicVariableInstances.size());
  }

  @Test
  public void createVariablesUsingVariableMap() {
    // given
    BpmnModelInstance simpleInstanceWithListener = Bpmn.createExecutableProcess("Process")
        .startEvent()
          .camundaExecutionListenerClass(ExecutionListener.EVENTNAME_END, ReadTransientVariableExecutionListener.class)
        .userTask()
        .endEvent()
        .done();
    testRule.deploy(simpleInstanceWithListener);

    // when
    VariableMap variables = Variables.createVariables();
    variables.put(VARIABLE_NAME, Variables.untypedValue(true, true));
    runtimeService.startProcessInstanceByKey("Process",
       variables
        );

    // then
    List<VariableInstance> variableInstances = runtimeService.createVariableInstanceQuery().list();
    List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery().list();
    assertEquals(0, variableInstances.size());
    assertEquals(0, historicVariableInstances.size());
  }

  @Test
  public void triggerConditionalEventWithTransientVariable() {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess(CONDITIONAL_PROCESS_KEY)
        .startEvent()
        .serviceTask()
        .camundaClass(SetVariableTransientDelegate.class.getName())
        .intermediateCatchEvent(CONDITION_ID)
        .conditionalEventDefinition()
        .condition(VAR_CONDITION)
        .conditionalEventDefinitionDone()
        .endEvent()
        .done();

    testRule.deploy(instance);

    // when
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(CONDITIONAL_PROCESS_KEY);

    // then
    assertEquals(true, processInstance.isEnded());
  }

  @Test
  public void testParallelProcessWithSetVariableTransientAfterReachingEventBasedGW() {
    BpmnModelInstance modelInstance =
        Bpmn.createExecutableProcess(CONDITIONAL_PROCESS_KEY)
          .startEvent()
          .parallelGateway()
          .id("parallel")
          .userTask("taskBeforeGw")
          .eventBasedGateway()
          .id("evenBased")
          .intermediateCatchEvent()
          .conditionalEventDefinition()
          .condition(VAR_CONDITION)
          .camundaVariableEvents(Arrays.asList("create", "update"))
          .conditionalEventDefinitionDone()
          .userTask()
          .name("taskAfter")
          .endEvent()
          .moveToNode("parallel")
          .userTask("taskBefore")
          .serviceTask()
          .camundaClass(SetVariableTransientDelegate.class.getName())
          .endEvent()
          .done();

    testRule.deploy(modelInstance);

    //given
    ProcessInstance procInst = runtimeService.startProcessInstanceByKey(CONDITIONAL_PROCESS_KEY);
    TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(procInst.getId());
    Task taskBeforeEGW = taskService.createTaskQuery().taskDefinitionKey("taskBeforeGw").singleResult();
    Task taskBeforeServiceTask = taskService.createTaskQuery().taskDefinitionKey("taskBefore").singleResult();

    //when task before event based gateway is completed and after that task before service task
    taskService.complete(taskBeforeEGW.getId());
    taskService.complete(taskBeforeServiceTask.getId());

    //then event based gateway is reached and executions stays there
    //variable is set after reaching event based gateway
    //after setting variable the conditional event is triggered and evaluated to true
    Task task = taskQuery.singleResult();
    assertNotNull(task);
    assertEquals("taskAfter", task.getName());
    //completing this task ends process instance
    taskService.complete(task.getId());
    assertNull(taskQuery.singleResult());
    assertNull(runtimeService.createProcessInstanceQuery().singleResult());
  }

  @Test
  public void setVariableTransientInRunningProcessInstance() {
    // given
    testRule.deploy(ProcessModels.ONE_TASK_PROCESS);

    // when
    runtimeService.startProcessInstanceByKey(ProcessModels.PROCESS_KEY);
    Execution execution = runtimeService.createExecutionQuery().singleResult();
    runtimeService.setVariable(execution.getId(), "foo", Variables.stringValue("bar", true));

    // then
    List<VariableInstance> variables = runtimeService.createVariableInstanceQuery().list();
    assertEquals(0, variables.size());
  }

  @Test
  public void setVariableTransientForCase() {
    // given
    testRule.deploy("org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn");

    // when
    engineRule.getCaseService().withCaseDefinitionByKey("oneTaskCase")
        .setVariable("foo", Variables.stringValue("bar", true)).create();

    // then
    List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().list();
    assertEquals(0, variables.size());
  }

  @Test
  public void testTransientVariableOvewritesPersistedVariableInSameScope() {
    testRule.deploy(ProcessModels.ONE_TASK_PROCESS);
    runtimeService.startProcessInstanceByKey("Process", Variables.createVariables().putValue("foo", "bar"));
    Execution execution = runtimeService.createExecutionQuery().singleResult();

    try {
      runtimeService.setVariable(execution.getId(), "foo", Variables.stringValue("xyz", true));
    } catch (ProcessEngineException e) {
      assertThat(e.getMessage(), containsString("Cannot set transient variable with name foo"));
    }
  }

  @Test
  public void testSameNamesDifferentScopes() {
    testRule.deploy(ProcessModels.SUBPROCESS_PROCESS);
    runtimeService.startProcessInstanceByKey("Process", Variables.createVariables().putValue("foo", Variables.stringValue("bar")));
    Execution execution = runtimeService.createExecutionQuery().activityId(USER_TASK_ID).singleResult();

    try {
      runtimeService.setVariable(execution.getId(), "foo", Variables.stringValue("xyz", true));
    } catch (ProcessEngineException e) {
      assertThat(e.getMessage(), containsString("Cannot set transient variable with name foo"));
    }
  }

  @Test
  public void testFormFieldsWithCustomTransientFlags() {
    // given
    testRule.deploy("org/camunda/bpm/engine/test/api/form/TransientVariableTest.taskFormFieldsWithTransientFlags.bpmn20.xml");
    runtimeService.startProcessInstanceByKey("testProcess");
    Task task = taskService.createTaskQuery().singleResult();

    // when
    Map<String, Object> formValues = new HashMap<String, Object>();
    formValues.put("stringField", Variables.stringValue("foobar", true));
    formValues.put("longField", 9L);
    engineRule.getFormService().submitTaskForm(task.getId(), formValues);

    // then
    List<VariableInstance> variables = runtimeService.createVariableInstanceQuery().list();
    assertEquals(1, variables.size());
    assertEquals(variables.get(0).getValue(), 9L);
  }

  @Test
  public void testStartProcessInstanceWithFormsUsingTransientVariables() {
    // given
    testRule.deploy("org/camunda/bpm/engine/test/api/form/TransientVariableTest.startFormFieldsWithTransientFlags.bpmn20.xml");
    ProcessDefinition processDefinition = engineRule.getRepositoryService().createProcessDefinitionQuery().singleResult();

    // when
    Map<String, Object> formValues = new HashMap<String, Object>();
    formValues.put("stringField", Variables.stringValue("foobar", true));
    formValues.put("longField", 9L);
    engineRule.getFormService().submitStartForm(processDefinition.getId(), formValues);

    // then
    List<VariableInstance> variables = runtimeService.createVariableInstanceQuery().list();
    assertEquals(1, variables.size());
    assertEquals(variables.get(0).getValue(), 9L);
  }

  @Test
  public void testSignalWithTransientVariables() {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess("Process")
    .startEvent()
    .intermediateCatchEvent("signalCatch")
      .signal("signal")
    .scriptTask("scriptTask")
      .scriptFormat("javascript")
      .camundaResultVariable("abc")
      .scriptText("execution.setVariable('abc', foo);")
    .endEvent()
    .done();

    testRule.deploy(instance);
    runtimeService.startProcessInstanceByKey("Process");

    // when
    runtimeService.signalEventReceived("signal",
        Variables.createVariables().putValue("foo", Variables.stringValue("bar", true)));

    // then
    List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().list();
    assertEquals(1, variables.size());
    assertEquals("abc", variables.get(0).getName());
  }

  @Test
  public void testStartMessageCorrelationWithTransientVariable() {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess("process")
      .startEvent()
        .message("message")
      .scriptTask("scriptTask")
        .scriptFormat("javascript")
        .camundaResultVariable("abc")
        .scriptText("execution.setVariable('abc', foo);")
      .endEvent()
      .done();

    testRule.deploy(instance);

    // when
    runtimeService.createMessageCorrelation("message")
      .setVariable("foo", Variables.stringValue("bar", true))
      .correlate();

    // then
    List<VariableInstance> variableInstances = runtimeService.createVariableInstanceQuery().list();
    assertEquals(0, variableInstances.size());
    List<HistoricVariableInstance> historicInstances = historyService.createHistoricVariableInstanceQuery().list();
    assertEquals(1, historicInstances.size());
    assertEquals("abc", historicInstances.get(0).getName());
    assertEquals("bar", historicInstances.get(0).getValue());
  }

  @Test
  public void testMessageCorrelationWithTransientVariable() {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess("process")
      .startEvent()
      .intermediateCatchEvent()
        .message("message")
      .scriptTask("scriptTask")
        .scriptFormat("javascript")
        .camundaResultVariable("abc")
        .scriptText("execution.setVariable('abc', blob);")
      .endEvent()
      .done();

    testRule.deploy(instance);
    runtimeService.startProcessInstanceByKey("process",
        Variables.createVariables().putValueTyped("foo", Variables.stringValue("foo", false)));

    // when
    VariableMap correlationKeys = Variables.createVariables().putValueTyped("foo", Variables.stringValue("foo", true));
    VariableMap variables = Variables.createVariables().putValueTyped("blob", Variables.stringValue("blob", true));
    runtimeService.correlateMessage("message", correlationKeys, variables);

    // then
    VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().singleResult();
    assertNull(variableInstance);
    HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery()
        .variableName("abc").singleResult();
    assertNotNull(historicVariableInstance);
    assertEquals("blob", historicVariableInstance.getValue());
  }

  @Test
  public void testParallelExecutions() {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess("Process")
      .startEvent()
      .parallelGateway()
      .scriptTask()
        .scriptFormat("javascript")
        .camundaResultVariable("abc")
        .scriptText("execution.setVariableLocal('abc', foo);")
      .endEvent()
      .moveToLastGateway()
      .scriptTask()
        .scriptFormat("javascript")
        .camundaResultVariable("abc")
        .scriptText("execution.setVariableLocal('abc', foo);")
      .endEvent()
      .done();

    testRule.deploy(instance);

    // when
    runtimeService.startProcessInstanceByKey("Process",
        Variables.createVariables().putValueTyped("foo", Variables.stringValue("bar", true)));

    // then
    List<VariableInstance> variables = runtimeService.createVariableInstanceQuery().list();
    assertEquals(0, variables.size());

    List<HistoricVariableInstance> historicVariables = historyService.createHistoricVariableInstanceQuery().variableName("abc").list();
    assertEquals(2, historicVariables.size());
  }

  @Test
  public void testExclusiveGateway() {
    // given
    testRule.deploy("org/camunda/bpm/engine/test/bpmn/gateway/ExclusiveGatewayTest.testDivergingExclusiveGateway.bpmn20.xml");

    // when
    runtimeService.startProcessInstanceByKey("exclusiveGwDiverging",
        Variables.createVariables().putValueTyped("input", Variables.integerValue(1, true)));

    // then
    List<VariableInstance> variables = runtimeService.createVariableInstanceQuery().list();
    assertEquals(0, variables.size());
    Task task = taskService.createTaskQuery().singleResult();
    assertEquals("theTask1", task.getTaskDefinitionKey());
  }

  @Test
  public void testChangeTransientVariable() throws URISyntaxException {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess("Process")
      .startEvent()
      .serviceTask()
        .camundaClass(ChangeVariableTransientDelegate.class.getName())
      .userTask("user")
      .endEvent()
      .done();

    testRule.deploy(instance);

    String output = "transientVariableOutput";
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put(output, false);

    // when
    runtimeService.startProcessInstanceByKey("Process", variables);

    // then
    List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery().list();
    List<VariableInstance> variableInstances = runtimeService.createVariableInstanceQuery().list();
    assertEquals(1, historicVariableInstances.size());
    assertEquals(1, variableInstances.size());
    assertEquals(output, variableInstances.get(0).getName());
    assertEquals(OUTPUT_VALUE, variableInstances.get(0).getValue());
  }

  @Test
  public void testSwitchTransientToNonVariable() throws URISyntaxException {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess("Process")
      .startEvent()
      .serviceTask()
        .camundaClass(SwitchTransientVariableDelegate.class.getName())
      .userTask("user")
      .endEvent()
      .done();

    testRule.deploy(instance);

    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("transient1", true);
    variables.put("transient2", false);

    // expect
    thrown.expect(ProcessEngineException.class);
    thrown.expectMessage("Cannot set transient variable with name variable to non-transient variable and vice versa.");

    // when
    runtimeService.startProcessInstanceByKey("Process", variables);
  }

  @Test
  public void testSwitchNonToTransientVariable() throws URISyntaxException {
    // given
    BpmnModelInstance instance = Bpmn.createExecutableProcess("Process")
      .startEvent()
      .serviceTask()
        .camundaClass(SwitchTransientVariableDelegate.class.getName())
      .userTask("user")
      .endEvent()
      .done();

    testRule.deploy(instance);

    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("transient1", false);
    variables.put("transient2", true);

    // expect
    thrown.expect(ProcessEngineException.class);
    thrown.expectMessage("Cannot set transient variable with name variable to non-transient variable and vice versa.");

    // when
    runtimeService.startProcessInstanceByKey("Process", variables);
  }

  public static class SetVariableTransientDelegate implements JavaDelegate {
    @Override
    public void execute(DelegateExecution execution) throws Exception {
      execution.setVariable(VARIABLE_NAME, Variables.integerValue(1, true));
    }
  }

  public static class ReadTransientVariablesOfAllTypesDelegate implements JavaDelegate {

    @Override
    public void execute(DelegateExecution execution) throws Exception {
      for (char i = 'a'; i < 'm'; i++) {
        Object value = execution.getVariable("" + i);
        // variable 'j' is a transient null
        if (i != 'j' ) {
          assertNotNull(value);
        } else assertNull(value);
      }
    }
  }

  public static class ReadTransientVariableExecutionListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution execution) throws Exception {
      Object variable = execution.getVariable(VARIABLE_NAME);
      assertNotNull(variable);
    }
  }

  public static class ChangeVariableTransientDelegate implements JavaDelegate {
    @Override
    public void execute(DelegateExecution execution) throws Exception {
      execution.setVariable(VARIABLE_NAME, Variables.integerValue(1, true));
      execution.setVariable(VARIABLE_NAME, Variables.integerValue(OUTPUT_VALUE, true));
      execution.setVariable("transientVariableOutput", execution.getVariable(VARIABLE_NAME));
    }
  }

  public static class SwitchTransientVariableDelegate implements JavaDelegate {
    @Override
    public void execute(DelegateExecution execution) throws Exception {
      Boolean transient1 = (Boolean) execution.getVariable("transient1");
      Boolean transient2 = (Boolean) execution.getVariable("transient2");
      execution.setVariable(VARIABLE_NAME, Variables.integerValue(1, transient1));
      execution.setVariable(VARIABLE_NAME, Variables.integerValue(2, transient2));
    }
  }

}


text:
The following steps will output the console to both serial and vga output

## Steps

* modify/create /etc/init/ttyS0.conf

  ```
  root@linux-cloud:/etc/grub.d# more /etc/init/ttyS0.conf
  # ttyS0 - getty
  #
  # This service maintains a getty on ttyS0 from the point the system is
  # started until it is shut down again.

  start on stopped rc RUNLEVEL=[2345] and (
              not-container or
              container CONTAINER=lxc or
              container CONTAINER=lxc-libvirt)

  stop on runlevel [!2345]

  pre-start script
      # getty will not be started if the serial console is not present
      stty -F /dev/ttyS0 -a 2> /dev/null > /dev/null || { stop ; exit 0; }
  end script

  respawn
  script
      exec /sbin/getty -L ttyS0 115200 vt102
  end script
  ```

* modify /etc/default/grub

  ```
  edit the following line:

  GRUB_CMDLINE_LINUX_DEFAULT="console=tty1 console=ttyS0"
  ```

redpajama_set_name: RedPajamaGithub


text:
package io.retxt.dispatch;

/**
 * Default PlatformQueues implementation that initializes them with {@link ManualDispatchQueue
 * ManualDispatchQueues}
 * <p>
 * Created by kdubb on 1/29/16.
 */
class DefaultPlatformQueues implements PlatformQueues {

  @Override
  public ManualDispatchQueue createMainQueue() {
    return new ManualDispatchQueue();
  }

  @Override
  public ManualDispatchQueue createUIQueue() {
    return new ManualDispatchQueue();
  }

}


text:
package cn.itcast.zt.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取用户 IP 地址
 * Created by zhangtian on 2017/4/14.
 */
public class IPAddressUtils {
    public static String getClientIpAddress(HttpServletRequest request){
        String ip = request.getHeader("X-Forwarded-For") ;
        if (ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        if (ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip ;
    }
}


text:
FROM ubuntu:14.04

MAINTAINER Eric Busboom "eric@clarinova.com"

RUN apt-get update
RUN apt-get upgrade -y

RUN apt-get install -y language-pack-en
ENV LANGUAGE en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LC_ALL en_US.UTF-8

RUN locale-gen en_US.UTF-8
RUN dpkg-reconfigure locales

RUN apt-get install -y build-essential make gcc wget curl git
RUN apt-get install -y python python-pip python-dev

RUN pip install 'git+https://github.com/sdrdl/ipydoc.git#egg=ipydoc' # change7

EXPOSE 4242

ENTRYPOINT ["ipydoc_director"]


text:
'use strict';
var decryptWalletCtrl = function($scope, $sce, walletService) {
	$scope.walletType = "";
	$scope.requireFPass = $scope.requirePPass = $scope.showFDecrypt = $scope.showPDecrypt = false;
	$scope.filePassword = "";
	$scope.fileContent = "";
	$scope.showContent = function($fileContent) {
		$scope.fileStatus = $sce.trustAsHtml(globalFuncs.getSuccessText("File Selected: " + document.getElementById('fselector').files[0].name));
		try {
			$scope.requireFPass = Wallet.walletRequirePass($fileContent);
			$scope.showFDecrypt = !$scope.requireFPass;
			$scope.fileContent = $fileContent;
		} catch (e) {
			$scope.fileStatus = $sce.trustAsHtml(globalFuncs.getDangerText(e));
		}
	};
	$scope.openFileDialog = function($fileContent) {
		document.getElementById('fselector').click();
	};
	$scope.onFilePassChange = function() {
		$scope.showFDecrypt = $scope.filePassword.length > 3;
	};
	$scope.onPrivKeyChange = function() {
		$scope.requirePPass = $scope.manualprivkey.length == 128 || $scope.manualprivkey.length == 132;
		$scope.showPDecrypt = $scope.manualprivkey.length == 64;
	};
	$scope.onPrivKeyPassChange = function() {
		$scope.showPDecrypt = $scope.privPassword.length > 6;
	};
	$scope.decryptWallet = function() {
	    $scope.wallet=null;
        $scope.decryptStatus="";
		try {
			if ($scope.showPDecrypt && $scope.requirePPass) {
				$scope.wallet = Wallet.fromMyEtherWalletKey($scope.manualprivkey, $scope.privPassword);
                walletService.password = $scope.privPassword;
			} else if ($scope.showPDecrypt && !$scope.requirePPass) {
				$scope.wallet = new Wallet($scope.manualprivkey);
                walletService.password = '';
			} else if ($scope.showFDecrypt) {
				$scope.wallet = Wallet.getWalletFromPrivKeyFile($scope.fileContent, $scope.filePassword);
                walletService.password = $scope.filePassword;
			}
            walletService.wallet = $scope.wallet;
		} catch (e) {
            $scope.decryptStatus = $sce.trustAsHtml(globalFuncs.getDangerText(globalFuncs.errorMsgs[6]+e));
		}
        if($scope.wallet!=null) $scope.decryptStatus = $sce.trustAsHtml(globalFuncs.getSuccessText(globalFuncs.successMsgs[1]));
	};
};
module.exports = decryptWalletCtrl;


text:
require 'test_helper'

class TestModelTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  test "the truth" do
    assert true
  end
end


text:
"use strict";

var React = require('react');
var ReactDOM = require('react-dom');

const { bool, object, string, func, number } = React.PropTypes

var animateScroll = require('./animate-scroll');
var scrollSpy = require('./scroll-spy');
var scroller = require('./scroller');

var Helpers = {

  Scroll: function (Component) {

    return React.createClass({

      propTypes: {
        to: string.isRequired,
        offset: number,
        onClick: func
      },

      getDefaultProps: function() {
        return {offset: 0};
      },

      scrollTo : function(to) {
        scroller.scrollTo(to, this.props.smooth, this.props.duration, this.props.offset);
      },

      handleClick: function(event) {

        /*
         * give the posibility to override onClick
         */

        if(this.props.onClick) {
          this.props.onClick(event);
        }

        /*
         * dont bubble the navigation
         */

        if (event.stopPropagation) event.stopPropagation();
        if (event.preventDefault) event.preventDefault();

        /*
         * do the magic!
         */

        this.scrollTo(this.props.to);

      },

      componentDidMount: function() {

        scrollSpy.mount();

        if(this.props.spy) {
          var to = this.props.to;
          var element = null;
          var elemTopBound = 0;
          var elemBottomBound = 0;

          scrollSpy.addStateHandler((function() {
            if(scroller.getActiveLink() != to) {
                this.setState({ active : false });
            }
          }).bind(this));

          scrollSpy.addSpyHandler((function(y) {

            if(!element) {
                element = scroller.get(to);

                var cords = element.getBoundingClientRect();
                elemTopBound = (cords.top + y);
                elemBottomBound = elemTopBound + cords.height;
            }

            var offsetY = y - this.props.offset;
            var isInside = (offsetY >= elemTopBound && offsetY <= elemBottomBound);
            var isOutside = (offsetY < elemTopBound || offsetY > elemBottomBound);
            var activeLink = scroller.getActiveLink();

            if (isOutside && activeLink === to) {
              scroller.setActiveLink(void 0);
              this.setState({ active : false });

            } else if (isInside && activeLink != to) {
              scroller.setActiveLink(to);
              this.setState({ active : true });

              if(this.props.onSetActive) {
                this.props.onSetActive(to);
              }

              scrollSpy.updateStates();

            }
          }).bind(this));
        }
      },
      componentWillUnmount: function() {
        scrollSpy.unmount();
      },
      render: function() {
        var className = "";
        if(this.state && this.state.active) {
          className = ((this.props.className || "") + " " + (this.props.activeClass || "active")).trim();
        } else {
          className = this.props.className
        }
        return <Component {...this.props} {...this.state} className={className}  onClick={this.handleClick} />;
      }
    });
  },

  Element: function(Component) {
    return React.createClass({
      propTypes: {
        name: React.PropTypes.string.isRequired
      },
      componentDidMount: function() {
        var domNode = ReactDOM.findDOMNode(this);
        scroller.register(this.props.name, domNode);
      },
      componentWillUnmount: function() {
        scroller.unregister(this.props.name);
      },
      render: function() {
        return <Component {...this.props} {...this.state} />;
      }
    });
  }
};

module.exports = Helpers;


text:
class AudioIface {
public:
  virtual ~AudioIface();

//   virtual void playFile(const char*) =0;

  virtual void finish() =0;
};

#endif // QNT_CORE_AUDIOIFACE_HPP


text:
If you see a Code of Conduct violation, follow these steps:

1.  Let the person know that what they did is not appropriate and ask them to stop and/or edit their message(s).
2.  That person should immediately stop the behavior and correct the issue.
3.  If this doesn't happen, or if you're uncomfortable speaking up, [contact admins](#contacting-admins).
4.  As soon as available, an admin will join, identify themselves, and take [further action (see below)](#further-enforcement), starting with a warning, then temporary deactivation, then long-term deactivation.

When reporting, please include any relevant details, links, screenshots, context, or other information that may be used to better understand and resolve the situation.

**The admin team will prioritize the well-being and comfort of the recipients of the violation over the comfort of the violator.** See [some examples below](#enforcement-examples).

## Our Pledge

In the interest of fostering an open and welcoming environment, we as members of the Bundler community pledge to making participation in our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, technical preferences, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

-   Using welcoming and inclusive language.
-   Being respectful of differing viewpoints and experiences.
-   Gracefully accepting constructive feedback.
-   Focusing on what is best for the community.
-   Showing empathy and kindness towards other community members.

Examples of unacceptable behavior by participants include:

-   The use of sexualized language or imagery and unwelcome sexual attention or advances, including when simulated online. The only exception to sexual topics is channels/spaces specifically for topics of sexual identity.
-   Trolling, insulting/derogatory comments, and personal or political attacks.
-   Casual mention of slavery or indentured servitude and/or false comparisons of one's occupation or situation to slavery. Please consider using or asking about alternate terminology when referring to such metaphors in technology.
-   Making light of/making mocking comments about trigger warnings and content warnings.
-   Public or private harassment, deliberate intimidation, or threats.
-   Publishing others' private information, such as a physical or electronic address, without explicit permission. This includes any sort of "outing" of any aspect of someone's identity without their consent.
-   Publishing screenshots or quotes, especially from identity channels, without all quoted users' _explicit_ consent.
-   Publishing or telling others that a member belongs to a particular identity channel without asking their consent first.
-   Publishing of non-harassing private communication.
-   Any of the above even when [presented as "ironic" or "joking"](https://en.wikipedia.org/wiki/Hipster_racism).
-   Any attempt to present "reverse-ism" versions of the above as violations. Examples of reverse-isms are "reverse racism", "reverse sexism", "heterophobia", and "cisphobia".
-   Unsolicited explanations under the assumption that someone doesn't already know it. Ask before you teach! Don't assume what people's knowledge gaps are.
-   [Feigning or exaggerating surprise](https://www.recurse.com/manual#no-feigned-surprise) when someone admits to not knowing something.
-   "[Well-actuallies](https://www.recurse.com/manual#no-well-actuallys)"
-   Other conduct which could reasonably be considered inappropriate in a professional or community setting.

## Scope

This Code of Conduct applies both within community spaces and in other spaces involving the community. This includes the GitHub repository, the Bundler Slack instance, the Bundler Twitter community, private email communications in the context of the community, and any events where members of the community are participating, as well as adjacent communities and venues affecting the community's members.

Depending on the violation, the admins may decide that violations of this code of conduct that have happened outside of the scope of the community may deem an individual unwelcome, and take appropriate action to maintain the comfort and safety of its members.

This Code of Conduct is detailed for the purpose of removing ambiguity, not for the sake of strictness. It is the sincere hope of admins that it helps foster mutual understanding, and the creation of a space where everyone can participate in a way relevant to the project itself, without things going horribly due to accidental/well-intentioned toe stepping. Please be kind to one another!

## Admin Enforcement Process

Once the admins get involved, they will follow a documented series of steps and do their best to preserve the well-being of community members. This section covers actual concrete steps.

### Contacting Admins

You may get in touch with the Bundler admin team through any of the following methods:

- Email [the Bundler maintainers](http://bundler.io/contributors.html) as a group at [team@bundler.io](mailto:team@bundler.io).
- Directly message any maintainer in private (through Slack, Twitter, email, or other available option) if that is more comfortable

### Further Enforcement

If you've already followed the [initial enforcement steps](#enforcement), these are the steps admins will take for further enforcement, as needed:

1.  Repeat the request to stop.
2.  If the person doubles down, they will be removed from the discussion (where possible), and given an official warning.
3.  If the behavior continues or is repeated later, the person will be blocked/deactivated for 24 hours.
4.  If the behavior continues or is repeated after the temporary deactivation, a long-term (6-12mo) deactivation will be used.

On top of this, admins may remove any offending messages, images, contributions, etc, as they deem necessary.

Admins reserve full rights to skip any of these steps, at their discretion, if the violation is considered to be a serious and/or immediate threat to the health and well-being of members of the community. These include any threats, serious physical or verbal attacks, and other such behavior that would be completely unacceptable in any social setting that puts our members at risk.

Members expelled from events or venues with any sort of paid attendance will not be refunded.

### Who Watches the Watchers?

Admins and other leaders who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the community's leadership. These may include anything from removal from the admin team to a permanent ban from the community.

### Enforcement Examples

#### The Best Case

The vast majority of situations work out like this, in our experience. This interaction is common, and generally positive.

> Alex: "Yeah I used X and it was really crazy!"

> Patt: "Hey, could you not use that word? What about 'ridiculous' instead?"

> Alex: "oh sorry, sure." -> edits old message to say "it was really confusing!"

#### The Admin Case

Sometimes, though, you need to get admins involved. Admins will do their best to resolve conflicts, but people who were harmed by something **will take priority**.

> Patt: "Honestly, sometimes I just really hate using $language and anyone who uses it probably sucks at their job."

> Alex: "Whoa there, could you dial it back a bit? There's a CoC thing about attacking folks' tech use like that."

> Patt: "I'm not attacking anyone, are you deaf?"

> Alex: _DMs admin_ "hey uh. Can someone look at #general? Patt is getting a bit aggro. I tried to nudge them about it, but nope."

> MxAdmin1: <joins #general> "Hey Patt, admin here. Could you tone it down? This sort of attack is really not okay in this space."

> Patt: "Leave me alone I haven't said anything bad wtf is wrong with you."

> MxAdmin1: _removes patt_ _DMs patt_ "I mean it. Please refer to the CoC over at bundler.io/conduct.html if you have questions, but you can consider this an actual warning. I'd appreciate it if you reworded your messages in #general, since they made folks there uncomfortable. Let's try and be kind, yeah?"

> Patt: _Replies to DM_ "@mxadmin1 Okay sorry. I'm just frustrated and I'm kinda burnt out and I guess I got carried away. I'll DM Alex a note apologizing and edit my messages. Sorry for the trouble."

> MxAdmin1: _Replies to DM_ "@patt Thanks for that. I hear you on the stress. Burnout sucks :/. Have a good one!"

#### The Nope Case

> PepeTheFrog🐸: "Hi, I am a literal actual nazi and I think white supremacists are quite fashionable."

> Patt: "NOOOOPE. OH NOPE NOPE."

> Alex: "JFC NO. NOPE. `/admin nope nope nope @ #javascript`"

> MxAdmin1: "👀 Nope. NOPE NOPE NOPE. 🔥"

> PepeTheFrog🐸 has been deactivated.

## Attribution

This Code of Conduct is adapted from the [package.community Code of Conduct], adapted from the [WeAllJS Code of Conduct](https://wealljs.org/code-of-conduct), itself adapted from [Contributor Covenant](http://contributor-covenant.org) version 1.4, available at [http://contributor-covenant.org/version/1/4](http://contributor-covenant.org/version/1/4), as well as the LGBTQ in Technology Slack [Code of Conduct](http://lgbtq.technology/coc.html).

Additional thanks to [Contributor Covenant](http://contributor-covenant.org) for the [default code of conduct](https://github.com/bundler/bundler/blob/master/lib/bundler/templates/newgem/CODE_OF_CONDUCT.md.tt) included in generated gems.


text:
#ifndef PLASMA_SKELETALANIMATION_H
#define PLASMA_SKELETALANIMATION_H

#include <Plasma/StdDefs.h>
#include <Plasma/Animation/Skeleton.h>

#include <Fusion/VM/VM.h>

#include <CGMath/Ref.h>

#include <Base/Util/Bits.h>
#include <Base/Util/RCObject.h>
#include <Base/Util/RCP.h>
#include <Base/ADT/Vector.h>

NAMESPACE_BEGIN

class SkeletalPose;

#ifdef ABSOLUTE
#undef ABSOLUTE
#endif

#ifdef RELATIVE
#undef RELATIVE
#endif

/*==============================================================================
  CLASS SkeletalAnimation
==============================================================================*/

//! A loopable sequence should finish with the same pose as the first one.

class SkeletalAnimation:
   public RCObject,
   public VMProxy
{

public:

   /*----- types and enumerations ----*/

   enum {
      ABSOLUTE,
      RELATIVE
   };

   typedef Vector< RCP<SkeletalPose> >  PoseContainer;

   /*----- methods -----*/

   PLASMA_DLL_API SkeletalAnimation();

   PLASMA_DLL_API RCP<SkeletalAnimation> clone() const;
   PLASMA_DLL_API RCP<SkeletalAnimation> clone( uint startPose, uint endPos ) const;

   // Skeleton.
   inline Skeleton* skeleton() const   { return _skeleton.ptr(); }
   inline void skeleton( Skeleton* s ) { _skeleton = s; }

   // Poses.
   inline void reservePoses( uint );
   inline SkeletalPose* addPose( const Reff& ref = Reff::identity() );
   inline SkeletalPose* addPose( SkeletalPose* );
   inline void removePose( uint );
   inline SkeletalPose* pose( uint ) const;

   PLASMA_DLL_API uint getPoses( float time, SkeletalPose*& p0, SkeletalPose*& p1, float& t );
   PLASMA_DLL_API uint getPosesClamped( float time, SkeletalPose*& p0, SkeletalPose*& p1, float& t );
   PLASMA_DLL_API void setPose( uint, const Vector<Quatf>&, const Reff& );
   PLASMA_DLL_API void setPose( uint, const Vector<Reff>&, const Reff& );

   inline uint numPoses() const           { return (uint)_poses.size(); }

   // Time.
   inline void rate( float r )            { _rate = r; }
   inline float rate() const              { return _rate; }
   inline float duration() const          { return _duration; }

   // Cyclic.
   inline bool cyclic() const             { return getbit( _flags, 0 ); }
   inline void cyclic( bool v )           { _flags = setbit( _flags, 0, v ); }

   // Type.
   inline uint type() const               { return getbits( _flags, 1, 1 ); }
   inline void type( uint t )             { _flags = setbits( _flags, 1, 1, t ); }
   PLASMA_DLL_API void makeRelative();
   PLASMA_DLL_API void makeAbsolute();

   inline const Vec3f& velocity() const   { return _velocity; }
   inline void velocity( const Vec3f& v ) { _velocity = v; }
   inline const Vec3f& offset() const     { return _offset; }
   inline void offset( const Vec3f& o )   { _offset = o; }

   // Utility.
   PLASMA_DLL_API void prepare();

   PLASMA_DLL_API void print() const;

   // VM.
   virtual const char* meta() const;

protected:

   /*----- methods -----*/

   PLASMA_DLL_API virtual ~SkeletalAnimation();

   inline void updateDuration() { _duration = (_poses.size()-1) / _rate; }

private:

   /*----- data members -----*/

   //! NAME          SIZE   LOCATION         DESCRIPTION
   //! cyclic        (1)   _flags[ 0: 0]     Set to 1 when an animation is cyclic.
   //! relative      (1)   _flags[ 1: 1]     Set to 1 when an animation is relative (absolute otherwise).

   uint32_t      _flags;
   PoseContainer _poses;
   float         _rate;
   float         _duration;
   Vec3f         _velocity;
   Vec3f         _offset;
   RCP<Skeleton> _skeleton;
};

/*==============================================================================
  CLASS SkeletalPose
==============================================================================*/

//!

class SkeletalPose
   : public RCObject
{

public:

   /*----- types and enumerations ----*/

   typedef Vector< Quatf >  BoneContainer;

   /*----- methods -----*/

   SkeletalPose( const Reff& ref = Reff::identity(), uint size = 0 );

   PLASMA_DLL_API RCP<SkeletalPose> clone() const;

   inline void referential( const Reff& ref )      { _referential = ref; }
   inline const Reff& referential() const          { return _referential; }

   inline void position( const Vec3f& pos )        { _referential.position( pos ); }
   inline const Vec3f& position() const            { return _referential.position(); }
   inline void orientation( const Quatf& orient )  { _referential.orientation( orient ); }
   inline const Quatf& orientation() const         { return _referential.orientation(); }

   inline void reserveBones( uint qty )            { _bonesOrient.reserve( qty ); }
   inline void addBone( const Quatf& orient )      { _bonesOrient.pushBack( orient ); }
   inline const BoneContainer& bones() const       { return _bonesOrient; }
   inline BoneContainer& bones()                   { return _bonesOrient; }
   inline uint numBones() const                    { return (uint)_bonesOrient.size(); }

   PLASMA_DLL_API void print() const;

protected:

   /*----- methods -----*/

   virtual ~SkeletalPose();

private:

   /*----- data members -----*/

   Reff          _referential;
   BoneContainer _bonesOrient;
};

//------------------------------------------------------------------------------
//!
inline void
SkeletalAnimation::reservePoses( uint qty )
{
   _poses.reserve( qty );
}

//------------------------------------------------------------------------------
//!
inline SkeletalPose*
SkeletalAnimation::addPose( const Reff& ref )
{
   _poses.pushBack( new SkeletalPose(ref) );
   updateDuration();
   return _poses.back().ptr();
}

//------------------------------------------------------------------------------
//!
inline SkeletalPose*
SkeletalAnimation::addPose( SkeletalPose* pose )
{
   _poses.pushBack( pose );
   updateDuration();
   return _poses.back().ptr();
}

//------------------------------------------------------------------------------
//!
inline void
SkeletalAnimation::removePose( const uint p )
{
   _poses.erase( _poses.begin() + p );
}

//------------------------------------------------------------------------------
//!
inline SkeletalPose*
SkeletalAnimation::pose( const uint p ) const
{
   return _poses[p].ptr();
}

NAMESPACE_END

#endif


text:
"""Code for parallel-building a set of targets, if needed."""
from __future__ import print_function
import errno, os, stat, signal, sys, tempfile, time
from . import cycles, env, helpers, jobserver, logs, paths, state
from .logs import debug2, err, warn, meta

def _nice(t):
    return state.relpath(t, env.v.STARTDIR)

def _try_stat(filename):
    try:
        return os.lstat(filename)
    except OSError as e:
        if e.errno == errno.ENOENT:
            return None
        else:
            raise

def _has_pep446():
    """Test the python version whether the PEP making file descriptors
    non-inheritable applies"""
    return sys.version_info >= (3,4)

log_reader_pid = None
stderr_fd = None

def close_stdin():
    f = open('/dev/null')
    os.dup2(f.fileno(), 0)
    f.close()

def start_stdin_log_reader(status, details, pretty, color,
                           debug_locks, debug_pids):
    """Redirect stderr to a redo-log instance with the given options.

    Then we automatically run logs.setup() to send the right data format
    to that redo-log instance.

    After this, be sure to run await_log_reader() before exiting.
    """
    global log_reader_pid
    global stderr_fd
    r, w = os.pipe()    # main pipe to redo-log
    ar, aw = os.pipe()  # ack pipe from redo-log --ack-fd
    if _has_pep446(): os.set_inheritable(aw, True)
    sys.stdout.flush()
    sys.stderr.flush()
    pid = os.fork()
    if pid:
        # parent
        log_reader_pid = pid
        stderr_fd = os.dup(2)  # save for after the log pipe gets closed
        os.close(r)
        os.close(aw)
        b = os.read(ar, 8)
        if not b:
            # subprocess died without sending us anything: that's bad.
            err('failed to start redo-log subprocess; cannot continue.\n')
            os._exit(99)
        assert b == b'REDO-OK\n'
        # now we know the subproc is running and will report our errors
        # to stderr, so it's okay to lose our own stderr.
        os.close(ar)
        os.dup2(w, 1)
        os.dup2(w, 2)
        os.close(w)
        logs.setup(tty=sys.stderr, parent_logs=True, pretty=False, color=False)
    else:
        # child
        try:
            os.close(ar)
            os.close(w)
            os.dup2(r, 0)
            os.close(r)
            # redo-log sends to stdout (because if you ask for logs, that's
            # the output you wanted!).  But redo itself sends logs to stderr
            # (because they're incidental to the thing you asked for).
            # To make these semantics work, we point redo-log's stdout at
            # our stderr when we launch it.
            os.dup2(2, 1)
            argv = [
                'redo-log',
                '--recursive', '--follow',
                '--ack-fd', str(aw),
                ('--status' if status and os.isatty(2) else '--no-status'),
                ('--details' if details else '--no-details'),
                ('--pretty' if pretty else '--no-pretty'),
                ('--debug-locks' if debug_locks else '--no-debug-locks'),
                ('--debug-pids' if debug_pids else '--no-debug-pids'),
            ]
            if color != 1:
                argv.append('--color' if color >= 2 else '--no-color')
            argv.append('-')
            os.execvp(argv[0], argv)
        except Exception as e:  # pylint: disable=broad-except
            sys.stderr.write('redo-log: exec: %s\n' % e)
        finally:
            os._exit(99)

def await_log_reader():
    """Await the redo-log instance we redirected stderr to, if any."""
    if not env.v.LOG:
        return
    if log_reader_pid > 0:
        # never actually close fd#1 or fd#2; insanity awaits.
        # replace it with something else instead.
        # Since our stdout/stderr are attached to redo-log's stdin,
        # this will notify redo-log that it's time to die (after it finishes
        # reading the logs)
        os.dup2(stderr_fd, 1)
        os.dup2(stderr_fd, 2)
        os.waitpid(log_reader_pid, 0)

class _BuildJob(object):
    def __init__(self, t, sf, lock, shouldbuildfunc, donefunc):
        self.t = t  # original target name, not relative to env.v.BASE
        self.sf = sf
        self.tmpname = None
        self.lock = lock
        self.shouldbuildfunc = shouldbuildfunc
        self.donefunc = donefunc
        self.before_t = _try_stat(self.t)

        # attributes of the running process
        self.outfile = None

    def start(self):
        """Actually start running this job in a subproc, if needed."""
        assert self.lock.owned
        try:
            try:
                is_target, dirty = self.shouldbuildfunc(self.t)
            except cycles.CyclicDependencyError:
                err('cyclic dependency while checking %s\n' % _nice(self.t))
                raise helpers.ImmediateReturn(208)
            if not dirty:
                # target doesn't need to be built; skip the whole task
                if is_target:
                    meta('unchanged', state.target_relpath(self.t))
                return self._finalize(0)
        except helpers.ImmediateReturn as e:
            return self._finalize(e.rv)

        if env.v.NO_OOB or dirty == True:  # pylint: disable=singleton-comparison
            self._start_self()
        else:
            self._start_deps_unlocked(dirty)

    def _start_self(self):
        """Run jobserver.start() to build this object's target file."""
        assert self.lock.owned
        t = self.t
        sf = self.sf
        newstamp = sf.read_stamp()
        if (sf.is_generated and
                newstamp != state.STAMP_MISSING and
                (sf.is_override or state.detect_override(sf.stamp, newstamp))):
            state.warn_override(_nice(t))
            if not sf.is_override:
                warn('%s - old: %r\n' % (_nice(t), sf.stamp))
                warn('%s - new: %r\n' % (_nice(t), newstamp))
                sf.set_override()
            sf.save()
            # fall through and treat it the same as a static file
        if (os.path.exists(t) and not os.path.isdir(t + '/.')
                and (sf.is_override or not sf.is_generated)):
            # an existing source file that was not generated by us.
            # This step is mentioned by djb in his notes.
            # For example, a rule called default.c.do could be used to try
            # to produce hello.c, but we don't want that to happen if
            # hello.c was created by the end user.
            debug2("-- static (%r)\n" % t)
            if not sf.is_override:
                sf.set_static()
            sf.save()
            return self._finalize(0)
        sf.zap_deps1()
        (dodir, dofile, _, basename, ext) = paths.find_do_file(sf)
        if not dofile:
            if os.path.exists(t):
                sf.set_static()
                sf.save()
                return self._finalize(0)
            else:
                err('no rule to redo %r\n' % t)
                sf.set_failed()
                sf.save()
                return self._finalize(1)
        # There is no good place for us to pre-create a temp file for
        # stdout.  The target dir might not exist yet, or it might currently
        # exist but get wiped by the .do script.  Other dirs, like the one
        # containing the .do file, might be mounted readonly.  We can put it
        # in the system temp dir, but then we can't necessarily rename it to
        # the target filename because it might cross filesystem boundaries.
        # Also, if redo is interrupted, it would leave a temp file lying
        # around.  To avoid all this, use mkstemp() to create a temp file
        # wherever it wants to, and immediately unlink it, but keep a file
        # handle open.  When the .do script finishes, we can copy the
        # content out of that nameless file handle into a file in the same
        # dir as the target (which by definition must now exist, if you
        # wanted the target to exist).
        #
        # On the other hand, the $3 temp filename can be hardcoded to be in
        # the target directory, even if that directory does not exist.
        # It's not *redo*'s job to create that file.  The .do file will
        # create it, if it wants, and it's the .do file's job to first ensure
        # that the directory exists.
        tmpbase = os.path.join(dodir, basename + ext)
        self.tmpname = tmpbase + '.redo.tmp'
        helpers.unlink(self.tmpname)
        ffd, fname = tempfile.mkstemp(prefix='redo.', suffix='.tmp')
        helpers.close_on_exec(ffd, True)
        os.unlink(fname)
        self.outfile = os.fdopen(ffd, 'w+b')
        # this will run in the dofile's directory, so use only basenames here
        arg1 = basename + ext  # target name (including extension)
        arg2 = basename        # target name (without extension)
        argv = ['sh', '-e',
                dofile,
                arg1,
                arg2,
                # $3 temp output file name
                state.relpath(os.path.abspath(self.tmpname), dodir),
               ]
        if env.v.VERBOSE:
            argv[1] += 'v'
        if env.v.XTRACE:
            argv[1] += 'x'
        firstline = open(os.path.join(dodir, dofile)).readline().strip()
        if firstline.startswith('#!/'):
            argv[0:2] = firstline[2:].split(' ')
        # make sure to create the logfile *before* writing the meta() about
        # it.  that way redo-log won't trace into an obsolete logfile.
        #
        # We open a temp file and atomically rename it into place here.
        # This guarantees that redo-log will never experience a file that
        # gets truncated halfway through reading (eg.  if we build the same
        # target more than once in a run).  Similarly, we don't want to
        # actually unlink() the file in case redo-log is about to start
        # reading a previous instance created during this session.  It
        # should always see either the old or new instance.
        if env.v.LOG:
            lfend = state.logname(self.sf.id)
            # Make sure the temp file is in the same directory as lfend,
            # so we can be sure of our ability to rename it atomically later.
            lfd, lfname = tempfile.mkstemp(
                prefix='redo.',
                suffix='.log.tmp',
                dir=os.path.dirname(lfend))
            os.fdopen(lfd, 'w')
            os.rename(lfname, lfend)
        dof = state.File(name=os.path.join(dodir, dofile))
        dof.set_static()
        dof.save()
        state.commit()
        meta('do', state.target_relpath(t))
        def call_subproc():
            self._subproc(dodir, basename, ext, argv)
        def call_exited(t, rv):
            self._subproc_exited(t, rv, argv)
        jobserver.start(t, call_subproc, call_exited)

    def _start_deps_unlocked(self, dirty):
        """Run jobserver.start to build objects needed to check deps.

        Out-of-band redo of some sub-objects.  This happens when we're not
        quite sure if t needs to be built or not (because some children
        look dirty, but might turn out to be clean thanks to redo-stamp
        checksums).  We have to call redo-unlocked to figure it all out.

        Note: redo-unlocked will handle all the updating of sf, so we don't
        have to do it here, nor call _record_new_state.  However, we have to
        hold onto the lock because otherwise we would introduce a race
        condition; that's why it's called redo-unlocked, because it doesn't
        grab a lock.
        """
        # FIXME: redo-unlocked is kind of a weird hack.
        #  Maybe we should just start jobs to build the necessary deps
        #  directly from this process, and when done, reconsider building
        #  the target we started with.  But that makes this one process's
        #  build recursive, where currently it's flat.
        here = os.getcwd()
        def _fix(p):
            return state.relpath(os.path.join(env.v.BASE, p), here)
        argv = (['redo-unlocked', _fix(self.sf.name)] +
                list(set(_fix(d.name) for d in dirty)))
        meta('check', state.target_relpath(self.t))
        state.commit()
        def subtask():
            os.environ['REDO_DEPTH'] = env.v.DEPTH + '  '
            # python ignores SIGPIPE
            signal.signal(signal.SIGPIPE, signal.SIG_DFL)
            os.execvp(argv[0], argv)
            assert 0
            # returns only if there's an exception
        def job_exited(t, rv):
            return self._finalize(rv)
        jobserver.start(self.t, jobfunc=subtask, donefunc=job_exited)

    def _subproc(self, dodir, basename, ext, argv):
        """The function called by jobserver.start to exec the build script.

        This is run in the *child* process.
        """
        # careful: REDO_PWD was the PWD relative to the STARTPATH at the time
        # we *started* building the current target; but that target ran
        # redo-ifchange, and it might have done it from a different directory
        # than we started it in.  So os.getcwd() might be != REDO_PWD right
        # now.
        assert state.is_flushed()
        newp = os.path.realpath(dodir)
        # CDPATH apparently caused unexpected 'cd' output on some platforms.
        os.unsetenv('CDPATH')
        os.environ['REDO_PWD'] = state.relpath(newp, env.v.STARTDIR)
        os.environ['REDO_TARGET'] = basename + ext
        os.environ['REDO_DEPTH'] = env.v.DEPTH + '  '
        if env.v.XTRACE == 1:
            os.environ['REDO_XTRACE'] = '0'
        if env.v.VERBOSE == 1:
            os.environ['REDO_VERBOSE'] = '0'
        cycles.add(self.lock.fid)
        if dodir:
            os.chdir(dodir)
        os.dup2(self.outfile.fileno(), 1)
        os.close(self.outfile.fileno())
        helpers.close_on_exec(1, False)
        if env.v.LOG:
            cur_inode = str(os.fstat(2).st_ino)
            if not env.v.LOG_INODE or cur_inode == env.v.LOG_INODE:
                # .do script has *not* redirected stderr, which means we're
                # using redo-log's log saving mode.  That means subprocs
                # should be logged to their own file.  If the .do script
                # *does* redirect stderr, that redirection should be inherited
                # by subprocs, so we'd do nothing.
                logf = open(state.logname(self.sf.id), 'w')
                new_inode = os.fstat(logf.fileno()).st_ino
                os.environ['REDO_LOG'] = '1'  # .do files can check this
                os.environ['REDO_LOG_INODE'] = str(new_inode)
                os.dup2(logf.fileno(), 2)
                helpers.close_on_exec(2, False)
                logf.close()
        else:
            if 'REDO_LOG_INODE' in os.environ:
                del os.environ['REDO_LOG_INODE']
            os.environ['REDO_LOG'] = ''
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)  # python ignores SIGPIPE
        if env.v.VERBOSE or env.v.XTRACE:
            logs.write('* %s' % ' '.join(argv).replace('\n', ' '))
        os.execvp(argv[0], argv)
        # FIXME: it would be nice to log the exit code to logf.
        #  But that would have to happen in the parent process, which doesn't
        #  have logf open.
        assert 0
        # returns only if there's an exception

    def _subproc_exited(self, t, rv, argv):
        """Called by the jobserver when our subtask exits.

        This is run in the *parent* process.
        """
        try:
            state.check_sane()
            rv = self._record_new_state(t, rv, argv)
            state.commit()
        finally:
            self._finalize(rv)

    def _record_new_state(self, t, rv, argv):
        """After a subtask finishes, handle its changes to the output file.

        This is run in the *parent* process.

        This includes renaming temp files into place and detecting mistakes
        (like writing directly to $1 instead of $3).  We also have to record
        the new file stamp data for the completed target.
        """
        outfile = self.outfile
        before_t = self.before_t
        after_t = _try_stat(t)
        st1 = os.fstat(outfile.fileno())
        st2 = _try_stat(self.tmpname)
        if (after_t and
                (not before_t or before_t.st_mtime != after_t.st_mtime) and
                not stat.S_ISDIR(after_t.st_mode)):
            err('%s modified %s directly!\n' % (argv[2], t))
            err('...you should update $3 (a temp file) or stdout, not $1.\n')
            rv = 206
        elif st2 and st1.st_size > 0:
            err('%s wrote to stdout *and* created $3.\n' % argv[2])
            err('...you should write status messages to stderr, not stdout.\n')
            rv = 207
        if rv == 0:
            # FIXME: race condition here between updating stamp/is_generated
            # and actually renaming the files into place.  There needs to
            # be some kind of two-stage commit, I guess.
            if st1.st_size > 0 and not st2:
                # script wrote to stdout.  Copy its contents to the tmpfile.
                helpers.unlink(self.tmpname)
                try:
                    newf = open(self.tmpname, 'wb')
                except IOError as e:
                    dnt = os.path.dirname(os.path.abspath(t))
                    if not os.path.exists(dnt):
                        # This could happen, so report a simple error message
                        # that gives a hint for how to fix your .do script.
                        err('%s: target dir %r does not exist!\n' % (t, dnt))
                    else:
                        # This could happen for, eg. a permissions error on
                        # the target directory.
                        err('%s: copy stdout: %s\n' % (t, e))
                    rv = 209
                else:
                    self.outfile.seek(0)
                    while 1:
                        b = self.outfile.read(1024*1024)
                        if not b:
                            break
                        newf.write(b)
                    newf.close()
                    st2 = _try_stat(self.tmpname)
            if st2:
                # either $3 file was created *or* stdout was written to.
                # therefore tmpfile now exists.
                try:
                    # Atomically replace the target file
                    os.rename(self.tmpname, t)
                except OSError as e:
                    # This could happen for, eg. a permissions error on
                    # the target directory.
                    err('%s: rename %s: %s\n' % (t, self.tmpname, e))
                    rv = 209
            else: # no output generated at all; that's ok
                helpers.unlink(t)
            sf = self.sf
            sf.refresh()
            sf.is_generated = True
            sf.is_override = False
            if sf.is_checked() or sf.is_changed():
                # it got checked during the run; someone ran redo-stamp.
                # update_stamp would call set_changed(); we don't want that,
                # so only use read_stamp.
                sf.stamp = sf.read_stamp()
            else:
                sf.csum = None
                sf.update_stamp()
                sf.set_changed()
        # rv might have changed up above
        if rv:
            helpers.unlink(self.tmpname)
            sf = self.sf
            sf.set_failed()
        sf.zap_deps2()
        sf.save()
        outfile.close()
        meta('done', '%d %s' % (rv, state.target_relpath(self.t)))
        return rv

    def _finalize(self, rv):
        """After a target is built, report completion and unlock.

        This is run in the *parent* process.
        Note: you usually need to call _record_new_state() first.
        """
        try:
            self.donefunc(self.t, rv)
            assert self.lock.owned
        finally:
            self.lock.unlock()

def run(targets, shouldbuildfunc):
    """Build the given list of targets, if necessary.

    Builds in parallel using whatever jobserver tokens can be obtained.

    Args:
      targets: a list of target filenames to consider building.
      shouldbuildfunc: a function(target) which determines whether the given
        target needs to be built, as of the time it is called.

    Returns:
      0 if all necessary targets returned exit code zero; nonzero otherwise.
    """
    retcode = [0]  # a list so that it can be reassigned from done()
    if env.v.SHUFFLE:
        import random
        random.shuffle(targets)

    locked = []

    def job_exited(t, rv):
        if rv:
            retcode[0] = 1

    if env.v.TARGET and not env.v.UNLOCKED:
        me = os.path.join(env.v.STARTDIR,
                          os.path.join(env.v.PWD, env.v.TARGET))
        myfile = state.File(name=me)
        selflock = state.Lock(state.LOG_LOCK_MAGIC + myfile.id)
    else:
        selflock = myfile = me = None

    for t in targets:
        if '\n' in t:
            err('%r: filenames containing newlines are not allowed.\n' % t)
            return 204

    def cheat():
        if not selflock:
            return 0
        selflock.trylock()
        if not selflock.owned:
            # redo-log already owns it: let's cheat.
            # Give ourselves one extra token so that the "foreground" log
            # can always make progress.
            return 1
        else:
            # redo-log isn't watching us (yet)
            selflock.unlock()
            return 0

    # In the first cycle, we just build as much as we can without worrying
    # about any lock contention.  If someone else has it locked, we move on.
    seen = {}
    lock = None
    for t in targets:
        if not t:
            err('cannot build the empty target ("").\n')
            retcode[0] = 204
            break
        assert state.is_flushed()
        if t in seen:
            continue
        seen[t] = 1
        if not jobserver.has_token():
            state.commit()
        jobserver.ensure_token_or_cheat(t, cheat)
        if retcode[0] and not env.v.KEEP_GOING:
            break
        if not state.check_sane():
            err('.redo directory disappeared; cannot continue.\n')
            retcode[0] = 205
            break
        f = state.File(name=t)
        lock = state.Lock(f.id)
        if env.v.UNLOCKED:
            lock.owned = True
        else:
            lock.trylock()
        if not lock.owned:
            meta('locked', state.target_relpath(t))
            locked.append((f.id, t, f.name))
        else:
            # We had to create f before we had a lock, because we need f.id
            # to make the lock.  But someone may have updated the state
            # between then and now.
            # FIXME: separate obtaining the fid from creating the File.
            # FIXME: maybe integrate locking into the File object?
            f.refresh()
            _BuildJob(t, f, lock,
                      shouldbuildfunc=shouldbuildfunc,
                      donefunc=job_exited).start()
        state.commit()
        assert state.is_flushed()
        lock = None

    del lock

    # Now we've built all the "easy" ones.  Go back and just wait on the
    # remaining ones one by one.  There's no reason to do it any more
    # efficiently, because if these targets were previously locked, that
    # means someone else was building them; thus, we probably won't need to
    # do anything.  The only exception is if we're invoked as redo instead
    # of redo-ifchange; then we have to redo it even if someone else already
    # did.  But that should be rare.
    while locked or jobserver.running():
        state.commit()
        jobserver.wait_all()
        assert jobserver._mytokens <= 1  # pylint: disable=protected-access
        jobserver.ensure_token_or_cheat('self', cheat)
        # at this point, we don't have any children holding any tokens, so
        # it's okay to block below.
        if retcode[0] and not env.v.KEEP_GOING:
            break
        if locked:
            if not state.check_sane():
                err('.redo directory disappeared; cannot continue.\n')
                retcode[0] = 205
                break
            fid, t, _ = locked.pop(0)
            lock = state.Lock(fid)
            backoff = 0.01
            lock.trylock()
            while not lock.owned:
                # Don't spin with 100% CPU while we fight for the lock.
                import random
                time.sleep(random.random() * min(backoff, 1.0))
                backoff *= 2
                # after printing this line, redo-log will recurse into t,
                # whether it's us building it, or someone else.
                meta('waiting', state.target_relpath(t))
                try:
                    lock.check()
                except cycles.CyclicDependencyError:
                    err('cyclic dependency while building %s\n' % _nice(t))
                    retcode[0] = 208
                    return retcode[0]
                # this sequence looks a little silly, but the idea is to
                # give up our personal token while we wait for the lock to
                # be released; but we should never run ensure_token() while
                # holding a lock, or we could cause deadlocks.
                jobserver.release_mine()
                lock.waitlock()
                # now t is definitely free, so we get to decide whether
                # to build it.
                lock.unlock()
                jobserver.ensure_token_or_cheat(t, cheat)
                lock.trylock()
            assert lock.owned
            meta('unlocked', state.target_relpath(t))
            if state.File(name=t).is_failed():
                err('%s: failed in another thread\n' % _nice(t))
                retcode[0] = 2
                lock.unlock()
            else:
                _BuildJob(t, state.File(fid=fid), lock,
                          shouldbuildfunc=shouldbuildfunc,
                          donefunc=job_exited).start()
            lock = None
    state.commit()
    return retcode[0]


text:
/* global describe it */

var Y = require('../')
  , Vow = require('vow')
  , assert = require('assert')

describe("Y.when", function(){
  var vow_promise
    , p

  it("should ruturn the exact same passed a `ya-promise` Promise", function(){
    var d = Y.defer()
      , p0 = d.promise
      , p1 = Y.when(p0)

    assert.strictEqual(p0, p1)
  })

  it("should return a native promise when passed a foreign promise", function(){
    vow_promise = Vow.promise()
    p = Y.when(vow_promise)
    assert.ok( Y.isPromise( p ) )
  })

  it("native promise should be fulfilled when the foreign promise is fulfilled", function(done){
    p.then(function(v){
      if ( v !== "ok" ) done(new Error("fulfilled native promise is not equal to 'ok'"))
      else done()
    })
    vow_promise.fulfill("ok")
  })

  it("should return a fulfilled promise when passes a non-thenable", function(done){
    var resolved = Y.when("resolved")
    resolved.then(function(v){
      if (v !== "resolved") done(new Error("fulfilled promise value not equal to 'resolve'"))
      else done()
    })
  })
})


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_82a.cpp
Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml
Template File: source-sinks-82a.tmpl.cpp
*/
/*
 * @description
 * CWE: 761 Free Pointer not at Start of Buffer
 * BadSource: listen_socket Read data using a listen socket (server side)
 * Sinks:
 *    GoodSink: free() memory correctly at the start of the buffer
 *    BadSink : free() memory not at the start of the buffer
 * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
 *
 * */

#include "std_testcase.h"
#include "CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_82.h"

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif

#define TCP_PORT 27015
#define LISTEN_BACKLOG 5

#define SEARCH_CHAR 'S'

namespace CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_82
{

#ifndef OMITBAD

void bad()
{
    char * data;
    data = (char *)malloc(100*sizeof(char));
    data[0] = '\0';
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        char *replace;
        SOCKET listenSocket = INVALID_SOCKET;
        SOCKET acceptSocket = INVALID_SOCKET;
        size_t dataLen = strlen(data);
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a listen socket */
            listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (listenSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = INADDR_ANY;
            service.sin_port = htons(TCP_PORT);
            if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
            {
                break;
            }
            acceptSocket = accept(listenSocket, NULL, NULL);
            if (acceptSocket == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed */
            recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* Append null terminator */
            data[dataLen + recvResult / sizeof(char)] = '\0';
            /* Eliminate CRLF */
            replace = strchr(data, '\r');
            if (replace)
            {
                *replace = '\0';
            }
            replace = strchr(data, '\n');
            if (replace)
            {
                *replace = '\0';
            }
        }
        while (0);
        if (listenSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(listenSocket);
        }
        if (acceptSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(acceptSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_82_base* baseObject = new CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_82_bad;
    baseObject->action(data);
    delete baseObject;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
    char * data;
    data = (char *)malloc(100*sizeof(char));
    data[0] = '\0';
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        char *replace;
        SOCKET listenSocket = INVALID_SOCKET;
        SOCKET acceptSocket = INVALID_SOCKET;
        size_t dataLen = strlen(data);
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a listen socket */
            listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (listenSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = INADDR_ANY;
            service.sin_port = htons(TCP_PORT);
            if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
            {
                break;
            }
            acceptSocket = accept(listenSocket, NULL, NULL);
            if (acceptSocket == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed */
            recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* Append null terminator */
            data[dataLen + recvResult / sizeof(char)] = '\0';
            /* Eliminate CRLF */
            replace = strchr(data, '\r');
            if (replace)
            {
                *replace = '\0';
            }
            replace = strchr(data, '\n');
            if (replace)
            {
                *replace = '\0';
            }
        }
        while (0);
        if (listenSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(listenSocket);
        }
        if (acceptSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(acceptSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_82_base* baseObject = new CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_82_goodB2G;
    baseObject->action(data);
    delete baseObject;
}

void good()
{
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_listen_socket_82; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#66000000"
    android:padding="@dimen/widget_margin"
    android:id="@+id/recap_id">

    <RelativeLayout
        android:id="@+id/recap_loader"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:visibility="gone">

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/recap_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:visibility="visible">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:padding="2dp"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/today_color_label"
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:focusable="false"
                    android:gravity="center"
                    android:layout_margin="2dp"
                    android:text="@string/blue_remaining_default"
                    android:textSize="12sp"
                    android:background="#66222222"
                    android:textColor="#ffffff"/>

                <TextView
                    android:id="@+id/tomorrow_color_label"
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:layout_margin="2dp"
                    android:focusable="false"
                    android:gravity="center"
                    android:text="@string/blue_remaining_default"
                    android:textSize="12sp"
                    android:background="#66222222"
                    android:textColor="#ffffff"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:layout_marginLeft="4dp"
                android:layout_marginRight="4dp"
                android:layout_marginTop="0dp"
                android:layout_marginBottom="4dp"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/remaining_blue"
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="3"
                    android:focusable="false"
                    android:gravity="center"
                    android:text="@string/blue_remaining_default"
                    android:textSize="10sp"
                    android:background="@color/tempo_blue"
                    android:textColor="#ffffff"/>

                <TextView
                    android:id="@+id/remaining_white"
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="3"
                    android:focusable="false"
                    android:gravity="center"
                    android:text="@string/white_remaining_default"
                    android:textSize="10sp"
                    android:background="@color/tempo_white"
                    android:textColor="#111111"/>

                <TextView
                    android:id="@+id/remaining_red"
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="3"
                    android:focusable="false"
                    android:gravity="center"
                    android:text="@string/red_remaining_default"
                    android:textSize="10sp"
                    android:background="@color/tempo_red"
                    android:textColor="#ffffff"/>

            </LinearLayout>

        </LinearLayout>

    </RelativeLayout>

</RelativeLayout>


text:
package org.osc.core.broker.service.persistence;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.apache.commons.collections4.CollectionUtils;
import org.osc.core.broker.model.entities.appliance.DistributedAppliance;
import org.osc.core.broker.model.entities.appliance.VirtualSystem;
import org.osc.core.broker.model.entities.virtualization.openstack.AvailabilityZone;
import org.osc.core.broker.model.entities.virtualization.openstack.DeploymentSpec;
import org.osc.core.broker.model.entities.virtualization.openstack.HostAggregate;
import org.osc.core.broker.service.dto.openstack.AvailabilityZoneDto;
import org.osc.core.broker.service.dto.openstack.DeploymentSpecDto;
import org.osc.core.broker.service.dto.openstack.HostAggregateDto;

public class DeploymentSpecEntityMgr {

    public static DeploymentSpec createEntity(// for add
            DeploymentSpecDto dto, VirtualSystem vs) throws Exception {
        DeploymentSpec ds = new DeploymentSpec(vs, dto.getRegion(), dto.getProjectId(), dto.getManagementNetworkId(),
                dto.getInspectionNetworkId(), dto.getFloatingIpPoolName());
        toEntity(ds, dto);
        return ds;

    }

    public static void toEntity(DeploymentSpec ds, DeploymentSpecDto dto) {
        ds.setName(dto.getName());
        ds.setManagementNetworkName(dto.getManagementNetworkName());
        ds.setInspectionNetworkName(dto.getInspectionNetworkName());
        ds.setProjectName(dto.getProjectName());
        ds.setInstanceCount(dto.getCount());
        ds.setShared(dto.isShared());
        ds.setNamespace(dto.getNamespace());
    }

    public static void fromEntity(DeploymentSpec ds, DeploymentSpecDto dto) {
        dto.setId(ds.getId());
        dto.setParentId(ds.getVirtualSystem().getId());
        dto.setName(ds.getName());
        dto.setProjectName(ds.getProjectName());
        dto.setProjectId(ds.getProjectId());
        dto.setRegion(ds.getRegion());
        dto.setFloatingIpPoolName(ds.getFloatingIpPoolName());
        dto.setManagementNetworkName(ds.getManagementNetworkName());
        dto.setManagementNetworkId(ds.getManagementNetworkId());
        dto.setInspectionNetworkName(ds.getInspectionNetworkName());
        dto.setInspectionNetworkId(ds.getInspectionNetworkId());
        dto.setPortGroupId(ds.getPortGroupId());
        dto.setCount(ds.getInstanceCount());
        dto.setNamespace(ds.getNamespace());
        dto.setExternalId(ds.getExternalId());
        if (ds.getLastJob() != null) {
            dto.setLastJobStatus(ds.getLastJob().getStatus().name());
            dto.setLastJobState(ds.getLastJob().getState().name());
            dto.setLastJobId(ds.getLastJob().getId());
        }
        dto.setShared(ds.isShared());
        dto.setMarkForDeletion(ds.getMarkedForDeletion());
        if (!ds.getAvailabilityZones().isEmpty()) {
            Set<AvailabilityZoneDto> azDtoSet = new HashSet<>();
            for (AvailabilityZone az : ds.getAvailabilityZones()) {
                AvailabilityZoneDto azDto = new AvailabilityZoneDto();
                AvailabilityZoneEntityMgr.fromEntity(az, azDto);
                azDtoSet.add(azDto);
            }
            dto.setAvailabilityZones(azDtoSet);
        } else if (!ds.getHosts().isEmpty()) {
            dto.setHosts(HostEntityMgr.fromEntity(ds.getHosts()));
        } else if (!ds.getHostAggregates().isEmpty()) {
            Set<HostAggregateDto> hostAggrSet = new HashSet<>();
            for (HostAggregate hostAggr : ds.getHostAggregates()) {
                HostAggregateDto hostAggrDto = new HostAggregateDto();
                HostAggregateEntityMgr.fromEntity(hostAggr, hostAggrDto);
                hostAggrSet.add(hostAggrDto);
            }
            dto.setHostAggregates(hostAggrSet);
        }
    }

    public static List<DeploymentSpec> listDeploymentSpecByVirtualSystem(EntityManager em, VirtualSystem vs) {
        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<DeploymentSpec> query = cb.createQuery(DeploymentSpec.class);

        Root<DeploymentSpec> root = query.from(DeploymentSpec.class);

        query = query.select(root).distinct(true)
                .where(cb.equal(root.get("virtualSystem"), vs));

        query = query.orderBy(cb.asc(root.get("name")));
        return em.createQuery(query).getResultList();
    }

    public static DeploymentSpec findDeploymentSpecByVirtualSystemProjectAndRegion(EntityManager em, VirtualSystem vs,
            String projectId, String region) {

        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<DeploymentSpec> query = cb.createQuery(DeploymentSpec.class);

        Root<DeploymentSpec> root = query.from(DeploymentSpec.class);

        query = query.select(root)
                .where(cb.equal(root.get("projectId"), projectId),
                        cb.equal(root.get("region"), region),
                        cb.equal(root.get("virtualSystem"), vs));

        try {
            return em.createQuery(query).getSingleResult();
        } catch (NoResultException nre) {
            return null;
        }
    }

    // TODO Larkins: Remove the hard coded region
    public static List<DeploymentSpec> findDeploymentSpecsByVirtualSystemProjectWithDefaultRegionOne(EntityManager em,
            VirtualSystem vs, String projectId) {

        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<DeploymentSpec> query = cb.createQuery(DeploymentSpec.class);

        Root<DeploymentSpec> root = query.from(DeploymentSpec.class);

        query = query.select(root).distinct(true)
                .where(cb.equal(root.get("projectId"), projectId),
                        cb.equal(root.get("virtualSystem"), vs),
                        cb.equal(root.get("region"), "RegionOne"));

        return em.createQuery(query).getResultList();
    }

    public static List<DeploymentSpec> findDeploymentSpecsByVirtualSystemProjectAndRegion(EntityManager em,
            VirtualSystem vs, String projectId, String region) {

        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<DeploymentSpec> query = cb.createQuery(DeploymentSpec.class);

        Root<DeploymentSpec> root = query.from(DeploymentSpec.class);

        query = query.select(root).distinct(true)
                .where(cb.equal(root.get("projectId"), projectId),
                        cb.equal(root.get("region"), region),
                        cb.equal(root.get("virtualSystem"), vs));

        return em.createQuery(query).getResultList();
    }

    public static DeploymentSpec findById(EntityManager em, Long id) {
        return em.find(DeploymentSpec.class, id);
    }

    public static List<DeploymentSpec> listDeploymentSpecByProjectId(EntityManager em, String projectId) {
        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<DeploymentSpec> query = cb.createQuery(DeploymentSpec.class);

        Root<DeploymentSpec> root = query.from(DeploymentSpec.class);

        query = query.select(root).distinct(true)
                .where(cb.equal(root.get("projectId"), projectId));

        return em.createQuery(query).getResultList();
    }

    public static boolean isDeploymentSpecAllHostInRegion(DeploymentSpec ds) {
        return ds.getAvailabilityZones().isEmpty() && ds.getHostAggregates().isEmpty() && ds.getHosts().isEmpty();
    }

    public static List<DeploymentSpec> listDeploymentSpecByDistributedAppliance(EntityManager em, DistributedAppliance da) {
        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<DeploymentSpec> query = cb.createQuery(DeploymentSpec.class);

        Root<DeploymentSpec> root = query.from(DeploymentSpec.class);

        query = query.select(root).distinct(true)
                .where(root.get("virtualSystem").in(da.getVirtualSystems()));

        return em.createQuery(query).getResultList();
    }

    public static boolean isProtectingWorkload(DeploymentSpec ds) {
        return CollectionUtils.emptyIfNull(ds.getDistributedApplianceInstances()).stream().anyMatch(dai -> !dai.getProtectedPorts().isEmpty());
    }
}