text:
<?php

namespace Grale\WebDav\Property;

use Grale\WebDav\Lock;

/**
 * @covers Grale\WebDav\Property\LockDiscovery
 */
class LockDiscoveryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var LockDiscovery
     */
    protected $property;

    public function setUp()
    {
        $lockOne = new Lock('shared');
        $lockOne->setToken('opaquelocktoken:e71df4fae-5dec-22d6-fea5-00a0c91e6be4');

        $lockTwo = new Lock('exclusive');
        $lockTwo->setToken('opaquelocktoken:e71d4fae-5dec-22df-fea5-00a0c93bd5eb1');

        $this->property = new LockDiscovery(array($lockOne, $lockTwo));
    }

    public function testGetValue()
    {
        $this->assertCount(2, $this->property->getValue());
    }

    public function testGetLocks()
    {
        $this->assertCount(2, $this->property->getLocks());
    }

    public function testGetWriteLocks()
    {
        $this->assertCount(2, $this->property->getLocks('write'));
    }

    public function testGetSharedLocks()
    {
        $this->assertCount(1, $this->property->getLocks('write', 'shared'));
    }

    public function testGetExclusiveLocks()
    {
        $this->assertCount(1, $this->property->getLocks('write', 'exclusive'));
    }

    public function testHasLock()
    {
        $this->assertTrue($this->property->hasLock());
    }

    public function testHasWriteLock()
    {
        $this->assertTrue($this->property->hasLock('write'));
    }

    public function testHasExclusiveLock()
    {
        $this->assertTrue($this->property->hasLock('write', 'exclusive'));
    }

    public function testHasSharedLock()
    {
        $this->assertTrue($this->property->hasLock('write', 'shared'));
    }

    public function testHasLockToken()
    {
        $this->assertTrue($this->property->hasLockToken('opaquelocktoken:e71df4fae-5dec-22d6-fea5-00a0c91e6be4'));
    }

    public function testGetLock()
    {
        $result = $this->property->getLock('opaquelocktoken:e71df4fae-5dec-22d6-fea5-00a0c91e6be4');
        $this->assertInstanceOf('\Grale\WebDav\Lock', $result);
    }

    public function testFromXmlWitoutAnyActiveLock()
    {
        $dom = new \DOMDocument();
        $dom->loadXML(
            '<?xml version="1.0" encoding="utf-8"?>
            <D:multistatus xmlns:D="DAV:">
              <D:lockdiscovery/>
            </D:multistatus>'
        );
        $property = LockDiscovery::fromXml($dom->documentElement);

        $this->assertCount(0, $property->getLocks());
    }

    public function testFromXml()
    {
        $dom = new \DOMDocument();
        $dom->loadXML(
            '<?xml version="1.0" encoding="utf-8"?>
            <D:multistatus xmlns:D="DAV:">
              <D:lockdiscovery>
                <D:activelock>
                  <D:locktype><D:write/></D:locktype>
                  <D:lockscope><D:exclusive/></D:lockscope>
                  <D:depth>Infinity</D:depth>
                  <D:owner>
                    <D:href>http://example.org/~ejw/contact.html</D:href>
                  </D:owner>
                  <D:timeout>Second-604800</D:timeout>
                  <D:locktoken>
                    <D:href>urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4</D:href>
                  </D:locktoken>
                  <D:lockroot>
                    <D:href>http://example.com/workspace/webdav/proposal.doc</D:href>
                  </D:lockroot>
                </D:activelock>
              </D:lockdiscovery>
            </D:multistatus>'
        );
        $property = LockDiscovery::fromXml($dom->documentElement);

        $this->assertCount(1, $property->getLocks());
        $this->assertTrue($property->hasLockToken('urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4'));
    }
}


text:
/*
 * Created by IntelliJ IDEA.
 * User: Lennart
 * Date: 18-okt-02
 * Time: 17:08:04
 */
package com.compomics.dbtoolkit.gui.interfaces;

import java.awt.*;

/*
 * CVS information:
 *
 * $Revision: 1.3 $
 * $Date: 2007/07/06 09:52:03 $
 */

/**
 * This interface describes the behaviour for a view class that can recursively
 * set a cursor type on all its subcomponents.
 *
 * @author Lennart Martens
 */
public interface CursorModifiable {

    /**
     * Call this method to set the specified type of constructor
     * on the view and all its subcomponents.
     *
     * @param   aCursor Cursor to set on the view and all subcomponents.
     */
    public abstract void setCursorOnComponents(Cursor aCursor);
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * DS207: Consider shorter variations of null checks
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */

const _ = require("lodash");

import { MigrationMixin } from "./migration-mixin";

const migration = {
  version: "1.19.0",
  description: "Adds complexity setting, based on old diagramOnly. Removes diagramOnly",
  date: "2017-09-26",

  doUpdate(data) {
    if (data.settings == null) { data.settings = {}; }
    const wasDiagramOnly = data.settings.diagramOnly || false;

    delete data.settings.diagramOnly;

    const defaultComplexity = wasDiagramOnly ?
      0 // was `AppSettingsStore.Complexity.diagramOnly` but this no longer exists as of 1.22.0
      :
      2; // was `AppSettingsStore.Complexity.DEFAULT` but this is now '1' as of 1.22.0

    return data.settings.complexity != null ? data.settings.complexity : (data.settings.complexity = defaultComplexity);
  }
};

export const migration_20 = _.mixin(migration, MigrationMixin);


text:
function runNewsYCSubmit() {
  location.href='http://news.ycombinator.com/submitlink?u='+encodeURIComponent(location.href)+'&t='+encodeURIComponent(document.title);
}


text:
if [ "$DISTNAME" == "nixos" ] ; then
	osctl ct start $CTID || fail "unable to start"
	sleep 10
	osctl ct stop $CTID || fail "unable to stop"
fi
osctl ct passwd $CTID root suCHS3crET || fail "unable to set password"


text:
package org.opensingular.form.type.core;

import org.opensingular.form.SISimple;

import java.time.YearMonth;
import java.time.ZoneId;
import java.util.Date;

public class SIDateTime extends SISimple<Date> implements SIComparable<Date> {
    public SIDateTime() {
    }

    public Date getDate() {
        return getValue();
    }

    public YearMonth getJavaYearMonth() {
        return YearMonth.from(getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
    }

}


text:
#import "ActViewController.h"
#import "ActTextField.h"

@class ActSummaryView, ActHorizontalBoxView, ActSplitView;

@interface ActSummaryViewController : ActViewController <NSTextViewDelegate>

@property(nonatomic, strong) ActSummaryView *summaryView;

@property(nonatomic, strong) ActHorizontalBoxView *dateBox;
@property(nonatomic, strong) ActExpandableTextField *dateTimeField;
@property(nonatomic, strong) ActExpandableTextField *dateDayField;
@property(nonatomic, strong) ActExpandableTextField *dateDateField;

@property(nonatomic, strong) ActHorizontalBoxView *typeBox;
@property(nonatomic, strong) ActExpandableTextField *typeActivityField;
@property(nonatomic, strong) ActExpandableTextField *typeTypeField;

@property(nonatomic, strong) ActHorizontalBoxView *statsBox;
@property(nonatomic, strong) ActExpandableTextField *statsDistanceField;
@property(nonatomic, strong) ActExpandableTextField *statsDurationField;
@property(nonatomic, strong) ActExpandableTextField *statsPaceField;

@property(nonatomic, strong) ActTextField *courseField;

- (IBAction)controlAction:(id)sender;

@end

// draws the background rounded rect

@interface ActSummaryView : NSView

@property(nonatomic, weak) ActSummaryViewController *controller;

@end


text:
<?php

namespace Magento\Newsletter\Model\ResourceModel\Subscriber;

use Magento\Newsletter\Model\Queue as ModelQueue;

/**
 * Newsletter subscribers collection
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * Queue link table name
     *
     * @var string
     */
    protected $_queueLinkTable;

    /**
     * Store table name
     *
     * @var string
     */
    protected $_storeTable;

    /**
     * Queue joined flag
     *
     * @var boolean
     */
    protected $_queueJoinedFlag = false;

    /**
     * Flag that indicates apply of customers info on load
     *
     * @var boolean
     */
    protected $_showCustomersInfo = false;

    /**
     * Filter for count
     *
     * @var array
     */
    protected $_countFilterPart = [];

    /**
     * Customer Eav data
     *
     * @var   \Magento\Eav\Helper\Data
     */
    protected $_customerHelperData;

    /**
     * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     * @param \Magento\Eav\Helper\Data $customerHelperData
     * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection
     * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource
     */
    public function __construct(
        \Magento\Framework\Data\Collection\EntityFactory $entityFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Eav\Helper\Data $customerHelperData,
        \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        $this->_customerHelperData = $customerHelperData;
        parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
    }

    /**
     * Constructor
     * Configures collection
     *
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->_init('Magento\Newsletter\Model\Subscriber', 'Magento\Newsletter\Model\ResourceModel\Subscriber');
        $this->_queueLinkTable = $this->getTable('newsletter_queue_link');
        $this->_storeTable = $this->getTable('store');

        $this->_map['fields']['type'] = $this->getResource()->getConnection()->getCheckSql(
            'main_table.customer_id = 0',
            1,
            2
        );
        $this->_map['fields']['website_id'] = 'store.website_id';
        $this->_map['fields']['group_id'] = 'store.group_id';
        $this->_map['fields']['store_id'] = 'main_table.store_id';
    }

    /**
     * Set loading mode subscribers by queue
     *
     * @param ModelQueue $queue
     * @return $this
     */
    public function useQueue(ModelQueue $queue)
    {
        $this->getSelect()->join(
            ['link' => $this->_queueLinkTable],
            "link.subscriber_id = main_table.subscriber_id",
            []
        )->where(
            "link.queue_id = ? ",
            $queue->getId()
        );
        $this->_queueJoinedFlag = true;
        return $this;
    }

    /**
     * Set using of links to only unsendet letter subscribers.
     *
     * @return $this
     */
    public function useOnlyUnsent()
    {
        if ($this->_queueJoinedFlag) {
            $this->addFieldToFilter('link.letter_sent_at', ['null' => 1]);
        }

        return $this;
    }

    /**
     * Adds customer info to select
     *
     * @return $this
     */
    public function showCustomerInfo()
    {
        $this->getSelect()->joinLeft(
            [
                'customer' => $this->getTable('customer_entity')
            ],
            'main_table.customer_id = customer.entity_id',
            ['firstname', 'lastname']
        );
        return $this;
    }

