text:
void KnossosDevToolsWindowDelegate::OnWindowCreated(CefRefPtr<CefWindow> window) {
  window->AddChildView(browser_view_);
  window->Show();
}

void KnossosDevToolsWindowDelegate::OnWindowDestroyed(CefRefPtr<CefWindow> window) {
  browser_view_ = nullptr;
}

CefRect KnossosDevToolsWindowDelegate::GetInitialBounds(CefRefPtr<CefWindow> window) {
  CefRect screen_size = KnossosHandler::GetInstance()->GetScreenSize();
  CefRect window_size;

  window_size.width = screen_size.width - 200;
  window_size.height = 400;

  window_size.x = (screen_size.width - window_size.width) / 2;
  window_size.y = screen_size.height / 2 + 500;

  return window_size;
}

void KnossosShowDevTools(CefRefPtr<CefBrowser> browser) {
  CefWindowInfo window_info;
  CefBrowserSettings settings;
  CefPoint point;
  CefRefPtr<CefClient> client = browser->GetHost()->GetClient();

#ifdef OS_MAC
  CefRect screen_size = KnossosHandler::GetInstance()->GetScreenSize();
  window_info.bounds.width = screen_size.width - 200;
  window_info.bounds.height = 400;

  window_info.bounds.x = (screen_size.width - window_info.bounds.width) / 2;
  window_info.bounds.y = screen_size.height / 2 + 500;

  CefString(&window_info.window_name).FromASCII("dev_tools");
#endif

  browser->GetHost()->ShowDevTools(window_info, client, settings, point);
}

redpajama_set_name: RedPajamaGithub


text:
int main (int argc, const char *argv[])
{
	puts("Hello, World!");
	return 0;
}


text:
package org.fest.swing.driver;

import static org.fest.assertions.Assertions.assertThat;
import static org.fest.swing.awt.AWT.centerOf;
import static org.fest.swing.test.core.CommonAssertions.assertThatErrorCauseIsDisabledComponent;
import static org.fest.swing.test.core.CommonAssertions.assertThatErrorCauseIsNotShowingComponent;
import static org.fest.swing.test.core.CommonAssertions.failWhenExpectingException;

import org.fest.swing.test.recorder.ClickRecorder;
import org.junit.Test;

/**
 * Tests for {@link ComponentDriver#doubleClick(java.awt.Component)}.
 *
 * @author Alex Ruiz
 * @author Yvonne Wang
 */
public class ComponentDriver_doubleClick_Test extends ComponentDriver_TestCase {
  @Test
  public void should_double_click_Component() {
    showWindow();
    ClickRecorder clickRecorder = ClickRecorder.attachTo(window.button);
    driver.doubleClick(window.button);
    assertThat(clickRecorder).wasDoubleClicked().clickedAt(centerOf(window.button));
  }

  @Test
  public void should_throw_error_if_Component_is_disabled() {
    ClickRecorder clickRecorder = ClickRecorder.attachTo(window.button);
    disableButton();
    try {
      driver.doubleClick(window.button);
      failWhenExpectingException();
    } catch (IllegalStateException e) {
      assertThatErrorCauseIsDisabledComponent(e);
    }
    assertThat(clickRecorder).wasNotClicked();
  }

  @Test
  public void should_throw_error_if_Component_is_not_showing_on_the_screen() {
    ClickRecorder clickRecorder = ClickRecorder.attachTo(window.button);
    try {
      driver.doubleClick(window.button);
      failWhenExpectingException();
    } catch (IllegalStateException e) {
      assertThatErrorCauseIsNotShowingComponent(e);
    }
    assertThat(clickRecorder).wasNotClicked();
  }
}


text:
package com.intellij.execution.jshell.protocol;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Eugene Zhuravlev
 * Date: 12-Jun-17
 */
@XmlRootElement
public class Event {

  private CodeSnippet myCauseSnippet;
  private CodeSnippet mySnippet;
  private CodeSnippet.Status myPreviousStatus;
  private CodeSnippet.Status myStatus;
  private String myValue;
  private String myExceptionText;
  private String myDiagnostic;

  public Event() {
  }

  public Event(CodeSnippet snippet, CodeSnippet causeSnippet,
               CodeSnippet.Status status, CodeSnippet.Status previousStatus,
               String value) {
    myCauseSnippet = causeSnippet;
    mySnippet = snippet;
    myPreviousStatus = previousStatus;
    myStatus = status;
    myValue = value;
  }

  public CodeSnippet.Status getPreviousStatus() {
    return myPreviousStatus;
  }

  @XmlElement
  public void setPreviousStatus(CodeSnippet.Status previousStatus) {
    myPreviousStatus = previousStatus;
  }

  public CodeSnippet.Status getStatus() {
    return myStatus;
  }

  @XmlElement
  public void setStatus(CodeSnippet.Status status) {
    myStatus = status;
  }

  public String getValue() {
    return myValue;
  }

  @XmlElement
  public void setValue(String value) {
    myValue = value;
  }

  public CodeSnippet getCauseSnippet() {
    return myCauseSnippet;
  }

  @XmlElement
  public void setCauseSnippet(CodeSnippet causeSnippet) {
    myCauseSnippet = causeSnippet;
  }

  public CodeSnippet getSnippet() {
    return mySnippet;
  }

  @XmlElement
  public void setSnippet(CodeSnippet snippet) {
    mySnippet = snippet;
  }

  public String getExceptionText() {
    return myExceptionText;
  }

  @XmlElement
  public void setExceptionText(String exceptionText) {
    myExceptionText = exceptionText;
  }

  public String getDiagnostic() {
    return myDiagnostic;
  }

