text:
package org.apache.sis.internal.jaxb.code;

import java.util.Arrays;
import java.util.Locale;
import java.util.Collections;
import javax.xml.bind.Marshaller;
import javax.xml.bind.JAXBException;
import org.opengis.metadata.citation.Role;
import org.opengis.metadata.citation.DateType;
import org.opengis.metadata.citation.CitationDate;
import org.opengis.metadata.citation.Responsibility;
import org.opengis.metadata.citation.PresentationForm;
import org.apache.sis.metadata.iso.citation.DefaultCitation;
import org.apache.sis.internal.jaxb.Schemas;
import org.apache.sis.xml.XML;
import org.apache.sis.xml.Namespaces;
import org.apache.sis.xml.MarshallerPool;
import org.apache.sis.test.XMLTestCase;
import org.junit.Test;

import static org.apache.sis.test.Assert.*;

/**
 * Tests the XML marshaling of {@code CodeList}.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @author  Guilhem Legal (Geomatys)
 * @since   0.3
 * @version 0.5
 * @module
 *
 * @see GEOTK-121
 */
public final strictfp class CodeListMarshallingTest extends XMLTestCase {
    /**
     * Returns a XML string to use for testing purpose.
     *
     * @param baseURL The base URL of XML schemas.
     */
    private static String getResponsiblePartyXML(final String baseURL) {
        return "<gmd:CI_ResponsibleParty xmlns:gmd=\"" + Namespaces.GMD + "\">\n" +
               "  <gmd:role>\n" +
               "    <gmd:CI_RoleCode codeList=\"" + baseURL + Schemas.CODELISTS_PATH + "#CI_RoleCode\"" +
                    " codeListValue=\"principalInvestigator\">" + "Principal investigator</gmd:CI_RoleCode>\n" +
               "  </gmd:role>\n" +
               "</gmd:CI_ResponsibleParty>";
    }

    /**
     * Returns a XML string to use for testing purpose.
     *
     * @param baseURL The base URL of XML schemas.
     */
    private static String getCitationXML(final String baseURL, final String language, final String value) {
        return "<gmd:CI_Date xmlns:gmd=\"" + Namespaces.GMD + "\">\n" +
               "  <gmd:dateType>\n" +
               "    <gmd:CI_DateTypeCode codeList=\"" + baseURL + Schemas.CODELISTS_PATH + "#CI_DateTypeCode\"" +
                    " codeListValue=\"creation\" codeSpace=\"" + language + "\">" + value + "</gmd:CI_DateTypeCode>\n" +
               "  </gmd:dateType>\n" +
               "</gmd:CI_Date>";
    }

    /**
     * Tests marshaling using the default URL.
     *
     * @throws JAXBException If an error occurred while marshaling the XML.
     */
    @Test
    public void testDefaultURL() throws JAXBException {
        final String expected = getResponsiblePartyXML(Schemas.METADATA_ROOT);
        final Responsibility rp = (Responsibility) XML.unmarshal(expected);
        assertEquals(Role.PRINCIPAL_INVESTIGATOR, rp.getRole());
        /*
         * Use the convenience method in order to avoid the effort of creating
         * our own MarshallerPool.
         */
        final String actual = XML.marshal(rp);
        assertXmlEquals(expected, actual, "xmlns:*");
    }

    /**
     * Tests marshaling using the ISO URL.
     *
     * @throws JAXBException If an error occurred while marshaling the XML.
     */
    @Test
    public void testISO_URL() throws JAXBException {
        final String expected = getResponsiblePartyXML(Schemas.ISO_19139_ROOT);
        final Responsibility rp = (Responsibility) XML.unmarshal(expected);
        assertEquals(Role.PRINCIPAL_INVESTIGATOR, rp.getRole());

        final MarshallerPool pool = getMarshallerPool();
        final Marshaller marshaller = pool.acquireMarshaller();
        marshaller.setProperty(XML.SCHEMAS, Collections.singletonMap("gmd",
                "http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas")); // Intentionally omit trailing '/'.
        final String actual = marshal(marshaller, rp);
        pool.recycle(marshaller);
        assertXmlEquals(expected, actual, "xmlns:*");
    }

    /**
     * Tests a code list localization.
     *
     * @throws JAXBException If an error occurred while marshaling the XML.
     */
    @Test
    public void testLocalization() throws JAXBException {
        final MarshallerPool pool = getMarshallerPool();
        final Marshaller marshaller = pool.acquireMarshaller();
        /*
         * First, test using the French locale.
         */
        marshaller.setProperty(XML.LOCALE, Locale.FRENCH);
        String expected = getCitationXML(Schemas.METADATA_ROOT, "fra", "Création");
        CitationDate ci = (CitationDate) XML.unmarshal(expected);
        assertEquals(DateType.CREATION, ci.getDateType());
        String actual = marshal(marshaller, ci);
        assertXmlEquals(expected, actual, "xmlns:*");
        /*
         * Tests again using the English locale.
         */
        marshaller.setProperty(XML.LOCALE, Locale.ENGLISH);
        expected = getCitationXML(Schemas.METADATA_ROOT, "eng", "Creation");
        ci = (CitationDate) XML.unmarshal(expected);
        assertEquals(DateType.CREATION, ci.getDateType());
        actual = marshal(marshaller, ci);
        assertXmlEquals(expected, actual, "xmlns:*");

        pool.recycle(marshaller);
    }

    /**
     * Tests marshaling of a code list which is not in the list of standard codes.
     *
     * @throws JAXBException If an error occurred while marshaling the XML.
     */
    @Test
    public void testExtraCodes() throws JAXBException {
        final DefaultCitation id = new DefaultCitation();
        id.setPresentationForms(Arrays.asList(
                PresentationForm.valueOf("IMAGE_DIGITAL"), // Existing code with UML id="imageDigital"
                PresentationForm.valueOf("test")));        // New code

        final String xml = marshal(id);

        // "IMAGE_DIGITAL" is marshalled as "imageDigital" because is contains a UML id, which is lower-case.
        assertXmlEquals(
                "<gmd:CI_Citation xmlns:gmd=\"" + Namespaces.GMD + "\">\n" +
                "  <gmd:presentationForm>\n" +
                "    <gmd:CI_PresentationFormCode codeListValue=\"imageDigital\">Image digital</gmd:CI_PresentationFormCode>\n" +
                "  </gmd:presentationForm>\n" +
                "  <gmd:presentationForm>\n" +
                "    <gmd:CI_PresentationFormCode codeListValue=\"test\">Test</gmd:CI_PresentationFormCode>\n" +
                "  </gmd:presentationForm>\n" +
                "</gmd:CI_Citation>\n",
                xml, "xmlns:*", "codeList", "codeSpace");
    }
}


text:
require('should');
const InitBlock = require('../../build/classes/InitBlock');
const Statement = require('../../build/classes/Statement');
const Identifier = require('../../build/classes/Identifier');
const Exponential = require('../../build/classes/Exponential');

const parser = require('../../build/parse');

function makeStmt(expr) {
  return InitBlock([Statement(expr)]);
}

describe('syntaxtree/Exponential', () => {
  it('should parse the exponential operator', () => {
    parser('x**y;').should.eql(makeStmt(
      Exponential(Identifier('x'), Identifier('y'))
    ));
  });
});

redpajama_set_name: RedPajamaGithub


text:
require 'concurrent'

require 'hystrix/circuit'
require 'hystrix/command'
require 'hystrix/command_executor'
require 'hystrix/command_executor_pool'
require 'hystrix/command_executor_pools'
require 'hystrix/event_bus'
require 'hystrix/loggable'
require 'hystrix/exceptions'
require 'hystrix/version'

module Hystrix
  extend Loggable
end


text:
<?php
/**
 * WPSEO plugin file.
 *
 * @package WPSEO\Admin
 */

// Mark this file as deprecated.
_deprecated_file( __FILE__, 'WPSEO 13.2' );

/**
 * This class handles the data for the option where the Ryte data is stored.
 *
 * @deprecated 13.2
 * @codeCoverageIgnore
 */
class WPSEO_OnPage_Option extends WPSEO_Ryte_Option {