    /**
     * Add type field expression to select
     *
     * @return $this
     */
    public function addSubscriberTypeField()
    {
        $this->getSelect()->columns(['type' => new \Zend_Db_Expr($this->_getMappedField('type'))]);
        return $this;
    }

    /**
     * Sets flag for customer info loading on load
     *
     * @return $this
     */
    public function showStoreInfo()
    {
        $this->getSelect()->join(
            ['store' => $this->_storeTable],
            'store.store_id = main_table.store_id',
            ['group_id', 'website_id']
        );

        return $this;
    }

    /**
     * Returns select count sql
     *
     * @return string
     */
    public function getSelectCountSql()
    {
        $select = parent::getSelectCountSql();
        $countSelect = clone $this->getSelect();

        $countSelect->reset(\Magento\Framework\DB\Select::HAVING);

        return $select;
    }

    /**
     * Load only subscribed customers
     *
     * @return $this
     */
    public function useOnlyCustomers()
    {
        $this->addFieldToFilter('main_table.customer_id', ['gt' => 0]);

        return $this;
    }

    /**
     * Show only with subscribed status
     *
     * @return $this
     */
    public function useOnlySubscribed()
    {
        $this->addFieldToFilter(
            'main_table.subscriber_status',
            \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED
        );

        return $this;
    }

    /**
     * Filter collection by specified store ids
     *
     * @param int[]|int $storeIds
     * @return $this
     */
    public function addStoreFilter($storeIds)
    {
        $this->addFieldToFilter('main_table.store_id', ['in' => $storeIds]);
        return $this;
    }

    /**
     * Get queue joined flag
     *
     * @return bool
     * @SuppressWarnings(PHPMD.BooleanGetMethodName)
     */
    public function getQueueJoinedFlag()
    {
        return $this->_queueJoinedFlag;
    }
}


text:
package ru.szhernovoy.store;

import ru.szhernovoy.generic.SimpleArray;

import java.util.NoSuchElementException;

/**
 * Created by Sergey on 08.09.2016.
 */
public class AbstractStore<T extends Base> implements Store<T> {

    private SimpleArray<T> sa;

    public AbstractStore(int size) {
        this.sa = new SimpleArray<T>(size);
     }

    public AbstractStore(SimpleArray<T> value) {
        this.sa = value;
    }

    private int findById(String id){
        int result = -1;
        for(int index =0 ;index < this.sa.getSize(); index++ ){
            if(this.sa.get(index).getId().equals(id)){
                result = index;
                break;
            }
        }

        if(result!= -1){
            return result;
        }
        else{
            throw new NoSuchElementException("Not element in array");
        }
    }

    @Override
    public boolean update(T t) {
        boolean result = false;

        int index = this.findById(t.getId());
        if(index > -1){
            this.sa.update(t, index);
            result = true;
        }
        return result;
    }

    @Override
    public boolean add(T t) {
        this.sa.add(t);
        return true;
    }

    @Override
    public boolean delete(String id) {

        boolean result = false;

        int index = this.findById(id);
        if(index > -1){
            this.sa.delete(index);
            result = true;
        }
        return result;
    }