  @XmlElement
  public void setDiagnostic(String diagnostic) {
    myDiagnostic = diagnostic;
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.machinelearningservices.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The SharedPrivateLinkResource model. */
@JsonFlatten
@Fluent
public class SharedPrivateLinkResource {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(SharedPrivateLinkResource.class);

    /*
     * Unique name of the private link.
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * The resource id that private link links to.
     */
    @JsonProperty(value = "properties.privateLinkResourceId")
    private String privateLinkResourceId;

    /*
     * The private link resource group id.
     */
    @JsonProperty(value = "properties.groupId")
    private String groupId;

    /*
     * Request message.
     */
    @JsonProperty(value = "properties.requestMessage")
    private String requestMessage;

    /*
     * Indicates whether the connection has been Approved/Rejected/Removed by
     * the owner of the service.
     */
    @JsonProperty(value = "properties.status")
    private PrivateEndpointServiceConnectionStatus status;

    /**
     * Get the name property: Unique name of the private link.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: Unique name of the private link.
     *
     * @param name the name value to set.
     * @return the SharedPrivateLinkResource object itself.
     */
    public SharedPrivateLinkResource withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the privateLinkResourceId property: The resource id that private link links to.
     *
     * @return the privateLinkResourceId value.
     */
    public String privateLinkResourceId() {
        return this.privateLinkResourceId;
    }

    /**
     * Set the privateLinkResourceId property: The resource id that private link links to.
     *
     * @param privateLinkResourceId the privateLinkResourceId value to set.
     * @return the SharedPrivateLinkResource object itself.
     */
    public SharedPrivateLinkResource withPrivateLinkResourceId(String privateLinkResourceId) {
        this.privateLinkResourceId = privateLinkResourceId;
        return this;
    }

    /**
     * Get the groupId property: The private link resource group id.
     *
     * @return the groupId value.
     */
    public String groupId() {
        return this.groupId;
    }

    /**
     * Set the groupId property: The private link resource group id.
     *
     * @param groupId the groupId value to set.
     * @return the SharedPrivateLinkResource object itself.
     */
    public SharedPrivateLinkResource withGroupId(String groupId) {
        this.groupId = groupId;
        return this;
    }

    /**
     * Get the requestMessage property: Request message.
     *
     * @return the requestMessage value.
     */
    public String requestMessage() {
        return this.requestMessage;
    }

    /**
     * Set the requestMessage property: Request message.
     *
     * @param requestMessage the requestMessage value to set.
     * @return the SharedPrivateLinkResource object itself.
     */
    public SharedPrivateLinkResource withRequestMessage(String requestMessage) {
        this.requestMessage = requestMessage;
        return this;
    }

    /**
     * Get the status property: Indicates whether the connection has been Approved/Rejected/Removed by the owner of the
     * service.
     *
     * @return the status value.
     */
    public PrivateEndpointServiceConnectionStatus status() {
        return this.status;
    }

    /**
     * Set the status property: Indicates whether the connection has been Approved/Rejected/Removed by the owner of the
     * service.
     *
     * @param status the status value to set.
     * @return the SharedPrivateLinkResource object itself.
     */
    public SharedPrivateLinkResource withStatus(PrivateEndpointServiceConnectionStatus status) {
        this.status = status;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
<?php

namespace Oro\Bundle\ImportExportBundle\Tests\Unit\Converter;

use Oro\Bundle\EntityExtendBundle\Extend\FieldTypeHelper;
use Oro\Bundle\ImportExportBundle\Converter\ConfigurableTableDataConverter;

class ConfigurableTableDataConverterTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var array
     */
    protected $fields = array(
        'ScalarEntity' => array(
            array(
                'name' => 'created',
                'label' => 'Created',
            ),
            array(
                'name' => 'name',
                'label' => 'Name',
            ),
            array(
                'name' => 'id',
                'label' => 'ID',
            ),
            array(
                'name' => 'description',
                'label' => 'Description',
            ),
        ),
        'SingleRelationEntity' => array(
            array(
                'name' => 'id',
                'label' => 'ID',
            ),
            array(
                'name' => 'name',
                'label' => 'Name',
            ),
            array(
                'name' => 'fullScalar',
                'label' => 'Full Scalar',
                'relation_type' => 'ref-one',
                'related_entity_name' => 'ScalarEntity',
            ),
            array(
                'name' => 'shortScalar',
                'label' => 'Short Scalar',
                'relation_type' => 'manyToOne',
                'related_entity_name' => 'ScalarEntity',
            ),
            array(
                'name' => 'innerRelation',
                'label' => 'Inner Relation',
                'relation_type' => 'ref-one',
                'related_entity_name' => 'IdentitySingleRelationEntity',
            ),
        ),
        'IdentitySingleRelationEntity' => array(
            array(
                'name' => 'id',
                'label' => 'ID',
            ),
            array(
                'name' => 'name',
                'label' => 'Name',
            ),
            array(
                'name' => 'identityRelation',
                'label' => 'Identity Relation',
                'relation_type' => 'ref-one',
                'related_entity_name' => 'ScalarEntity',
            ),
        ),
        'DictionaryEntity' => array(
            array(
                'name' => 'id',
                'label' => 'ID',
            ),
            array(
                'name' => 'scalarEntity',
                'label' => 'Scalar Entity',
                'relation_type' => 'ref-one',
                'related_entity_name' => 'ScalarEntity',
            ),
            array(
                'name' => 'dictionaryScalarEntities',
                'label' => 'Dictionary Scalar Entities',
                'relation_type' => 'ref-many',
                'related_entity_name' => 'ScalarEntity',
            ),
        ),
        'MultipleRelationEntity' => array(
            array(
                'name' => 'id',
                'label' => 'ID',
            ),
            array(
                'name' => 'scalarEntities',
                'label' => 'Scalar Entities',
                'relation_type' => 'ref-many',
                'related_entity_name' => 'ScalarEntity',
            ),
            array(
                'name' => 'singleRelationEntities',
                'label' => 'Single Relation Entities',
                'relation_type' => 'oneToMany',
                'related_entity_name' => 'SingleRelationEntity',
            ),
            array(
                'name' => 'dictionaryEntities',
                'label' => 'Dictionary Entities',
                'relation_type' => 'manyToMany',
                'related_entity_name' => 'DictionaryEntity',
            )
        ),
    );

    /**
     * @var array
     */
    protected $config = array(
        'ScalarEntity' => array(
            'id' => array(
                'order' => 10
            ),
            'name' => array(
                'header' => 'Entity Name',
                'identity' => true,
                'order' => 20,
            ),
            'description' => array(
                'excluded' => true,
            ),
        ),
        'SingleRelationEntity' => array(
            'id' => array(
                'order' => 10
            ),
            'name' => array(
                'order' => 20,
            ),
            'fullScalar' => array(
                'order' => 30,
                'full' => true,
            ),
            'shortScalar' => array(
                'order' => 40,
            ),
            'innerRelation' => array(
                'order' => 50,
            ),
        ),
        'IdentitySingleRelationEntity' => array(
            'id' => array(
                'order' => 10
            ),
            'name' => array(
                'order' => 20,
            ),
            'identityRelation' => array(
                'order' => 30,
                'identity' => true,
            ),
        ),
        'DictionaryEntity' => array(
            'id' => array(
                'order' => 10
            ),
            'scalarEntity' => array(
                'order' => 20,
            ),
            'dictionaryScalarEntities' => array(
                'order' => 30,
            ),
        ),
        'MultipleRelationEntity' => array(
            'id' => array(
                'order' => 10
            ),
            'scalarEntities' => array(
                'order' => 20
            ),
            'singleRelationEntities' => array(
                'order' => 30,
                'full' => true,
            ),
            'dictionaryEntities' => array(
                'order' => 40,
                'full' => true,
            ),
        ),
    );

    /**
     * @var array
     */
    protected $relations = array(
        'DictionaryEntity' => array(
            'dictionaryScalarEntities' => 2,
        ),
        'MultipleRelationEntity' => array(
            'scalarEntities' => 3,
            'singleRelationEntities' => 1,
            'dictionaryEntities' => 2,
        )
    );

    /**
     * @var ConfigurableTableDataConverter
     */
    protected $converter;

    protected function setUp()
    {
        $fieldHelper = $this->prepareFieldHelper();
        $relationCalculator = $this->prepareRelationCalculator();
        $this->converter = new ConfigurableTableDataConverter($fieldHelper, $relationCalculator);
    }

    /**
     * @expectedException \Oro\Bundle\ImportExportBundle\Exception\LogicException
     * @expectedExceptionMessage Entity class for data converter is not specified
     */
    public function testAssertEntityName()
    {
        $this->converter->convertToExportFormat(array());
    }

    /**
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     * @return array
     */
    public function exportDataProvider()
    {
        return array(
            'empty scalar' => array(
                'entityName' => 'ScalarEntity',
                'input' => array(),
                'expected' => array(
                    'ID' => '',
                    'Entity Name' => '',
                    'Created' => '',
                ),
            ),
            'full scalar' => array(
                'entityName' => 'ScalarEntity',
                'input' => array(
                    'id' => 42,
                    'name' => 'qwerty',
                    'created' => '2012-12-12 12:12:12'
                ),
                'expected' => array(
                    'ID' => '42',
                    'Entity Name' => 'qwerty',
                    'Created' => '2012-12-12 12:12:12',
                ),
            ),
            'empty single relation' => array(
                'entityName' => 'SingleRelationEntity',
                'input' => array(),
                'expected' => array(
                    'ID' => '',
                    'Name' => '',
                    'Full Scalar ID' => '',
                    'Full Scalar Entity Name' => '',
                    'Full Scalar Created' => '',
                    'Short Scalar Entity Name' => '',
                    'Inner Relation Identity Relation Entity Name' => '',
                ),
            ),
            'full single relation' => array(
                'entityName' => 'SingleRelationEntity',
                'input' => array(
                    'id' => 1,
                    'name' => 'Relation Name',
                    'fullScalar' => array(
                        'id' => 42,
                        'name' => 'qwerty',
                        'created' => '2012-12-12 12:12:12',
                    ),
                    'shortScalar' => array('name' => 'asdfgh'),
                    'innerRelation' => array('identityRelation' => array ('name' => 'test123')),
                ),
                'expected' => array(
                    'ID' => '1',
                    'Name' => 'Relation Name',
                    'Full Scalar ID' => '42',
                    'Full Scalar Entity Name' => 'qwerty',
                    'Full Scalar Created' => '2012-12-12 12:12:12',
                    'Short Scalar Entity Name' => 'asdfgh',
                    'Inner Relation Identity Relation Entity Name' => 'test123'
                ),
            ),
            'empty multiple relation' => array(
                'entityName' => 'MultipleRelationEntity',
                'input' => array(),
                'expected' => array(
                    'ID' => '',
                    'Scalar Entities 1 Entity Name' => '',
                    'Scalar Entities 2 Entity Name' => '',
                    'Scalar Entities 3 Entity Name' => '',
                    'Single Relation Entities 1 ID' => '',
                    'Single Relation Entities 1 Name' => '',
                    'Single Relation Entities 1 Full Scalar ID' => '',
                    'Single Relation Entities 1 Full Scalar Entity Name' => '',
                    'Single Relation Entities 1 Full Scalar Created' => '',
                    'Single Relation Entities 1 Short Scalar Entity Name' => '',
                    'Single Relation Entities 1 Inner Relation Identity Relation Entity Name' => '',
                    'Dictionary Entities 1 ID' => '',
                    'Dictionary Entities 1 Scalar Entity Entity Name' => '',
                    'Dictionary Entities 1 Dictionary Scalar Entities 1 Entity Name' => '',
                    'Dictionary Entities 1 Dictionary Scalar Entities 2 Entity Name' => '',
                    'Dictionary Entities 2 ID' => '',
                    'Dictionary Entities 2 Scalar Entity Entity Name' => '',
                    'Dictionary Entities 2 Dictionary Scalar Entities 1 Entity Name' => '',
                    'Dictionary Entities 2 Dictionary Scalar Entities 2 Entity Name' => '',
                ),
            ),
            'full multiple relation' => array(
                'entityName' => 'MultipleRelationEntity',
                'input' => array(
                    'id' => 12,
                    'scalarEntities' => array(
                        array('name' => 'first'),
                        array('name' => 'second'),
                        array('name' => 'third')
                    ),
                    'singleRelationEntities' => array(
                        array(
                            'id' => 23,
                            'name' => 'relation',
                            'fullScalar' => array(
                                'id' => 43,
                                'name' => 'qwerty',
                                'created' => '2012-12-12 12:12:12',
                            ),
                            'shortScalar' => array('name' => 'asdfgh'),
                            'innerRelation' => array('identityRelation' => array ('name' => 'test123')),
                        )
                    ),
                    'dictionaryEntities' => array(
                        array(
                            'id' => 55,
                            'scalarEntity' => array(
                                'name' => 'dictionary_scalar_1',
                            ),
                            'dictionaryScalarEntities' => array(
                                array('name' => 'dict_1'),
                                array('name' => 'dict_2'),
                            ),
                        ),
                        array(
                            'id' => 56,
                            'scalarEntity' => array(
                                'name' => 'dictionary_scalar_2',
                            ),
                            'dictionaryScalarEntities' => array(
                                array('name' => 'dict_3'),
                                array('name' => 'dict_4'),
                            ),
                        ),
                    )
                ),
                'expected' => array(
                    'ID' => '12',
                    'Scalar Entities 1 Entity Name' => 'first',
                    'Scalar Entities 2 Entity Name' => 'second',
                    'Scalar Entities 3 Entity Name' => 'third',
                    'Single Relation Entities 1 ID' => '23',
                    'Single Relation Entities 1 Name' => 'relation',
                    'Single Relation Entities 1 Full Scalar ID' => '43',
                    'Single Relation Entities 1 Full Scalar Entity Name' => 'qwerty',
                    'Single Relation Entities 1 Full Scalar Created' => '2012-12-12 12:12:12',
                    'Single Relation Entities 1 Short Scalar Entity Name' => 'asdfgh',
                    'Single Relation Entities 1 Inner Relation Identity Relation Entity Name' => 'test123',
                    'Dictionary Entities 1 ID' => '55',
                    'Dictionary Entities 1 Scalar Entity Entity Name' => 'dictionary_scalar_1',
                    'Dictionary Entities 1 Dictionary Scalar Entities 1 Entity Name' => 'dict_1',
                    'Dictionary Entities 1 Dictionary Scalar Entities 2 Entity Name' => 'dict_2',
                    'Dictionary Entities 2 ID' => '56',
                    'Dictionary Entities 2 Scalar Entity Entity Name' => 'dictionary_scalar_2',
                    'Dictionary Entities 2 Dictionary Scalar Entities 1 Entity Name' => 'dict_3',
                    'Dictionary Entities 2 Dictionary Scalar Entities 2 Entity Name' => 'dict_4',
                ),
            ),
        );
    }

    /**
     * @param string $entityName
     * @param array $input
     * @param array $expected
     * @dataProvider exportDataProvider
     */
    public function testExport($entityName, array $input, array $expected)
    {
        $this->converter->setEntityName($entityName);
        $this->assertSame($expected, $this->converter->convertToExportFormat($input));
    }

    /**
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     * @return array
     */
    public function importDataProvider()
    {
        return array(
            'empty scalar' => array(
                'entityName' => 'ScalarEntity',
                'input' => array(),
                'expected' => array(),
            ),
            'full scalar' => array(
                'entityName' => 'ScalarEntity',
                'input' => array(
                    'ID' => '42',
                    'Entity Name' => 'qwerty',
                    'Created' => '2012-12-12 12:12:12',
                ),
                'expected' => array(
                    'id' => '42',
                    'name' => 'qwerty',
                    'created' => '2012-12-12 12:12:12'
                ),
            ),
            'empty single relation' => array(
                'entityName' => 'SingleRelationEntity',
                'input' => array(),
                'expected' => array(),
            ),
            'full single relation' => array(
                'entityName' => 'SingleRelationEntity',
                'input' => array(
                    'ID' => '1',
                    'Name' => 'Relation Name',
                    'Full Scalar ID' => '42',
                    'Full Scalar Entity Name' => 'qwerty',
                    'Full Scalar Created' => '2012-12-12 12:12:12',
                    'Short Scalar Entity Name' => 'asdfgh',
                    'Inner Relation Identity Relation Entity Name' => 'test123',
                ),
                'expected' => array(
                    'id' => '1',
                    'name' => 'Relation Name',
                    'fullScalar' => array(
                        'id' => '42',
                        'name' => 'qwerty',
                        'created' => '2012-12-12 12:12:12',
                    ),
                    'shortScalar' => array(
                        'name' => 'asdfgh',
                    ),
                    'innerRelation' => array(
                        'identityRelation' => array (
                            'name' => 'test123'
                        )
                    ),
                ),
            ),
            'empty multiple relation' => array(
                'entityName' => 'MultipleRelationEntity',
                'input' => array(),
                'expected' => array(),
            ),
            'full multiple relation' => array(
                'entityName' => 'MultipleRelationEntity',
                'input' => array(
                    'ID' => '12',
                    'Scalar Entities 1 Entity Name' => 'first',
                    'Scalar Entities 2 Entity Name' => 'second',
                    'Scalar Entities 3 Entity Name' => 'third',
                    'Single Relation Entities 1 ID' => '23',
                    'Single Relation Entities 1 Name' => 'relation',
                    'Single Relation Entities 1 Full Scalar ID' => '43',
                    'Single Relation Entities 1 Full Scalar Entity Name' => 'qwerty',
                    'Single Relation Entities 1 Full Scalar Created' => '2012-12-12 12:12:12',
                    'Single Relation Entities 1 Short Scalar Entity Name' => 'asdfgh',
                    'Dictionary Entities 1 ID' => '55',
                    'Dictionary Entities 1 Scalar Entity Entity Name' => 'dictionary_scalar_1',
                    'Dictionary Entities 1 Dictionary Scalar Entities 1 Entity Name' => 'dict_1',
                    'Dictionary Entities 1 Dictionary Scalar Entities 2 Entity Name' => 'dict_2',
                    'Dictionary Entities 2 ID' => '56',
                    'Dictionary Entities 2 Scalar Entity Entity Name' => 'dictionary_scalar_2',
                    'Dictionary Entities 2 Dictionary Scalar Entities 1 Entity Name' => 'dict_3',
                    'Dictionary Entities 2 Dictionary Scalar Entities 2 Entity Name' => 'dict_4',
                ),
                'expected' => array(
                    'id' => '12',
                    'scalarEntities' => array(
                        array('name' => 'first'),
                        array('name' => 'second'),
                        array('name' => 'third')
                    ),
                    'singleRelationEntities' => array(
                        array(
                            'id' => '23',
                            'name' => 'relation',
                            'fullScalar' => array(
                                'id' => '43',
                                'name' => 'qwerty',
                                'created' => '2012-12-12 12:12:12',
                            ),
                            'shortScalar' => array('name' => 'asdfgh'),
                        )
                    ),
                    'dictionaryEntities' => array(
                        array(
                            'id' => '55',
                            'scalarEntity' => array(
                                'name' => 'dictionary_scalar_1',
                            ),
                            'dictionaryScalarEntities' => array(
                                array('name' => 'dict_1'),
                                array('name' => 'dict_2'),
                            ),
                        ),
                        array(
                            'id' => '56',
                            'scalarEntity' => array(
                                'name' => 'dictionary_scalar_2',
                            ),
                            'dictionaryScalarEntities' => array(
                                array('name' => 'dict_3'),
                                array('name' => 'dict_4'),
                            ),
                        ),
                    )
                ),
            ),
        );
    }

    /**
     * @param string $entityName
     * @param array $input
     * @param array $expected
     * @dataProvider importDataProvider
     */
    public function testImport($entityName, array $input, array $expected)
    {
        $this->converter->setEntityName($entityName);
        $this->assertSame($expected, $this->converter->convertToImportFormat($input));
    }

    public function testGetFieldHeaderWithRelation()
    {
        $fieldName = 'name';
        $simpleFieldValue = $this->converter->getFieldHeaderWithRelation('SingleRelationEntity', $fieldName);
        $this->assertEquals($simpleFieldValue, ucfirst($fieldName));

        $relationFieldValue = $this->converter->getFieldHeaderWithRelation('SingleRelationEntity', 'fullScalar');
        $this->assertEquals($relationFieldValue, 'Full Scalar Entity Name');
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function prepareFieldHelper()
    {
        $configProvider = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider')
            ->disableOriginalConstructor()
            ->getMock();
        $fieldProvider = $this->getMockBuilder('Oro\Bundle\EntityBundle\Provider\EntityFieldProvider')
            ->disableOriginalConstructor()
            ->getMock();
        $fieldTypeHelper = new FieldTypeHelper([]);

        $fieldHelper = $this->getMockBuilder('Oro\Bundle\EntityBundle\Helper\FieldHelper')
            ->setConstructorArgs([$fieldProvider, $configProvider, $fieldTypeHelper])
            ->setMethods(array('getConfigValue', 'getFields', 'processRelationAsScalar'))
            ->getMock();
        $fieldHelper->expects($this->any())->method('getConfigValue')
            ->will(
                $this->returnCallback(
                    function ($entityName, $fieldName, $parameter, $default = null) {
                        return isset($this->config[$entityName][$fieldName][$parameter])
                            ? $this->config[$entityName][$fieldName][$parameter]
                            : $default;
                    }
                )
            );
        $fieldHelper->expects($this->any())->method('getFields')->with($this->isType('string'), true)
            ->will(
                $this->returnCallback(
                    function ($entityName) {
                        return isset($this->fields[$entityName]) ? $this->fields[$entityName] : array();
                    }
                )
            );
        return $fieldHelper;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function prepareRelationCalculator()
    {
        $relationCalculator = $this->getMockBuilder('Oro\Bundle\ImportExportBundle\Converter\RelationCalculator')
            ->disableOriginalConstructor()
            ->getMock();
        $relationCalculator->expects($this->any())->method('getMaxRelatedEntities')
            ->will(
                $this->returnCallback(
                    function ($entityName, $fieldName) {
                        return isset($this->relations[$entityName][$fieldName])
                            ? $this->relations[$entityName][$fieldName]
                            : 0;
                    }
                )
            );

        return $relationCalculator;
    }
}


text:
DFT
===

Discrete Fourier Transform experiments


text:
import os
import sys
import ctypes
import signal
import warnings

# Work around cross module rtti errors on linux.
sys.setdlopenflags( sys.getdlopenflags() | ctypes.RTLD_GLOBAL )

# Get rid of the annoying signal handler which turns Ctrl-C into a KeyboardInterrupt exception
signal.signal( signal.SIGINT, signal.SIG_DFL )

# Reenable deprecation warnings - Python2.7 turns them off by default so otherwise we'd never get
# to catch all the naughty deprecated things we do.
warnings.simplefilter( "default", DeprecationWarning )

import IECore

helpText = """Usage :

    gaffer -help                    Print this message
    gaffer -help appName            Print help specific to named application
    gaffer appName [flags]          Run named application with specified flags
    gaffer fileName.gfr [flags]     Run gui application with specified script and flags
    gaffer [flags]                  Run gui application with specified flags
"""

appLoader = IECore.ClassLoader.defaultLoader( "GAFFER_APP_PATHS" )
applicationText = "Installed applications :\n\n" + "\n".join( "    " + x for x in appLoader.classNames() ) + "\n"

def loadApp( appName ) :

	if appName in appLoader.classNames() :
		return appLoader.load( appName )()
	else :
		sys.stderr.write( "ERROR : Application \"%s\" not installed on GAFFER_APP_PATHS\n" % appName )
		sys.stderr.write( "\n" + applicationText )
		sys.exit( 1 )

def checkCleanExit() :

	# Get the Gaffer and GafferUI modules, but only if the app actually
	# imported them. We don't want to force their importation because it's
	# just a waste of time if they weren't used.
	Gaffer = sys.modules.get( "Gaffer" )
	GafferUI = sys.modules.get( "GafferUI" )

	if Gaffer is None and GafferUI is None :
		return

	# Clean up any garbage left behind by Cortex's wrapper mechanism - because
	# the Gaffer.Application itself is derived from IECore.Parameterised, which
	# as far as I can tell is wrapped unnecessarily, we must call this to allow
	# the application to be deleted at all. Note that we're deliberately not also
	# calling gc.collect() - our intention here isn't to clean up on shutdown, but
	# to highlight problems caused by things not cleaning up after themselves during
	# execution. We aim to eliminate all circular references from our code, to avoid
	# garbage collection overhead and to avoid problems caused by referencing Qt widgets
	# which were long since destroyed in C++.
	## \todo Reevaluate the need for this call after Cortex 9 development.
	IECore.RefCounted.collectGarbage()
	# Importing here rather than at the top of the file prevents false
	# positives being reported in gc.get_objects() below. I have no idea why,
	# but if not imported here, get_objects() will report objects which have
	# nothing referring to them and which should be dead, even with an
	# explicit call to gc.collect() beforehand.
	import gc

	# Check for things that shouldn't exist at shutdown, and
	# warn of anything we find.
	scriptNodes = []
	widgets = []
	for o in gc.get_objects() :
		if Gaffer is not None and isinstance( o, Gaffer.ScriptNode ) :
			scriptNodes.append( o )
		elif GafferUI is not None and isinstance( o, GafferUI.Widget ) :
			widgets.append( o )

	if scriptNodes :
		IECore.msg(
			IECore.Msg.Level.Debug,
			"Gaffer shutdown", "%d remaining ScriptNode%s detected. Debugging with objgraph is recommended." % (
				len( scriptNodes ),
				"s" if len( scriptNodes ) > 1 else "",
			)
		)

	if widgets :

		count = {}
		for widget in widgets :
			widgetType = widget.__class__.__name__
			count[widgetType] = count.get( widgetType, 0 ) + 1

		summaries = [ "%s (%d)" % ( k, count[k] ) for k in sorted( count.keys() ) ]

		IECore.msg(
			IECore.Msg.Level.Debug,
			"Gaffer shutdown", "%d remaining Widget%s detected : \n\n%s\n\nDebugging with objgraph is recommended." % (
				len( widgets ),
				"s" if len( widgets ) > 1 else "",
				"\t" + "\n\t".join( summaries )
			)
		)

args = sys.argv[1:]
if args and args[0] in ( "-help", "-h", "--help", "-H" ) :
	if len( args ) > 1 :
		app = loadApp( args[1] )
		formatter = IECore.WrappedTextFormatter( sys.stdout )
		formatter.paragraph( "Name : " + app.path )
		if app.description :
			formatter.paragraph( app.description + "\n" )
		if len( app.parameters().values() ):
			formatter.heading( "Parameters" )
			formatter.indent()
			for p in app.parameters().values() :
				IECore.formatParameterHelp( p, formatter )
			formatter.unindent()
		sys.exit( 0 )
	else :
		sys.stdout.write( helpText )
		sys.stdout.write( "\n" + applicationText )
		sys.exit( 0 )
else :
	appName = "gui"
	appArgs = args
	if len( args ) :
		if not args[0].startswith( "-" ) and not args[0].endswith( ".gfr" ) :
			appName = args[0]
			appArgs = args[1:]

	app = loadApp( appName )
	IECore.ParameterParser().parse( appArgs, app.parameters() )

	result = app.run()

	del app
	checkCleanExit()

	sys.exit( result )


text:
define(['require','jquery','underscore','config'],function(require,$,_,Config) {
			/**
			TODO<br />
			@module Templates
			@class Templates
			**/
			var module = (function() {
				this._name = 'templates';
				var templateArray = [];
				var _templates = Config.getModulePath()+'templates/templates.js';
				var isRegisterd = function() {
					return ( typeof module.subscribe === 'function' ) && ( typeof module.publish === 'function');
				}

				var _init = function(container) {
					this.container = $(container);

					if (isRegisterd()) {
				// inject script templates
				module.publish(Config.CHANNEL_INJECT_SCRIPTTEMPLATE,{url : _templates});
				/** *************************************** */
				/* CALL FUNCTIONS HERER */
				/** *************************************** */
				addListener();
				addGui();
				/** *************************************** */
			} else {
				throw 'Module [ '
				+ this.name
				+ ' ] not registered! Use VLib.registerModule(obj) first.';
			}

		};

		/** *************************************** */
		/* ADD LISTENERS HERER */
		/** *************************************** */
		var addListener = function() {
			//console.log("[ "+module.name+" ] add listener");
			module.subscribe(Config.CHANNEL_RESPOND_TEMPLATES,
				respondTemplatesHandle);

			module.subscribe(Config.CHANNEL_RESPOND_DELETETEMPLATECALLBACK, deleteTemplateCBHandle);

		};
		/** *************************************** */
		/* ADD FUNCTIONS HERE */
		/** *************************************** */
		var addGui = function(){

			_.templateSettings.variable = "rc";
			// get template code
			var templateData = {
				title : 'Saved Plots'
			};
			var template = _.template($("script.templateListContainer").html());

			module.container.html(template(templateData));

			// request templates
			//console.log('[ Templates ][ addGui ] requestTemplates');
			module.publish(Config.CHANNEL_REQUEST_TEMPLATES);
		};
		var deleteTemplateCallback = function(){
			this.publish(Config.CHANNEL_ERROR,'templates. saveTemplateCallback not set!');
		};
		/* LISTENERS */
		var deleteTemplateCBHandle = function(callback){
			if(typeof(callback) !== 'function'){
				this.publish(Config.CHANNEL_ERROR,'deleteTemplateCallback is NOT a function!');
				return;
			}
			deleteTemplateCallback = callback;
		}
		/**
		 * click listener
		 * broadcasts template to subscribers of chanel XXX
		 */
		 var templateClickListener = function(){
		 	$('.vLibTemplate').click(function(){
		 		var id = $(this).attr('id');
		 		var index = id.split('-')[1];

		 		module.publish(Config.CHANNEL_RESET,{});
		 		module.publish(Config.CHANNEL_TEMPLATES_TEMPLATE_SELECTED,{template:_.clone(templateArray[index])});
		 		//module.publish(Config.CHANNEL_RENDER_TEMPLATE,{template:_.clone(templateArray[index])});
		 	});
		 	$('.vLibTemplateDelete').click(function(){
		 		var id = $(this).attr('id');
		 		var index = id.split('-')[1];
		 		var template = templateArray[index];
		 		if(!confirm('Delete template [ id='+template.id+', name='+template.name+' ]?'))
		 			return;

		 		deleteTemplateCallback(_.clone(template));

		 	});

		 }
		/**
		 * @param obj: Array of objects
		 * 	each object: {
		 * 		id 		: int
		 * 		sceneGraph	: object,
		 * 		name		: string,
		 * 		description	: string,
		 * 		timestamp	: string
		 *  }
		 */
		 var respondTemplatesHandle = function(obj){

		 	//console.log("[templates] respondTemplatesHandle() called");
		 	templateArray = _.clone(obj);
		 	var t = module.container.find('#templateContainer');
		 	t.html("");
		 	if(obj.length == 0) return;

		 	var template = _.template($("script.templateContainer").html());
		 	_.templateSettings.variable = "rc";
		 	$.each(obj,function(i,o){
		 		t.append(template({index:i,id:o.id,name:o.name,description:o.description}));
		 	});
		 	templateClickListener();
		 }

		 /* public */
		 return {
		 	name : _name,
		 	init : _init

		 }
		})();
		return module;

	});


text:
if hash go 2>/dev/null; then
    export GOPATH=$HOME/.local
fi


text:
package org.auscope.nvcl.server.vo;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import au.com.bytecode.opencsv.CSVWriter;

public class TSGScalarArrayVo {

	private static final Logger logger = LogManager.getLogger(TSGScalarArrayVo.class);
    private float interval = (float) 1.0;
    private float floorDepth = 99999;
    private float ceilingDepth = -99999;
    public List<TSGScalarVo> scalarArray = new ArrayList<TSGScalarVo>();
    public List<TSGScalarVo> downSampledScalarArray = new ArrayList<TSGScalarVo>();
    public TSGScalarArrayVo(float interval) {
        this.interval = interval;
    }

    public void add(TSGScalarVo spectralData) {
        float depthValue = spectralData.getDepth();
        if (depthValue < floorDepth)
            floorDepth = depthValue;

        if (depthValue > ceilingDepth)
            ceilingDepth = depthValue;

        scalarArray.add(spectralData);
    }

    public float getInterval() {
        return interval;
    }

    public void setInterval(float interval) {
        this.interval = interval;
    }

    public int downSample2() {
        int f = (int)(floorDepth/interval);
        float depthStart = f > 0 ? f*interval : floorDepth;
        float depthEnd = (depthStart + interval) > ceilingDepth ? ceilingDepth : (depthStart+interval);
        float depth;
        int count = 0;
        double sumValue = 0.0;
        double value = 0.0;
        for (TSGScalarVo scalar : scalarArray) {
            depth = scalar.getDepth();
            value = scalar.getValue();
            logger.debug(depth + "    " + value + "    " + scalar.isMask());

            if (depth >= depthStart && depth < depthEnd) {
                if (!scalar.isMask()) //skip the masked one.
                    continue;
                sumValue += value;
                count ++;
            } else if (depth >= depthEnd) {
                if (count >0 && sumValue > 0.0) {
                    float downSampledDepth = (depthStart + depthEnd)/2;
                    downSampledScalarArray.add(new TSGScalarVo(String.valueOf(downSampledDepth), true, sumValue/count,count));
                    logger.debug("Bin:" + downSampledDepth + ":count:"  + count + ":sumValue:" + sumValue + ":avgValue:" + sumValue/count + ":count:" + count);
                }
                depthStart = depthEnd;
                depthEnd = (depthEnd + interval) > ceilingDepth ? ceilingDepth : (depthEnd + interval); //depthEnd + interval;
                sumValue = 0.0;
                count = 0;

            } else {
            	logger.error("TSGScalarArrayVo:Exception: terrible array sequence!!!!");
            }
        }

        //the last downSampled

        if (count >0 && sumValue > 0.0) {
            float downSampledDepth = (depthStart + depthEnd)/2;
            downSampledScalarArray.add(new TSGScalarVo(String.valueOf(downSampledDepth), true, sumValue/count,count));
            logger.debug("Bin:" + downSampledDepth + ":count:"  + count + ":sumValue:" + sumValue + ":avgValue" + sumValue/count);
        }
        logger.debug("TSGScalarArrayVo:downSample:totalSize=" + downSampledScalarArray.size());
        return downSampledScalarArray.size();

    }

    public int downSample() {
        int size = (int) ((ceilingDepth - floorDepth)/ interval) +1;
        for (int i=0;i<size;i++) {
            float downSampledDepth = floorDepth + i*interval;
            downSampledScalarArray.add(new TSGScalarVo(String.valueOf(downSampledDepth), true, 0,0));
        }
        logger.debug("InitDownSampledScalarArraySize=" + downSampledScalarArray.size());

        float depth;
        double value;
        for (TSGScalarVo scalar : scalarArray) {
            depth = scalar.getDepth();
            value = scalar.getValue();
            //logger.debug(depth + "    " + value + "    " + scalar.isMask());

            if (!scalar.isMask()) //skip the masked one.
                continue;
            int index = (int)((depth-floorDepth)/interval);
            if (index >= size)
            	logger.error("TSGScalarArrayVo:Exception: terrible array sequence!!!!");

            TSGScalarVo downSampledScalar = downSampledScalarArray.get(index);
            double sumValue = downSampledScalar.getValue() + value;
            downSampledScalar.setValue(sumValue);
            downSampledScalar.setCount(downSampledScalar.getCount() +1);
        }

        for (int i=0;i<size;i++) {
            TSGScalarVo downSampledScalar = downSampledScalarArray.get(i);
            if (downSampledScalar.getCount() == 0) {
                downSampledScalar.setValue(Double.NaN);
            } else {
                downSampledScalar.setValue(downSampledScalar.getValue() / downSampledScalar.getCount());
            }
            //logger.debug("Bin:" + downSampledScalar.getDepthS() + ":value:" + downSampledScalar.getValue()  + ":count:"  + downSampledScalar.getCount() );
        }
        logger.debug("TSGScalarArrayVo:downSample:totalSize=" + downSampledScalarArray.size());
        return downSampledScalarArray.size();

    }

    public int writeScalarCSV(String fileName) {
        CSVWriter writer;
        try {
            writer = new CSVWriter(new FileWriter(fileName));
            writer.writeNext("depth,value,mask".split(","));
            float depth;
            double value = 0.0;
            boolean mask;
            for (TSGScalarVo spectralData : scalarArray) {
                depth = spectralData.getDepth();
                value = spectralData.getValue();
                mask = spectralData.isMask();
                // only write values if mask == true and the value is not NaN.
                // The client should normally apply this masking but portal currently doesn't
                // so its done here.
                if (mask && !Double.isNaN(value))
                {
                	String record = depth + "," + value + "," + mask ;
                	writer.writeNext(record.split(","));
                }
            }
            writer.close();
        } catch (IOException e) {
            logger.error("failed to write CSV "+fileName+"Exception was:"+e);
        }
        return scalarArray.size();
    }
    public int writeDownSampledScalarCSV(String fileName) {
        CSVWriter writer;
        try {
            writer = new CSVWriter(new FileWriter(fileName));
            writer.writeNext("depth,value,count".split(","));
            float depth;
            double value = 0.0;
            int count = 0;
            for (TSGScalarVo scalar : downSampledScalarArray) {
                depth = scalar.getDepth();
                value = scalar.getValue();
                count = scalar.getCount();
                String record = depth + "," + value + "," + count ;
                writer.writeNext(record.split(","));
            }
            writer.close();
        } catch (IOException e) {
        	logger.error("failed to write CSV "+fileName+"Exception was:"+e);
        }
        return downSampledScalarArray.size();
    }

    public boolean query(String units, String logicalOp, double threshHold) {
        boolean isHit = false;
        // double valueSum = 0.0;
        float ratio = (float) 0.0;
        /* Now, iterate over the map's contents, sorted by key. */
        for (TSGScalarVo spectralData : downSampledScalarArray) {
            double value = spectralData.getValue();
            if (units.equalsIgnoreCase("pct")) {
                if (logicalOp.equalsIgnoreCase("gt")) {
                    if (ratio > value) {
                        isHit = true;
                        break;
                    }
                } else if (logicalOp.equalsIgnoreCase("lt")) {
                    if (ratio < value) {
                        isHit = true;
                        break;
                    }
                } else if (logicalOp.equalsIgnoreCase("eq")) {
                    if (Math.abs(ratio - value) < 1.0) { // float equal when abs
                                                         // < 1%
                        isHit = true;
                        break;
                    }
                }else {
                	logger.error("TSGScalarArrayVo:Exception: Unrecognize logicalOp:" + logicalOp);
                }

            } else if (units.equalsIgnoreCase("count")){
                if (logicalOp.equalsIgnoreCase("gt")) {
                    if (value > threshHold) {
                        isHit = true;
                        break;
                    }
                } else if (logicalOp.equalsIgnoreCase("lt")) {
                    if (value < threshHold) {
                        isHit = true;
                        break;
                    }
                } else if (logicalOp.equalsIgnoreCase("eq")) {
                    if (Math.abs(value - threshHold) < 1.0) { // float equal
                                                              // when abs < 1
                        isHit = true;
                        break;
                    }
                } else {
                	logger.error("TSGScalarArrayVo:Exception: Unrecognize logicalOp:" + logicalOp);
                }
            } else {
            	logger.error("TSGScalarArrayVo:Exception: Unrecognize units:" + units);
            }
        }

        return isHit;
    }
}


text:
/, SuspendingEventArgs^ /* e */)
{
    //TODO: Save application state and stop any background activity
}

/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
{
    throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
}


text:
var fs = require('fs');

var browserify = require('browserify');
var watchify = require('watchify');

var compressAttributes = require('./compress_attributes');
var formatBundleMsg = require('./format_bundle_msg');
var constants = require('./constants');

/**
 * Make a plotly.js browserify bundle function watched by watchify.
 *
 * N.B. This module is meant for dev builds; the output bundle is placed
 *      in plotly.js/build/
 *      Use `npm run build` for dist builds.
 *
 * @param {function} onFirstBundleCallback executed when first bundle is completed
 *
 */
module.exports = function makeWatchifiedBundle(onFirstBundleCallback) {
    var b = browserify(constants.pathToPlotlyIndex, {
        debug: true,
        standalone: 'Plotly',
        transform: [compressAttributes],
        cache: {},
        packageCache: {},
        plugin: [watchify]
    });

    var firstBundle = true;

    if(firstBundle) {
        console.log([
            '***',
            'Building the first bundle, this should take ~10 seconds',
            '***\n'
        ].join(' '));
    }

    b.on('update', bundle);
    formatBundleMsg(b, 'plotly.js');

    function bundle() {
        b.bundle(function(err) {
            if(err) console.error(JSON.stringify(String(err)));

            if(firstBundle) {
                onFirstBundleCallback();
                firstBundle = false;
            }
        })
        .pipe(
            fs.createWriteStream(constants.pathToPlotlyBuild)
        );
    }

    return bundle;
};


text:
*A*: Please, try to execute the command manually in your shell. Snappy is a thin PHP wrapper and most likely your issue is with wkhtmltopdf itself or is already described in this FAQ. If not, feel free to open the issue in Snappy issue tracker.

How to get the command to execute -

```php
var_dump($snappy->getCommand('http://google.com', 'test.pdf'), array('some' => 'option'));
```

Please, note that wkhtmltopdf takes only input url or file name as a source.

###### *Q*: My tables are broken when it is rendered on multiple pages with break.

*A*: Add ```thead``` and ```tbody``` tags. Add the following css
```css
table, tr, td, th, tbody, thead, tfoot {
    page-break-inside: avoid !important;
}
```

###### *Q*: I have a PNG with a transparent background. When generating a PDF, the background turns black.

*A*: It is wkhtmltopdf bug as described in https://github.com/wkhtmltopdf/wkhtmltopdf/issues/2214. You should update wkhtmltopdf to at least 0.12.3-dev

###### *Q*: Is there a way to secure the pdf so it can't be edited?

*A*:  There is no way to add a password via wkhtmltopdf, but there is a way via other linux tools like pdftk

###### *Q*: We are using wkhtmltopdf to export html to pdf. It breaks the HTML in two pages of pdf. Can we add a break?

*A*: It is known problem of `wkhtmltopdf`. You can use css `page-break-after`, like:
```html
<style type="text/css">
    .page {
        overflow: hidden;
        page-break-after: always;
    }
</style>

<div class="page">
   new page
</div>
```

###### *Q*: It says `wkhtmltopdf: cannot connect to X server` or `xvfb-run: error: Xvfb failed to start.`

*A*: Please, check your `wkhtmltopdf` version. It is recommended to use at least `0.12.2.1` and what is important - starting from `wkhtmltopdf >= 0.12.2` it doesn't require X server or emulation anymore. You can download new version from http://wkhtmltopdf.org/downloads.html or install via composer for Linux servers as stated in [README](https://github.com/KnpLabs/snappy#wkhtmltopdf-binary-as-composer-dependencies). If there is no possibility to update `wkhtmltopdf`, please check http://stackoverflow.com/questions/9604625/wkhtmltopdf-cannot-connect-to-x-server

###### *Q*: My PDF is always generated for a small screen resolution\I always receive a mobile version.

*A*: It is well-known issue of wkhtmltopdf, you can check https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1508. One of solutions is to use xvbf and to setup xvbf resolution to desired one.

###### *Q*: My chars with accents in HTML document are not correctly rendered.

*A*: Make sure that you have set `<meta charset="UTF-8" />`

###### *Q*: My document text is not correctly rendered, it is just black squares

*A*: Make sure you have installed `xfonts-base`, `xfonts-75dpi` and `urw-fonts`


text:
namespace tensorflow {
namespace boosted_trees {
namespace utils {

using ExampleRowRange = SparseColumnIterable::ExampleRowRange;
using Iterator = SparseColumnIterable::Iterator;

namespace {

// Iterator over indices matrix rows.
class IndicesRowIterator
    : public std::iterator<std::random_access_iterator_tag, const int64> {
 public:
  IndicesRowIterator() : iter_(nullptr), row_idx_(-1) {}
  IndicesRowIterator(SparseColumnIterable* iter, int row_idx)
      : iter_(iter), row_idx_(row_idx) {}
  IndicesRowIterator(const IndicesRowIterator& other)
      : iter_(other.iter_), row_idx_(other.row_idx_) {}

  IndicesRowIterator& operator=(const IndicesRowIterator& other) {
    iter_ = other.iter_;
    row_idx_ = other.row_idx_;
    return (*this);
  }

  IndicesRowIterator& operator++() {
    ++row_idx_;
    return (*this);
  }

  IndicesRowIterator operator++(int) {
    IndicesRowIterator tmp(*this);
    ++row_idx_;
    return tmp;
  }

  reference operator*() const { return iter_->ix()(row_idx_, 0); }

  pointer operator->() { return &iter_->ix()(row_idx_, 0); }

  IndicesRowIterator& operator--() {
    --row_idx_;
    return (*this);
  }

  IndicesRowIterator operator--(int) {
    IndicesRowIterator tmp(*this);
    --row_idx_;
    return tmp;
  }

  IndicesRowIterator& operator+=(const difference_type& step) {
    row_idx_ += step;
    return (*this);
  }
  IndicesRowIterator& operator-=(const difference_type& step) {
    row_idx_ -= step;
    return (*this);
  }

  IndicesRowIterator operator+(const difference_type& step) const {
    IndicesRowIterator tmp(*this);
    tmp += step;
    return tmp;
  }

  IndicesRowIterator operator-(const difference_type& step) const {
    IndicesRowIterator tmp(*this);
    tmp -= step;
    return tmp;
  }

  difference_type operator-(const IndicesRowIterator& other) const {
    return row_idx_ - other.row_idx_;
  }

  bool operator!=(const IndicesRowIterator& other) const {
    QCHECK_EQ(iter_, other.iter_);
    return (row_idx_ != other.row_idx_);
  }

  bool operator<(const IndicesRowIterator& other) const {
    return (row_idx_ < other.row_idx_);
  }

  bool operator==(const IndicesRowIterator& other) const {
    QCHECK_EQ(iter_, other.iter_);
    return (row_idx_ == other.row_idx_);
  }

  Eigen::Index row_idx() const { return row_idx_; }

 private:
  SparseColumnIterable* iter_;
  Eigen::Index row_idx_;
};
}  // namespace

Iterator::Iterator(SparseColumnIterable* iter, int64 example_idx)
    : iter_(iter), example_idx_(example_idx), end_(iter->ix_.dimension(0)) {
  cur_ = next_ = std::lower_bound(IndicesRowIterator(iter, 0),
                                  IndicesRowIterator(iter, end_), example_idx_)
                     .row_idx();
  UpdateNext();
}

}  // namespace utils
}  // namespace boosted_trees
}  // namespace tensorflow


text:
require 'fog/compute/models/server'

module Fog
  module Compute
    class Vsphere

      class Server < Fog::Compute::Server
        extend Fog::Deprecation
        deprecate(:ipaddress, :public_ip_address)

        # This will be the instance uuid which is globally unique across
        # a vSphere deployment.
        identity  :id

        # JJM REVISIT (Extend the model of a vmware server)
        # SEE: http://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.VirtualMachine.html
        # (Take note of the See also section.)
        # In particular:
        #   GuestInfo: information about the guest operating system
        #   VirtualMachineConfigInfo: Access to the VMX file and configuration

        attribute :name
        # UUID may be the same from VM to VM if the user does not select (I copied it)
        attribute :uuid
        attribute :hostname
        attribute :operatingsystem
        attribute :public_ip_address, :aliases => 'ipaddress'
        attribute :power_state,   :aliases => 'power'
        attribute :tools_state,   :aliases => 'tools'
        attribute :tools_version
        attribute :mac_addresses, :aliases => 'macs'
        attribute :hypervisor,    :aliases => 'host'
        attribute :connection_state
        attribute :mo_ref
        attribute :path
        attribute :relative_path
        attribute :memory_mb
        attribute :cpus
        attribute :corespersocket
        attribute :interfaces
        attribute :volumes
        attribute :customvalues
        attribute :overall_status, :aliases => 'status'
        attribute :cluster
        attribute :datacenter
        attribute :resource_pool
        attribute :instance_uuid # move this --> id
        attribute :guest_id
        attribute :scsi_controller # this is the first scsi controller. Right now no more of them can be used.

        def initialize(attributes={} )
          super defaults.merge(attributes)
          self.instance_uuid ||= id # TODO: remvoe instance_uuid as it can be replaced with simple id
          initialize_interfaces
          initialize_volumes
          initialize_customvalues
          initialize_scsi_controller
        end

        # Lazy Loaded Attributes
        [:datacenter, :cluster, :hypervisor, :resource_pool, :mac_addresses].each do |attr|
          define_method attr do
            attributes[attr] = attributes[attr].call if attributes[attr].is_a?(Proc)
            attributes[attr]
          end
        end
        # End Lazy Loaded Attributes

        def vm_reconfig_memory(options = {})
          requires :instance_uuid, :memory
          service.vm_reconfig_memory('instance_uuid' => instance_uuid, 'memory' => memory_mb)
        end

        def vm_reconfig_cpus(options = {})
          requires :instance_uuid, :cpus, :corespersocket
          service.vm_reconfig_cpus('instance_uuid' => instance_uuid, 'cpus' => cpus, 'corespersocket' => corespersocket)
        end

        def vm_reconfig_hardware(hardware_spec, options = {})
          requires :instance_uuid
          service.vm_reconfig_hardware('instance_uuid' => instance_uuid, 'hardware_spec' => hardware_spec)
        end

        def start(options = {})
          requires :instance_uuid
          service.vm_power_on('instance_uuid' => instance_uuid)
        end

        def stop(options = {})
          options = { :force => !tools_installed? || !tools_running? }.merge(options)
          requires :instance_uuid
          service.vm_power_off('instance_uuid' => instance_uuid, 'force' => options[:force])
        end

        def reboot(options = {})
          options = { :force => false }.merge(options)
          requires :instance_uuid
          service.vm_reboot('instance_uuid' => instance_uuid, 'force' => options[:force])
        end

        def destroy(options = {})
          requires :instance_uuid
          if ready?
            # need to turn it off before destroying
            stop(options)
            wait_for { !ready? }
          end
          service.vm_destroy('instance_uuid' => instance_uuid)
        end

        def migrate(options = {})
          options = { :priority => 'defaultPriority' }.merge(options)
          requires :instance_uuid
          service.vm_migrate('instance_uuid' => instance_uuid, 'priority' => options[:priority])
        end

        # Clone from a server object
        #
        # ==== Parameters
        # *<~Hash>:
        #   * 'name'<~String> - *REQUIRED* Name of the _new_ VirtualMachine
        #   * See more options in vm_clone request/compute/vm_clone.rb
        #
        def clone(options = {})
          requires :name, :datacenter, :relative_path

          # Convert symbols to strings
          req_options = options.inject({}) { |hsh, (k,v)| hsh[k.to_s] = v; hsh }

          # Give our path to the request
          req_options['template_path'] ="#{relative_path}/#{name}"
          req_options['datacenter'] = "#{datacenter}"

          # Perform the actual clone
          clone_results = service.vm_clone(req_options)

          # We need to assign the service, otherwise we can't reload the model
          # Create the new VM model. TODO This only works when "wait=true"
          new_vm = self.class.new(clone_results['new_vm'].merge(:service => self.service))

          # We need to assign the collection otherwise we
          # cannot reload the model.
          new_vm.collection = self.collection

          # Return the new VM model.
          new_vm
        end

        def ready?
          power_state == "poweredOn"
        end

        def tools_installed?
          tools_state != "toolsNotInstalled"
        end

        def tools_running?
          tools_state == "toolsOk"
        end

        # defines VNC attributes on the hypervisor
        def config_vnc(options = {})
          requires :instance_uuid
          service.vm_config_vnc(options.merge('instance_uuid' => instance_uuid))
        end

        # returns a hash of VNC attributes required for service
        def vnc
          requires :instance_uuid
          service.vm_get_vnc(instance_uuid)
        end

        def memory
          memory_mb * 1024 * 1024
        end

        def sockets
          cpus / corespersocket
        end

        def mac
          interfaces.first.mac unless interfaces.empty?
        end

        def interfaces
          attributes[:interfaces] ||= id.nil? ? [] : service.interfaces( :server => self )
        end

        def interface_ready? attrs
          (attrs.is_a? Hash and attrs[:blocking]) or attrs.is_a? Fog::Compute::Vsphere::Interface
        end

        def add_interface attrs
          Fog::Logger.deprecation("<server>.add_interface is deprecated. Call <server>.interfaces.create instead.")

          interfaces.create(attrs)
        end

        def update_interface attrs
          wait_for { not ready? } if interface_ready? attrs
          service.update_vm_interface(id, attrs)
        end

        def destroy_interface attrs
          Fog::Logger.deprecation("<server>.destroy_vm_interface is deprecated. Call <server>.interfaces.get(:key => <nic_key>).destroy instead.")

          interfaces.get(attrs[:key] || attrs['key']).destroy
        end

        def volumes
          attributes[:volumes] ||= id.nil? ? [] : service.volumes(:server => self)
        end

        def customvalues
          attributes[:customvalues] ||= id.nil? ? [] : service.customvalues( :vm => self )
        end

        def scsi_controller
          self.attributes[:scsi_controller] ||= service.get_vm_first_scsi_controller(id)
        end

        def folder
          return nil unless datacenter and path
          attributes[:folder] ||= service.folders(:datacenter => datacenter, :type => :vm).get(path)
        end

        def save
          requires :name, :cluster, :datacenter
          if persisted?
            raise "update is not supported yet"
           # service.update_vm(attributes)
          else
            self.id = service.create_vm(attributes)
          end
          reload
        end

        def new?
          id.nil?
        end

        def reload
          # reload does not re-read assoiciated attributes, so we clear it manually
          [:interfaces, :volumes].each do |attr|
            self.attributes.delete(attr)
          end
          super
        end

        private

        def defaults
          {
            :cpus      => 1,
#            :corespersocket => 1,
            :memory_mb => 512,
            :guest_id  => 'otherGuest',
            :path      => '/'
          }
        end

        def initialize_interfaces
          if attributes[:interfaces] and attributes[:interfaces].is_a?(Array)
            self.attributes[:interfaces].map! { |nic| nic.is_a?(Hash) ? service.interfaces.new(nic) : nic }
          end
        end

        def initialize_volumes
          if attributes[:volumes] and attributes[:volumes].is_a?(Array)
            self.attributes[:volumes].map! { |vol| vol.is_a?(Hash) ? service.volumes.new(vol) : vol }
          end
        end

        def initialize_customvalues
          if attributes[:customvalues] and attributes[:customvalues].is_a?(Array)
            self.attributes[:customvalues].map { |cfield| cfield.is_a?(Hash) ? service.customvalue.new(cfield) : cfield}
          end
        end

        def initialize_scsi_controller
          if attributes[:scsi_controller] and attributes[:scsi_controller].is_a?(Hash)
            Fog::Compute::Vsphere::SCSIController.new(self.attributes[:scsi_controller])
          end
        end

      end

    end
  end
end


text:
layout: page
title: "CHEN 4460: Polymer Engineering Statistics"
comments: true
description: "blanks"
keywords: "CHEN,4460,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 3.41%

**Percent incomplete**: 0.0%

**Average grade** (4.0 scale): 2.92

**Standard deviation in grades** (4.0 scale): 0.12

**Average workload** (raw): 3.09

**Standard deviation in workload** (raw): 0.28

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 4.25

**Standard deviation in course rating** (6 point scale): 0.58

**Average instructor rating** (6 point scale): 4.32

**Standard deviation in instructor rating** (6 point scale): 0.44

**Instructors**: Douglas Gin, Mark Stoykovich

#### GENERAL CLASS INFORMATION

**Years provided**: Spring 2007, Spring 2009, Spring 2011, Spring 2013, Spring 2015

**Credits**: 3

**RAP/Honors class?** Neither

**Number of Sections**: 5

**Department**: CHEN

**College**: College of Engineering and Applied Science

**Level**: Upper

**Activity**: LEC - Lecture


text:
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/browser_watcher/watcher_metrics_provider_win.h"

#include <limits>
#include <vector>

#include "base/metrics/sparse_histogram.h"
#include "base/process/process_handle.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/registry.h"

namespace browser_watcher {

namespace {

void CompileAsserts() {
  // Process ID APIs on Windows talk in DWORDs, whereas for string formatting
  // and parsing, this code uses int. In practice there are no process IDs with
  // the high bit set on Windows, so there's no danger of overflow if this is
  // done consistently.
  static_assert(sizeof(DWORD) == sizeof(int),
                "process ids are expected to be no larger than int");
}

// This function does soft matching on the PID recorded in the key only.
// Due to PID reuse, the possibility exists that the process that's now live
// with the given PID is not the same process the data was recorded for.
// This doesn't matter for the purpose, as eventually the data will be
// scavenged and reported.
bool IsDeadProcess(base::StringPiece16 key_or_value_name) {
  // Truncate the input string to the first occurrence of '-', if one exists.
  size_t num_end = key_or_value_name.find(L'-');
  if (num_end != base::StringPiece16::npos)
    key_or_value_name = key_or_value_name.substr(0, num_end);

  // Convert to the numeric PID.
  int pid = 0;
  if (!base::StringToInt(key_or_value_name, &pid) || pid == 0)
    return true;

  // This is a very inexpensive check for the common case of our own PID.
  if (static_cast<base::ProcessId>(pid) == base::GetCurrentProcId())
    return false;

  // The process is not our own - see whether a process with this PID exists.
  // This is more expensive than the above check, but should also be very rare,
  // as this only happens more than once for a given PID if a user is running
  // multiple Chrome instances concurrently.
  base::ProcessHandle process = base::kNullProcessHandle;
  if (base::OpenProcessHandle(static_cast<base::ProcessId>(pid), &process)) {
    base::CloseProcessHandle(process);

    // The fact that it was possible to open the process says it's live.
    return false;
  }

  return true;
}

void RecordExitCodes(const base::string16& registry_path) {
  base::win::RegKey regkey(HKEY_CURRENT_USER,
                           registry_path.c_str(),
                           KEY_QUERY_VALUE | KEY_SET_VALUE);
  if (!regkey.Valid())
    return;

  size_t num = regkey.GetValueCount();
  if (num == 0)
    return;
  std::vector<base::string16> to_delete;

  // Record the exit codes in a sparse stability histogram, as the range of
  // values used to report failures is large.
  base::HistogramBase* exit_code_histogram =
      base::SparseHistogram::FactoryGet(
          WatcherMetricsProviderWin::kBrowserExitCodeHistogramName,
          base::HistogramBase::kUmaStabilityHistogramFlag);

  for (size_t i = 0; i < num; ++i) {
    base::string16 name;
    if (regkey.GetValueNameAt(static_cast<int>(i), &name) == ERROR_SUCCESS) {
      DWORD exit_code = 0;
      if (regkey.ReadValueDW(name.c_str(), &exit_code) == ERROR_SUCCESS) {
        // Do not report exit codes for processes that are still live,
        // notably for our own process.
        if (exit_code != STILL_ACTIVE || IsDeadProcess(name)) {
          to_delete.push_back(name);
          exit_code_histogram->Add(exit_code);
        }
      }
    }
  }

  // Delete the values reported above.
  for (size_t i = 0; i < to_delete.size(); ++i)
    regkey.DeleteValue(to_delete[i].c_str());
}

void ReadSingleExitFunnel(
    base::win::RegKey* parent_key, const base::char16* name,
    std::vector<std::pair<base::string16, int64>>* events_out) {
  DCHECK(parent_key);
  DCHECK(name);
  DCHECK(events_out);

  base::win::RegKey regkey(parent_key->Handle(), name, KEY_READ | KEY_WRITE);
  if (!regkey.Valid())
    return;

  // Exit early if no work to do.
  size_t num = regkey.GetValueCount();
  if (num == 0)
    return;

  // Enumerate the recorded events for this process for processing.
  std::vector<std::pair<base::string16, int64>> events;
  for (size_t i = 0; i < num; ++i) {
    base::string16 event_name;
    LONG res = regkey.GetValueNameAt(static_cast<int>(i), &event_name);
    if (res == ERROR_SUCCESS) {
      int64 event_time = 0;
      res = regkey.ReadInt64(event_name.c_str(), &event_time);
      if (res == ERROR_SUCCESS)
        events.push_back(std::make_pair(event_name, event_time));
    }
  }

  // Attempt to delete the values before reporting anything.
  // Exit if this fails to make sure there is no double-reporting on e.g.
  // permission problems or other corruption.
  for (size_t i = 0; i < events.size(); ++i) {
    const base::string16& event_name = events[i].first;
    LONG res = regkey.DeleteValue(event_name.c_str());
    if (res != ERROR_SUCCESS) {
      LOG(ERROR) << "Failed to delete value " << event_name;
      return;
    }
  }

  events_out->swap(events);
}

void MaybeRecordSingleExitFunnel(base::win::RegKey* parent_key,
                                 const base::char16* name,
                                 bool report) {
  std::vector<std::pair<base::string16, int64>> events;
  ReadSingleExitFunnel(parent_key, name, &events);
  if (!report)
    return;

  // Find the earliest event time.
  int64 min_time = std::numeric_limits<int64>::max();
  for (size_t i = 0; i < events.size(); ++i)
    min_time = std::min(min_time, events[i].second);

  // Record the exit funnel event times in a sparse stability histogram.
  for (size_t i = 0; i < events.size(); ++i) {
    std::string histogram_name(
        WatcherMetricsProviderWin::kExitFunnelHistogramPrefix);
    histogram_name.append(base::WideToUTF8(events[i].first));
    base::TimeDelta event_time =
        base::Time::FromInternalValue(events[i].second) -
            base::Time::FromInternalValue(min_time);
    base::HistogramBase* histogram =
        base::SparseHistogram::FactoryGet(
            histogram_name.c_str(),
            base::HistogramBase::kUmaStabilityHistogramFlag);

    // Record the time rounded up to the nearest millisecond.
    histogram->Add(event_time.InMillisecondsRoundedUp());
  }
}

void MaybeRecordExitFunnels(const base::string16& registry_path, bool report) {
  base::win::RegistryKeyIterator it(HKEY_CURRENT_USER, registry_path.c_str());
  if (!it.Valid())
    return;

  // Exit early if no work to do.
  if (it.SubkeyCount() == 0)
    return;

  // Open the key we use for deletion preemptively to prevent reporting
  // multiple times on permission problems.
  base::win::RegKey key(HKEY_CURRENT_USER,
                        registry_path.c_str(),
                        KEY_QUERY_VALUE);
  if (!key.Valid()) {
    LOG(ERROR) << "Failed to open " << registry_path << " for writing.";
    return;
  }

  std::vector<base::string16> to_delete;
  for (; it.Valid(); ++it) {
    // Defer reporting on still-live processes.
    if (IsDeadProcess(it.Name())) {
      MaybeRecordSingleExitFunnel(&key, it.Name(), report);
      to_delete.push_back(it.Name());
    }
  }

  for (size_t i = 0; i < to_delete.size(); ++i) {
    LONG res = key.DeleteEmptyKey(to_delete[i].c_str());
    if (res != ERROR_SUCCESS)
      LOG(ERROR) << "Failed to delete key " << to_delete[i];
  }
}

}  // namespace

const char WatcherMetricsProviderWin::kBrowserExitCodeHistogramName[] =
    "Stability.BrowserExitCodes";
const char WatcherMetricsProviderWin::kExitFunnelHistogramPrefix[] =
    "Stability.ExitFunnel.";

WatcherMetricsProviderWin::WatcherMetricsProviderWin(
    const base::char16* registry_path, bool report_exit_funnels) :
        registry_path_(registry_path),
        report_exit_funnels_(report_exit_funnels) {
}

WatcherMetricsProviderWin::~WatcherMetricsProviderWin() {
}

void WatcherMetricsProviderWin::ProvideStabilityMetrics(
    metrics::SystemProfileProto* /* system_profile_proto */) {
  // Note that if there are multiple instances of Chrome running in the same
  // user account, there's a small race that will double-report the exit codes
  // from both/multiple instances. This ought to be vanishingly rare and will
  // only manifest as low-level "random" noise. To work around this it would be
  // necessary to implement some form of global locking, which is not worth it
  // here.
  RecordExitCodes(registry_path_);
  MaybeRecordExitFunnels(registry_path_, report_exit_funnels_);
}

}  // namespace browser_watcher


text:
package org.codehaus.httpcache4j.auth;

import org.codehaus.httpcache4j.HTTPHost;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author Erlend Hamnaberg
 * @version $Revision: $
 */
public class DefaultSchemeRegistry implements SchemeRegistry {
    private ConcurrentMap<HTTPHost, AuthScheme> registry = new ConcurrentHashMap<HTTPHost, AuthScheme>();

    public void register(HTTPHost host, AuthScheme scheme) {
        registry.put(host, scheme);
    }

    public boolean matches(HTTPHost host) {
        return host != null && registry.containsKey(host);
    }

    public void clear() {
        registry.clear();
    }

    public AuthScheme get(HTTPHost host) {
        return registry.get(host);
    }

    public void remove(HTTPHost host) {
        registry.remove(host);
    }
}


text:
/*global describe, it*/
'use strict';

var chai = require('chai')
  , chaiAsPromised = require("chai-as-promised")
  , endpoint = require('../lib/endpoint')
  , nock = require('nock')
  , Opts = require('./opts')
  ;

chai.use(chaiAsPromised);
nock.disableNetConnect();

var expect = chai.expect
  , Schedulable = require('../lib/mixins/schedulable')
  , mock = nock('http://localhost', {
    reqheaders: {
      'content-type': 'application/json;charset=utf-8'
    }
  })
  ;

describe('Schedulable', function () {

  var api = endpoint('/test', Opts, Schedulable).value;

  describe('#schedule()', function () {

    it('should return a promise of a single entity', function () {
      var request = {}
        , response = {}
        ;

      mock.post('/v1/test', request)
        .reply(202, response);

      var result = api.schedule({}, 'test');

      return Promise.all([
        expect(result).to.eventually.be.an('object'),
        expect(result).to.eventually.be.deep.equal(response)
      ]);
    });

    it('should send an auth token', function () {
      var request = {}
        , response = {}
        ;

      mock.post('/v1/test', request)
        .matchHeader('x-auth-token', 'token-aaaa')
        .reply(202, response);

      var result = api.schedule({}, 'test', {token: 'token-aaaa'});

      return result.then(function () {
        /* jshint expr: true */
        expect(mock.isDone()).to.be.true;
      });
    });

    it('should send an API key', function () {
      var request = {}
        , response = {}
        ;

      mock.post('/v1/test', request)
        .matchHeader('st2-api-key', 'key-cccc')
        .reply(202, response);

      var result = api.schedule({}, 'test', {key: 'key-cccc'});

      return result.then(function () {
        /* jshint expr: true */
        expect(mock.isDone()).to.be.true;
      });
    });

    it('should reject the promise if server returns other than 202 status code', function () {
      var request = {}
        , response = 'accepted instead of scheduled'
        ;

      mock.post('/v1/test', request)
        .reply(201, response);

      var result = api.schedule({}, 'test');

      return Promise.all([
        expect(result).to.be.rejected,
        result.catch(function (err) {
          expect(err).to.have.property('name', 'APIError');
          expect(err).to.have.property('status', 201);
          expect(err).to.have.property('message', response);
        })
      ]);
    });

  });

});


text:
int main()
{
    using std::cerr;
    using std::endl;

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        cerr << "SDL_Init Error: " << SDL_GetError() << endl;
        return EXIT_FAILURE;
    }

    SDL_Window* win = SDL_CreateWindow("Hello World!", 100, 100, 620, 387, SDL_WINDOW_SHOWN);
    if (win == nullptr) {
        cerr << "SDL_CreateWindow Error: " << SDL_GetError() << endl;
        return EXIT_FAILURE;
    }

    SDL_Renderer* ren
        = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (ren == nullptr) {
        cerr << "SDL_CreateRenderer Error" << SDL_GetError() << endl;
		if (win != nullptr) {
			SDL_DestroyWindow(win);
		}
		SDL_Quit();
        return EXIT_FAILURE;
    }

    SDL_Surface* bmp = SDL_LoadBMP("../img/grumpy-cat.bmp");
    if (bmp == nullptr) {
        cerr << "SDL_LoadBMP Error: " << SDL_GetError() << endl;
		if (ren != nullptr) {
			SDL_DestroyRenderer(ren);
		}
		if (win != nullptr) {
			SDL_DestroyWindow(win);
		}
		SDL_Quit();
        return EXIT_FAILURE;
    }

    SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, bmp);
    if (tex == nullptr) {
        cerr << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << endl;
		if (bmp != nullptr) {
			SDL_FreeSurface(bmp);
		}
		if (ren != nullptr) {
			SDL_DestroyRenderer(ren);
		}
		if (win != nullptr) {
			SDL_DestroyWindow(win);
		}
		SDL_Quit();
        return EXIT_FAILURE;
    }
    SDL_FreeSurface(bmp);

    for (int i = 0; i < 20; i++) {
        SDL_RenderClear(ren);
        SDL_RenderCopy(ren, tex, nullptr, nullptr);
        SDL_RenderPresent(ren);
        SDL_Delay(100);
    }

    SDL_DestroyTexture(tex);
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);
    SDL_Quit();

    return EXIT_SUCCESS;
}


text:
namespace OpenApoc
{
class Image;
class Sample;
class DoodadType;
class GameState;

class HazardType : public StateObject<HazardType>
{
  public:
	StateRef<DoodadType> doodadType;
	sp<Sample> sound;