	/**
	 * Setting the object by setting the properties.
	 *
	 * @deprecated 13.2
	 * @codeCoverageIgnore
	 */
	public function __construct() {
		_deprecated_function( __METHOD__, 'WPSEO 13.2', WPSEO_Ryte_Option::class );
	}
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Statistics extends CI_Controller {

	function __construct() {
		parent::__construct();
		if(!$this->session->userdata('email')) {redirect(base_url('admin/login'));}
		$this->load->model(array('Configs_ad_model', 'Statistics_ad_model'));
		$this->pageTitle = 'სტატისტიკა';
	}

	public function index()
	{
		$data['pageTitle'] = $this->pageTitle;
		$data['parents'] = $this->Statistics_ad_model->read_parents();
		$this->load->view('admin/statistics/manage', $data);
	}

	public function create()
	{
		$data['pageTitle'] = $this->pageTitle;
		$data['langs'] = $this->Configs_ad_model->langs();

		$this->load->view('admin/statistics/create', $data);

		if($this->input->post()) {
			$this->Statistics_ad_model->create($data['langs']);
			redirect(base_url().'admin/statistics');
		}
	}

	public function update()
	{
		$data['pageTitle'] = $this->pageTitle;
		$data['langs'] = $this->Configs_ad_model->langs();
		$data['item'] = $this->Statistics_ad_model->read();

		$this->load->view('admin/statistics/update', $data);

		if($this->input->post()) {
			$this->Statistics_ad_model->update();
			redirect(base_url().'admin/statistics');
		}
	}

	public function update_sorting()
	{
		$data['statistics'] = $this->Statistics_ad_model->update_sorting();
	}

	public function delete()
	{
		$this->Statistics_ad_model->delete();
		redirect(base_url().'admin/statistics');
	}

}


text:
package es.bsc.compss.agent.rest.master;

import es.bsc.compss.comm.CommAdaptor;
import es.bsc.compss.exceptions.ConstructConfigurationException;
import es.bsc.compss.types.COMPSsWorker;
import es.bsc.compss.types.data.operation.DataOperation;
import es.bsc.compss.types.resources.configuration.Configuration;
import es.bsc.compss.types.resources.jaxb.ResourcesExternalAdaptorProperties;
import es.bsc.compss.types.resources.jaxb.ResourcesPropertyAdaptorType;
import es.bsc.compss.types.uri.MultiURI;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Adaptor implements CommAdaptor {

    @Override
    public void init() {

    }

    @Override
    public Configuration constructConfiguration(Map<String, Object> projectConf, Map<String, Object> resourcesConf)
        throws ConstructConfigurationException {

        AgentConfiguration ac = new AgentConfiguration(this.getClass().getName());

        ResourcesExternalAdaptorProperties eap = (ResourcesExternalAdaptorProperties) resourcesConf.get("Properties");
        for (ResourcesPropertyAdaptorType prop : eap.getProperty()) {
            ac.addProperty(prop.getName(), prop.getValue());
        }
        /*
         * ac.setHost((String) props.get("host")); MethodResourceDescription mrd = (MethodResourceDescription)
         * props.get("description"); ac.setDescription(mrd); ac.setLimitOfTasks(mrd.getTotalCPUComputingUnits());
         */
        return ac;
    }

    @Override
    public COMPSsWorker initWorker(Configuration config) {
        AgentConfiguration ac = (AgentConfiguration) config;
        return new RemoteRESTAgent(ac);
    }

    @Override
    public void stop() {
        // You cannot stop a remote agent.
    }

    @Override
    public List<DataOperation> getPending() {
        // There are never pending data operations since you never copy data onto it
        return new LinkedList<>();
    }

    @Override
    public void completeMasterURI(MultiURI muri) {
        // NO need to do anything since everything is copied through the StorageItf
    }

    @Override
    public void stopSubmittedJobs() {
        // You can't do that
    }

}


text:
import React, { Component } from 'react'
import { Entity, Modifier, EditorState } from 'draft-js'
import { createPlugin, pluginUtils } from 'draft-extend'
import { Button, Modal, message } from 'antd'
import LinkSelect from '../../Resource/LinkSelect'
import { WX, DOC, BAIKE } from '../../../constants/api'
// import './index.css'

const ENTITY_TYPE = 'LINK'
class baike extends Component {
    constructor() {
        super()
        this.state = {
            visible: false,
            record: null
        }
    }
    toggleVisible = () => this.setState({ visible: !this.state.visible })
    okHandler = () => {
        const { record } = this.state
        if (record) {
            const { editorState, onChange } = this.props
            const contentState = Modifier.insertText(
                editorState.getCurrentContent(),
                editorState.getSelection(),
                record.title,
                null,
                Entity.create(
                    ENTITY_TYPE,
                    'MUTABLE',
                    {
                        href: record.path,
                        target: '_blank',
                        title: record.title,
                        descript: record.descript,
                        name: 'baike',
                        className: 'icon-artboard f-fc4'
                    }
                )
            );
            onChange(
                EditorState.push(
                    editorState,
                    contentState,
                    'apply-entity'
                )
            )
            this.toggleVisible()
        } else {
            message.warn('请至少选择一项!')
        }
    }
    render() {
        const { visible } = this.state
        return (

                <Modal
                    visible={visible}
                    title="选择百科"
                    onOk={this.okHandler}
                    onCancel={this.toggleVisible}
                    maskClosable={false}
                >
                    <LinkSelect category={BAIKE} onChange={val => this.setState({ record: val })} />
                </Modal>
                <Button onClick={() => this.setState({ visible: true })}>添加百科</Button>

        )
    }
}

class doc extends Component {
    constructor() {
        super()
        this.state = {
            visible: false,
            record: null
        }
    }
    toggleVisible = () => this.setState({ visible: !this.state.visible })
    okHandler = () => {
        const { record } = this.state
        if (record) {
            const { editorState, onChange } = this.props
            const contentState = Modifier.insertText(
                editorState.getCurrentContent(),
                editorState.getSelection(),
                record.title,
                null,
                Entity.create(
                    ENTITY_TYPE,
                    'MUTABLE',
                    {
                        href: record.path,
                        target: '_blank',
                        name: 'doc',
                        title: record.title,
                        descript: record.descript,
                        className: 'icon-wenxian f-fc3'
                    }
                )
            );
            onChange(
                EditorState.push(
                    editorState,
                    contentState,
                    'apply-entity'
                )
            )
            this.toggleVisible()
        } else {
            message.warn('请至少选择一项!')
        }
    }
    render() {
        const { visible } = this.state
        return (

                <Modal
                    visible={visible}
                    title="选择文献"
                    onOk={this.okHandler}
                    onCancel={this.toggleVisible}
                    maskClosable={false}
                >
                    <LinkSelect category={DOC} onChange={val => this.setState({ record: val })} />
                </Modal>
                <Button onClick={() => this.setState({ visible: true })}>添加文献</Button>

        )
    }
}
class weixin extends Component {
    constructor() {
        super()
        this.state = {
            visible: false,
            record: null
        }
    }
    toggleVisible = () => this.setState({ visible: !this.state.visible })
    okHandler = () => {
        const { record } = this.state
        if (record) {
            const { editorState, onChange } = this.props
            const contentState = Modifier.insertText(
                editorState.getCurrentContent(),
                editorState.getSelection(),
                record.title,
                null,
                Entity.create(
                    ENTITY_TYPE,
                    'MUTABLE',
                    {
                        href: record.path,
                        target: '_blank',
                        name: 'wx',
                        title: record.title,
                        descript: record.descript,
                        className: 'icon-weixin f-fc2'
                    }
                )
            );
            onChange(
                EditorState.push(
                    editorState,
                    contentState,
                    'apply-entity'
                )
            )
            this.toggleVisible()
        } else {
            message.warn('请选择一项!')
        }
    }
    render() {
        const { visible } = this.state
        return (

                <Modal
                    visible={visible}
                    title="选择微信"
                    onOk={this.okHandler}
                    onCancel={this.toggleVisible}
                    maskClosable={false}
                >
                    <LinkSelect category={WX} onChange={val => this.setState({ record: val })} />
                </Modal>
                <Button onClick={() => this.setState({ visible: true })}>添加微信</Button>

        )
    }
}

const LinkDecorator = {
    strategy: pluginUtils.entityStrategy(ENTITY_TYPE),
    component: (props) => {
        const entity = Entity.get(props.entityKey)
        const { href, name, target, title, descript, className } = entity.getData()
        return (

                    {title}
                    {descript}

        )
    }
}

// Convert links in input HTML to entities
const htmlToEntity = (nodeName, node) => {
    if (nodeName === 'a') {
        return Entity.create(
            ENTITY_TYPE,
            'MUTABLE',
            {
                href: node.getAttribute('href'),
                target: node.getAttribute('target'),
                name: node.getAttribute('name'),
                title: node.getAttribute('title'),
                descript: node.getAttribute('descript'),
                className: node.childNodes[0].getAttribute('class')
            }
        )
    }
};

// Convert entities to HTML for output
const entityToHTML = (entity, originalText) => {
    if (entity.type === ENTITY_TYPE) {
        const { href, name, target, className, title, descript } = entity.data
        return `<a href="${href}" class="currencyStyle" name="${name}" target="${target}" title="${title}" descript="${descript}"><i class="${className}" /><div><span>${title}</span><em>${descript}</em></div></a>`;
    }
    return originalText;
};

const LinkPlugin = createPlugin({
    displayName: 'LinkPlugin',
    buttons: [ weixin, doc, baike ],
    decorators: [LinkDecorator],
    htmlToEntity,
    entityToHTML
});

export default LinkPlugin;


text:
package goose

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"

	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
	_ "github.com/mattn/go-sqlite3"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func getSqlite3Driver(t *testing.T) DBDriver {
	return DBDriver{
		Name:    "sqlite3",
		Dialect: Sqlite3Dialect{},
		OpenStr: ":memory:",
	}
}

func getMysqlDriver(t *testing.T) DBDriver {
	dsn := os.Getenv("MYSQL_DATABASE_DSN")
	if dsn == "" {
		t.SkipNow()
	}
	return DBDriver{
		Name:    "mysql",
		Dialect: MySqlDialect{},
		OpenStr: dsn,
	}
}

func getPostgresDriver(t *testing.T) DBDriver {
	dsn := os.Getenv("POSTGRES_DATABASE_DSN")
	if dsn == "" {
		t.SkipNow()
	}
	return DBDriver{
		Name:    "postgres",
		Dialect: PostgresDialect{},
		OpenStr: dsn,
	}
}

func getRedshiftDriver(t *testing.T) DBDriver {
	dsn := os.Getenv("REDSHIFT_DATABASE_DSN")
	if dsn == "" {
		t.SkipNow()
	}
	return DBDriver{
		Name:    "postgres",
		Dialect: RedshiftDialect{},
		OpenStr: dsn,
	}
}

func TestMigrationSorterLen(t *testing.T) {
	ms := migrationSorter{
		{Version: 1},
		{Version: 2},
		{Version: 4},
		{Version: 3},
	}
	l := ms.Len()
	if l != 4 {
		t.Errorf("expected ms.Len() == 4, but got %d\n", l)
	}
}

func TestMigrationSorterSwap(t *testing.T) {
	ms := migrationSorter{
		{Version: 1},
		{Version: 2},
		{Version: 4},
		{Version: 3},
	}
	ms.Swap(1, 2)
	if ms[1].Version != 4 {
		t.Errorf("expected ms[1].Version == 4, but got %d\n", ms[1].Version)
	}
	if ms[2].Version != 2 {
		t.Errorf("expected ms[2].Version == 2, but got %d\n", ms[1].Version)
	}
}

func TestMigrationSorterLess(t *testing.T) {
	ms := migrationSorter{
		{Version: 1},
		{Version: 2},
		{Version: 4},
		{Version: 3},
	}
	v := ms.Less(2, 3)
	if v != false {
		t.Errorf("expected ms.Less(2,3) == false, but got %v\n", v)
	}
	v = ms.Less(3, 2)
	if v != true {
		t.Errorf("expected ms.Less(3,2) == true, but got %v\n", v)
	}
}

func setupMigrationsDir(migrationMap map[string][2]string) (string, func()) {
	td, err := ioutil.TempDir("", "goose-test-")
	if err != nil {
		panic(err)
	}

	dbPath := filepath.Join(td, "db")
	migrationsPath := filepath.Join(dbPath, "migrations")
	os.MkdirAll(migrationsPath, 0700)

	for name, migrations := range migrationMap {
		migStr := `-- +goose Up
` + migrations[0] + `

-- +goose Down
` + migrations[1] + `
`
		if err := ioutil.WriteFile(filepath.Join(migrationsPath, name), []byte(migStr), 0600); err != nil {
			panic(err)
		}
	}

	return migrationsPath, func() { os.RemoveAll(td) }
}

func TestCollectMigrations(t *testing.T) {
	md, mdCleanup := setupMigrationsDir(map[string][2]string{
		"20010203040506_first.sql":  [2]string{"SELECT 1;", "SELECT 1;"},
		"20010203040507_second.sql": [2]string{"SELECT 2;", "SELECT 2;"},
		"20010203040508_third.sql":  [2]string{"SELECT 3;", "SELECT 3;"},
	})
	defer mdCleanup()

	migs, err := CollectMigrations(md)
	require.NoError(t, err)

	assert.Len(t, migs, 3)
	assert.Contains(t, migs, &Migration{
		Version:   20010203040506,
		IsApplied: false,
		Source:    filepath.Join(md, "20010203040506_first.sql"),
	})
	assert.Contains(t, migs, &Migration{
		Version:   20010203040507,
		IsApplied: false,
		Source:    filepath.Join(md, "20010203040507_second.sql"),
	})
	assert.Contains(t, migs, &Migration{
		Version:   20010203040508,
		IsApplied: false,
		Source:    filepath.Join(md, "20010203040508_third.sql"),
	})
}

func testRunMigrationsOnDb(t *testing.T, driver DBDriver) {
	md, mdCleanup := setupMigrationsDir(map[string][2]string{
		"20010203040506_setup.sql": [2]string{"CREATE TABLE test(value VARCHAR(20));", "DROP TABLE test;"},
		"20010203040507_one.sql":   [2]string{"INSERT INTO test(value) VALUES('one');", "DELETE FROM test WHERE value = 'one';"},
		"20010203040508_two.sql":   [2]string{"INSERT INTO test(value) VALUES('two');", "DELETE FROM test WHERE value = 'two';"},
	})
	defer mdCleanup()
	conf := &DBConf{
		Driver:        driver,
		MigrationsDir: md,
	}

	db, err := OpenDBFromDBConf(conf)
	require.NoError(t, err)

	db.Exec("DROP TABLE goose_db_version")
	db.Exec("DROP TABLE test")

	err = RunMigrationsOnDb(conf, conf.MigrationsDir, 20010203040508, db)
	require.NoError(t, err)

	rows, err := db.Query("SELECT value FROM test")
	require.NoError(t, err)
	defer rows.Close()
	var values []string
	for rows.Next() {
		var value string
		err := rows.Scan(&value)
		require.NoError(t, err)
		values = append(values, value)
	}

	assert.Len(t, values, 2)
	assert.Contains(t, values, "one")
	assert.Contains(t, values, "two")
}
func TestRunMigrationsOnDb_sqlite3(t *testing.T) {
	testRunMigrationsOnDb(t, getSqlite3Driver(t))
}
func TestRunMigrationsOnDb_mysql(t *testing.T) {
	testRunMigrationsOnDb(t, getMysqlDriver(t))
}
func TestRunMigrationsOnDb_postgres(t *testing.T) {
	testRunMigrationsOnDb(t, getPostgresDriver(t))
}
func TestRunMigrationsOnDb_redshift(t *testing.T) {
	testRunMigrationsOnDb(t, getRedshiftDriver(t))
}

func testRunMigrationsOnDb_missingMiddle(t *testing.T, driver DBDriver) {
	md, mdCleanup := setupMigrationsDir(map[string][2]string{
		"20010203040506_setup.sql": [2]string{"CREATE TABLE test(value VARCHAR(20));", "DROP TABLE test;"},
		"20010203040507_one.sql":   [2]string{"INSERT INTO test(value) VALUES('one');", "DELETE FROM test WHERE value = 'one';"},
		"20010203040508_two.sql":   [2]string{"INSERT INTO test(value) VALUES('two');", "DELETE FROM test WHERE value = 'two';"},
	})
	defer mdCleanup()
	conf := &DBConf{
		Driver:        driver,
		MigrationsDir: md,
	}

	db, err := OpenDBFromDBConf(conf)
	require.NoError(t, err)

	db.Exec("DROP TABLE goose_db_version")
	db.Exec("DROP TABLE test")

	// make the middle migration disappear for a moment
	err = os.Rename(filepath.Join(md, "20010203040507_one.sql"), filepath.Join(md, "20010203040507_one.sql_"))
	require.NoError(t, err)

	err = RunMigrationsOnDb(conf, conf.MigrationsDir, 20010203040508, db)
	require.NoError(t, err)

	rows, err := db.Query("SELECT value FROM test")
	require.NoError(t, err)
	defer rows.Close()
	var values []string
	for rows.Next() {
		var value string
		err := rows.Scan(&value)
		require.NoError(t, err)
		values = append(values, value)
	}

	assert.Len(t, values, 1)
	assert.Contains(t, values, "two")

	// now put it back
	err = os.Rename(filepath.Join(md, "20010203040507_one.sql_"), filepath.Join(md, "20010203040507_one.sql"))
	require.NoError(t, err)

	err = RunMigrationsOnDb(conf, conf.MigrationsDir, 20010203040508, db)
	require.NoError(t, err)

	rows, err = db.Query("SELECT value FROM test")
	require.NoError(t, err)
	defer rows.Close()
	values = []string{}
	for rows.Next() {
		var value string
		err := rows.Scan(&value)
		require.NoError(t, err)
		values = append(values, value)
	}

	assert.Len(t, values, 2)
	assert.Contains(t, values, "one")
	assert.Contains(t, values, "two")
}
func TestRunMigrationsOnDb_missingMiddle_sqlite3(t *testing.T) {
	testRunMigrationsOnDb_missingMiddle(t, getSqlite3Driver(t))
}
func TestRunMigrationsOnDb_missingMiddle_mysql(t *testing.T) {
	testRunMigrationsOnDb_missingMiddle(t, getMysqlDriver(t))
}
func TestRunMigrationsOnDb_missingMiddle_postgres(t *testing.T) {
	testRunMigrationsOnDb_missingMiddle(t, getPostgresDriver(t))
}
func TestRunMigrationsOnDb_missingMiddle_redshift(t *testing.T) {
	testRunMigrationsOnDb_missingMiddle(t, getRedshiftDriver(t))
}

func testRunMigrationsOnDb_down(t *testing.T, driver DBDriver) {
	md, mdCleanup := setupMigrationsDir(map[string][2]string{
		"20010203040506_setup.sql": [2]string{"CREATE TABLE test(value VARCHAR(20));", "DROP TABLE test;"},
		"20010203040507_one.sql":   [2]string{"INSERT INTO test(value) VALUES('one');", "DELETE FROM test WHERE value = 'one';"},
		"20010203040508_two.sql":   [2]string{"INSERT INTO test(value) VALUES('two');", "DELETE FROM test WHERE value = 'two';"},
	})
	defer mdCleanup()
	conf := &DBConf{
		Driver:        driver,
		MigrationsDir: md,
	}

	db, err := OpenDBFromDBConf(conf)
	require.NoError(t, err)

	db.Exec("DROP TABLE goose_db_version")
	db.Exec("DROP TABLE test")

	// up
	err = RunMigrationsOnDb(conf, conf.MigrationsDir, 20010203040508, db)
	require.NoError(t, err)

	// down
	err = RunMigrationsOnDb(conf, conf.MigrationsDir, 20010203040507, db)
	require.NoError(t, err)

	rows, err := db.Query("SELECT value FROM test")
	require.NoError(t, err)
	defer rows.Close()
	var values []string
	for rows.Next() {
		var value string
		err := rows.Scan(&value)
		require.NoError(t, err)
		values = append(values, value)
	}

	assert.Len(t, values, 1)
	assert.Contains(t, values, "one")
}
func TestRunMigrationsOnDb_down_sqlite3(t *testing.T) {
	testRunMigrationsOnDb_down(t, getSqlite3Driver(t))
}
func TestRunMigrationsOnDb_down_mysql(t *testing.T) {
	testRunMigrationsOnDb_down(t, getMysqlDriver(t))
}
func TestRunMigrationsOnDb_down_postgres(t *testing.T) {
	testRunMigrationsOnDb_down(t, getPostgresDriver(t))
}
func TestRunMigrationsOnDb_down_redshift(t *testing.T) {
	testRunMigrationsOnDb_down(t, getRedshiftDriver(t))
}

func testRunMigrationsOnDb_upDownUp(t *testing.T, driver DBDriver) {
	md, mdCleanup := setupMigrationsDir(map[string][2]string{
		"20010203040506_setup.sql": [2]string{"CREATE TABLE test(value VARCHAR(20));", "DROP TABLE test;"},
		"20010203040507_one.sql":   [2]string{"INSERT INTO test(value) VALUES('one');", "DELETE FROM test WHERE value = 'one';"},
		"20010203040508_two.sql":   [2]string{"INSERT INTO test(value) VALUES('two');", "DELETE FROM test WHERE value = 'two';"},
	})
	defer mdCleanup()
	conf := &DBConf{
		Driver:        driver,
		MigrationsDir: md,
	}

	db, err := OpenDBFromDBConf(conf)
	require.NoError(t, err)

	db.Exec("DROP TABLE goose_db_version")
	db.Exec("DROP TABLE test")

	// up
	err = RunMigrationsOnDb(conf, conf.MigrationsDir, 20010203040508, db)
	require.NoError(t, err)

	// down
	err = RunMigrationsOnDb(conf, conf.MigrationsDir, 0, db)
	require.NoError(t, err)

	rows, err := db.Query("SELECT value FROM test")
	require.Error(t, err) // table won't exist

	// up
	err = RunMigrationsOnDb(conf, conf.MigrationsDir, 20010203040508, db)
	require.NoError(t, err)

	rows, err = db.Query("SELECT value FROM test")
	require.NoError(t, err)
	defer rows.Close()
	var values []string
	for rows.Next() {
		var value string
		err := rows.Scan(&value)
		require.NoError(t, err)
		values = append(values, value)
	}

	assert.Len(t, values, 2)
	assert.Contains(t, values, "one")
	assert.Contains(t, values, "two")
}
func TestRunMigrationsOnDb_upDownUp_sqlite3(t *testing.T) {
	testRunMigrationsOnDb_upDownUp(t, getSqlite3Driver(t))
}
func TestRunMigrationsOnDb_upDownUp_mysql(t *testing.T) {
	testRunMigrationsOnDb_upDownUp(t, getMysqlDriver(t))
}
func TestRunMigrationsOnDb_upDownUp_postgres(t *testing.T) {
	testRunMigrationsOnDb_upDownUp(t, getPostgresDriver(t))
}
func TestRunMigrationsOnDb_upDownUp_redshift(t *testing.T) {
	testRunMigrationsOnDb_upDownUp(t, getRedshiftDriver(t))
}


text:
require File.expand_path('../../../test_helper', __FILE__)

module Etsy
  class ListingTest < Test::Unit::TestCase