    @Override
    public T get(String id) {
        int index = this.findById(id);
        return this.sa.get(index);
    }

}


text:
#include "pt_decoder_fixture.h"

#include "pt_decoder.h"

#include <check.h>

struct pt_decoder_fixture_s pt_decoder_fixture;

struct dfix_desc dfix_standard = {
	/* .name = */ "standard",
	/* .setup = */ pt_dfix_setup_standard
};

struct dfix_desc dfix_nosync = {
	/* .name = */ "nosync",
	/* .setup = */ pt_dfix_setup_nosync
};

static void init_fixture(void)
{
	struct pt_decoder_fixture_s *dfix = &pt_decoder_fixture;
	struct pt_config *config = &dfix->config;
	int errcode;

	(void) memset(dfix->buffer, 0, sizeof(dfix->buffer));

	errcode = pt_encoder_init(&pt_decoder_fixture.encoder, config);
	ck_int_eq(errcode, 0);

	pt_decoder_fixture.decoder = pt_alloc_decoder(config);
	ck_nonnull(pt_decoder_fixture.decoder);

	pt_decoder_fixture.decoder->ip.ip = pt_dfix_bad_ip;
	pt_decoder_fixture.decoder->ip.need_full_ip = 0;
	pt_decoder_fixture.decoder->ip.suppressed = 0;

	dfix->last_ip = pt_decoder_fixture.decoder->ip;
}

void pt_dfix_setup_config(struct pt_config *config)
{
	int errcode;

	errcode = pt_configure(config);
	ck_int_ge(errcode, 0);

	config->begin = pt_decoder_fixture.buffer;
	config->end = pt_decoder_fixture.buffer +
		sizeof(pt_decoder_fixture.buffer);
}

void pt_dfix_setup_nosync(void)
{
	pt_dfix_setup_config(&pt_decoder_fixture.config);
	init_fixture();
}

void pt_dfix_setup_standard(void)
{
	struct pt_decoder_fixture_s *dfix = &pt_decoder_fixture;

	pt_dfix_setup_nosync();

	/* Synchronize the decoder at the beginning of the buffer. */
	dfix->decoder->pos = dfix->config.begin;
}

void pt_teardown_decoder_fixture(void)
{
	struct pt_decoder_fixture_s *dfix = &pt_decoder_fixture;

	pt_free_decoder(dfix->decoder);
	dfix->decoder = NULL;
}

void pt_dfix_check_last_ip(const char *file, int line)
{
	struct pt_decoder_fixture_s *dfix = &pt_decoder_fixture;
	struct pt_decoder *decoder = dfix->decoder;
	struct pt_last_ip *dip = &decoder->ip, *fip = &dfix->last_ip;

	ck_assert_msg(dip->ip == fip->ip, "Bad last-ip.ip. Got: 0x%" PRIx64
		      ", want: 0x%" PRIx64 " at %s:%d.",
		      dip->ip, fip->ip, file, line);
	ck_assert_msg(dip->need_full_ip == fip->need_full_ip,
		      "Bad last-ip.need_full_ip. Got: %u, want: %u at %s:%d.",
		      dip->need_full_ip, fip->need_full_ip, file, line);
	ck_assert_msg(dip->suppressed == fip->suppressed,
		      "Bad last-ip.suppressed. Got: %u, want: %u at %s:%d.",
		      dip->suppressed, fip->suppressed, file, line);
}

void pt_dfix_check_tnt_cache(const char *file, int line)
{
	struct pt_decoder_fixture_s *dfix = &pt_decoder_fixture;
	struct pt_decoder *decoder = dfix->decoder;
	struct pt_tnt_cache *dtnt = &decoder->tnt, *ftnt = &dfix->tnt;

	ck_assert_msg(dtnt->tnt == ftnt->tnt,
		      "Bad tnt-cache.tnt. Got: 0x%" PRIx64 ", expected: 0x%"
		      PRIx64 " at %s:%d.", dtnt->tnt, ftnt->tnt, file, line);
	ck_assert_msg(dtnt->index == ftnt->index,
		      "Bad tnt-cache.index. Got: 0x%" PRIx64 ", expected: 0x%"
		      PRIx64 " at %s:%d.", dtnt->index, ftnt->index, file,
		      line);
}

static const char *create_tcase_name(const char *dd, const char *td)
{
	size_t namelen;
	char *name;
	int status;

	if (!td)
		return dd;

	namelen = strlen(td) + strlen(dd) + 3;
	name = malloc(namelen);
	if (!name)
		return dd;

	status = snprintf(name, namelen, "%s: %s", dd, td);
	if (status < 0) {
		free(name);
		return dd;
	}

	return name;
}

void pt_add_tcase(Suite *suite,
		   const struct tcase_desc *td,
		   const struct dfix_desc *dd)
{
	TCase *tcase;
	const char *name;

	name = create_tcase_name(dd->name, td->name);

	tcase = tcase_create(name);

	add_dfix(tcase, dd->setup);

	td->add_tests(tcase);

	suite_add_tcase(suite, tcase);
}

void *check_encode_pad(struct pt_encoder *encoder)
{
	int bytes;

	bytes = pt_encode_pad(encoder);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_psb(struct pt_encoder *encoder)
{
	int bytes;

	bytes = pt_encode_psb(encoder);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_psbend(struct pt_encoder *encoder)
{
	int bytes;

	bytes = pt_encode_psbend(encoder);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_tip(struct pt_encoder *encoder, uint64_t ip,
		       enum pt_ip_compression ipc)
{
	int bytes;

	bytes = pt_encode_tip(encoder, ip, ipc);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_tnt_8(struct pt_encoder *encoder, uint8_t tnt, int size)
{
	int bytes;

	bytes = pt_encode_tnt_8(encoder, tnt, size);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_tnt_64(struct pt_encoder *encoder, uint64_t tnt, int size)
{
	int bytes;

	bytes = pt_encode_tnt_64(encoder, tnt, size);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_tip_pge(struct pt_encoder *encoder, uint64_t ip,
			   enum pt_ip_compression ipc)
{
	int bytes;

	bytes = pt_encode_tip_pge(encoder, ip, ipc);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_tip_pgd(struct pt_encoder *encoder, uint64_t ip,
			   enum pt_ip_compression ipc)
{
	int bytes;

	bytes = pt_encode_tip_pgd(encoder, ip, ipc);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_fup(struct pt_encoder *encoder, uint64_t ip,
		       enum pt_ip_compression ipc)
{
	int bytes;

	bytes = pt_encode_fup(encoder, ip, ipc);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_pip(struct pt_encoder *encoder, uint64_t cr3)
{
	int bytes;

	bytes = pt_encode_pip(encoder, cr3);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_ovf(struct pt_encoder *encoder)
{
	int bytes;

	bytes = pt_encode_ovf(encoder);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_mode_exec(struct pt_encoder *encoder,
			     enum pt_exec_mode mode)
{
	int bytes;

	bytes = pt_encode_mode_exec(encoder, mode);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_mode_tsx(struct pt_encoder *encoder, uint8_t flags)
{
	int bytes;

	bytes = pt_encode_mode_tsx(encoder, flags);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_tsc(struct pt_encoder *encoder, uint64_t tsc)
{
	int bytes;

	bytes = pt_encode_tsc(encoder, tsc);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}

void *check_encode_cbr(struct pt_encoder *encoder, uint8_t cbr)
{
	int bytes;

	bytes = pt_encode_cbr(encoder, cbr);
	ck_int_gt(bytes, 0);

	return encoder->pos;
}


text:
package com.fasterxml.jackson.module.paramnames;

import java.util.Arrays;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;

public class ModuleTestBase
{
    protected static ObjectMapper newMapper() {
        return new ObjectMapper()
                .registerModule(new ParameterNamesModule());
    }

    protected static JsonMapper.Builder mapperBuilder() {
        return JsonMapper.builder()
                .addModule(new ParameterNamesModule());
    }

    protected static String q(String value) {
        return "\"" + value + "\"";
    }

    protected static String a2q(String json) {
        return json.replace("'", "\"");
    }

    protected void verifyException(Throwable e, String... matches)
    {
        String msg = e.getMessage();
        String lmsg = (msg == null) ? "" : msg.toLowerCase();
        for (String match : matches) {
            String lmatch = match.toLowerCase();
            if (lmsg.indexOf(lmatch) >= 0) {
                return;
            }
        }
        throw new Error("Expected an exception with one of substrings ("+Arrays.asList(matches)+"): got one with message \""+msg+"\"");
    }
}


text:
source $DOT/.dot/functions/try

try pinstall brew ctags

# Linters
try pinstall brew shellcheck
try pinstall gem rubocop
try pinstall npm dockerlint
try pinstall npm eslint
try pinstall npm eslint-plugin-promise
try pinstall npm eslint-config-standard
try pinstall npm eslint-plugin-standard
try pinstall npm sass-lint
try pinstall pip3 flake8
try pinstall pip3 pylint

exit $TRY_CODE


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

namespace ConsoleApplication6
{
    public class Dog
    {
        public string name;
        public string breed;
        public int age;
        public static int numLegs = 4;

        public Dog()
        {
            age = 0;
            name = "";
            breed = "";
        }

        public Dog(int age, string name, string breed)
        {
            this.age = age;
            this.name = name;
            this.breed = breed;

        }

        public void Bark()
        {
            Console.WriteLine(this.name + " says Woof woof!");
            Console.WriteLine("I have" + numLegs + " legs");

        }
    }
}


text:
classFeature = {
}
classFeature.__index = classFeature

-- write support code
function classFeature:supcode ()
end

-- output tag
function classFeature:decltype ()
end

-- register feature
function classFeature:register ()
end

-- translate verbatim
function classFeature:preamble ()
end

-- check if it is a variable
function classFeature:isvariable ()
 return false
end

-- checi if it requires collection
function classFeature:requirecollection (t)
 return false
end

-- build names
function classFeature:buildnames ()
 if self.name and self.name~='' then
  local n = split(self.name,'@')
  self.name = n[1]
		if not n[2] then
		 n[2] = applyrenaming(n[1])
		end
  self.lname = n[2] or gsub(n[1],"%[.-%]","")
 end
 self.name = getonlynamespace() .. self.name
end

-- check if feature is inside a container definition
-- it returns the container class name or nil.
function classFeature:incontainer (which)
 if self.parent then
  local parent = self.parent
  while parent do
   if parent.classtype == which then
    return parent.name
   end
   parent = parent.parent
  end
 end
 return nil
end

function classFeature:inclass ()
 return self:incontainer('class')
end

function classFeature:inmodule ()
 return self:incontainer('module')
end

function classFeature:innamespace ()
 return self:incontainer('namespace')
end

-- return C binding function name based on name
-- the client specifies a prefix
function classFeature:cfuncname (n)
 if self.parent then
  n = self.parent:cfuncname(n)
 end

 if self.lname and
	   strsub(self.lname,1,1)~="."  -- operator are named as ".add"
	then
  return n..'_'..self.lname
 else
  return n..'_'..self.name
 end
end


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.1.1.1-0
description: Global.NaN is a data property with default attribute values (false)
includes:
    - runTestCase.js
    - fnGlobalObject.js
---*/

function testcase() {
    var desc = Object.getOwnPropertyDescriptor(fnGlobalObject(), 'NaN');
  if (desc.writable === false &&
      desc.enumerable === false &&
      desc.configurable === false) {
    return true;
  }
 }
runTestCase(testcase);


text:
.PHONY: setup
setup:
	mv template.env.dev env.dev
	mv template.env.prod env.prod

.PHONY: dev
dev: ; MANUALRUN=1 docker-compose -f docker-compose.yml -f docker-compose.linked.yml up

.PHONY: build
build:
	docker-compose -f docker-compose.yml -f docker-compose.linked.yml build

.PHONY: schema
schema:
	docker exec -ti bookingdev_api yarn run knex -- migrate:latest

.PHONY: frontend.cli
frontend.cli:
	docker exec -ti bookingdev_frontend bash

.PHONY: api.cli
api.cli:
	docker exec -ti bookingdev_api bash

.PHONY: clean
clean:
	docker rm -f bookingdev_frontend bookingdev_api bookingdev_postgres bookingdev_redis

.PHONY: database.create
database.create:
	docker exec bookingdev_api yarn run knex -- migrate:latest

.PHONY: database.destroy
database.destroy:
	cat scripts/sql/drop.sql | bash scripts/postgres.sh psql


text:
package java8professional.chapter04.primitives.functionalinterfaces.java.util.function.others;

import java.util.stream.IntStream;
import java.util.stream.Stream;

@FunctionalInterface
public interface ToIntFunction<X> {

    Integer apply(X x);

    public static void main(String[] args) {
        IntStream stream = Stream.of(1, 2, 3).mapToInt(x -> x + 1);
        stream.forEach(System.out::println);
    }

}


text:
import path from 'path';

export const DEFAULT_APP_NAME = 'APP';
export const ELECTRON_VERSION = '1.6.6';
export const PLACEHOLDER_APP_DIR = path.join(__dirname, './../', 'app');


text:
namespace TypeVisualiserUnitTests.Model
{
    using System;
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Rhino.Mocks;
    using StructureMap;
    using TypeVisualiser.Model;

    [TestClass]
    public class ModelBuilderTest
    {
        private MockRepository mockery;
        private ModelBuilder target;
        private IContainer factory;
        private IVisualisableTypeWithAssociations mockSubject;

        [TestInitialize]
        public void TestInitialise()
        {
            this.mockery = new MockRepository();
            this.mockSubject = this.mockery.Stub<IVisualisableTypeWithAssociations>();
            this.factory = new Container(config => config.For<IVisualisableTypeWithAssociations>().Use(mockSubject));

            this.target = new ModelBuilder();
            PrivateAccessor.SetField(this.target, "doNotUseFactory", this.factory);
        }

        [TestCleanup]
        public void TestCleanup()
        {
            this.mockery = null;
            this.mockSubject = null;
            this.factory.Dispose();
            this.factory = null;
        }

        [TestMethod]
        public void CanConstruct()
        {
        }

        [TestMethod]
        public void BuildSubjectShouldSucceedGivenStringType()
        {
            var result = this.target.BuildSubject(typeof(string), 0);
            result.Should().NotBeNull();
        }

        [TestMethod]
        public void BuildSubjectShouldThrowGivenNull()
        {
            this.target.Invoking(x => x.BuildSubject((Type)null, 0)).ShouldThrow<ArgumentNullException>();
        }

        [TestMethod]
        public void BuildTypeShouldReturnTypeGivenTypeNameAlreadyInAppDomain()
        {
            var result = this.target.BuildType(null, typeof(string).AssemblyQualifiedName);
            result.Name.Should().BeEquivalentTo("String");
        }
    }
}


text:
I have created simple R wrapper functions for plotting the exposome globe. Now you can adjust commonly used parameters without going into the coding detail.
All materials are in the directory "R_function".

You can provide one sample or two samples (e.g., twins, couples) as the input.
<img src="https://github.com/jakemkc/exposome_variability/blob/master/R_function/chord_2_samples.png">

### Instruction
For MacOS:
1. Download the fake correlation matrix file (fakeData.Rdata), which contains two samples as used in the paper, and save it into the "Downloads" folder
2. Download the function script (chord_function.R), and save it into the "Downloads" folder
3. Download the example script, and run in Rstudio (example_1_sample.R or example_2_samples.R)
4. You can see the globe figure in Rstudio, and a pdf copy will also be saved to your "Downloads" folder
5. You can edit the pdf in any vector graphic editor (e.g., Inkscape) to fine tune different aspects of the figure

For other OSes:
- The steps are basically the same as above, but you have to modify the paths for 1) and 2) in the example script. Also, you need to run "dev.copy2pdf" instead of "quartz.save" to export the figure. I have included the saving command in the example script too.

### Go further
You can adjust the settings in the wrapper functions to see how they will affect the look of the globe. Alternatively, you can check the circlize package ebook provided by the author (https://jokergoo.github.io/circlize_book/book/)

### Citation
Please cite:
Chung, M. K., Kannan, K., Louis, G. M. & Patel, C. J. Toward capturing the exposome: exposure biomarker variability and coexposure patterns in the shared environment. Environmental Science & Technology 52, 8801–8810 (2018). http://pubs.acs.org/doi/10.1021/acs.est.8b01467

1.Gu, Z., Gu, L., Eils, R., Schlesner, M. & Brors, B. circlize Implements and enhances circular visualization in R. Bioinformatics 30, 2811–2812 (2014). https://doi.org/10.1093/bioinformatics/btu393.

------
## Authors
- Ming Kei (Jake) Chung
  - github: [\@jakemkc](http://github.com/jakemkc)
  - twitter: [\@jakekei](http://twitter.com/jakekei)
  - email: jake_chung[at]hms[dot]harvard[dot]edu
- Kurunthachalam Kannan
  - email: kurunthachalam[dot]kannan[at]health[dot]ny[dot]gov
- Germaine M. Buck Louis
  - email: louisg[at]mail[dot]nih[dot]gov
- Chirag J. Patel
  - github: [\@chiragjp](http://github.com/chiragjp)
  - web: [www.chiragjpgroup.org](http://www.chiragjpgroup.org)

## Abstract
### *BACKGROUND*
Along with time, variation in the exposome is dependent on the location and sex of study participants. One specific factor that may influence exposure co-variations is a shared household environment.

### *OBJECTIVES*
To examine the influence of shared household and partner's sex in relation to the variation in 128 endocrine disrupting chemical (EDC) exposures among couples.

### *METHODS*
In a cohort comprising 501 couples trying for pregnancy, we measured 128 (13 chemical classes) persistent and non persistent EDCs and estimated 1) sex-specific differences; 2) variance explained by shared household; and 3) Spearman's rank correlation coefficients (rs) for females, males, and couples.

## Getting Started
- This github repository analytical materials for characterzing the correlations in 501 subjects recruited in the LIFE Study.
- Code for data clean-up, processing, analysis, and visulization can be found on [GitHub](https://github.com/jakemkc/exposome_variability)
- Main findings of our study can be found [here](results/results.md)
- Preprint paper can be downloaded from [BioRxiv](https://doi.org/10.1101/175513)
- Please contact us for further information, thank you.


text:
from collections import defaultdict
from datetime import datetime
from optparse import make_option

from boto.ses import SESConnection

from django.core.management.base import BaseCommand

from django_ses.models import SESStat
from django_ses.views import stats_to_list
from django_ses import settings

def stat_factory():
    return {
        'delivery_attempts': 0,
        'bounces': 0,
        'complaints': 0,
        'rejects': 0,
    }

class Command(BaseCommand):
    """
    Get SES sending statistic and store the result, grouped by date.
    """

    def handle(self, *args, **options):

        connection = SESConnection(
            aws_access_key_id=settings.ACCESS_KEY,
            aws_secret_access_key=settings.SECRET_KEY,
        )
        stats = connection.get_send_statistics()
        data_points = stats_to_list(stats, localize=False)
        stats_dict = defaultdict(stat_factory)

        for data in data_points:
            attempts = int(data['DeliveryAttempts'])
            bounces = int(data['Bounces'])
            complaints = int(data['Complaints'])
            rejects = int(data['Rejects'])
            date = data['Timestamp'].split('T')[0]
            stats_dict[date]['delivery_attempts'] += attempts
            stats_dict[date]['bounces'] += bounces
            stats_dict[date]['complaints'] += complaints
            stats_dict[date]['rejects'] += rejects

        for k, v in stats_dict.items():
            stat, created = SESStat.objects.get_or_create(
                date=k,
                defaults={
                    'delivery_attempts': v['delivery_attempts'],
                    'bounces': v['bounces'],
                    'complaints': v['complaints'],
                    'rejects': v['rejects'],
            })

            # If statistic is not new, modify data if values are different
            if not created and stat.delivery_attempts != v['delivery_attempts']:
                stat.delivery_attempts = v['delivery_attempts']
                stat.bounces = v['bounces']
                stat.complaints = v['complaints']
                stat.rejects = v['rejects']
                stat.save()


text:
import abc

from neutron.agent import rpc as agent_rpc
from neutron import manager
from neutron_lib.agent import l2_extension
from neutron_lib.agent import topics
from neutron_lib import rpc as n_rpc
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging

from networking_sfc.services.sfc.drivers.ovs import rpc_topics as sfc_topics

LOG = logging.getLogger(__name__)

class SfcPluginApi():
    def __init__(self, topic, host):
        self.host = host
        self.target = oslo_messaging.Target(topic=topic, version='1.0')
        self.client = n_rpc.get_client(self.target)

    def update_flowrules_status(self, context, flowrules_status):
        cctxt = self.client.prepare()
        return cctxt.call(
            context, 'update_flowrules_status',
            flowrules_status=flowrules_status)

    def get_flowrules_by_host_portid(self, context, port_id):
        cctxt = self.client.prepare()
        return cctxt.call(
            context, 'get_flowrules_by_host_portid',
            host=self.host, port_id=port_id)

class SfcAgentDriver(metaclass=abc.ABCMeta):
    """Defines stable abstract interface for SFC Agent Driver."""

    @abc.abstractmethod
    def initialize(self):
        """Perform SFC agent driver initialization."""

    def consume_api(self, agent_api):
        """Consume the AgentAPI instance from the SfcAgentExtension class

        :param agent_api: An instance of an agent specific API
        """

    def update_flow_rules(self, flowrule, flowrule_status):
        """Update a flow rule in driver."""

    def delete_flow_rule(self, flowrule, flowrule_status):
        """Delete a flow rule in driver."""

class SfcAgentExtension(l2_extension.L2AgentExtension):

    def initialize(self, connection, driver_type):
        """Initialize agent extension."""
        self.sfc_driver = manager.NeutronManager.load_class_for_provider(
            'networking_sfc.sfc.agent_drivers', driver_type)()
        self.sfc_driver.consume_api(self.agent_api)
        self.sfc_driver.initialize()

        self._sfc_setup_rpc()

    def consume_api(self, agent_api):
        """Receive neutron agent API object

        Allows an extension to gain access to resources internal to the
        neutron agent and otherwise unavailable to the extension.
        """
        self.agent_api = agent_api

    def handle_port(self, context, port):
        """Handle agent SFC extension port add/update."""
        port_id = port['port_id']
        resync = False
        flowrule_status = []
        try:
            LOG.debug("a new device %s is found", port_id)
            flows_list = (
                self.sfc_plugin_rpc.get_flowrules_by_host_portid(
                    context, port_id
                )
            )
            if flows_list:
                for flow in flows_list:
                    self.sfc_driver.update_flow_rules(
                        flow, flowrule_status)
        except Exception as e:
            LOG.exception(e)
            LOG.error("SFC L2 extension handle_port failed")
            resync = True

        if flowrule_status:
            self.sfc_plugin_rpc.update_flowrules_status(
                context, flowrule_status)

        return resync

    def delete_port(self, context, port):
        """Handle agent SFC extension port delete."""
        port_id = port['port_id']
        resync = False
        LOG.info("a device %s is removed", port_id)
        try:
            self._delete_ports_flowrules_by_id(context, port_id)
        except Exception as e:
            LOG.exception(e)
            LOG.error(
                "delete port flow rule failed for %(port_id)s",
                {'port_id': port_id}
            )
            resync = True

        return resync

    def update_flow_rules(self, context, **kwargs):
        flowrule_status = []
        try:
            flowrules = kwargs['flowrule_entries']
            LOG.debug("update_flow_rules received,  flowrules = %s",
                      flowrules)

            if flowrules:
                self.sfc_driver.update_flow_rules(
                    flowrules, flowrule_status)
        except Exception as e:
            LOG.exception(e)
            LOG.error("update_flow_rules failed")

        if flowrule_status:
            self.sfc_plugin_rpc.update_flowrules_status(
                context, flowrule_status)

    def delete_flow_rules(self, context, **kwargs):
        flowrule_status = []
        try:
            flowrules = kwargs['flowrule_entries']
            LOG.debug("delete_flow_rules received,  flowrules= %s", flowrules)
            if flowrules:
                self.sfc_driver.delete_flow_rule(
                    flowrules, flowrule_status)
        except Exception as e:
            LOG.exception(e)
            LOG.error("delete_flow_rules failed")

        if flowrule_status:
            self.sfc_plugin_rpc.update_flowrules_status(
                context, flowrule_status)

    def _sfc_setup_rpc(self):
        self.sfc_plugin_rpc = SfcPluginApi(
            sfc_topics.SFC_PLUGIN, cfg.CONF.host)

        self.topic = sfc_topics.SFC_AGENT
        self.endpoints = [self]
        consumers = [
            [sfc_topics.PORTFLOW, topics.UPDATE],
            [sfc_topics.PORTFLOW, topics.DELETE]
        ]

        # subscribe sfc plugin message
        self.connection = agent_rpc.create_consumers(
            self.endpoints,
            self.topic,
            consumers)

    def _delete_ports_flowrules_by_id(self, context, ports_id):
        flowrule_status = []
        try:
            LOG.debug("delete_port_id_flows received, ports_id= %s", ports_id)
            count = 0
            if ports_id:
                for port_id in ports_id:
                    flowrule = (
                        self.sfc_plugin_rpc.get_flowrules_by_host_portid(
                            context, port_id
                        )
                    )
                    if flowrule:
                        self.sfc.driver.delete_flow_rule(
                            flowrule, flowrule_status)
            LOG.debug(
                "_delete_ports_flowrules_by_id received, count= %s", count)
        except Exception as e:
            LOG.exception(e)
            LOG.error("delete_port_id_flows failed")
        if flowrule_status:
            self.sfc_plugin_rpc.update_flowrules_status(
                context, flowrule_status)


text:
global.Symbol = () => ({})
const dd = require('../dotdom');

describe('.dom', function () {

  describe('#H', function () {

    describe('Factory', function () {

      it('should create vnode without arguments', function () {
        const vdom = dd.H('div');

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({c: []});
      });

      it('should create vnode with props', function () {
        const vdom = dd.H('div', {foo: 'bar'});

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({foo: 'bar', c: []});
      });

      it('should create vnode with props and children', function () {
        const cdom = dd.H('div');
        const vdom = dd.H('div', {foo: 'bar'}, cdom);

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          foo: 'bar',
          c: [ cdom ]
        });
      });

      it('should create vnode with props and children as array', function () {
        const cdom1 = dd.H('div');
        const cdom2 = dd.H('div');
        const cdom3 = dd.H('div');
        const vdom = dd.H('div', {foo: 'bar'}, cdom1, [cdom2, cdom3]);

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          foo: 'bar',
          c: [ cdom1, cdom2, cdom3 ]
        });
      });

      it('should create vnode with props and mixed children', function () {
        const cdom = dd.H('div');
        const vdom = dd.H('div', {foo: 'bar'}, 'foo', cdom);

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          foo: 'bar',
          c: [ 'foo', cdom ]
        });
      });

      it('should create vnode with props and string children', function () {
        const vdom = dd.H('div', {foo: 'bar'}, 'foo');

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          foo: 'bar',
          c: [ 'foo' ]
        });
      });

      it('should create vnode with only child', function () {
        const vdom = dd.H('div', 'foo');

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          c: [ 'foo' ]
        });
      });

      it('should create vnode with children', function () {
        const vdom = dd.H('div', 'foo', 'bar', 'baz');

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          c: [ 'foo', 'bar', 'baz' ]
        });
      });

      it('should create vnode with children in arrays', function () {
        const vdom = dd.H('div', 'foo', ['bar', 'baz']);

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          c: [ 'foo', 'bar', 'baz' ]
        });
      });

      it('should create vnode with mixed children', function () {
        const cdom = dd.H('div');
        const vdom = dd.H('div', cdom, 'foo');

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          c: [ cdom, 'foo' ]
        });
      });

      it('should accept `null` as an empty properties object', function () {
        const vdom = dd.H('div', null, 'foo');

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          c: [ 'foo' ]
        });
      });

    });

    describe('Proxy', function () {

      it('H.apply should be proxied', function () {
        const cdom = dd.H('div');
        const vdom = dd.H.apply({}, ['div', cdom, 'foo']);

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          c: [ cdom, 'foo' ]
        });
      });

      it('H.call should be proxied', function () {
        const cdom = dd.H('div');
        const vdom = dd.H.call({}, 'div', cdom, 'foo');

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          c: [ cdom, 'foo' ]
        });
      });

      it('H.<tag> should be a shorthand', function () {
        const cdom = dd.H('div');
        const vdom = dd.H.div(cdom, 'foo');

        expect(vdom.$).toEqual('div');
        expect(vdom.a).toEqual({
          c: [ cdom, 'foo' ]
        });
      });

    });

  });

  describe('#R', function () {
    describe('DOM Manipulation', function () {

      it('should render simple DOM', function () {
        const dom = document.createElement('div');
        const vdom = dd.H('div');

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      });

      it('should render 1-level nested DOM', function () {
        const dom = document.createElement('div');
        const vdom = dd.H('div', dd.H('a'), dd.H('b'));

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      });

      it('should render 2-level nested DOM', function () {
        const dom = document.createElement('div');
        const vdom = dd.H('div',
          dd.H('a', dd.H('ul')),
          dd.H('b', dd.H('ol'))
        );

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      });

      it('should render text children', function () {
        const dom = document.createElement('div');
        const vdom = dd.H('div', 'foo');

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '
foo
'
        );
      });

      it('should render combined dom and text nodes', function () {
        const dom = document.createElement('div');
        const vdom = dd.H('div', dd.H('a'), 'foo', dd.H('b'));

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '
foo
'
        );
      });

      it('should apply style properties', function () {
        const dom = document.createElement('div');
        const vdom = dd.H('div', {style: {color: 'red'}});

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      });

      it('should apply element attributes', function () {
        const dom = document.createElement('div');
        const vdom = dd.H('a', {href: '/'});

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          ''
        );
      });

      it('should apply event handlers', function () {
        const dom = document.createElement('div');
        const callback = jest.fn();
        const vdom = dd.H('a', {href: '/', onclick:callback});

        dd.R(vdom, dom);

        expect(dom.innerHTML).toEqual(
          ''
        );

        const event = new window.MouseEvent('click');
        dom.firstChild.dispatchEvent(event);

        expect(callback).toBeCalled();
      });

      it('should accept props and children', function () {
        const dom = document.createElement('div');
        const vdom = dd.H('a', {href: '/'}, 'test');

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          'test'
        );
      });

    });

    describe('Lifecycle Methods', function () {

      it('should correctly call .m when mounted', function () {
        const dom = document.createElement('div');
        const updateHandler = jest.fn();
        const SampleComponent = (props, state, setState, hooks) => {
          hooks.m.push(updateHandler);
          return dd.H(props.tag);
        };

        const vdom1 = dd.H(SampleComponent, {tag: 'div'});
        dd.R(vdom1, dom)

        const dom1 = dom.firstChild;

        expect(updateHandler.mock.calls.length).toEqual(1)
        expect(updateHandler.mock.calls).toEqual([
          [dom1, undefined]
        ])
      });

      it('should correctly call .d when DOM element tag changed', function () {
        const dom = document.createElement('div');
        const updateHandler = jest.fn();
        const SampleComponent = (props, state, setState, hooks) => {
          hooks.d.push(updateHandler);
          return dd.H(props.tag);
        };

        const vdom1 = dd.H(SampleComponent, {tag: 'div'});
        dd.R(vdom1, dom)

        const dom1 = dom.firstChild;

        const vdom2 = dd.H(SampleComponent, {tag: 'span'});
        dd.R(vdom2, dom)

        const dom2 = dom.firstChild;

        expect(updateHandler.mock.calls.length).toEqual(1)
        expect(updateHandler.mock.calls).toEqual([
          [dom2, dom1]
        ])
      });

      it('should correctly call .d when props change', function () {
        const dom = document.createElement('div');
        const updateHandler = jest.fn();
        const SampleComponent = (props, state, setState, hooks) => {
          hooks.d.push(updateHandler);
          return dd.H('div', {className: props.className});
        };

        const vdom1 = dd.H(SampleComponent, {className: 'foo'});
        dd.R(vdom1, dom)

        const dom1 = dom.firstChild;

        const vdom2 = dd.H(SampleComponent, {className: 'bar'});
        dd.R(vdom2, dom)

        const dom2 = dom.firstChild;

        expect(updateHandler.mock.calls.length).toEqual(1)
        expect(updateHandler.mock.calls).toEqual([
          [dom1, dom1]
        ])
      });

      it('should correctly call .u when replaced with plain tag', function () {
        const dom = document.createElement('div');
        const updateHandler = jest.fn();
        const SampleComponent = (props, state, setState, hooks) => {
          hooks.u.push(updateHandler); //updateHandler
          return dd.H(props.tag);
        };

        const vdom1 = dd.H(SampleComponent, {tag: 'div'});
        dd.R(vdom1, dom)

        const dom1 = dom.firstChild;

        const vdom2 = dd.H('span');
        dd.R(vdom2, dom)

        expect(updateHandler.mock.calls.length).toEqual(1)
        expect(updateHandler.mock.calls).toEqual([
          [undefined,undefined]
        ])
      });

      it('should correctly call .u when replaced with component', function () {
        const dom = document.createElement('div');
        const updateHandler = jest.fn();
        const ComponentA = (props, state, setState, hooks) => {
          hooks.u.push(updateHandler);
          return dd.H(props.tag);
        };
        const ComponentB = (props, state, setState, hooks) => {
          return dd.H(props.tag);
        };

        const vdom1 = dd.H(ComponentA, {tag: 'div'});
        dd.R(vdom1, dom)

        const dom1 = dom.firstChild;

        const vdom2 = dd.H(ComponentB, {tag: 'div'});
        dd.R(vdom2, dom)

        expect(updateHandler.mock.calls.length).toEqual(1)
        expect(updateHandler.mock.calls).toEqual([
          [undefined,undefined]
        ])
      });

      it('should correctly call .m on the component replaced with', function () {
        const dom = document.createElement('div');
        const mountHandler = jest.fn();
        const ComponentA = (props, state, setState, hooks) => {
          return dd.H(props.tag);
        };
        const ComponentB = (props, state, setState, hooks) => {
          hooks.m.push(mountHandler);
          return dd.H(props.tag);
        };

        const vdom1 = dd.H(ComponentA, {tag: 'div'});
        dd.R(vdom1, dom)

        const dom1 = dom.firstChild;

        const vdom2 = dd.H(ComponentB, {tag: 'div'});
        dd.R(vdom2, dom)

        const dom2 = dom.firstChild;

        expect(vdom1).not.toBe(vdom2);
        expect(mountHandler.mock.calls.length).toEqual(1)
        expect(mountHandler.mock.calls).toEqual([
          [dom2, dom1]
        ])
      });

      it('should correctly call .u when removed', function () {
        const dom = document.createElement('div');
        const updateHandler = jest.fn();
        const SampleComponent = (props, state, setState, hooks) => {
          hooks.u.push(updateHandler);
          return dd.H(props.tag);
        };

        const vdom1 = dd.H(SampleComponent, {tag: 'div'});
        dd.R(vdom1, dom)

        const dom1 = dom.firstChild;

        dd.R([], dom)

        expect(updateHandler.mock.calls.length).toEqual(1)
        expect(updateHandler.mock.calls).toEqual([
          [undefined,undefined]
        ])
      });

      it('should correctly call .u when removed as a deep child', function () {
        const dom = document.createElement('div');
        const updateHandler = jest.fn();
        const SampleComponent = (props, state, setState, hooks) => {
          hooks.u.push(updateHandler);
          return dd.H(props.tag);
        };

        const vdom1 = dd.H('div',
          dd.H('div',
            dd.H(SampleComponent, {tag: 'div'})
          )
        );
        dd.R(vdom1, dom)

        const dom1 = dom.firstChild;

        dd.R([], dom)

        expect(updateHandler.mock.calls.length).toEqual(1)
        expect(updateHandler.mock.calls).toEqual([
          [undefined,undefined]
        ])
      });

      it('should correctly call .u when removed as a deep child because of root replacement', function () {
        const dom = document.createElement('div');
        const updateHandler = jest.fn();
        const SampleComponent = (props, state, setState, hooks) => {
          hooks.u.push(updateHandler);
          return dd.H(props.tag);
        };
        const ComponentA = (props, state, setState, hooks) => {
          return dd.H('div', props.c);
        };
        const ComponentB = (props, state, setState, hooks) => {
          return dd.H('div', props.c);
        };

        const vdom1 = dd.H('div',
          dd.H(ComponentA,
            dd.H(SampleComponent, {tag: 'div'})
          )
        );
        dd.R(vdom1, dom)

        const dom1 = dom.firstChild;

        const vdom2 = dd.H('div',
          dd.H(ComponentB)
        );

        dd.R([], dom)

        expect(updateHandler.mock.calls.length).toEqual(1)
        expect(updateHandler.mock.calls).toEqual([
          [undefined,undefined]
        ])
      });

      it('should correctly call .m, .d, .u in a mount, update, unmount cycle', function () {
        const dom = document.createElement('div');
        const mHandler = jest.fn();
        const dHandler = jest.fn();
        const uHandler = jest.fn();

        const SampleComponent = (props, state, setState, hooks) => {
          hooks.m.push(mHandler);
          hooks.d.push(dHandler);
          hooks.u.push(uHandler);
          return dd.H('div', {className: props.className});
        };

        const vdom1 = dd.H(SampleComponent, {className: 'foo'});
        dd.R(vdom1, dom)

        expect(mHandler.mock.calls.length).toEqual(1)
        expect(dHandler.mock.calls.length).toEqual(0)
        expect(uHandler.mock.calls.length).toEqual(0)

        const dom1 = dom.firstChild;

        const vdom2 = dd.H(SampleComponent, {className: 'bar'});
        dd.R(vdom2, dom)

        expect(mHandler.mock.calls.length).toEqual(1)
        expect(dHandler.mock.calls.length).toEqual(1)
        expect(uHandler.mock.calls.length).toEqual(0)

        const dom2 = dom.firstChild;

        dd.R([], dom)

        expect(mHandler.mock.calls.length).toEqual(1)
        expect(dHandler.mock.calls.length).toEqual(1)
        expect(uHandler.mock.calls.length).toEqual(1)

      });

      it('should correctly call `.u.` after setState', function () {
        const dom = document.createElement('div');
        const dHandler = jest.fn();
        const guardCounter = { c:0 };

        const SampleComponent = (props, state, setState, hooks) => {
          if (guardCounter.c++ > 10) throw new Error("Max call exceeded");

          hooks.d.push(dHandler);
          hooks.d.push(() => {
            if (state.value == 1) {
              setState({ value: 2 });
            }
          });
          hooks.m.push(() => {
            setState({ value: 1 })
          });

          return dd.H('div', {className: state.value});
        };

        const vdom1 = dd.H(SampleComponent);
        dd.R(vdom1, dom)

        expect(dHandler.mock.calls.length).toEqual(2)
        expect(dom.innerHTML).toEqual(
          '

'
        );

      });

      it('should not cause infinite loop when using setState in `.m`', function () {
        const dom = document.createElement('div');
        const guardCounter = { c:0 };

        const SampleComponent = (props, state, setState, hooks) => {
          if (guardCounter.c++ > 10) throw new Error("Max call exceeded");

          hooks.m.push(() => {
            setState({ value: 1 })
          });
          return dd.H('div', {className: state.value});
        };

        const vdom1 = dd.H(SampleComponent);
        dd.R(vdom1, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      });

    });

    describe('Reconciliation', function () {
      it('should not replace DOM if tag & props are the same', function () {
        const dom = document.createElement('div');
        const vdom1 = dd.H('div');
        const vdom2 = dd.H('div');

        dd.R(vdom1, dom)
        const c1 = dom.firstChild;

        dd.R(vdom2, dom)
        const c2 = dom.firstChild;

        expect(c1).toBe(c2);
      });

      it('should replace DOM if tag has changed', function () {
        const dom = document.createElement('div');
        const vdom1 = dd.H('div');
        const vdom2 = dd.H('span');

        dd.R(vdom1, dom)
        const c1 = dom.firstChild;

        dd.R(vdom2, dom)
        const c2 = dom.firstChild;

        expect(c1).not.toBe(c2);
      });

      it('should not replace DOM if props have changed', function () {
        const dom = document.createElement('div');
        const vdom1 = dd.H('div', {foo: 1});
        const vdom2 = dd.H('div', {foo: 2});

        dd.R(vdom1, dom)
        const c1 = dom.firstChild;

        dd.R(vdom2, dom)
        const c2 = dom.firstChild;

        expect(c1).toBe(c2);
      });

      it('should not replace DOM if only children have changed', function () {
        const dom = document.createElement('div');
        const vdom1 = dd.H('div', dd.H('span', 'foo'));
        const vdom2 = dd.H('div', dd.H('span', 'bar'));

        dd.R(vdom1, dom)
        const c1 = dom.firstChild;

        dd.R(vdom2, dom)
        const c2 = dom.firstChild;

        expect(c1).toBe(c2);
      });

      it('should add new DOM elements keeping the old ones intact', function () {
        const dom = document.createElement('div');
        const vdom1 = [dd.H('div')];
        const vdom2 = [dd.H('div'), dd.H('span')];

        dd.R(vdom1, dom)
        const c1 = dom.firstChild;
        expect(dom.children.length).toEqual(1);

        dd.R(vdom2, dom)
        const c2 = dom.firstChild;
        expect(dom.children.length).toEqual(2);

        expect(c1).toBe(c2);
      });

      it('should remove excess DOM elements', function () {
        const dom = document.createElement('div');
        const vdom1 = [dd.H('div'), dd.H('span')];
        const vdom2 = [dd.H('div')];

        dd.R(vdom1, dom)
        expect(dom.children.length).toEqual(2);

        dd.R(vdom2, dom)
        expect(dom.children.length).toEqual(1);
      });

      it('should not try to re-assign attributes with same value', function () {
        let state = {};
        const p1Handler = jest.fn((value) => state.p1 = value);
        const p2Handler = jest.fn((value) => state.p2 = value);
        const dom = document.createElement('div');
        const vdom0 = [dd.H('div')];
        const vdom1 = [dd.H('div', {p1: 'foo'})];
        const vdom2 = [dd.H('div', {p1: 'foo', p2: 'bar'})];

        dd.R(vdom0, dom)
        expect(dom.children.length).toEqual(1);
        Object.defineProperty(dom.children[0], 'p1', {
          set: p1Handler,
          get: () => state.p1
        })
        Object.defineProperty(dom.children[0], 'p2', {
          set: p2Handler,
          get: () => state.p2
        })

        dd.R(vdom1, dom)
        dd.R(vdom2, dom)
        expect(dom.children.length).toEqual(1);
        expect(p1Handler.mock.calls).toEqual([
          ['foo']
        ])
        expect(p2Handler.mock.calls).toEqual([
          ['bar']
        ])
      });

      it('should only assign style properties recursively', function () {
        let state = {};
        const p1Handler = jest.fn((value) => state.p1 = value);
        const p2Handler = jest.fn((value) => state.p2 = value);
        const dom = document.createElement('div');
        const vdom0 = [dd.H('div')];
        const vdom1 = [dd.H('div', {style: {p1: 'foo'}})];
        const vdom2 = [dd.H('div', {style: {p1: 'foo', p2: 'bar'}})];

        dd.R(vdom0, dom)
        expect(dom.children.length).toEqual(1);
        Object.defineProperty(dom.children[0].style, 'p1', {
          set: p1Handler,
          get: () => state.p1
        })
        Object.defineProperty(dom.children[0].style, 'p2', {
          set: p2Handler,
          get: () => state.p2
        })

        dd.R(vdom1, dom)
        dd.R(vdom2, dom)
        expect(dom.children.length).toEqual(1);
        expect(p1Handler.mock.calls).toEqual([
          ['foo'],
          ['foo']
        ])
        expect(p2Handler.mock.calls).toEqual([
          ['bar']
        ])
      });

      it('should discard state if parent DOM element changes', function () {
        const dom = document.createElement('div');
        const ChildComponent = function(props, {clicks=0}, setState) {
          return dd.H('button', {
            onclick() {
              setState({
                clicks: clicks + 1
              })
            }
          }, `${clicks} clicks`)
        }
        const Toggler = function(props, {first=true}, setState) {
          return dd.H('div',
            dd.H('button', {
              onclick() {
                setState({first: !first})
              }
            }, 'toggle'),
            first
              ? dd.H('div', dd.H(ChildComponent))
              : dd.H('span', dd.H(ChildComponent))
          )
        }

        const vdom = dd.H(Toggler);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '
<button>toggle</button>
<button>0 clicks</button>

'
        );

        const event = new window.MouseEvent('click');
        dom.firstChild.childNodes[1].childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>toggle</button>
<button>1 clicks</button>

'
        );

        dom.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>toggle</button><button>0 clicks</button>
'
        );

        dom.firstChild.childNodes[1].childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>toggle</button><button>1 clicks</button>
'
        );

      });

      it('should not re-render contents of raw elements', function () {
        const dom = document.createElement('div');
        const RawComponent = function(props, state, setState, hooks) {
          hooks.r = 1;
          return dd.H('div', {
            innerHTML: 'inner'
          })
        }

        const vdom = dd.H(RawComponent);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '
inner
'
        );

        const refA = dom.firstChild.firstChild;

        dd.R(vdom, dom)
        expect(dom.innerHTML).toEqual(
          '
inner
'
        );

        const refB = dom.firstChild.firstChild;

        expect(refA).toBe(refB);

      });

      it('should not re-render contents of raw elements, if parent is updated', function () {
        const dom = document.createElement('div');
        const RawComponent = function(props, state, setState, hooks) {
          hooks.r = 1;
          return dd.H('div', {
            innerHTML: 'inner'
          })
        }
        const DynamicParent = function(props, {clicks=0}, setState) {
          return dd.H('button', {
            onclick() {
              setState({
                clicks: clicks + 1
              })
            }
          }, dd.H('span', `${clicks} clicks`), dd.H(RawComponent))
        }

        const vdom = dd.H(DynamicParent);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '<button>0 clicks
inner
</button>'
        );

        const refA = dom.firstChild.firstChild.nextSibling.firstChild;

        dd.R(vdom, dom)
        expect(dom.innerHTML).toEqual(
          '<button>0 clicks
inner
</button>'
        );

        const refB = dom.firstChild.firstChild.nextSibling.firstChild;

        const event = new window.MouseEvent('click');
        dom.firstChild.dispatchEvent(event);

        expect(dom.innerHTML).toEqual(
          '<button>1 clicks
inner
</button>'
        );

        const refC = dom.firstChild.firstChild.nextSibling.firstChild;

        expect(refA).toBe(refB);
        expect(refA).toBe(refC);

      });

    });

    describe('Components', function () {
      it('should render simple component', function () {
        const dom = document.createElement('div');
        const Component = function() {
          return dd.H('div')
        }
        const vdom = dd.H(Component);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      });

      it('should render nested components', function () {
        const dom = document.createElement('div');
        const Component = function() {
          return dd.H('div')
        }
        const HostComponent = function() {
          return dd.H('div',
            dd.H(Component),
            dd.H(Component)
          )
        }
        const vdom = dd.H(HostComponent);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      });

      it('should render direct components', function () {
        const dom = document.createElement('div');
        const Component = function() {
          return dd.H('div')
        }
        const HostComponent = function() {
          return dd.H(Component);
        }
        const vdom = dd.H(HostComponent);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      });

      it('should pass children to components', function () {
        const dom = document.createElement('div');
        const Component = function(props) {
          return dd.H('div', props.c)
        }
        const HostComponent = function() {
          return dd.H(
            Component,
            dd.H('div', 'foo'),
            dd.H('div', 'bar')
          );
        }
        const vdom = dd.H(HostComponent);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

foo

bar

'
        );
      });

      it('should render component with props', function () {
        const dom = document.createElement('div');
        const Component = function(props) {
          return dd.H('a', {href: props.href})
        }
        const vdom = dd.H(Component, {href: '/'});

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          ''
        );
      });

      it('should render stateful components', function () {
        const dom = document.createElement('div');
        const Component = function(props, {href='/'}) {
          return dd.H('a', {
            href: href
          })
        }
        const vdom = dd.H(Component, {href: '/'});

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          ''
        );
      });

      it('should update stateful components', function () {
        const dom = document.createElement('div');
        const Component = function(props, {clicks=0}, setState) {
          return dd.H('button', {
            onclick() {
              setState({
                clicks: clicks + 1
              })
            }
          }, `${clicks} clicks`)
        }
        const vdom = dd.H(Component);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '<button>0 clicks</button>'
        );

        const event = new window.MouseEvent('click');

        dom.firstChild.dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>1 clicks</button>'
        );

        dom.firstChild.dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>2 clicks</button>'
        );
      });

      it('should update stateful components, merging partial state', function () {
        const dom = document.createElement('div');
        const Component = function(props, {a='0', b='0'}, setState) {
          return dd.H('button', {
            onkeydown() { setState({ a: '1' }) },
            onkeyup()   { setState({ b: '1' }) }
          }, `${a}${b}`)
        }
        const vdom = dd.H(Component);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '<button>00</button>'
        );

        const eKeydown = new window.MouseEvent('keydown');
        const eKeyup = new window.MouseEvent('keyup');

        dom.firstChild.dispatchEvent(eKeydown);
        expect(dom.innerHTML).toEqual(
          '<button>10</button>'
        );

        dom.firstChild.dispatchEvent(eKeyup);
        expect(dom.innerHTML).toEqual(
          '<button>11</button>'
        );
      });

      it('should maintain state of child components', function () {
        const dom = document.createElement('div');
        const Component = function(props, {clicks=0}, setState) {
          return dd.H('button', {
            onclick() {
              setState({
                clicks: clicks + 1
              })
            }
          }, `${clicks} clicks`)
        }
        const HostComponent = function(props, {clicks=0}, setState) {
          return dd.H('button',
            {
              onclick() {
                setState({
                  clicks: clicks + 1
                })
              }
            },
            dd.H('div', `${clicks} clicks`),
            dd.H(Component),
            dd.H(Component)
          )
        }
        const vdom = dd.H(HostComponent);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '<button>
0 clicks
<button>0 clicks</button><button>0 clicks</button></button>'
        );

        const event = new window.MouseEvent('click');

        dom.firstChild.dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
1 clicks
<button>0 clicks</button><button>0 clicks</button></button>'
        );

        dom.firstChild.childNodes[1].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