	// Lifetime of a hazard
	// In TB, hazard damages and spreads once every turn end
	// In RT, it does so every 4 seconds

	unsigned minLifetime = 0;
	unsigned maxLifetime = 0;

	// Whether frames follow the logic of fire
	bool fire = false;

	// Get first frame used for age and offset
	sp<Image> getFrame(unsigned age, int offset);

	// Get a random lifetime for the hazard of this type
	int getLifetime(GameState &state);
};

class DamageModifier : public StateObject<DamageModifier>
{
  public:
	// nothing?
};

enum class DamageSource
{
	Impact,
	Hazard,
	Debuff
};

class DamageType : public StateObject<DamageType>
{
  public:
	enum class BlockType
	{
		Physical,
		Psionic,
		Gas,
		Fire
	};
	enum class EffectType
	{
		None,
		Stun,
		Smoke,
		Fire,
		Enzyme,
		Brainsucker,
		Psionic
	};

	UString name;

	bool ignore_shield = false;
	// When causing unit death makes it non-violent
	bool non_violent = false;
	sp<Image> icon_sprite;
	std::map<StateRef<DamageModifier>, int> modifiers;

	// Whether this damage type produces explosion on hit
	bool explosive = false;
	// Doodad used by explosion, if nullptr will use common explosion doodad set
	StateRef<DoodadType> explosionDoodad;
	BlockType blockType = BlockType::Physical;
	EffectType effectType = EffectType::None;
	StateRef<HazardType> hazardType;