    context "The Listing class" do

      should "be able to find a single listing" do
        listings = mock_request('/listings/123', {}, 'Listing', 'getListing.single.json')
        Listing.find(123).should == listings.first
      end

      should "be able to find multiple listings" do
        listings = mock_request('/listings/123,456', {}, 'Listing', 'getListing.multiple.json')
        Listing.find('123', '456').should == listings
      end

      context "within the scope of a shop" do

        should "be able to find the first 25 active listings" do
          listings = mock_request('/shops/1/listings/active', {}, 'Listing', 'findAllShopListings.json')
          Listing.find_all_by_shop_id(1).should == listings
        end

        should "be able to find expired listings" do
          listings = mock_request('/shops/1/listings/expired', {}, 'Listing', 'findAllShopListings.json')
          Listing.find_all_by_shop_id(1, :state => :expired).should == listings
        end

        should "be able to find inactive listings" do
          listings = mock_request('/shops/1/listings/inactive', {}, 'Listing', 'findAllShopListings.json')
          Listing.find_all_by_shop_id(1, :state => :inactive).should == listings
        end

        should "be able to find draft listings" do
          listings = mock_request('/shops/1/listings/draft', {}, 'Listing', 'findAllShopListings.json')
          Listing.find_all_by_shop_id(1, :state => :draft).should == listings
        end

        should "be able to find sold_out listings" do
          listings = mock_request('/shops/1/listings/sold_out', {}, 'Listing', 'findAllShopListings.json')
          Listing.find_all_by_shop_id(1, :state => :sold_out).should == listings
        end

        should "be able to find featured listings" do
          listings = mock_request('/shops/1/listings/featured', {}, 'Listing', 'findAllShopListings.json')
          Listing.find_all_by_shop_id(1, :state => :featured).should == listings
        end