1 clicks
<button>1 clicks</button><button>0 clicks</button></button>'
        );

        dom.firstChild.childNodes[1].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
1 clicks
<button>2 clicks</button><button>0 clicks</button></button>'
        );

        dom.firstChild.childNodes[2].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
1 clicks
<button>2 clicks</button><button>1 clicks</button></button>'
        );

        dom.firstChild.childNodes[2].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
1 clicks
<button>2 clicks</button><button>2 clicks</button></button>'
        );

        dom.firstChild.dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
2 clicks
<button>2 clicks</button><button>2 clicks</button></button>'
        );
      });

      it('should discard child state when it\'s type changes', function () {
        const dom = document.createElement('div');
        const ComponentA = function(props, {clicks=0}, setState) {
          return dd.H('button', {
            title: 'a',
            onclick() {
              setState({
                clicks: clicks + 1
              })
            }
          }, `${clicks} clicks`)
        }
        const ComponentB = function(props, {clicks=0}, setState) {
          return dd.H('button', {
            title: 'b',
            onclick() {
              setState({
                clicks: clicks + 1
              })
            }
          }, `${clicks} clicks`)
        }
        const HostComponent = function(props, {clicks=0}, setState) {
          const children = [];
          if (clicks % 2) {
            children.push(dd.H(ComponentA));
            children.push(dd.H(ComponentB));
          } else {
            children.push(dd.H(ComponentB));
            children.push(dd.H(ComponentA));
          }

          return dd.H('button',
            {
              onclick() {
                setState({
                  clicks: clicks + 1
                })
              }
            },
            dd.H('div', `${clicks} clicks`),
            children[0],
            children[1]
          )
        }
        const vdom = dd.H(HostComponent);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '<button>
0 clicks
<button title="b">0 clicks</button><button title="a">0 clicks</button></button>'
        );

        const event = new window.MouseEvent('click');

        dom.firstChild.dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
1 clicks
<button title="a">0 clicks</button><button title="b">0 clicks</button></button>'
        );

        dom.firstChild.childNodes[1].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