	// True if explosive damage should reduce with distance (gas deals full damage everywhere)
	bool hasDamageDissipation() const
	{
		return blockType != BlockType::Gas && blockType != BlockType::Psionic;
	}
	// True if this damage type deals damage on initial impact
	bool doesImpactDamage() const
	{
		return blockType != BlockType::Gas && blockType != BlockType::Psionic;
	}
	// True if this always impacts unit's head
	bool alwaysImpactsHead() const { return blockType == BlockType::Gas; }
	// True if this ignores armor value
	bool ignoresArmorValue() const { return effectType == EffectType::Smoke; }
	// True if this deals damage to armor
	bool dealsArmorDamage() const
	{
		return effectType != EffectType::Stun && effectType != EffectType::Smoke &&
		       effectType != EffectType::Fire && effectType != EffectType::Psionic;
	}
	// True if this damage type deals fatal wounds
	bool dealsFatalWounds() const
	{
		return effectType != EffectType::Stun && effectType != EffectType::Smoke &&
		       effectType != EffectType::Psionic;
	}
	// True if this deals stun damage instead of health damage
	bool dealsStunDamage() const
	{
		return effectType == EffectType::Stun || effectType == EffectType::Smoke;
	}

	// Sounds when this explodes
	std::list<sp<Sample>> explosionSounds;

	int dealDamage(int damage, StateRef<DamageModifier> modifier) const;
};
} // namespace OpenApoc