        should "be able to find sold listings" do
          transaction_1 = stub(:listing_id => 1)
          transaction_2 = stub(:listing_id => 2)
          transaction_3 = stub(:listing_id => 1)

          transactions = [transaction_1, transaction_2, transaction_3]

          Transaction.stubs(:find_all_by_shop_id).with(1, {}).returns(transactions)
          Listing.stubs(:find).with([1, 2], {}).returns(['listings'])

          Listing.find_all_by_shop_id(1, :state => :sold).should == ['listings']
        end

        should "defer associations to listings from transaction (sold listings)" do
          transaction_1 = stub(:listing_id => 1)
          transaction_2 = stub(:listing_id => 2)

          Transaction.stubs(:find_all_by_shop_id).with(1, {}).returns [transaction_1, transaction_2]
          Listing.stubs(:find).with([1, 2], {:includes => :an_association}).returns(['listings'])

          Listing.find_all_by_shop_id(1, :state => :sold, :includes => :an_association).should == ['listings']
        end

        should "pass options through to the listing call" do
          transaction_1 = stub(:listing_id => 1)
          transaction_2 = stub(:listing_id => 2)

          Transaction.stubs(:find_all_by_shop_id).with(1, {:other => :params}).returns [transaction_1, transaction_2]
          Listing.stubs(:find).with([1, 2], {:other => :params}).returns(['listings'])

          Listing.find_all_by_shop_id(1, :state => :sold, :other => :params).should == ['listings']

        end

        should "not ask the API for listings if there are no transactions" do
          Transaction.stubs(:find_all_by_shop_id).with(1, {}).returns([])
          Listing.expects(:find).never
          Listing.sold_listings(1, {})
        end

        should "be able to override limit and offset" do
          options = {:limit => 100, :offset => 100}
          listings = mock_request('/shops/1/listings/active', options, 'Listing', 'findAllShopListings.json')
          Listing.find_all_by_shop_id(1, options).should == listings
        end

        should "raise an exception when calling with an invalid state" do
          options = {:state => :awesome}
          lambda { Listing.find_all_by_shop_id(1, options) }.should raise_error(ArgumentError)
        end

      end

      context "within the scope of a category" do
        should "be able to find active listings" do
          active_listings = mock_request('/listings/active', {:category => 'accessories'}, 'Listing', 'findAllListingActive.category.json')
          Listing.find_all_active_by_category('accessories').should == active_listings
        end
      end

    end

    context "An instance of the Listing class" do

      context "with response data" do
        setup do
          data = read_fixture('listing/findAllShopListings.json')
          @listing = Listing.new(data.first)
        end

        should "have a value for :id" do
          @listing.id.should == 59495892
        end

        should "have a value for :state" do
          @listing.state.should == 'active'
        end

        should "have a value for :title" do
          @listing.title.should == "initials carved into tree love stamp"
        end

        should "have a value for :description" do
          @listing.description.should == "there! our initials are now carved deeply into this rough tree bark of memory"
        end

        should "have a value for :url" do
          @listing.url.should == "http://www.etsy.com/listing/59495892/initials-carved-into-tree-love-stamp"
        end

        should "have a value for :view_count" do
          @listing.view_count.should == 37
        end

        should "have a value for :created_at" do
          @listing.created_at.should == Time.at(1287602289)
        end

        should "have a value for :modified_at" do
          @listing.modified_at.should == Time.at(1287602289)
        end

        should "have a value for :price" do
          @listing.price.should == "15.00"
        end

        should "have a value for :quantity" do
          @listing.quantity.should == 1
        end

        should "have a value for :currency" do
          @listing.currency.should == "USD"
        end

        should "have a value for :ending_at" do
          @listing.ending_at.should == Time.at(1298178000)
        end

        should "have a value for :tags" do
          @listing.tags.should == %w(tag_1 tag_2)
        end

        should "have a value for :materials" do
          @listing.materials.should == %w(material_1 material_2)
        end

        should "have a value for :hue" do
          @listing.hue.should == 0
        end

        should "have a value for :saturation" do
          @listing.saturation.should == 0
        end

        should "have a value for :brightness" do
          @listing.brightness.should == 100
        end

        should "have a value for :black_and_white?" do
          @listing.black_and_white?.should == false
        end
      end

      %w(active removed sold_out expired alchemy).each do |state|
        should "know that the listing is #{state}" do
          listing = Listing.new
          listing.expects(:state).with().returns(state.sub('_', ''))

          listing.send("#{state}?".to_sym).should be(true)
        end

        should "know that the listing is not #{state}" do
          listing = Listing.new
          listing.expects(:state).with().returns(state.reverse)

          listing.send("#{state}?".to_sym).should be(false)
        end
      end

      context "with oauth" do
        should "have a collection of images" do
          listing = Listing.new
          listing.stubs(:id).with().returns(1)
          listing.stubs(:token).with().returns("token")
          listing.stubs(:secret).with().returns("secret")

          Image.stubs(:find_all_by_listing_id).with(1, {access_token: "token", access_secret: "secret"}).returns('images')

          listing.images.should == 'images'
        end
      end

      context "without oauth" do
        should "have a collection of images" do
          listing = Listing.new
          listing.stubs(:id).with().returns(1)

          Image.stubs(:find_all_by_listing_id).with(1, {}).returns('images')

          listing.images.should == 'images'
        end
      end

      should "have a default image" do
        listing = Listing.new
        listing.stubs(:images).with().returns(%w(image_1 image_2))

        listing.image.should == 'image_1'
      end

    end

    context "with favorite listings data" do
        setup do
          data = read_fixture('listing/findAllShopListings.json')
          @listing = Listing.new(data.first)
          listing_1 = stub(:listing_id => @listing.id, :user_id => 1)
          listing_2 = stub(:listing_id => @listing.id, :user_id => 2)
          @favorite_listings = [listing_1, listing_2]
        end