1 clicks
<button title="a">1 clicks</button><button title="b">0 clicks</button></button>'
        );

        dom.firstChild.childNodes[2].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
1 clicks
<button title="a">1 clicks</button><button title="b">1 clicks</button></button>'
        );

        dom.firstChild.dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
2 clicks
<button title="b">0 clicks</button><button title="a">0 clicks</button></button>'
        );

        dom.firstChild.childNodes[1].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
2 clicks
<button title="b">1 clicks</button><button title="a">0 clicks</button></button>'
        );

        dom.firstChild.childNodes[2].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
2 clicks
<button title="b">1 clicks</button><button title="a">1 clicks</button></button>'
        );

        dom.firstChild.dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '<button>
3 clicks
<button title="a">0 clicks</button><button title="b">0 clicks</button></button>'
        );
      });

      it('should reset state of child components when parent is changed', function () {
        const dom = document.createElement('div');
        const ChildComponent = function(props, {clicks=0}, setState) {
          return dd.H('button', {
            onclick() {
              setState({
                clicks: clicks + 1
              })
            }
          }, `${clicks} clicks`)
        }
        const ComponentA = function(props, state, setState) {
          return dd.H('div', {title: 'a'},
            dd.H(ChildComponent)
          )
        }
        const ComponentB = function(props, state, setState) {
          return dd.H('div', {title: 'b'},
            dd.H(ChildComponent)
          )
        }
        const Toggler = function(props, {first=true}, setState) {
          return dd.H('div',
            dd.H('button', {
              onclick() {
                setState({first: !first})
              }
            }, 'toggle'),
            first
              ? dd.H(ComponentA)
              : dd.H(ComponentB)
          )
        }

        const vdom = dd.H(Toggler);

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '
<button>toggle</button>
<button>0 clicks</button>

'
        );

        const event = new window.MouseEvent('click');
        dom.firstChild.childNodes[1].childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>toggle</button>
<button>1 clicks</button>

'
        );

        dom.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>toggle</button>