        should "have all listings" do
          FavoriteListing.stubs(:find_all_listings_favored_by).with(@listing.id, {:access_token => nil, :access_secret => nil}).returns(@favorite_listings)
          User.stubs(:find).with([1, 2], {:access_token => nil, :access_secret => nil}).returns(['users'])
          @listing.admirers({:access_token => nil, :access_secret => nil}).should == ['users']
        end
      end
  end
end


text:
/* eslint-disable @angular-eslint/component-selector */
/* eslint-disable @angular-eslint/directive-selector */
import { CommonModule, NgClass } from '@angular/common';
import {
  AfterContentChecked,
  AfterContentInit,
  AfterViewChecked,
  AfterViewInit,
  ChangeDetectorRef,
  Component,
  Directive,
  ElementRef,
  EventEmitter,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  Output,
  SimpleChange,
  Type,
  ViewContainerRef,
} from '@angular/core';

import { TestFixture, TestSetup } from '../../test';
import { ComponentOutletInjectorDirective } from '../component-outlet';
import { DynamicComponent as NdcDynamicComponent } from '../dynamic.component';
import { IoFactoryService } from '../io';
import {
  DirectiveRef,
  DynamicDirectiveDef,
  dynamicDirectiveDef,
  DynamicDirectivesDirective,
} from './dynamic-directives.directive';

describe('Directive: DynamicDirectives', () => {
  @Component({ selector: 'dynamic', template: `` })
  class DynamicComponent {}

  @Component({
    selector: 'host',
    template: `<ng-container
      [ngComponentOutlet]="component"
      [ndcDynamicDirectives]="directives"
      (ndcDynamicDirectivesCreated)="onCreated($event)"
    ></ng-container>`,
  })
  class HostComponent {
    component?: Type<any> | null;
    directives?: DynamicDirectiveDef<any>[] | null;
    onCreated = jest.fn();
  }

  @Directive({ selector: '[mock]' })
  class MockDirective
    implements
      OnInit,
      OnDestroy,
      OnChanges,
      AfterViewInit,
      AfterViewChecked,
      AfterContentInit,
      AfterContentChecked
  {
    static INSTANCES = new Set<MockDirective>();
    @Input()
    set in(val: any) {
      this.logHook('inputSet:' + val)();
      this._in = val;
    }
    get in(): any {
      return this._in;
    }
    private _in: any;
    @Input()
    in2: any;
    @Output()
    out = new EventEmitter<any>();
    @Output()
    out2 = new EventEmitter<any>();
    hooksOrder: string[] = [];
    ngAfterContentChecked = jest
      .fn()
      .mockImplementation(this.logHook('ngAfterContentChecked'));
    ngAfterContentInit = jest
      .fn()
      .mockImplementation(this.logHook('ngAfterContentInit'));
    ngAfterViewChecked = jest
      .fn()
      .mockImplementation(this.logHook('ngAfterViewChecked'));
    ngAfterViewInit = jest
      .fn()
      .mockImplementation(this.logHook('ngAfterViewInit'));
    ngOnChanges = jest.fn().mockImplementation(this.logHook('ngOnChanges'));
    ngOnInit = jest.fn().mockImplementation(this.logHook('ngOnInit'));
    ngDoCheck = jest.fn().mockImplementation(this.logHook('ngDoCheck'));
    ngOnDestroy = jest.fn().mockImplementation(() => {
      this.logHook('ngOnDestroy')();
      MockDirective.INSTANCES.delete(this);
    });
    constructor() {
      MockDirective.INSTANCES.add(this);
    }
    private logHook(name: string) {
      return () => this.hooksOrder.push(name);
    }
  }

  @Directive({ selector: '[mock2]' })
  class Mock2Directive extends MockDirective {}

  class DirectivesTestFixture<THost> extends TestFixture<THost> {
    getDirectives() {
      return Array.from(MockDirective.INSTANCES);
    }
    getFirstDirective() {
      return this.getDirectives().shift();
    }
    getLastDirective() {
      return this.getDirectives().pop();
    }
  }

  const testSetup = new TestSetup(HostComponent, {
    props: { component: DynamicComponent },
    ngModule: {
      declarations: [
        DynamicDirectivesDirective,
        ComponentOutletInjectorDirective,
        HostComponent,
        DynamicComponent,
      ],
      providers: [IoFactoryService],
    },
    fixtureCtor: DirectivesTestFixture,
  });

  beforeEach(() => {
    MockDirective.INSTANCES.clear();
  });

  describe('directives', () => {
    it('should init directives', async () => {
      const directives = [
        dynamicDirectiveDef(MockDirective),
        dynamicDirectiveDef(Mock2Directive),
      ];

      const fixture = await testSetup.redner();

      expect(MockDirective.INSTANCES.size).toBe(0);

      fixture.setHostProps({ directives });

      expect(MockDirective.INSTANCES.size).toBe(2);
    });

    it('should destroy all directives', async () => {
      const directives = [
        dynamicDirectiveDef(MockDirective),
        dynamicDirectiveDef(Mock2Directive),
      ];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(2);

      fixture.setHostProps({ directives: null });

      expect(MockDirective.INSTANCES.size).toBe(0);
    });

    it('should call static life-cycle hooks in order', async () => {
      const directives = [dynamicDirectiveDef(MockDirective)];

      const fixture = await testSetup.redner({ props: { directives } });

      const dir = fixture.getFirstDirective()!;

      expect(dir).toBeDefined();
      expect(dir.ngOnInit).toHaveBeenCalledTimes(1);
      expect(dir.ngAfterContentInit).toHaveBeenCalledTimes(1);
      expect(dir.ngAfterContentChecked).toHaveBeenCalledTimes(1);
      expect(dir.ngAfterViewInit).toHaveBeenCalledTimes(1);
      expect(dir.ngAfterViewChecked).toHaveBeenCalledTimes(1);

      // Verify order
      expect(dir.hooksOrder).toEqual([
        'ngOnInit',
        'ngDoCheck',
        'ngAfterContentInit',
        'ngAfterContentChecked',
        'ngAfterViewInit',
        'ngAfterViewChecked',
      ]);
    });

    // Due to removed OnChanges notification functionality for components
    // Directives now do not have a way to get OnChanges notifications
    xit('should set inputs before ngOnInit hook called', async () => {
      const directives = [dynamicDirectiveDef(MockDirective, { in: true })];

      const fixture = await testSetup.redner({ props: { directives } });

      const dir = fixture.getFirstDirective()!;

      expect(dir).toBeDefined();
      expect(dir.hooksOrder).toEqual([
        'inputSet:true',
        'ngOnChanges',
        'ngOnInit',
        'ngDoCheck',
        'ngAfterContentInit',
        'ngAfterContentChecked',
        'ngAfterViewInit',
        'ngAfterViewChecked',
      ]);
    });

    it('should not init directives of same type', async () => {
      const directives = [
        dynamicDirectiveDef(MockDirective),
        dynamicDirectiveDef(MockDirective),
        dynamicDirectiveDef(MockDirective),
      ];

      await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(1);
    });

    it('should init added directive', async () => {
      const directives = [dynamicDirectiveDef(MockDirective)];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(1);

      fixture.setHostProps({
        directives: [
          dynamicDirectiveDef(MockDirective),
          dynamicDirectiveDef(Mock2Directive),
        ],
      });

      expect(MockDirective.INSTANCES.size).toBe(2);
    });

    it('should init pushed directive', async () => {
      const directives = [dynamicDirectiveDef(MockDirective)];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(1);

      directives.push(dynamicDirectiveDef(Mock2Directive));

      fixture.detectChanges();

      expect(MockDirective.INSTANCES.size).toBe(2);
    });

    it('should destroy removed directive', async () => {
      const directives = [
        dynamicDirectiveDef(MockDirective),
        dynamicDirectiveDef(Mock2Directive),
      ];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(2);

      fixture.setHostProps({
        directives: [dynamicDirectiveDef(MockDirective)],
      });

      expect(MockDirective.INSTANCES.size).toBe(1);
    });

    it('should not do anything when no component', async () => {
      const directives = [dynamicDirectiveDef(MockDirective)];

      await testSetup.redner({
        props: { directives, component: null },
      });

      expect(MockDirective.INSTANCES.size).toBe(0);
    });

    it('should destroy directives when component unset', async () => {
      const directives = [dynamicDirectiveDef(MockDirective)];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(1);

      const dir = fixture.getFirstDirective()!;

      fixture.setHostProps({ component: null });

      expect(MockDirective.INSTANCES.size).toBe(0);
      expect(dir).toBeDefined();
      expect(dir.ngOnDestroy).toHaveBeenCalledTimes(1);
    });

    it('should re-create directives when component changed', async () => {
      @Component({ selector: 'dynamic2', template: '' })
      class Dynamic2Component {}

      const directives = [dynamicDirectiveDef(MockDirective)];

      const fixture = await testSetup.redner({
        props: { directives },
        ngModule: { declarations: [Dynamic2Component] },
      });

      expect(MockDirective.INSTANCES.size).toBe(1);

      const dir1 = fixture.getFirstDirective();

      fixture.setHostProps({ component: Dynamic2Component });

      expect(MockDirective.INSTANCES.size).toBe(1);

      const dir2 = fixture.getFirstDirective();

      expect(dir1).not.toBe(dir2);
    });
  });

  describe('@Output(ndcDynamicDirectivesCreated)', () => {
    it('should emit with dynamic directive refs', async () => {
      const directives = [dynamicDirectiveDef(MockDirective)];

      const fixture = await testSetup.redner({ props: { directives } });

      const dir = fixture.getFirstDirective();

      expect(fixture.getHost().onCreated).toHaveBeenCalledWith([
        expect.objectContaining({
          type: MockDirective,
          instance: dir,
        }),
      ]);
    });

    it('should emit with only added directive refs', async () => {
      const directives = [dynamicDirectiveDef(MockDirective)];

      const fixture = await testSetup.redner({ props: { directives } });

      fixture.getHost().onCreated.mockClear();

      fixture.setHostProps({
        directives: [
          dynamicDirectiveDef(MockDirective),
          dynamicDirectiveDef(Mock2Directive),
        ],
      });

      const lastDir = fixture.getLastDirective();

      expect(fixture.getHost().onCreated).toHaveBeenCalledTimes(1);
      expect(fixture.getHost().onCreated).toHaveBeenCalledWith([
        expect.objectContaining({
          type: Mock2Directive,
          instance: lastDir,
        }),
      ]);
    });
  });

  describe('injector', () => {
    it('should be able to inject `ElementRef`', async () => {
      @Directive({ selector: '[test]' })
      class TestDirective {
        constructor(public elem: ElementRef) {}
      }
      const directives = [dynamicDirectiveDef(TestDirective)];

      const fixture = await testSetup.redner({
        props: { directives },
        ngModule: { declarations: [TestDirective] },
      });

      const dir = fixture.getHost().onCreated.mock
        .lastCall[0][0] as DirectiveRef<TestDirective>;

      expect(dir.instance.elem).toBeInstanceOf(ElementRef);
    });

    it('should be able to inject `ChangeDetectorRef`', async () => {
      @Directive({ selector: '[test]' })
      class TestDirective {
        constructor(public cdr: ChangeDetectorRef) {}
      }
      const directives = [dynamicDirectiveDef(TestDirective)];

      const fixture = await testSetup.redner({
        props: { directives },
        ngModule: { declarations: [TestDirective] },
      });

      const dir = fixture.getHost().onCreated.mock
        .lastCall[0][0] as DirectiveRef<TestDirective>;

      expect(dir.instance.cdr).toEqual(
        expect.objectContaining(ChangeDetectorRef.prototype),
      );
    });

    it('should be able to inject `ViewContainerRef`', async () => {
      @Directive({ selector: '[test]' })
      class TestDirective {
        constructor(public vcr: ViewContainerRef) {}
      }
      const directives = [dynamicDirectiveDef(TestDirective)];

      const fixture = await testSetup.redner({
        props: { directives },
        ngModule: { declarations: [TestDirective] },
      });

      const dir = fixture.getHost().onCreated.mock
        .lastCall[0][0] as DirectiveRef<TestDirective>;

      expect(dir.instance.vcr).toEqual(
        expect.objectContaining(ViewContainerRef.prototype),
      );
    });
  });

  describe('directive inputs', () => {
    it('should set inputs on directive instance', async () => {
      const directives = [
        dynamicDirectiveDef(MockDirective, { in: 'in' }),
        dynamicDirectiveDef(Mock2Directive, { in2: 'in2' }),
      ];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(2);

      const [dir1, dir2] = fixture.getDirectives();

      expect(dir1.in).toBe('in');
      expect(dir2.in2).toBe('in2');
    });

    // BUG: OnCHanges are not called on dynamic directives currently
    xit('should call `OnChanges` hook with initial changes', async () => {
      const directives = [
        dynamicDirectiveDef(MockDirective, { in: 'val1' }),
        dynamicDirectiveDef(Mock2Directive, { in2: 'val2' }),
      ];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(2);

      const [dir1, dir2] = fixture.getDirectives();

      expect(dir1.ngOnChanges).toHaveBeenCalledWith({
        in: new SimpleChange(undefined, 'val1', true),
      });
      expect(dir2.ngOnChanges).toHaveBeenCalledWith({
        in2: new SimpleChange(undefined, 'val2', true),
      });
    });

    // BUG: OnCHanges are not called on dynamic directives currently
    xit('should call `OnChanges` when inputs change', async () => {
      const inputs1 = { in: 'val1' };
      const inputs2 = { in2: 'val2' };
      const directives = [
        dynamicDirectiveDef(MockDirective, inputs1),
        dynamicDirectiveDef(Mock2Directive, inputs2),
      ];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(2);

      const [dir1, dir2] = fixture.getDirectives();

      dir1.ngOnChanges.mockReset();
      dir2.ngOnChanges.mockReset();

      inputs1.in = 'new-val1';
      inputs2.in2 = 'new-val2';
      fixture.detectChanges();

      expect(dir1.ngOnChanges).toHaveBeenCalledWith({
        in: new SimpleChange('val1', 'new-val1', false),
      });
      expect(dir2.ngOnChanges).toHaveBeenCalledWith({
        in2: new SimpleChange('val2', 'new-val2', false),
      });

      dir1.ngOnChanges.mockReset();
      dir2.ngOnChanges.mockReset();

      inputs2.in2 = 'another-val2';
      fixture.detectChanges();

      expect(dir1.ngOnChanges).not.toHaveBeenCalled();
      expect(dir2.ngOnChanges).toHaveBeenCalledWith({
        in2: new SimpleChange('new-val2', 'another-val2', false),
      });
    });

    // BUG: OnCHanges are not called on dynamic directives currently
    xit('should call `OnChanges` when inputs replaced', async () => {
      const dirDef1 = dynamicDirectiveDef(MockDirective, { in: 'val1' });
      const dirDef2 = dynamicDirectiveDef(Mock2Directive, { in2: 'val2' });
      const directives = [dirDef1, dirDef2];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(2);

      const [dir1, dir2] = fixture.getDirectives();

      dir1.ngOnChanges.mockReset();
      dir2.ngOnChanges.mockReset();

      dirDef1.inputs = { in: 'new-val1' };
      fixture.detectChanges();

      expect(dir1.ngOnChanges).toHaveBeenCalledWith({
        in: new SimpleChange('val1', 'new-val1', false),
      });
      expect(dir2.ngOnChanges).not.toHaveBeenCalled();

      dir1.ngOnChanges.mockReset();
      dir2.ngOnChanges.mockReset();

      dirDef2.inputs = { in2: 'new-val2' };
      fixture.detectChanges();

      expect(dir1.ngOnChanges).not.toHaveBeenCalled();
      expect(dir2.ngOnChanges).toHaveBeenCalledWith({
        in2: new SimpleChange('val2', 'new-val2', false),
      });
    });
  });

  describe('directive outputs', () => {
    it('should be connected', async () => {
      const callback1 = jest.fn();
      const callback2 = jest.fn();
      const directives = [
        dynamicDirectiveDef(MockDirective, undefined, { out: callback1 }),
        dynamicDirectiveDef(Mock2Directive, undefined, { out: callback2 }),
      ];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(2);

      const [dir1, dir2] = fixture.getDirectives();

      dir1.out.emit('data1');
      dir2.out.emit('data2');

      expect(callback1).toHaveBeenCalledWith('data1');
      expect(callback2).toHaveBeenCalledWith('data2');
    });

    it('should be connected when changed and disconnected from old', async () => {
      const callback = jest.fn();
      const outputs = { out: callback };
      const directives = [
        dynamicDirectiveDef(MockDirective, undefined, outputs),
      ];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(1);

      const dir = fixture.getFirstDirective()!;

      const callback2 = jest.fn();
      outputs.out = callback2;

      fixture.detectChanges();

      dir.out.emit('data');

      expect(callback2).toHaveBeenCalledWith('data');
      expect(callback).not.toHaveBeenCalled();
    });

    it('should disconnect when removed', async () => {
      const callback = jest.fn();
      const outputs = { out: callback };
      const directives = [
        dynamicDirectiveDef(MockDirective, undefined, outputs),
      ];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(1);

      const dir = fixture.getFirstDirective()!;

      outputs.out = null!;

      fixture.detectChanges();

      dir.out.emit('data');

      expect(callback).not.toHaveBeenCalled();
    });

    it('should disconnect when host component destroyed', async () => {
      const callback = jest.fn();
      const directives = [
        dynamicDirectiveDef(MockDirective, undefined, { out: callback }),
      ];

      const fixture = await testSetup.redner({ props: { directives } });

      expect(MockDirective.INSTANCES.size).toBe(1);

      const dir = fixture.getFirstDirective()!;

      fixture.setHostProps({ component: null });

      dir.out.emit('data');

      expect(callback).not.toHaveBeenCalled();
    });
  });

  describe('integration', () => {
    it('should apply NgClass', async () => {
      const directives = [
        dynamicDirectiveDef(NgClass, { ngClass: 'cls1 cls2' }),
      ];

      const fixture = await testSetup.redner({
        props: { directives },
        ngModule: { imports: [CommonModule] },
      });

      const dynamicElem = fixture.getComponentElement(DynamicComponent)!;

      expect(dynamicElem).toBeTruthy();
      expect(dynamicElem.classes).toEqual({ cls1: true, cls2: true });
    });

    it('should work with `ngComponentOutlet` * syntax', async () => {
      const directives = [
        dynamicDirectiveDef(NgClass, { ngClass: 'cls1 cls2' }),
      ];

      const fixture = await testSetup.redner({
        props: { directives },
        template: `
          <ng-container
            *ngComponentOutlet="component; ndcDynamicDirectives: directives"
          ></ng-container>
        `,
        ngModule: { imports: [CommonModule] },
      });

      const dynamicElem = fixture.getComponentElement(DynamicComponent)!;

      expect(dynamicElem).toBeTruthy();
      expect(dynamicElem.classes).toEqual({ cls1: true, cls2: true });
    });

    it('should work with `ndc-dynamic`', async () => {
      const directives = [
        dynamicDirectiveDef(NgClass, { ngClass: 'cls1 cls2' }),
      ];

      const fixture = await testSetup.redner({
        props: { directives },
        template: `
          <ndc-dynamic
            [ndcDynamicComponent]="component"
            [ndcDynamicDirectives]="directives"
          ></ndc-dynamic>
        `,
        ngModule: {
          imports: [CommonModule],
          declarations: [NdcDynamicComponent],
        },
      });

      const dynamicElem = fixture.getComponentElement(DynamicComponent)!;

      expect(dynamicElem).toBeTruthy();
      expect(dynamicElem.classes).toEqual({ cls1: true, cls2: true });
    });
  });
});


text:
jQuery.fn.listAttributes = function(prefix) {
	var list = [];
	$(this).each(function() {
		// console.info(this);
		var attributes = [];
		for(var key in this.attributes) {
			if(!isNaN(key)) {
				if(!prefix || this.attributes[key].name.substr(0,prefix.length) == prefix) {
					attributes.push(this.attributes[key].name);
				}
			}
		}
		list.push(attributes);
	});
	return (list.length > 1 ? list : list[0]);
};


text:
module.exports = function(element, fn) {
  var window = this;
  var document = window.document;

  var attachEvent = document.attachEvent;
  if (typeof navigator !== "undefined") {
    var isIE = navigator.userAgent.match(/Trident/);
  }

  var requestFrame = (function() {
    var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(fn) {
        return window.setTimeout(fn, 20);
      };
    return function(fn) {
      return raf(fn);
    };
  })();

  var cancelFrame = (function() {
    var cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame ||
      window.clearTimeout;
    return function(id) {
      return cancel(id);
    };
  })();

  function resizeListener(e) {
    var win = e.target || e.srcElement;
    if (win.__resizeRAF__) {
      cancelFrame(win.__resizeRAF__);
    }
    win.__resizeRAF__ = requestFrame(function() {
      var trigger = win.__resizeTrigger__;
      trigger.__resizeListeners__.forEach(function(fn) {
        fn.call(trigger, e);
      });
    });
  }

  function objectLoad(e) {
    this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__;
    this.contentDocument.defaultView.addEventListener('resize', resizeListener);
  }

  if (!element.__resizeListeners__) {
    element.__resizeListeners__ = [];
    if (attachEvent) {
      element.__resizeTrigger__ = element;
      element.attachEvent('onresize', resizeListener);
    } else {
      if (getComputedStyle(element).position == 'static') {
        element.style.position = 'relative';
      }
      var obj = element.__resizeTrigger__ = document.createElement('object');
      obj.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
      obj.setAttribute('class', 'resize-sensor');
      obj.__resizeElement__ = element;
      obj.onload = objectLoad;
      obj.type = 'text/html';
      if (isIE) {
        element.appendChild(obj);
      }
      obj.data = 'about:blank';
      if (!isIE) {
        element.appendChild(obj);
      }
    }
  }
  element.__resizeListeners__.push(fn);
};


text:
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import { LoadableThanks } from './index'
import { actions as petitionActions } from '../actions/petitionActions'

// This component is used in place of the Thanks component after a user has signed a petition,
// for creating a petition, see CreateFinished
// and handles lazy-loading the actual Thanks component (with LoadableThanks)
class ThanksShim extends React.Component {
  componentWillMount() {
    const { dispatch, petition } = this.props
    if (!petition) {
      const query = this.props.location.query
      if (query.name) {
        dispatch(petitionActions.loadPetition(query.name))
      } else if (query.petition_id) {
        dispatch(petitionActions.loadPetition(query.petition_id))
      }
    }
  }

  render() {
    return (
      <div className='moveon-petitions share container background-moveon-white bump-top-1'>
        {(this.props.petition ?
          <LoadableThanks
            petition={this.props.petition}
            signatureMessage={this.props.signatureMessage}
            fromSource={this.props.location.query.from_source}
          />
          : ''
        )}
      </div>
    )
  }
}

ThanksShim.propTypes = {
  petition: PropTypes.object,
  signatureMessage: PropTypes.object,
  dispatch: PropTypes.func,
  location: PropTypes.object
}

function mapStateToProps(store, ownProps) {
  const pkey = ownProps.location.query.name || ownProps.location.query.petition_id
  const petition = pkey && store.petitionStore.petitions[pkey]
  return {
    petition,
    searchQuery: {},
    signatureMessage: (petition
                       && petition.petition_id
                       && store.petitionStore.signatureMessages
                       && store.petitionStore.signatureMessages[petition.petition_id])
  }
}

export default connect(mapStateToProps)(ThanksShim)


text:
namespace base {
class SingleThreadTaskRunner;
}

namespace data_usage {
struct DataUse;
}

namespace chrome {

namespace android {

class ExternalDataUseObserverBridge;

// This class allows platform APIs that are external to Chromium to observe how
// much data is used by Chromium on the current Android device. This class
// registers as a data use observer with DataUseAggregator (as long as there is
// at least one valid matching rule is present), filters the received
// observations by applying the regex matching to the URLs of the requests, and
// notifies the filtered data use to the platform. This class is not thread
// safe, and must only be accessed on IO thread.
class ExternalDataUseObserver : public data_usage::DataUseAggregator::Observer {
 public:
  // Result of data usage report submission.  This enum must remain synchronized
  // with the enum of the same name in metrics/histograms/histograms.xml.
  enum DataUsageReportSubmissionResult {
    // Submission of data use report to the external observer was successful.
    DATAUSAGE_REPORT_SUBMISSION_SUCCESSFUL = 0,
    // Submission of data use report to the external observer returned error.
    DATAUSAGE_REPORT_SUBMISSION_FAILED = 1,
    // Submission of data use report to the external observer timed out.
    DATAUSAGE_REPORT_SUBMISSION_TIMED_OUT = 2,
    // Data use report was lost before an attempt was made to submit it.
    DATAUSAGE_REPORT_SUBMISSION_LOST = 3,
    DATAUSAGE_REPORT_SUBMISSION_MAX = 4
  };

  // External data use observer field trial name.
  static const char kExternalDataUseObserverFieldTrial[];

  ExternalDataUseObserver(
      data_usage::DataUseAggregator* data_use_aggregator,
      const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
      const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner);
  ~ExternalDataUseObserver() override;

  // Returns the pointer to the DataUseTabModel object owned by |this|. The
  // caller does not owns the returned pointer.
  DataUseTabModel* GetDataUseTabModel() const;

  // Called by ExternalDataUseObserverBridge::OnReportDataUseDone when a data
  // use report has been submitted. |success| is true if the request was
  // successfully submitted to the external data use observer by Java.
  void OnReportDataUseDone(bool success);

  // Called by ExternalDataUseObserverBridge. |should_register| is true if
  // |this| should register as a data use observer.
  void ShouldRegisterAsDataUseObserver(bool should_register);

  // Fetches the matching rules asynchronously.
  void FetchMatchingRules();

  base::WeakPtr<ExternalDataUseObserver> GetWeakPtr();

 private:
  friend class DataUseTabModelTest;
  friend class DataUseUITabModelTest;
  friend class ExternalDataUseObserverTest;
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest, BufferDataUseReports);
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest, BufferSize);
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest, DataUseReportTimedOut);
#if defined(OS_ANDROID)
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest,
                           DataUseReportingOnApplicationStatusChange);