<button>0 clicks</button>

'
        );

        dom.firstChild.childNodes[1].childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>toggle</button>
<button>1 clicks</button>

'
        );

      });

      it('should correctly update independent instances of same component', function () {
        const dom = document.createElement('div');
        const Component = function(props, {clicks=0}, setState) {
          return dd.H('button', {
            onclick() {
              setState({
                clicks: clicks + 1
              })
            }
          }, `${clicks} clicks`)
        }
        const vdom = dd.H('div',
          dd.H(Component),
          dd.H(Component)
        );

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '
<button>0 clicks</button><button>0 clicks</button>
'
        );

        const event = new window.MouseEvent('click');

        dom.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>1 clicks</button><button>0 clicks</button>
'
        );

        dom.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>2 clicks</button><button>0 clicks</button>
'
        );

        dom.firstChild.childNodes[1].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>2 clicks</button><button>1 clicks</button>
'
        );

        dom.firstChild.childNodes[1].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>2 clicks</button><button>2 clicks</button>
'
        );

        dom.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>3 clicks</button><button>2 clicks</button>
'
        );
      });

      it('should correctly update independent children and parent component', function () {
        const dom = document.createElement('div');
        const ChildA = function(props, {clicks=0}, setState) {
          return dd.H('button',
            {
              title: 'a',
              onclick() {
                setState({clicks: clicks+1})
              }
            },
            `${clicks} clicks`
          )
        }
        const ChildB = function(props, {clicks=0}, setState) {
          return dd.H('button',
            {
              title: 'b',
              onclick() {
                setState({clicks: clicks+1})
              }
            },
            `${clicks} clicks`
          )
        }
        const Root = function(props, {clicks=0}, setState) {
          return dd.H('div',
            dd.H('button', {
              onclick() {
                setState({clicks: clicks+1})
              }
            }, `${clicks} clicks`),
            dd.H('div',
              dd.H(ChildA),
              dd.H(ChildB)
            )
          )
        }

        const vdom = dd.H(Root);
        const event = new window.MouseEvent('click');

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '
<button>0 clicks</button>
<button title="a">0 clicks</button><button title="b">0 clicks</button>

'
        );

        dom.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>1 clicks</button>
<button title="a">0 clicks</button><button title="b">0 clicks</button>

'
        );

        dom.firstChild.childNodes[1].childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>1 clicks</button>
<button title="a">1 clicks</button><button title="b">0 clicks</button>

'
        );

        dom.firstChild.childNodes[1].childNodes[1].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>1 clicks</button>
<button title="a">1 clicks</button><button title="b">1 clicks</button>

'
        );

        dom.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>2 clicks</button>
<button title="a">1 clicks</button><button title="b">1 clicks</button>

'
        );

        dom.firstChild.childNodes[1].childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>2 clicks</button>
<button title="a">2 clicks</button><button title="b">1 clicks</button>

'
        );

        dom.firstChild.childNodes[1].childNodes[1].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>2 clicks</button>
<button title="a">2 clicks</button><button title="b">2 clicks</button>

'
        );

      });

      it('should preserve state when re-ordering the same component', function () {
        const dom = document.createElement('div');
        const Child = function(props, {clicks=0}, setState) {
          return dd.H('button',
            {
              onclick() {
                setState({clicks: clicks+1})
              }
            },
            `${clicks} clicks`
          )
        }
        const Root = function(props, {swap}, setState) {
          const { components } = props;

          return dd.H('div',
            {
              onclick() { setState({swap: !swap}) }
            },
            swap
              ? components.map((_, i) => components[components.length - i - 1])
              : components
          )
        }

        // Create the instances
        const components = [ dd.H(Child), dd.H(Child), dd.H(Child)];
        const vdom = dd.H(Root, { components });
        const event = new window.MouseEvent('click');

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '
<button>0 clicks</button><button>0 clicks</button><button>0 clicks</button>
'
        );

        dom.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>1 clicks</button><button>0 clicks</button><button>0 clicks</button>
'
        );

        dom.firstChild.childNodes[2].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>1 clicks</button><button>0 clicks</button><button>1 clicks</button>
'
        );

        dom.firstChild.childNodes[2].dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>1 clicks</button><button>0 clicks</button><button>2 clicks</button>
'
        );

        dom.firstChild.dispatchEvent(event);
        expect(dom.innerHTML).toEqual(
          '
<button>2 clicks</button><button>0 clicks</button><button>1 clicks</button>
'
        );

      });

      it('should be able to manipulate ordered list of stateful items', function () {
        const dom = document.createElement('div');
        const StatefulChild = function({id=''}, state, setState) {
          let {clicks=0} = state;
          return dd.H('button',
            {
              onclick() {
                setState({clicks: clicks+1})
              }
            },
            `id=${id}, clicks=${clicks}`
          )
        }
        const StatefulList = function(props, {items=[], ofs=0}, setState) {
          const share = {};
          Object.assign(share,{ofs});

          return dd.H('div',
            dd.H('div',
              dd.H('button', { onclick: () => {
                e = dd.H(StatefulChild, {id: items.length});
                e.s = {};
                items.unshift(e);
                setState({items});
              }}, 'Add Head'),
              dd.H('button', { onclick: () => {
                items.push(dd.H(StatefulChild, {id: items.length}));
                setState({items});
              }}, 'Add Tail'),
              dd.H('button', { onclick: () => {
                items.shift();
                setState({items});
              }}, 'Rm Head'),
              dd.H('button', { onclick: () => {
                items.pop();
                setState({items});
              }}, 'Rm Tail')
            ),
            dd.H('div', items),
          )
        }

        const vdom = dd.H(StatefulList);
        const event = new window.MouseEvent('click');

        dd.R(vdom, dom)

        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '

'
        );

        //
        // Condition some items
        //
        dom.firstChild.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '
<button>id=0, clicks=0</button>
'
        );

        dom.firstChild.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '
<button>id=1, clicks=0</button><button>id=0, clicks=0</button>
'
        );

        dom.firstChild.firstChild.nextSibling.childNodes[0].dispatchEvent(event);
        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '
<button>id=1, clicks=1</button><button>id=0, clicks=0</button>
'
        );

        dom.firstChild.firstChild.nextSibling.childNodes[1].dispatchEvent(event);
        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '
<button>id=1, clicks=1</button><button>id=0, clicks=1</button>
'
        );

        dom.firstChild.firstChild.nextSibling.childNodes[1].dispatchEvent(event);
        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '
<button>id=1, clicks=1</button><button>id=0, clicks=2</button>
'
        );

        //    DO : Add an item on top of the list
        // EXPECT: State of the child items correctly shifted to the right
        //
        dom.firstChild.firstChild.childNodes[0].dispatchEvent(event);
        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '
<button>id=2, clicks=0</button><button>id=1, clicks=1</button><button>id=0, clicks=2</button>
'
        );

        //    DO : Add an item on bottom of the list
        // EXPECT: No side-effects
        //
        dom.firstChild.firstChild.childNodes[1].dispatchEvent(event);
        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '
<button>id=2, clicks=0</button><button>id=1, clicks=1</button><button>id=0, clicks=2</button><button>id=3, clicks=0</button>
'
        );

        //    DO : Remove an item from the top of the list
        // EXPECT: State of the child items correctly shifted to the left
        //
        dom.firstChild.firstChild.childNodes[2].dispatchEvent(event);
        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '
<button>id=1, clicks=1</button><button>id=0, clicks=2</button><button>id=3, clicks=0</button>
'
        );

        //    DO : Remove an item from the bottom of the list
        // EXPECT: No side-effects
        //
        dom.firstChild.firstChild.childNodes[3].dispatchEvent(event);
        expect(dom.firstChild.firstChild.nextSibling.outerHTML).toEqual(
          '
<button>id=1, clicks=1</button><button>id=0, clicks=2</button>
'
        );

      });

    });

    describe('Tag Shorthands', function () {

      it(`should dynamically create tag shorthands`, function () {
        const dom = document.createElement('div');
        const {div} = dd.H;
        const vdom = div();

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          `<div></div>`
        );
      });

      it('should expand className shorthands', function () {
        const dom = document.createElement('div');
        const {div} = dd.H;
        const vdom = div.class1();

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      })

      it('should expand multiple className shorthands', function () {
        const dom = document.createElement('div');
        const {div} = dd.H;
        const vdom = div.class1.class2.class3();

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      })

      it('should append className shorthands on className props', function () {
        const dom = document.createElement('div');
        const {div} = dd.H;
        const vdom = div.class1.class2.class3({className: 'foo'});

        dd.R(vdom, dom)

        expect(dom.innerHTML).toEqual(
          '

'
        );
      })
    });
  });

});


text:
import React from 'react';
import expect from 'expect';
import request from 'superagent';
import {spy, stub} from 'sinon';
import alt from '../../alt';
import SessionActions from '../../actions/SessionActions';
import SessionStore from '../SessionStore';
import AltTestingUtils from 'alt-utils/lib/AltTestingUtils';

describe('Session Store tests', () => {
  it('listens for session Actions', () => {
    stub(alt.dispatcher, 'dispatch').returns(true);
    let user = {username: 'koech', id: 123};
    let action = SessionActions.SESSION_SUCCESS;
    alt.dispatcher.dispatch({action, user});
    expect(alt.dispatcher.dispatch.called).toBe(true);
    alt.dispatcher.dispatch.restore();
  });

});


text:
use term::{Modifier, Key, KeyReader, Color, Surface, TermStream, TermBuffer, UserInput, Point, Rect};
use termion::cursor;

use std::io::Write;
use std::collections::VecDeque;

pub struct TextInput {
    history: VecDeque<Vec<char>>,
    history_index: usize,
    cursor: i32,
    dirty: bool,
    reader: KeyReader,
}

impl TextInput {
    pub fn new() -> TextInput {
        let mut input = TextInput {
            history_index: 0,
            history: VecDeque::new(),
            cursor: 0,
            dirty: true,
            reader: KeyReader::stdin(),
        };

        input.history.push_front(Vec::new());

        input
    }

    pub fn set_dirty(&mut self) { self.dirty = true; }
    pub fn is_dirty(&self) -> bool { self.dirty }

    pub fn read(&mut self) -> Option<UserInput> {
        let keys: Vec<_> = self.reader.by_ref().collect();
        for m in keys {
            match m {
                Modifier::None(k) => {
                    match k {
                        Key::Close =>{ return Some(UserInput::Close); },
                        Key::Up => {
                            if self.history_index + 1 < self.history.len() {
                                self.set_dirty();
                                self.history_index += 1;
                                self.cursor = self.history[self.history_index].len() as i32;
                            }
                        },
                        Key::Down => {
                            if self.history_index > 0 {
                                self.set_dirty();
                                self.history_index -= 1;
                                self.cursor = self.history[self.history_index].len() as i32;
                            }

                        },
                        Key::Right => {
                            let len = self.history[self.history_index].len() as i32;
                            if self.cursor + 1 <= len {
                                self.set_dirty();
                                self.cursor += 1;
                            }
                        },
                        Key::Left => {
                            if self.cursor > 0 {
                                self.set_dirty();
                                self.cursor -= 1;
                            }
                        },
                        Key::Ins => {},
                        Key::Del => {
                            let len = self.history[self.history_index].len() as i32;
                            if self.cursor < len {
                                self.set_dirty();
                                self.cursor += 1;
                                self.delete_character();
                            }
                        },
                        Key::Home => {
                            self.set_dirty();
                            self.cursor = 0;
                        },
                        Key::End => {
                            self.set_dirty();
                            let len = self.history[self.history_index].len() as i32;
                            self.cursor = len;
                        },
                        Key::PageUp => { return Some(UserInput::ScrollUp); },
                        Key::PageDown => { return Some(UserInput::ScrollDown); },
                        Key::Backspace => {
                            self.delete_character();
                        },
                        Key::Return => {
                            let result = self.current_line();
                            self.cursor = 0;
                            if self.history_index == 0 {
                                self.history.push_front(Vec::new());
                            } else {
                                self.history_index = 0;
                                self.history[0] = Vec::new();
                            }
                            self.set_dirty();
                            return Some(UserInput::Text(result));
                        },
                        Key::Printable(c) => {
                            self.type_character(c);
                        },
                        _ => {}
                    }
                },
                Modifier::Alt(k) => {
                    match k {
                        Key::Printable(c) if (c as u32) >= 0x30 && (c as u32) < 0x3A => {
                            return Some(UserInput::SetTab(c as u32 - 0x30));
                        },
                        Key::Left => {
                            return Some(UserInput::PrevTab);
                        },
                        Key::Right => {
                            return Some(UserInput::NextTab);
                        },
                        _ => {}
                    }
                },
                _ => {}
            }
        }
        None
    }

    pub fn current_line(&self) -> String {
        use ::std::iter::FromIterator;
        String::from_iter(self.history[self.history_index].iter().map(|x|*x))
    }

    fn type_character(&mut self, c: char) {
        let len = self.history[self.history_index].len() as i32;
        if self.cursor <= len {
            self.set_dirty();
            self.history[self.history_index].insert(self.cursor as usize, c);
            self.cursor += 1;
        }
    }

    fn delete_character(&mut self) {
        if self.cursor > 0 {
            self.set_dirty();
            self.cursor -= 1;
            let _ = self.history[self.history_index].remove(self.cursor as usize);
        }
    }

    pub fn render(&mut self, window: &mut TermBuffer) {
        if !window.is_invalid() && !self.is_dirty() { return; }

        let height = window.height();
        let width = window.width();

        let mut surface = Surface::new(Rect(Point(0,0), width, 1));
        let line =  self.current_line();

        let offset = self.get_render_offset(width) as usize;
        let mut end = offset + width as usize;
        if end > line.len() { end = line.len(); }

        surface.text(&line[offset..end], Point(0,0));
        surface.set_color(Point(0,0), Some(Color::White), Some(Color::Black));
        window.blit(&surface, Point(0, height - 1));

        self.dirty = false;
    }

    fn get_render_offset(&self, width: i32) -> i32 {
        if self.cursor > width - 3 {
            self.cursor - (width - 3)
        } else {
            0
        }
    }

    pub fn get_display_cursor(&self, window: &TermBuffer) -> i32 {
        let width = window.width();
        self.cursor - self.get_render_offset(width)
    }

    pub fn set_cursor(&mut self, stream: &mut TermStream, window: &TermBuffer) {
        let _ = stream.write_all(&*format!("{}",
                    cursor::Goto(self.get_display_cursor(window) as u16 + 1,
                    window.height() as u16)).into_bytes());
        let _ = stream.flush();
    }
}


text:
from datadog_checks.base import ConfigurationError

def initialize_instance(values, **kwargs):
    # TODO: remove when deprecation is finalized https://github.com/DataDog/integrations-core/pull/9340
    if 'username' not in values and 'user' in values:
        values['username'] = values['user']

    _validate_authenticator_option(values)

    if 'private_key_password' in values and 'private_key_path' not in values:
        raise ConfigurationError(
            'Option `private_key_password` is set but not option `private_key_path`. '
            'Set `private_key_path` or remove `private_key_password` entry.'
        )

    if values.get('only_custom_queries', False) and len(values.get('metric_groups', [])) > 0:
        raise ConfigurationError(
            'Option `only_custom_queries` and `metric_groups` are not compatible. '
            '`only_custom_queries` prevents `metric_groups` to be collected.'
        )

    return values

def _validate_authenticator_option(values):
    authenticator = values.get('authenticator', 'snowflake')
    # `key` needs at least one item in `values` to be set
    authenticator_dependencies = {
        'snowflake': ['password', 'private_key_path'],
        'snowflake_jwt': ['private_key_path'],
        'oauth': ['token', 'token_path'],
    }

    if authenticator not in authenticator_dependencies:
        raise ConfigurationError(
            'Unkwown authenticator option {}, supported options are {}.'.format(
                authenticator, authenticator_dependencies.keys()
            )
        )

    if not any([opt in values for opt in authenticator_dependencies[authenticator]]):
        raise ConfigurationError(
            'Authenticator option `{}` needs `{}` option to be set.'.format(
                authenticator, '` or `'.join(authenticator_dependencies[authenticator])
            )
        )