#endif
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest, HashFunction);
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest,
                           MatchingRuleFetchOnControlAppInstall);
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest, MultipleMatchingRules);
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest,
                           PeriodicFetchMatchingRules);
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest,
                           RegisteredAsDataUseObserver);
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest, ReportsMergedCorrectly);
  FRIEND_TEST_ALL_PREFIXES(DataUseUITabModelTest, ReportTabEventsTest);
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest,
                           TimestampsMergedCorrectly);
  FRIEND_TEST_ALL_PREFIXES(ExternalDataUseObserverTest, Variations);

  // DataUseReportKey is a unique identifier for a data use report.
  struct DataUseReportKey {
    DataUseReportKey(const std::string& label,
                     const std::string& tag,
                     net::NetworkChangeNotifier::ConnectionType connection_type,
                     const std::string& mcc_mnc);

    DataUseReportKey(const DataUseReportKey& other);

    bool operator==(const DataUseReportKey& other) const;

    // Label provided by the matching rules.
    const std::string label;

    // Tag to report for the data usage.
    const std::string tag;

    // Type of network used by the request.
    const net::NetworkChangeNotifier::ConnectionType connection_type;

    // mcc_mnc operator of the provider of the SIM as obtained from
    // TelephonyManager#getNetworkOperator() Java API in Android.
    const std::string mcc_mnc;
  };

  // DataUseReport is paired with a  DataUseReportKey object. DataUseReport
  // contains the bytes send/received during a specific interval. Only the bytes
  // from the data use reports that have the |label|, |connection_type|, and
  // |mcc_mnc| specified in the corresponding DataUseReportKey object are
  // counted in the DataUseReport.
  struct DataUseReport {
    // |start_time| and |end_time| are the start and end timestamps (in UTC
    // since the standard Java epoch of 1970-01-01 00:00:00) of the interval
    // that this data report covers. |bytes_downloaded| and |bytes_uploaded| are
    // the total bytes received and send during this interval.
    DataUseReport(const base::Time& start_time,
                  const base::Time& end_time,
                  int64_t bytes_downloaded,
                  int64_t bytes_uploaded);

    // Start time of |this| data report (in UTC since the standard Java epoch of
    // 1970-01-01 00:00:00).
    const base::Time start_time;

    // End time of |this| data report (in UTC since the standard Java epoch of
    // 1970-01-01 00:00:00)
    const base::Time end_time;

    // Number of bytes downloaded and uploaded by Chromium from |start_time| to
    // |end_time|.
    const int64_t bytes_downloaded;
    const int64_t bytes_uploaded;
  };

  // Class that implements hash operator on DataUseReportKey.
  class DataUseReportKeyHash {
   public:
    // A simple heuristical hash function that satisifes the property that two
    // equal data structures have the same hash value.
    size_t operator()(const DataUseReportKey& k) const;
  };

  typedef base::hash_map<DataUseReportKey, DataUseReport, DataUseReportKeyHash>
      DataUseReports;

  // Maximum buffer size. If an entry needs to be added to the buffer that has
  // size |kMaxBufferSize|, then the oldest entry will be removed.
  static const size_t kMaxBufferSize;

  // data_usage::DataUseAggregator::Observer implementation:
  void OnDataUse(const data_usage::DataUse& data_use) override;

  // Called by DataUseTabModel when tracking info has been retrieved for the
  // |data_use| object. |tracking_info_valid| is true if |tracking_info| is
  // populated that applies to the |data_use| object. |tracking_info| is owned
  // by the caller.
  void DataUseTrackingInfoRetrieved(
      const data_usage::DataUse& data_use,
      const base::Time& start_time,
      const base::Time& end_time,
      const DataUseTabModel::TrackingInfo* tracking_info,
      bool tracking_info_valid);

  // Adds |data_use| to buffered reports. |data_use| is the data use report
  // received from DataUseAggregator. |label| is a non-empty label that applies
  // to |data_use|. |tag| is the tag to be applied for this data use.
  // |start_time| and |end_time| are the start, and end times of the interval
  // during which bytes reported in |data_use| went over the network.
  void BufferDataUseReport(const data_usage::DataUse& data_use,
                           const std::string& label,
                           const std::string& tag,
                           const base::Time& start_time,
                           const base::Time& end_time);

  // Submits the first data report among the buffered data reports in
  // |buffered_data_reports_|. Since an unordered map is used to buffer the
  // reports, the order of reports may change. The reports are buffered in an
  // arbitrary order and there are no guarantees that the next report to be
  // submitted is the oldest one buffered. |immediate| indicates whether to
  // submit the report immediately or to wait until |data_use_report_min_bytes_|
  // unreported bytes are buffered.
  void SubmitBufferedDataUseReport(bool immediate);

#if defined(OS_ANDROID)
  // Called whenever the application transitions from foreground to background
  // or vice versa.
  void OnApplicationStateChange(base::android::ApplicationState new_state);
#endif

  // Aggregator that sends data use observations to |this|.
  data_usage::DataUseAggregator* data_use_aggregator_;

  // |external_data_use_observer_bridge_| is owned by |this|, and interacts with
  // the Java code. It is created on IO thread but afterwards, should only be
  // accessed on UI thread.
  ExternalDataUseObserverBridge* external_data_use_observer_bridge_;

  // Maintains tab sessions and is owned by |this|. It is created on IO thread
  // but afterwards, should only be accessed on UI thread.
  DataUseTabModel* data_use_tab_model_;

  // Time when the currently pending data use report was submitted.
  // |last_data_report_submitted_ticks_| is null if no data use report is
  // currently pending.
  base::TimeTicks last_data_report_submitted_ticks_;

  // |pending_report_bytes_| is the total byte count in the data use report that
  // is currently pending.
  int64_t pending_report_bytes_;

  // Buffered data reports that need to be submitted to the
  // |external_data_use_observer_bridge_|.
  DataUseReports buffered_data_reports_;

  // |ui_task_runner_| is used to call methods on UI thread.
  scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;

  // Time when the data use reports were last received from DataUseAggregator.
  base::Time previous_report_time_;

  // Time when the matching rules were last fetched.
  base::TimeTicks last_matching_rules_fetch_time_;

  // Total number of bytes transmitted or received across all the buffered
  // reports.
  int64_t total_bytes_buffered_;

  // Duration after which matching rules are periodically fetched.
  const base::TimeDelta fetch_matching_rules_duration_;

  // Minimum number of bytes that should be buffered before a data use report is
  // submitted.
  const int64_t data_use_report_min_bytes_;

  // If a data use report is pending for more than |data_report_submit_timeout_|
  // duration, it is considered as timed out.
  const base::TimeDelta data_report_submit_timeout_;

#if defined(OS_ANDROID)
  // Listens to when Chromium gets backgrounded and submits buffered data use
  // reports.
  std::unique_ptr<base::android::ApplicationStatusListener> app_state_listener_;
#endif

  // True if |this| is currently registered as a data use observer.
  bool registered_as_data_use_observer_;

  base::ThreadChecker thread_checker_;

  base::WeakPtrFactory<ExternalDataUseObserver> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(ExternalDataUseObserver);
};

}  // namespace android

}  // namespace chrome

#endif  // CHROME_BROWSER_ANDROID_DATA_USAGE_EXTERNAL_DATA_USE_OBSERVER_H_


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

package org.chromium.net;

import android.content.Context;
import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.base.PathUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.net.test.EmbeddedTestServer;

import java.io.File;
import java.util.HashMap;

/**
 * Test for deprecated {@link HttpUrlRequest} API.
 */
@SuppressWarnings("deprecation")
public class CronetUrlTest extends CronetTestBase {
    private EmbeddedTestServer mTestServer;
    private String mUrl;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mTestServer = EmbeddedTestServer.createAndStartDefaultServer(getContext());
        mUrl = mTestServer.getURL("/echo?status=200");
    }

    @Override
    protected void tearDown() throws Exception {
        mTestServer.stopAndDestroyServer();
        super.tearDown();
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testLoadUrl() throws Exception {
        CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);

        // Make sure that the URL is set as expected.
        assertEquals(mUrl, testFramework.getUrl());
        assertEquals(200, testFramework.getHttpStatusCode());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testInvalidUrl() throws Exception {
        CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi("127.0.0.1:8000");

        // The load should fail.
        assertEquals(0, testFramework.getHttpStatusCode());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testPostData() throws Exception {
        String[] commandLineArgs = {CronetTestFramework.POST_DATA_KEY, "test",
                CronetTestFramework.LIBRARY_INIT_KEY, CronetTestFramework.LibraryInitType.LEGACY};
        CronetTestFramework testFramework =
                startCronetTestFrameworkWithUrlAndCommandLineArgs(mUrl, commandLineArgs);

        // Make sure that the URL is set as expected.
        assertEquals(mUrl, testFramework.getUrl());
        assertEquals(200, testFramework.getHttpStatusCode());
    }

    @SmallTest
    @Feature({"Cronet"})
    @OnlyRunNativeCronet // No NetLog from HttpURLConnection
    public void testNetLog() throws Exception {
        Context context = getContext();
        File directory = new File(PathUtils.getDataDirectory(context));
        File file = File.createTempFile("cronet", "json", directory);
        HttpUrlRequestFactory factory = HttpUrlRequestFactory.createFactory(
                context,
                new UrlRequestContextConfig().setLibraryName("cronet_tests"));
        // Start NetLog immediately after the request context is created to make
        // sure that the call won't crash the app even when the native request
        // context is not fully initialized. See crbug.com/470196.
        factory.startNetLogToFile(file.getPath(), false);
        // Starts a request.
        HashMap<String, String> headers = new HashMap<String, String>();
        TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
        HttpUrlRequest request = factory.createRequest(
                mUrl, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
        request.start();
        listener.blockForComplete();
        factory.stopNetLog();
        assertTrue(file.exists());
        assertTrue(file.length() != 0);
        assertTrue(file.delete());
        assertTrue(!file.exists());
    }

    static class BadHttpUrlRequestListener extends TestHttpUrlRequestListener {
        static final String THROW_TAG = "BadListener";

        public BadHttpUrlRequestListener() {
        }

        @Override
        public void onResponseStarted(HttpUrlRequest request) {
            throw new NullPointerException(THROW_TAG);
        }
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testCalledByNativeException() throws Exception {
        CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);

        HashMap<String, String> headers = new HashMap<String, String>();
        BadHttpUrlRequestListener listener = new BadHttpUrlRequestListener();

        // Create request with bad listener to trigger an exception.
        HttpUrlRequest request = testFramework.mRequestFactory.createRequest(
                mUrl, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
        request.start();
        listener.blockForComplete();
        assertTrue(request.isCanceled());
        assertNotNull(request.getException());
        assertEquals(BadHttpUrlRequestListener.THROW_TAG,
                     request.getException().getCause().getMessage());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testSetUploadDataWithNullContentType() throws Exception {
        CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);

        HashMap<String, String> headers = new HashMap<String, String>();
        BadHttpUrlRequestListener listener = new BadHttpUrlRequestListener();

        // Create request.
        HttpUrlRequest request = testFramework.mRequestFactory.createRequest(
                mUrl, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
        byte[] uploadData = new byte[] {1, 2, 3};
        try {
            request.setUploadData(null, uploadData);
            fail("setUploadData should throw on null content type");
        } catch (NullPointerException e) {
            // Nothing to do here.
        }
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testLegacyLoadUrl() throws Exception {
        CronetEngine.Builder builder = new CronetEngine.Builder(getContext());
        builder.enableLegacyMode(true);

        CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);

        // Make sure that the URL is set as expected.
        assertEquals(mUrl, testFramework.getUrl());
        assertEquals(200, testFramework.getHttpStatusCode());
    }

    @SmallTest
    @Feature({"Cronet"})
    public void testRequestHead() throws Exception {
        CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);

        HashMap<String, String> headers = new HashMap<String, String>();
        TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();

        // Create request.
        HttpUrlRequest request = testFramework.mRequestFactory.createRequest(
                mUrl, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
        request.setHttpMethod("HEAD");
        request.start();
        listener.blockForComplete();
        assertEquals(200, listener.mHttpStatusCode);
        // HEAD requests do not get any response data and Content-Length must be
        // ignored.
        assertEquals(0, listener.mResponseAsBytes.length);
    }
}


text:
let util = require("../util");

/**
 * Utility Class
 */
class NetworkUtil {
  /**
   * @ignore
   */
  constructor() {}

  /**
   * Find the center position of the network considering the bounding boxes
   *
   * @param {Array.<Node>} allNodes
   * @param {Array.<Node>} [specificNodes=[]]
   * @returns {{minX: number, maxX: number, minY: number, maxY: number}}
   * @static
   */
  static getRange(allNodes, specificNodes = []) {
    var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
    if (specificNodes.length > 0) {
      for (var i = 0; i < specificNodes.length; i++) {
        node = allNodes[specificNodes[i]];
        if (minX > node.shape.boundingBox.left) {
          minX = node.shape.boundingBox.left;
        }
        if (maxX < node.shape.boundingBox.right) {
          maxX = node.shape.boundingBox.right;
        }
        if (minY > node.shape.boundingBox.top) {
          minY = node.shape.boundingBox.top;
        } // top is negative, bottom is positive
        if (maxY < node.shape.boundingBox.bottom) {
          maxY = node.shape.boundingBox.bottom;
        } // top is negative, bottom is positive
      }
    }

    if (minX === 1e9 && maxX === -1e9 && minY === 1e9 && maxY === -1e9) {
      minY = 0, maxY = 0, minX = 0, maxX = 0;
    }
    return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  }

  /**
   * Find the center position of the network
   *
   * @param {Array.<Node>} allNodes
   * @param {Array.<Node>} [specificNodes=[]]
   * @returns {{minX: number, maxX: number, minY: number, maxY: number}}
   * @static
   */
  static getRangeCore(allNodes, specificNodes = []) {
    var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
    if (specificNodes.length > 0) {
      for (var i = 0; i < specificNodes.length; i++) {
        node = allNodes[specificNodes[i]];
        if (minX > node.x) {
          minX = node.x;
        }
        if (maxX < node.x) {
          maxX = node.x;
        }
        if (minY > node.y) {
          minY = node.y;
        } // top is negative, bottom is positive
        if (maxY < node.y) {
          maxY = node.y;
        } // top is negative, bottom is positive
      }
    }

    if (minX === 1e9 && maxX === -1e9 && minY === 1e9 && maxY === -1e9) {
      minY = 0, maxY = 0, minX = 0, maxX = 0;
    }
    return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  }

  /**
   * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
   * @returns {{x: number, y: number}}
   * @static
   */
  static findCenter(range) {
    return {x: (0.5 * (range.maxX + range.minX)),
      y: (0.5 * (range.maxY + range.minY))};
  }

  /**
   * This returns a clone of the options or options of the edge or node to be used for construction of new edges or check functions for new nodes.
   * @param {vis.Item} item
   * @param {'node'|undefined} type
   * @returns {{}}
   * @static
   */
  static cloneOptions(item, type) {
    let clonedOptions = {};
    if (type === undefined || type === 'node') {
      util.deepExtend(clonedOptions, item.options, true);
      clonedOptions.x = item.x;
      clonedOptions.y = item.y;
      clonedOptions.amountOfConnections = item.edges.length;
    }
    else {
      util.deepExtend(clonedOptions, item.options, true);
    }
    return clonedOptions;
  }

}

export default NetworkUtil;


text:
package DiameterOfBinaryTree;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class DiameterOfBinaryTreeSolutionTest {

    private DiameterOfBinaryTreeSolution solution = new DiameterOfBinaryTreeSolution();

    @Test
    public void nullInput() {
        int diameter = solution.diameterOfBinaryTree(null);

        assertThat(diameter).isEqualTo(0);
    }

    @Test
    public void singleNode() {
        int diameter = solution.diameterOfBinaryTree(new TreeNode(1));

        assertThat(diameter).isEqualTo(0);
    }

    @Test
    public void twoNodes() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);

        int diameter = solution.diameterOfBinaryTree(root);

        assertThat(diameter).isEqualTo(1);
    }

    @Test
    public void threeNodes() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);

        int diameter = solution.diameterOfBinaryTree(root);

        assertThat(diameter).isEqualTo(2);
    }

    @Test
    public void fiveNodes() {
        TreeNode root = new TreeNode(1);
        TreeNode left = new TreeNode(2);
        left.left = new TreeNode(4);
        left.right = new TreeNode(5);
        root.left = left;
        root.right = new TreeNode(3);

        int diameter = solution.diameterOfBinaryTree(root);

        assertThat(diameter).isEqualTo(3);
    }

    @Test
    public void diameterWithoutRoot() {
        TreeNode root = new TreeNode(1);
        TreeNode right = new TreeNode(2);
        TreeNode rightLeft = new TreeNode(3);
        rightLeft.left = new TreeNode(5);
        right.left = rightLeft;
        TreeNode rightRight = new TreeNode(4);
        rightRight.right = new TreeNode(6);
        right.right = rightRight;
        root.right = right;

        int diameter = solution.diameterOfBinaryTree(root);

        assertThat(diameter).isEqualTo(4);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/veffectsys.iml" filepath="$PROJECT_DIR$/.idea/veffectsys.iml" />
    </modules>
  </component>
</project>


text:
class TMainForm : public TForm
{
__published:	// IDE-managed Components
	TVirtualStringTree *VST;
	TButton *ClearButton;
	TButton *CloseButton;
	TButton *Button1;
	TButton *AddOneButton;
	TEdit *Edit1;
	TLabel *Label1;
	void __fastcall AddButtonClick(TObject *Sender);
	void __fastcall ClearButtonClick(TObject *Sender);
	void __fastcall CloseButtonClick(TObject *Sender);
	void __fastcall VSTFreeNode(TBaseVirtualTree *Sender, PVirtualNode Node);
	void __fastcall VSTInitNode(TBaseVirtualTree *Sender, PVirtualNode ParentNode, PVirtualNode Node,
          TVirtualNodeInitStates &InitialStates);
	void __fastcall FormCreate(TObject *Sender);
	void __fastcall VSTGetText(TBaseVirtualTree *Sender, PVirtualNode Node, TColumnIndex Column,
          TVSTTextType TextType, UnicodeString &Text);

private:	// User declarations
public:		// User declarations
	__fastcall TMainForm(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TMainForm *MainForm;
//---------------------------------------------------------------------------
#endif


text:
<?php

namespace Helpers\DB;

/**
 * PDO implementation to CRUD
 */
class EntityManager {

    protected static $crud;

    /**
     * Need a connection to the database
     */
    private $dbmanager;

    /**
     * Constructor
     */
    public function __construct() {
        $this->dbmanager = DBManager::getInstance();
    }

    protected function __clone() {
    } // Méthode de clonage en privé aussi.

    public static function getInstance() {
        if (!isset(self::$crud)) // Si on n'a pas encore instancié notre classe.
        {
            self::$crud = new self; // On s'instancie nous-mêmes. :)
        }

        return self::$crud;
    }

    /**
     * Save inside the DB
     */
    public function save($instance) {
        if($instance==false) return;

        if ($instance->isNew()) {
            $this->insert($instance);
        } else {
            $this->update($instance);
        }
    }

    /**
     * Insert INTO ....
     */
    private function insert($instance) {
        $tableName = $instance->getTableName();

        $sql = "INSERT INTO $tableName VALUES(NULL";

        $vars = get_class_vars(get_class($instance));
        $nb = count($vars);

        for ($i = 0; $i < $nb; $i++)
            $sql = $sql . ",?";
        $sql = $sql . ")";

        $values = array();
        foreach ($vars as $k => $v) {
            $values[] = $instance->$k;
        }
        $this->dbmanager->prepare($sql);
        $this->dbmanager->execute($values);
        $instance->setId($this->dbmanager->lastInsertId());
    }

    /**
     * UPDATE ...
     */
    private function update($instance) {
        $tableName = $instance->getTableName();
        $sql = "UPDATE $tableName SET ";
        $vars = get_class_vars(get_class($instance));

        $values = array();
        $first = true;
        foreach ($vars as $k => $v) {
            $values[] = $instance->$k;
            if ($first == false)
                $sql = $sql . ",";
            $sql = $sql . "$k = ?";
            $first = false;
        }

        $sql = $sql . " WHERE id=?";
        $values[] = $instance->getId();
        $this->dbmanager->prepare($sql);
        $this->dbmanager->execute($values);

    }

    /**
     * DELETE FROM ....
     */
    public function delete($instance) {
        if($instance==false || $instance->isNew() == true) return;

        $tableName = $instance->getTableName();

        $sql = "DELETE FROM $tableName WHERE id=?";

        $this->dbmanager->prepare($sql);
        $this->dbmanager->execute(array($instance->getId()));
    }
}

?>


text:
using System;
using System.Threading;
using System.Web;
using Inbox2.Core.Configuration;
using Inbox2.Framework;
using Inbox2.Framework.Extensions;
using Inbox2.Framework.Localization;
using Inbox2.Framework.Threading;
using Inbox2.Framework.Threading.Progress;
using Inbox2.Framework.VirtualMailBox.Entities;
using Inbox2.Platform.Channels;
using Inbox2.Platform.Channels.Entities;
using Inbox2.Platform.Framework.Extensions;
using Inbox2.Platform.Framework.Web;
using Inbox2.Platform.Interfaces.Enumerations;
using Inbox2.Platform.Logging;

namespace Inbox2.Core.Threading.Commands
{
	class SendStatusUpdateCommand : ConnectedCommand
	{
		private readonly UserStatus status;

		public SendStatusUpdateCommand(UserStatus status)
		{
			this.status = status;
		}

		protected override void ExecuteCore()
		{
			var group = new ProgressGroup { Status = Strings.UpdatingStatus };

			ProgressManager.Current.Register(group);

			try
			{
				foreach (var config in status.TargetChannels)
				{
					var channel = ChannelsManager.GetChannelObject(config.ChannelId);

					try
					{
						group.SourceChannelId = config.ChannelId;

						ChannelContext.Current.ClientContext = new ChannelClientContext(ClientState.Current.Context, config);

						Logger.Debug("Updating status. Channel = {0}", LogSource.BackgroundTask, config.DisplayName);

						if (config.IsConnected)
						{
							var data = String.Format("wrap_access_token={0}&channels={1}&inreplyto={2}&body={3}",
								CloudApi.AccessToken, config.ChannelKey, status.InReplyTo, HttpUtility.UrlEncode(status.Status));

							HttpServiceRequest.Post(String.Concat(CloudApi.ApiBaseUrl, "send/statusupdate"), data, true);

						}
						else
						{
							channel.StatusUpdatesChannel.UpdateMyStatus(status.DuckCopy<ChannelStatusUpdate>());
						}
					}
					catch (Exception ex)
					{
						ClientState.Current.ShowMessage(
							new AppMessage(
								String.Concat(
									String.Format(Strings.ErrorOccuredDuringStatusUpdate, channel.Configuration.DisplayName),
									String.Format(Strings.ServerSaid, ex.Message)))
							{
								SourceChannelId = config.ChannelId
							}, MessageType.Error);

						throw;
					}
				}

				Thread.CurrentThread.ExecuteOnUIThread(() =>
					ClientState.Current.ShowMessage(
						new AppMessage(Strings.StatusUpdatedSuccessfully)
							{
								EntityId = status.StatusId,
								EntityType = EntityType.UserStatus
							}, MessageType.Success));
			}
			finally
			{
				group.IsCompleted = true;
			}
		}
	}
}